1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use std::collections::HashMap;
use std::iter::repeat;
use std::sync::{Arc, Weak};
use elements::{Module, InitExpr, Opcode, Type, FunctionType, FuncBody, Internal};
use interpreter::Error;
use interpreter::imports::ModuleImports;
use interpreter::memory::MemoryInstance;
use interpreter::program::ProgramInstanceEssence;
use interpreter::runner::{Interpreter, FunctionContext};
use interpreter::stack::StackWithLimit;
use interpreter::table::TableInstance;
use interpreter::value::{RuntimeValue, TryInto};
use interpreter::variable::{VariableInstance, VariableType};

#[derive(Default, Clone)]
/// Execution context.
pub struct ExecutionParams<'a> {
	/// Arguments.
	pub args: Vec<RuntimeValue>,
	/// Execution-local external modules.
	pub externals: HashMap<String, Arc<ModuleInstanceInterface + 'a>>,
}

/// Module instance API.
pub trait ModuleInstanceInterface {
	/// Execute start function of the module.
	fn execute_main(&self, params: ExecutionParams) -> Result<Option<RuntimeValue>, Error>;
	/// Execute function with the given index.
	fn execute_index(&self, index: u32, params: ExecutionParams) -> Result<Option<RuntimeValue>, Error>;
	/// Execute function with the given export name.
	fn execute_export(&self, name: &str, params: ExecutionParams) -> Result<Option<RuntimeValue>, Error>;
	/// Get export entry.
	fn export_entry(&self, name: &str) -> Result<Internal, Error>;
	/// Get table reference.
	fn table(&self, index: ItemIndex) -> Result<Arc<TableInstance>, Error>;
	/// Get memory reference.
	fn memory(&self, index: ItemIndex) -> Result<Arc<MemoryInstance>, Error>;
	/// Get global reference.
	fn global(&self, index: ItemIndex) -> Result<Arc<VariableInstance>, Error>;
	/// Call function with given index in functions index space.
	fn call_function(&self, outer: CallerContext, index: ItemIndex) -> Result<Option<RuntimeValue>, Error>;
	/// Call function with given index in the given table.
	fn call_function_indirect(&self, outer: CallerContext, table_index: ItemIndex, type_index: u32, func_index: u32) -> Result<Option<RuntimeValue>, Error>;
	/// Call function with internal index.
	fn call_internal_function(&self, outer: CallerContext, index: u32, function_type: Option<&FunctionType>) -> Result<Option<RuntimeValue>, Error>;
}

/// Item index in items index space.
#[derive(Debug, Clone, Copy)]
pub enum ItemIndex {
	/// Index in index space.
	IndexSpace(u32),
	/// Internal item index (i.e. index of item in items section).
	Internal(u32),
	/// External module item index (i.e. index of item in the import section).
	External(u32),
}

/// Module instance.
pub struct ModuleInstance {
	/// Module.
	module: Module,
	/// Module imports.
	imports: ModuleImports,
	/// Tables.
	tables: Vec<Arc<TableInstance>>,
	/// Linear memory regions.
	memory: Vec<Arc<MemoryInstance>>,
	/// Globals.
	globals: Vec<Arc<VariableInstance>>,
}

/// Caller context.
pub struct CallerContext<'a> {
	/// Value stack limit
	pub value_stack_limit: usize,
	/// Frame stack limit
	pub frame_stack_limit: usize,
	/// Stack of the input parameters
	pub value_stack: &'a mut StackWithLimit<RuntimeValue>,
	/// Execution-local external modules.
	pub externals: &'a HashMap<String, Arc<ModuleInstanceInterface + 'a>>,
}

impl<'a> ExecutionParams<'a> {
	/// Create new execution params with given externa; module override.
	pub fn with_external(name: String, module: Arc<ModuleInstanceInterface + 'a>) -> Self {
		let mut externals = HashMap::new();
		externals.insert(name, module);
		ExecutionParams {
			args: Vec::new(),
			externals: externals,
		}
	}

