Files
wasmtime/tests/all/linker.rs
Alex Crichton 2afaac5181 Return anyhow::Error from host functions instead of Trap, redesign Trap (#5149)
* Return `anyhow::Error` from host functions instead of `Trap`

This commit refactors how errors are modeled when returned from host
functions and additionally refactors how custom errors work with `Trap`.
At a high level functions in Wasmtime that previously worked with
`Result<T, Trap>` now work with `Result<T>` instead where the error is
`anyhow::Error`. This includes functions such as:

* Host-defined functions in a `Linker<T>`
* `TypedFunc::call`
* Host-related callbacks like call hooks

Errors are now modeled primarily as `anyhow::Error` throughout Wasmtime.
This subsequently removes the need for `Trap` to have the ability to
represent all host-defined errors as it previously did. Consequently the
`From` implementations for any error into a `Trap` have been removed
here and the only embedder-defined way to create a `Trap` is to use
`Trap::new` with a custom string.

After this commit the distinction between a `Trap` and a host error is
the wasm backtrace that it contains. Previously all errors in host
functions would flow through a `Trap` and get a wasm backtrace attached
to them, but now this only happens if a `Trap` itself is created meaning
that arbitrary host-defined errors flowing from a host import to the
other side won't get backtraces attached. Some internals of Wasmtime
itself were updated or preserved to use `Trap::new` to capture a
backtrace where it seemed useful, such as when fuel runs out.

The main motivation for this commit is that it now enables hosts to
thread a concrete error type from a host function all the way through to
where a wasm function was invoked. Previously this could not be done
since the host error was wrapped in a `Trap` that didn't provide the
ability to get at the internals.

A consequence of this commit is that when a host error is returned that
isn't a `Trap` we'll capture a backtrace and then won't have a `Trap` to
attach it to. To avoid losing the contextual information this commit
uses the `Error::context` method to attach the backtrace as contextual
information to ensure that the backtrace is itself not lost.

This is a breaking change for likely all users of Wasmtime, but it's
hoped to be a relatively minor change to workaround. Most use cases can
likely change `-> Result<T, Trap>` to `-> Result<T>` and otherwise
explicit creation of a `Trap` is largely no longer necessary.

* Fix some doc links

* add some tests and make a backtrace type public (#55)

* Trap: avoid a trailing newline in the Display impl

which in turn ends up with three newlines between the end of the
backtrace and the `Caused by` in the anyhow Debug impl

* make BacktraceContext pub, and add tests showing downcasting behavior of anyhow::Error to traps or backtraces

* Remove now-unnecesary `Trap` downcasts in `Linker::module`

* Fix test output expectations

* Remove `Trap::i32_exit`

This commit removes special-handling in the `wasmtime::Trap` type for
the i32 exit code required by WASI. This is now instead modeled as a
specific `I32Exit` error type in the `wasmtime-wasi` crate which is
returned by the `proc_exit` hostcall. Embedders which previously tested
for i32 exits now downcast to the `I32Exit` value.

* Remove the `Trap::new` constructor

This commit removes the ability to create a trap with an arbitrary error
message. The purpose of this commit is to continue the prior trend of
leaning into the `anyhow::Error` type instead of trying to recreate it
with `Trap`. A subsequent simplification to `Trap` after this commit is
that `Trap` will simply be an `enum` of trap codes with no extra
information. This commit is doubly-motivated by the desire to always use
the new `BacktraceContext` type instead of sometimes using that and
sometimes using `Trap`.

Most of the changes here were around updating `Trap::new` calls to
`bail!` calls instead. Tests which assert particular error messages
additionally often needed to use the `:?` formatter instead of the `{}`
formatter because the prior formats the whole `anyhow::Error` and the
latter only formats the top-most error, which now contains the
backtrace.

* Merge `Trap` and `TrapCode`

With prior refactorings there's no more need for `Trap` to be opaque or
otherwise contain a backtrace. This commit parse down `Trap` to simply
an `enum` which was the old `TrapCode`. All various tests and such were
updated to handle this.

The main consequence of this commit is that all errors have a
`BacktraceContext` context attached to them. This unfortunately means
that the backtrace is printed first before the error message or trap
code, but given all the prior simplifications that seems worth it at
this time.

* Rename `BacktraceContext` to `WasmBacktrace`

This feels like a better name given how this has turned out, and
additionally this commit removes having both `WasmBacktrace` and
`BacktraceContext`.

* Soup up documentation for errors and traps

* Fix build of the C API

Co-authored-by: Pat Hickey <pat@moreproductive.org>
2022-11-02 16:29:31 +00:00

380 lines
12 KiB
Rust

use anyhow::Result;
use std::cell::Cell;
use std::rc::Rc;
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
use std::sync::Arc;
use wasmtime::*;
#[test]
fn link_undefined() -> Result<()> {
let mut store = Store::<()>::default();
let linker = Linker::new(store.engine());
let module = Module::new(store.engine(), r#"(module (import "" "" (func)))"#)?;
assert!(linker.instantiate(&mut store, &module).is_err());
let module = Module::new(store.engine(), r#"(module (import "" "" (global i32)))"#)?;
assert!(linker.instantiate(&mut store, &module).is_err());
let module = Module::new(store.engine(), r#"(module (import "" "" (memory 1)))"#)?;
assert!(linker.instantiate(&mut store, &module).is_err());
let module = Module::new(
store.engine(),
r#"(module (import "" "" (table 1 funcref)))"#,
)?;
assert!(linker.instantiate(&mut store, &module).is_err());
Ok(())
}
#[test]
fn link_twice_bad() -> Result<()> {
let mut store = Store::<()>::default();
let mut linker = Linker::<()>::new(store.engine());
// functions
linker.func_wrap("f", "", || {})?;
assert!(linker.func_wrap("f", "", || {}).is_err());
assert!(linker
.func_wrap("f", "", || -> Result<()> { loop {} })
.is_err());
// globals
let ty = GlobalType::new(ValType::I32, Mutability::Const);
let global = Global::new(&mut store, ty, Val::I32(0))?;
linker.define("g", "1", global.clone())?;
assert!(linker.define("g", "1", global.clone()).is_err());
let ty = GlobalType::new(ValType::I32, Mutability::Var);
let global = Global::new(&mut store, ty, Val::I32(0))?;
linker.define("g", "2", global.clone())?;
assert!(linker.define("g", "2", global.clone()).is_err());
let ty = GlobalType::new(ValType::I64, Mutability::Const);
let global = Global::new(&mut store, ty, Val::I64(0))?;
linker.define("g", "3", global.clone())?;
assert!(linker.define("g", "3", global.clone()).is_err());
// memories
let ty = MemoryType::new(1, None);
let memory = Memory::new(&mut store, ty)?;
linker.define("m", "", memory.clone())?;
assert!(linker.define("m", "", memory.clone()).is_err());
let ty = MemoryType::new(2, None);
let memory = Memory::new(&mut store, ty)?;
assert!(linker.define("m", "", memory.clone()).is_err());
// tables
let ty = TableType::new(ValType::FuncRef, 1, None);
let table = Table::new(&mut store, ty, Val::FuncRef(None))?;
linker.define("t", "", table.clone())?;
assert!(linker.define("t", "", table.clone()).is_err());
let ty = TableType::new(ValType::FuncRef, 2, None);
let table = Table::new(&mut store, ty, Val::FuncRef(None))?;
assert!(linker.define("t", "", table.clone()).is_err());
Ok(())
}
#[test]
fn function_interposition() -> Result<()> {
let mut store = Store::<()>::default();
let mut linker = Linker::new(store.engine());
linker.allow_shadowing(true);
let mut module = Module::new(
store.engine(),
r#"(module (func (export "green") (result i32) (i32.const 7)))"#,
)?;
for _ in 0..4 {
let instance = linker.instantiate(&mut store, &module)?;
linker.define(
"red",
"green",
instance.get_export(&mut store, "green").unwrap().clone(),
)?;
module = Module::new(
store.engine(),
r#"(module
(import "red" "green" (func (result i32)))
(func (export "green") (result i32) (i32.mul (call 0) (i32.const 2)))
)"#,
)?;
}
let instance = linker.instantiate(&mut store, &module)?;
let func = instance
.get_export(&mut store, "green")
.unwrap()
.into_func()
.unwrap();
let func = func.typed::<(), i32, _>(&store)?;
assert_eq!(func.call(&mut store, ())?, 112);
Ok(())
}
// Same as `function_interposition`, but the linker's name for the function
// differs from the module's name.
#[test]
fn function_interposition_renamed() -> Result<()> {
let mut store = Store::<()>::default();
let mut linker = Linker::new(store.engine());
linker.allow_shadowing(true);
let mut module = Module::new(
store.engine(),
r#"(module (func (export "export") (result i32) (i32.const 7)))"#,
)?;
for _ in 0..4 {
let instance = linker.instantiate(&mut store, &module)?;
linker.define(
"red",
"green",
instance.get_export(&mut store, "export").unwrap().clone(),
)?;
module = Module::new(
store.engine(),
r#"(module
(import "red" "green" (func (result i32)))
(func (export "export") (result i32) (i32.mul (call 0) (i32.const 2)))
)"#,
)?;
}
let instance = linker.instantiate(&mut store, &module)?;
let func = instance.get_func(&mut store, "export").unwrap();
let func = func.typed::<(), i32, _>(&store)?;
assert_eq!(func.call(&mut store, ())?, 112);
Ok(())
}
// Similar to `function_interposition`, but use `Linker::instance` instead of
// `Linker::define`.
#[test]
fn module_interposition() -> Result<()> {
let mut store = Store::<()>::default();
let mut linker = Linker::new(store.engine());
linker.allow_shadowing(true);
let mut module = Module::new(
store.engine(),
r#"(module (func (export "export") (result i32) (i32.const 7)))"#,
)?;
for _ in 0..4 {
let instance = linker.instantiate(&mut store, &module)?;
linker.instance(&mut store, "instance", instance)?;
module = Module::new(
store.engine(),
r#"(module
(import "instance" "export" (func (result i32)))
(func (export "export") (result i32) (i32.mul (call 0) (i32.const 2)))
)"#,
)?;
}
let instance = linker.instantiate(&mut store, &module)?;
let func = instance
.get_export(&mut store, "export")
.unwrap()
.into_func()
.unwrap();
let func = func.typed::<(), i32, _>(&store)?;
assert_eq!(func.call(&mut store, ())?, 112);
Ok(())
}
#[test]
fn allow_unknown_exports() -> Result<()> {
let mut store = Store::<()>::default();
let mut linker = Linker::new(store.engine());
let module = Module::new(
store.engine(),
r#"(module (func (export "_start")) (global (export "g") i32 (i32.const 0)))"#,
)?;
assert!(linker.module(&mut store, "module", &module).is_err());
let mut linker = Linker::new(store.engine());
linker.allow_unknown_exports(true);
linker.module(&mut store, "module", &module)?;
Ok(())
}
#[test]
fn no_leak() -> Result<()> {
struct DropMe(Rc<Cell<bool>>);
impl Drop for DropMe {
fn drop(&mut self) {
self.0.set(true);
}
}
let flag = Rc::new(Cell::new(false));
{
let mut store = Store::new(&Engine::default(), DropMe(flag.clone()));
let mut linker = Linker::new(store.engine());
let module = Module::new(
store.engine(),
r#"
(module
(func (export "_start"))
)
"#,
)?;
linker.module(&mut store, "a", &module)?;
}
assert!(flag.get(), "store was leaked");
Ok(())
}
#[test]
fn no_leak_with_imports() -> Result<()> {
struct DropMe(Arc<AtomicUsize>);
impl Drop for DropMe {
fn drop(&mut self) {
self.0.fetch_add(1, SeqCst);
}
}
let flag = Arc::new(AtomicUsize::new(0));
{
let mut store = Store::new(&Engine::default(), DropMe(flag.clone()));
let mut linker = Linker::new(store.engine());
let drop_me = DropMe(flag.clone());
linker.func_wrap("", "", move || drop(&drop_me))?;
let module = Module::new(
store.engine(),
r#"
(module
(import "" "" (func))
(func (export "_start"))
)
"#,
)?;
linker.module(&mut store, "a", &module)?;
}
assert!(flag.load(SeqCst) == 2, "something was leaked");
Ok(())
}
#[test]
fn get_host_function() -> Result<()> {
let engine = Engine::default();
let module = Module::new(&engine, r#"(module (import "mod" "f1" (func)))"#)?;
let mut linker = Linker::new(&engine);
linker.func_wrap("mod", "f1", || {})?;
let mut store = Store::new(&engine, ());
assert!(linker
.get_by_import(&mut store, &module.imports().nth(0).unwrap())
.is_some());
Ok(())
}
#[test]
fn funcs_live_on_to_fight_another_day() -> Result<()> {
struct DropMe(Arc<AtomicUsize>);
impl Drop for DropMe {
fn drop(&mut self) {
self.0.fetch_add(1, SeqCst);
}
}
let flag = Arc::new(AtomicUsize::new(0));
let engine = Engine::default();
let mut linker = Linker::new(&engine);
let drop_me = DropMe(flag.clone());
linker.func_wrap("", "", move || drop(&drop_me))?;
assert_eq!(flag.load(SeqCst), 0);
let get_and_call = || -> Result<()> {
assert_eq!(flag.load(SeqCst), 0);
let mut store = Store::new(&engine, ());
let func = linker.get(&mut store, "", "").unwrap();
func.into_func().unwrap().call(&mut store, &[], &mut [])?;
assert_eq!(flag.load(SeqCst), 0);
Ok(())
};
get_and_call()?;
get_and_call()?;
drop(linker);
assert_eq!(flag.load(SeqCst), 1);
Ok(())
}
#[test]
fn alias_one() -> Result<()> {
let mut store = Store::<()>::default();
let mut linker = Linker::new(store.engine());
assert!(linker.alias("a", "b", "c", "d").is_err());
linker.func_wrap("a", "b", || {})?;
assert!(linker.alias("a", "b", "c", "d").is_ok());
assert!(linker.get(&mut store, "a", "b").is_some());
assert!(linker.get(&mut store, "c", "d").is_some());
Ok(())
}
#[test]
fn instance_pre() -> Result<()> {
let engine = Engine::default();
let mut linker = Linker::new(&engine);
linker.func_wrap("", "", || {})?;
let module = Module::new(&engine, r#"(module (import "" "" (func)))"#)?;
let instance_pre = linker.instantiate_pre(&mut Store::new(&engine, ()), &module)?;
instance_pre.instantiate(&mut Store::new(&engine, ()))?;
instance_pre.instantiate(&mut Store::new(&engine, ()))?;
let mut store = Store::new(&engine, ());
let global = Global::new(
&mut store,
GlobalType::new(ValType::I32, Mutability::Const),
1.into(),
)?;
linker.define("", "g", global)?;
let module = Module::new(
&engine,
r#"(module
(import "" "" (func))
(import "" "g" (global i32))
)"#,
)?;
let instance_pre = linker.instantiate_pre(&mut store, &module)?;
instance_pre.instantiate(&mut store)?;
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(())
}