Add a method to Linker and flag to wasmtime-cli to trap unknown import funcs (#4312)

* Add a method to Linker and flag to wasmtime-cli to trap unknown import funcs

Sometimes users have a Command module which imports functions unknown to
the wasmtime-cli, but does not call them at runtime. This PR provides a
convenience method on Linker to define all unknown import functions in
a given Module as a trivial implementation which traps, and hooks this
up to a new cli flag --trap-unknown-imports.

* add cfg guards - func_new requires compiler (naturally)
This commit is contained in:
Pat Hickey
2022-06-27 06:55:50 -07:00
committed by GitHub
parent 87007c5839
commit 84a43d86a1
3 changed files with 92 additions and 3 deletions

View File

@@ -340,3 +340,40 @@ fn instance_pre() -> Result<()> {
instance_pre.instantiate(&mut store)?;
Ok(())
}
#[test]
fn test_trapping_unknown_import() -> Result<()> {
const WAT: &str = r#"
(module
(type $t0 (func))
(import "" "imp" (func $.imp (type $t0)))
(func $run call $.imp)
(func $other)
(export "run" (func $run))
(export "other" (func $other))
)
"#;
let mut store = Store::<()>::default();
let module = Module::new(store.engine(), WAT).expect("failed to create module");
let mut linker = Linker::new(store.engine());
linker.define_unknown_imports_as_traps(&module)?;
let instance = linker.instantiate(&mut store, &module)?;
// "run" calls an import function which will not be defined, so it should trap
let run_func = instance
.get_func(&mut store, "run")
.expect("expected a run func in the module");
assert!(run_func.call(&mut store, &[], &mut []).is_err());
// "other" does not call the import function, so it should not trap
let other_func = instance
.get_func(&mut store, "other")
.expect("expected an other func in the module");
other_func.call(&mut store, &[], &mut [])?;
Ok(())
}