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
extern crate wasmi;
use std::env::args;
use std::fs::File;
use wasmi::memory_units::*;
use wasmi::{
Error, FuncInstance, FuncRef, GlobalDescriptor, GlobalInstance, GlobalRef, ImportsBuilder,
MemoryDescriptor, MemoryInstance, MemoryRef, Module, ModuleImportResolver, ModuleInstance,
NopExternals, RuntimeValue, Signature, TableDescriptor, TableInstance, TableRef,
};
fn load_from_file(filename: &str) -> Module {
use std::io::prelude::*;
let mut file = File::open(filename).unwrap();
let mut buf = Vec::new();
file.read_to_end(&mut buf).unwrap();
Module::from_buffer(buf).unwrap()
}
struct ResolveAll;
impl ModuleImportResolver for ResolveAll {
fn resolve_func(&self, _field_name: &str, signature: &Signature) -> Result<FuncRef, Error> {
Ok(FuncInstance::alloc_host(signature.clone(), 0))
}
fn resolve_global(
&self,
_field_name: &str,
global_type: &GlobalDescriptor,
) -> Result<GlobalRef, Error> {
Ok(GlobalInstance::alloc(
RuntimeValue::default(global_type.value_type()),
global_type.is_mutable(),
))
}
fn resolve_memory(
&self,
_field_name: &str,
memory_type: &MemoryDescriptor,
) -> Result<MemoryRef, Error> {
Ok(MemoryInstance::alloc(
Pages(memory_type.initial() as usize),
memory_type.maximum().map(|m| Pages(m as usize)),
)
.unwrap())
}
fn resolve_table(
&self,
_field_name: &str,
table_type: &TableDescriptor,
) -> Result<TableRef, Error> {
Ok(TableInstance::alloc(table_type.initial(), table_type.maximum()).unwrap())
}
}
fn main() {
let args: Vec<_> = args().collect();
if args.len() != 2 {
println!("Usage: {} <wasm file>", args[0]);
return;
}
let module = load_from_file(&args[1]);
let _ = ModuleInstance::new(
&module,
&ImportsBuilder::default()
.with_resolver("env", &ResolveAll)
.with_resolver("global", &ResolveAll)
.with_resolver("foo", &ResolveAll)
.with_resolver("global.Math", &ResolveAll)
.with_resolver("asm2wasm", &ResolveAll)
.with_resolver("spectest", &ResolveAll),
)
.expect("Failed to instantiate module")
.run_start(&mut NopExternals)
.expect("Failed to run start function in module");
}