From 07fbe31ec22953f41d56d98b758c0bd66f3a49fe Mon Sep 17 00:00:00 2001 From: Sergey Pepyakin Date: Wed, 14 Feb 2018 13:36:27 +0300 Subject: [PATCH] Add `instantiate` bin (#53) This change adds a handy utility to test whether the given module deserializes, validates and instantiates successfully. --- src/bin/instantiate.rs | 81 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 src/bin/instantiate.rs diff --git a/src/bin/instantiate.rs b/src/bin/instantiate.rs new file mode 100644 index 0000000..e5042f9 --- /dev/null +++ b/src/bin/instantiate.rs @@ -0,0 +1,81 @@ +//! Handy utility to test whether the given module deserializes, +//! validates and instantiates successfully. + +extern crate wasmi; + +use std::env::args; +use std::fs::File; +use wasmi::{ + Error, FuncInstance, FuncRef, GlobalDescriptor, GlobalInstance, GlobalRef, + ImportsBuilder, MemoryDescriptor, MemoryInstance, MemoryRef, Module, + ModuleImportResolver, ModuleInstance, NopExternals, RuntimeValue, Signature, + TableDescriptor, TableInstance, TableRef}; +use wasmi::memory_units::*; + +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 { + Ok(FuncInstance::alloc_host(signature.clone(), 0)) + } + + fn resolve_global( + &self, + _field_name: &str, + global_type: &GlobalDescriptor, + ) -> Result { + Ok(GlobalInstance::alloc( + RuntimeValue::default(global_type.value_type()), + global_type.is_mutable(), + )) + } + + fn resolve_memory( + &self, + _field_name: &str, + memory_type: &MemoryDescriptor, + ) -> Result { + 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 { + Ok(TableInstance::alloc(table_type.initial(), table_type.maximum()).unwrap()) + } +} + +fn main() { + let args: Vec<_> = args().collect(); + if args.len() != 2 { + println!("Usage: {} ", args[0]); + return; + } + let module = load_from_file(&args[1]); + let _ = ModuleInstance::new( + &module, + &ImportsBuilder::default() + // Well known imports. + .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"); +}