	/// Add argument.
	pub fn add_argument(mut self, arg: RuntimeValue) -> Self {
		self.args.push(arg);
		self
	}
}

impl<'a> From<Vec<RuntimeValue>> for ExecutionParams<'a> {
	fn from(args: Vec<RuntimeValue>) -> ExecutionParams<'a> {
		ExecutionParams {
			args: args,
			externals: HashMap::new(),
		}
	}
}

impl ModuleInstance {
	/// Instantiate given module within program context.
	pub fn new(program: Weak<ProgramInstanceEssence>, module: Module) -> Result<Self, Error> {
		// TODO: missing validation step
	
		// load entries from import section
		let imports = ModuleImports::new(program, module.import_section());

		// instantiate linear memory regions, if any
		let memory = match module.memory_section() {
			Some(memory_section) => memory_section.entries()
										.iter()
										.map(MemoryInstance::new)
										.collect::<Result<Vec<_>, _>>()?,
			None => Vec::new(),
		};

		// instantiate tables, if any
		let tables = match module.table_section() {
			Some(table_section) => table_section.entries()
										.iter()
										.map(|tt| TableInstance::new(VariableType::AnyFunc, tt)) // TODO: actual table type
										.collect::<Result<Vec<_>, _>>()?,
			None => Vec::new(),
		};

		// instantiate globals, if any
		let globals = match module.global_section() {
			Some(global_section) => global_section.entries()
										.iter()
										.map(|g| {
											get_initializer(g.init_expr(), &module, &imports)
												.map_err(|e| Error::Initialization(e.into()))
												.and_then(|v| VariableInstance::new_global(g.global_type(), v).map(Arc::new))
										})
										.collect::<Result<Vec<_>, _>>()?,
			None => Vec::new(),
		};

		let mut module = ModuleInstance {
			module: module,
			imports: imports,
			memory: memory,
			tables: tables,
			globals: globals,
		};
		module.complete_initialization()?;
		Ok(module)
	}

	/// Complete module initialization.
	fn complete_initialization(&mut self) -> Result<(), Error> {
		// use data section to initialize linear memory regions
		if let Some(data_section) = self.module.data_section() {
			for (data_segment_index, data_segment) in data_section.entries().iter().enumerate() {
				let offset: u32 = get_initializer(data_segment.offset(), &self.module, &self.imports)?.try_into()?;
				self.memory(ItemIndex::IndexSpace(data_segment.index()))
					.map_err(|e| Error::Initialization(format!("DataSegment {} initializes non-existant MemoryInstance {}: {:?}", data_segment_index, data_segment.index(), e)))
					.and_then(|m| m.set(offset, data_segment.value()))
					.map_err(|e| Error::Initialization(e.into()))?;
			}
		}

		// use element section to fill tables
		if let Some(element_section) = self.module.elements_section() {
			for (element_segment_index, element_segment) in element_section.entries().iter().enumerate() {
				let offset: u32 = get_initializer(element_segment.offset(), &self.module, &self.imports)?.try_into()?;
				self.table(ItemIndex::IndexSpace(element_segment.index()))
					.map_err(|e| Error::Initialization(format!("ElementSegment {} initializes non-existant Table {}: {:?}", element_segment_index, element_segment.index(), e)))
					.and_then(|m| m.set_raw(offset, element_segment.members()))
					.map_err(|e| Error::Initialization(e.into()))?;
			}
		}

		Ok(())
	}
}

impl ModuleInstanceInterface for ModuleInstance {
	fn execute_main(&self, params: ExecutionParams) -> Result<Option<RuntimeValue>, Error> {
		let index = self.module.start_section().ok_or(Error::Program("module has no start section".into()))?;
		self.execute_index(index, params)
	}

	fn execute_index(&self, index: u32, params: ExecutionParams) -> Result<Option<RuntimeValue>, Error> {
		let args_len = params.args.len();
		let mut args = StackWithLimit::with_data(params.args, args_len);
		let caller_context = CallerContext::topmost(&mut args, &params.externals);
		self.call_function(caller_context, ItemIndex::IndexSpace(index))
	}

