1 //! Dummy implementations of things that a Wasm module can import. 2 3 use wasmtime::{error::Context as _, *}; 4 5 /// Create a set of dummy functions/globals/etc for the given imports. 6 pub fn dummy_linker<T>(store: &mut Store<T>, module: &Module) -> Result<Linker<T>> { 7 let mut linker = Linker::new(store.engine()); 8 linker.allow_shadowing(true); 9 for import in module.imports() { 10 let extern_ = import.ty().default_value(&mut *store).with_context(|| { 11 format!( 12 "failed to create dummy value of `{}::{}` - {:?}", 13 import.module(), 14 import.name(), 15 import.ty(), 16 ) 17 })?; 18 linker 19 .define(&store, import.module(), import.name(), extern_) 20 .unwrap(); 21 } 22 Ok(linker) 23 } 24 25 #[cfg(test)] 26 mod tests { 27 28 use super::*; 29 30 fn store() -> Store<()> { 31 let mut config = Config::default(); 32 config.wasm_multi_memory(true); 33 let engine = wasmtime::Engine::new(&config).unwrap(); 34 Store::new(&engine, ()) 35 } 36 37 #[test] 38 fn dummy_table_import() { 39 let mut store = store(); 40 let table_type = TableType::new(RefType::EXTERNREF, 10, None); 41 let table = table_type.default_value(&mut store).unwrap(); 42 assert_eq!(table.size(&store), 10); 43 for i in 0..10 { 44 assert!(table.get(&mut store, i).unwrap().unwrap_extern().is_none()); 45 } 46 } 47 48 #[test] 49 fn dummy_global_import() { 50 let mut store = store(); 51 let global_type = GlobalType::new(ValType::I32, Mutability::Const); 52 let global = global_type.default_value(&mut store).unwrap(); 53 assert!(global.ty(&store).content().is_i32()); 54 assert_eq!(global.ty(&store).mutability(), Mutability::Const); 55 } 56 57 #[test] 58 fn dummy_memory_import() { 59 let mut store = store(); 60 let memory_type = MemoryType::new(1, None); 61 let memory = memory_type 62 .default_value(&mut store) 63 .unwrap() 64 .into_memory() 65 .unwrap(); 66 assert_eq!(memory.size(&store), 1); 67 } 68 69 #[test] 70 fn dummy_function_import() { 71 let mut store = store(); 72 let func_ty = FuncType::new(store.engine(), vec![ValType::I32], vec![ValType::I64]); 73 let func = func_ty.default_value(&mut store).unwrap(); 74 let actual_ty = func.ty(&store); 75 assert!(FuncType::eq(&actual_ty, &func_ty)); 76 } 77 } 78