	fn execute_export(&self, name: &str, params: ExecutionParams) -> Result<Option<RuntimeValue>, Error> {
		let index = self.module.export_section()
			.ok_or(Error::Function("missing export section".into()))
			.and_then(|s| s.entries().iter()
				.find(|e| e.field() == name && match e.internal() {
					&Internal::Function(_) => true,
					_ => false,
				})
				.ok_or(Error::Function(format!("missing export section exported function with name {}", name)))
				.map(|e| match e.internal() {
					&Internal::Function(index) => index,
					_ => unreachable!(), // checked couple of lines above
				})
			)?;
		self.execute_index(index, params)
	}

	fn export_entry(&self, name: &str) -> Result<Internal, Error> {
		self.module.export_section()
			.ok_or(Error::Program(format!("trying to import {} from module without export section", name)))
			.and_then(|s| s.entries().iter()
				.find(|e| e.field() == name)
				.map(|e| *e.internal())
				.ok_or(Error::Program(format!("unresolved import {}", name))))
	}

	fn table(&self, index: ItemIndex) -> Result<Arc<TableInstance>, Error> {
		match self.imports.parse_table_index(index) {
			ItemIndex::IndexSpace(_) => unreachable!("parse_table_index resolves IndexSpace option"),
			ItemIndex::Internal(index) => self.tables.get(index as usize).cloned()
				.ok_or(Error::Table(format!("trying to access table with local index {} when there are only {} local tables", index, self.tables.len()))),
			ItemIndex::External(index) => self.module.import_section()
				.ok_or(Error::Table(format!("trying to access external table with index {} in module without import section", index)))
				.and_then(|s| s.entries().get(index as usize)
					.ok_or(Error::Table(format!("trying to access external table with index {} in module with {}-entries import section", index, s.entries().len()))))
				.and_then(|e| self.imports.table(None, e)),
		}
	}

	fn memory(&self, index: ItemIndex) -> Result<Arc<MemoryInstance>, Error> {
		match self.imports.parse_memory_index(index) {
			ItemIndex::IndexSpace(_) => unreachable!("parse_memory_index resolves IndexSpace option"),
			ItemIndex::Internal(index) => self.memory.get(index as usize).cloned()
				.ok_or(Error::Memory(format!("trying to access memory with local index {} when there are only {} memory regions", index, self.memory.len()))),
			ItemIndex::External(index) => self.module.import_section()
				.ok_or(Error::Memory(format!("trying to access external memory with index {} in module without import section", index)))
				.and_then(|s| s.entries().get(index as usize)
					.ok_or(Error::Memory(format!("trying to access external memory with index {} in module with {}-entries import section", index, s.entries().len()))))
				.and_then(|e| self.imports.memory(None, e)),
		}
	}

	fn global(&self, index: ItemIndex) -> Result<Arc<VariableInstance>, Error> {
		match self.imports.parse_global_index(index) {
			ItemIndex::IndexSpace(_) => unreachable!("parse_global_index resolves IndexSpace option"),
			ItemIndex::Internal(index) => self.globals.get(index as usize).cloned()
				.ok_or(Error::Global(format!("trying to access global with local index {} when there are only {} globals", index, self.globals.len()))),
			ItemIndex::External(index) => self.module.import_section()
				.ok_or(Error::Global(format!("trying to access external global with index {} in module without import section", index)))
				.and_then(|s| s.entries().get(index as usize)
					.ok_or(Error::Global(format!("trying to access external global with index {} in module with {}-entries import section", index, s.entries().len()))))
				.and_then(|e| self.imports.global(None, e)),
		}
	}

	fn call_function(&self, outer: CallerContext, index: ItemIndex) -> Result<Option<RuntimeValue>, Error> {
		match self.imports.parse_function_index(index) {
			ItemIndex::IndexSpace(_) => unreachable!("parse_function_index resolves IndexSpace option"),
			ItemIndex::Internal(index) => self.call_internal_function(outer, index, None),
			ItemIndex::External(index) =>
				self.module.import_section()
				.ok_or(Error::Function(format!("trying to access external function with index {} in module without import section", index)))
				.and_then(|s| s.entries().get(index as usize)
					.ok_or(Error::Function(format!("trying to access external function with index {} in module with {}-entries import section", index, s.entries().len()))))
				.and_then(|e| Ok((self.imports.module(Some(outer.externals), e.module())?, self.imports.function(Some(outer.externals), e)?)))
				.and_then(|(m, index)| m.call_internal_function(outer, index, None)),
		}
	}

	fn call_function_indirect(&self, outer: CallerContext, table_index: ItemIndex, type_index: u32, func_index: u32) -> Result<Option<RuntimeValue>, Error> {
		let function_type = match self.module.type_section()
			.ok_or(Error::Function(format!("trying to indirect call function {} with non-existent function section", func_index)))
			.and_then(|s| s.types().get(type_index as usize)
				.ok_or(Error::Function(format!("trying to indirect call function {} with non-existent type index {}", func_index, type_index))))? {
			&Type::Function(ref function_type) => function_type,
		};

		match self.imports.parse_table_index(table_index) {
			ItemIndex::IndexSpace(_) => unreachable!("parse_function_index resolves IndexSpace option"),
			ItemIndex::Internal(table_index) => {
				let table = self.table(ItemIndex::Internal(table_index))?;
				let index = match table.get(func_index)? {
					RuntimeValue::AnyFunc(index) => index,
					_ => return Err(Error::Function(format!("trying to indirect call function {} via non-anyfunc table {}", func_index, table_index))),
				};
				self.call_internal_function(outer, index, Some(function_type))
			},
			ItemIndex::External(table_index) => {
				let table = self.table(ItemIndex::External(table_index))?;
				let index = match table.get(func_index)? {
					RuntimeValue::AnyFunc(index) => index,
					_ => return Err(Error::Function(format!("trying to indirect call function {} via non-anyfunc table {}", func_index, table_index))),
				};
				let module = self.module.import_section()
					.ok_or(Error::Function(format!("trying to access external table with index {} in module without import section", table_index)))
					.and_then(|s| s.entries().get(table_index as usize)
						.ok_or(Error::Function(format!("trying to access external table with index {} in module with {}-entries import section", table_index, s.entries().len()))))
					.and_then(|e| self.imports.module(Some(outer.externals), e.module()))?;
				module.call_internal_function(outer, index, Some(function_type))
			}
		}
	}

	fn call_internal_function(&self, mut outer: CallerContext, index: u32, function_type: Option<&FunctionType>) -> Result<Option<RuntimeValue>, Error> {
		// TODO: cache
		// internal index = index of function in functions section && index of code in code section
		// get function type index
		let function_type_index = self.module
			.functions_section()
			.ok_or(Error::Function(format!("trying to call function with index {} in module without function section", index)))
			.and_then(|s| s.entries()
				.get(index as usize)
				.ok_or(Error::Function(format!("trying to call function with index {} in module with {} functions", index, s.entries().len()))))?
			.type_ref();
		// function type index = index of function type in types index
		// get function type
		let item_type = self.module
			.type_section()
			.ok_or(Error::Function(format!("trying to call function with index {} in module without types section", index)))
			.and_then(|s| s.types()
				.get(function_type_index as usize)
				.ok_or(Error::Function(format!("trying to call function with type index {} in module with {} types", index, s.types().len()))))?;
		let actual_function_type = match item_type {
			&Type::Function(ref function_type) => function_type,
		};
		if let Some(ref function_type) = function_type {
			if function_type != &actual_function_type {
				return Err(Error::Function(format!("expected function with signature ({:?}) -> {:?} when got with ({:?}) -> {:?}",
					function_type.params(), function_type.return_type(), actual_function_type.params(), actual_function_type.return_type())));
			}
		}
		// get function body
		let function_body = self.module
			.code_section()
			.ok_or(Error::Function(format!("trying to call function with index {} in module without code section", index)))
			.and_then(|s| s.bodies()
				.get(index as usize)
				.ok_or(Error::Function(format!("trying to call function with index {} in module with {} functions codes", index, s.bodies().len()))))?;

		// each functions has its own value stack
		// but there's global stack limit
		// args, locals
		let function_code = function_body.code().elements();
		let value_stack_limit = outer.value_stack_limit;
		let frame_stack_limit = outer.frame_stack_limit;
		let locals = prepare_function_locals(actual_function_type, function_body, &mut outer)?;
		let mut innner = FunctionContext::new(self, outer.externals, value_stack_limit, frame_stack_limit, actual_function_type, locals);
		Interpreter::run_function(&mut innner, function_code)
	}
}

impl<'a> CallerContext<'a> {
	/// Top most args
	pub fn topmost(args: &'a mut StackWithLimit<RuntimeValue>, externals: &'a HashMap<String, Arc<ModuleInstanceInterface + 'a>>) -> Self {
		CallerContext {
			value_stack_limit: 1024,
			frame_stack_limit: 1024,
			value_stack: args,
			externals: externals,
		}
	}

	/// Nested context
	pub fn nested(outer: &'a mut FunctionContext) -> Self {
		CallerContext {
			value_stack_limit: outer.value_stack().limit() - outer.value_stack().len(),
			frame_stack_limit: outer.frame_stack().limit() - outer.frame_stack().len(),
			value_stack: &mut outer.value_stack,
			externals: &outer.externals,
		}
	}
}

fn prepare_function_locals(function_type: &FunctionType, function_body: &FuncBody, outer: &mut CallerContext) -> Result<Vec<VariableInstance>, Error> {
	// locals = function arguments + defined locals
	function_type.params().iter().rev()
		.map(|param_type| {
			let param_value = outer.value_stack.pop()?;
			let actual_type = param_value.variable_type();
			let expected_type = (*param_type).into();
			if actual_type != Some(expected_type) {
				return Err(Error::Function(format!("invalid parameter type {:?} when expected {:?}", actual_type, expected_type)));
			}

			VariableInstance::new(true, expected_type, param_value)
		})
		.collect::<Vec<_>>().into_iter().rev()
		.chain(function_body.locals()
			.iter()
			.flat_map(|l| repeat(l.value_type().into()).take(l.count() as usize))
			.map(|vt| VariableInstance::new(true, vt, RuntimeValue::default(vt))))
		.collect::<Result<Vec<_>, _>>()
}

fn get_initializer(expr: &InitExpr, module: &Module, imports: &ModuleImports) -> Result<RuntimeValue, Error> {
	let first_opcode = expr.code().get(0).ok_or(Error::Initialization(format!("empty instantiation-time initializer")))?;
	match first_opcode {
		&Opcode::GetGlobal(index) => {
			let index = match imports.parse_global_index(ItemIndex::IndexSpace(index)) {
				ItemIndex::External(index) => index,
				_ => return Err(Error::Global(format!("trying to initialize with non-external global {}", index))),
			};
			module.import_section()
				.ok_or(Error::Global(format!("trying to initialize with external global with index {} in module without import section", index)))
				.and_then(|s| s.entries().get(index as usize)
					.ok_or(Error::Global(format!("trying to initialize with external global with index {} in module with {}-entries import section", index, s.entries().len()))))
				.and_then(|e| imports.global(None, e))
				.map(|g| g.get())
		},
		&Opcode::I32Const(val) => Ok(RuntimeValue::I32(val)),
		&Opcode::I64Const(val) => Ok(RuntimeValue::I64(val)),
		&Opcode::F32Const(val) => Ok(RuntimeValue::decode_f32(val)),
		&Opcode::F64Const(val) => Ok(RuntimeValue::decode_f64(val)),
		_ => Err(Error::Initialization(format!("not-supported {:?} instruction in instantiation-time initializer", first_opcode))),
	}
}