* 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>
176 lines
5.2 KiB
Rust
176 lines
5.2 KiB
Rust
use wasmtime::{Engine, Linker, Module, Store, Val};
|
|
|
|
wiggle::from_witx!({
|
|
witx: ["$CARGO_MANIFEST_DIR/tests/atoms.witx"],
|
|
block_on: {
|
|
atoms::double_int_return_float
|
|
}
|
|
});
|
|
|
|
pub struct Ctx;
|
|
impl wiggle::GuestErrorType for types::Errno {
|
|
fn success() -> Self {
|
|
types::Errno::Ok
|
|
}
|
|
}
|
|
|
|
const TRIGGER_PENDING: u32 = 0;
|
|
|
|
#[wiggle::async_trait]
|
|
impl atoms::Atoms for Ctx {
|
|
fn int_float_args(&mut self, an_int: u32, an_float: f32) -> Result<(), types::Errno> {
|
|
println!("INT FLOAT ARGS: {} {}", an_int, an_float);
|
|
Ok(())
|
|
}
|
|
async fn double_int_return_float(
|
|
&mut self,
|
|
an_int: u32,
|
|
) -> Result<types::AliasToFloat, types::Errno> {
|
|
if an_int == TRIGGER_PENDING {
|
|
// Define a Future that is pending forever. This is `futures::future::pending()`
|
|
// without incurring the dep.
|
|
use std::future::Future;
|
|
use std::pin::Pin;
|
|
use std::task::{Context, Poll};
|
|
struct Pending;
|
|
impl Future for Pending {
|
|
type Output = ();
|
|
fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
|
|
Poll::Pending
|
|
}
|
|
}
|
|
// This await will pend, which should cause the dummy executor to Trap.
|
|
Pending.await;
|
|
}
|
|
Ok((an_int as f32) * 2.0)
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_sync_host_func() {
|
|
let engine = Engine::default();
|
|
let mut linker = Linker::new(&engine);
|
|
atoms::add_to_linker(&mut linker, |cx| cx).unwrap();
|
|
let mut store = store(&engine);
|
|
let shim_mod = shim_module(&engine);
|
|
let shim_inst = linker.instantiate(&mut store, &shim_mod).unwrap();
|
|
|
|
let mut results = [Val::I32(0)];
|
|
shim_inst
|
|
.get_func(&mut store, "int_float_args_shim")
|
|
.unwrap()
|
|
.call(&mut store, &[0i32.into(), 123.45f32.into()], &mut results)
|
|
.unwrap();
|
|
|
|
assert_eq!(
|
|
results[0].unwrap_i32(),
|
|
types::Errno::Ok as i32,
|
|
"int_float_args errno"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn test_async_host_func() {
|
|
let engine = Engine::default();
|
|
let mut linker = Linker::new(&engine);
|
|
atoms::add_to_linker(&mut linker, |cx| cx).unwrap();
|
|
let mut store = store(&engine);
|
|
|
|
let shim_mod = shim_module(&engine);
|
|
let shim_inst = linker.instantiate(&mut store, &shim_mod).unwrap();
|
|
|
|
let input: i32 = 123;
|
|
let result_location: i32 = 0;
|
|
|
|
let mut results = [Val::I32(0)];
|
|
shim_inst
|
|
.get_func(&mut store, "double_int_return_float_shim")
|
|
.unwrap()
|
|
.call(
|
|
&mut store,
|
|
&[input.into(), result_location.into()],
|
|
&mut results,
|
|
)
|
|
.unwrap();
|
|
|
|
assert_eq!(
|
|
results[0].unwrap_i32(),
|
|
types::Errno::Ok as i32,
|
|
"double_int_return_float errno"
|
|
);
|
|
|
|
// The actual result is in memory:
|
|
let mem = shim_inst.get_memory(&mut store, "memory").unwrap();
|
|
let mut result_bytes: [u8; 4] = [0, 0, 0, 0];
|
|
mem.read(&store, result_location as usize, &mut result_bytes)
|
|
.unwrap();
|
|
let result = f32::from_le_bytes(result_bytes);
|
|
assert_eq!((input * 2) as f32, result);
|
|
}
|
|
|
|
#[test]
|
|
fn test_async_host_func_pending() {
|
|
let engine = Engine::default();
|
|
let mut linker = Linker::new(&engine);
|
|
atoms::add_to_linker(&mut linker, |cx| cx).unwrap();
|
|
let mut store = store(&engine);
|
|
|
|
let shim_mod = shim_module(&engine);
|
|
let shim_inst = linker.instantiate(&mut store, &shim_mod).unwrap();
|
|
|
|
let result_location: i32 = 0;
|
|
|
|
// This input triggers the host func pending forever
|
|
let input: i32 = TRIGGER_PENDING as i32;
|
|
let trap = shim_inst
|
|
.get_func(&mut store, "double_int_return_float_shim")
|
|
.unwrap()
|
|
.call(
|
|
&mut store,
|
|
&[input.into(), result_location.into()],
|
|
&mut [Val::I32(0)],
|
|
)
|
|
.unwrap_err();
|
|
assert!(
|
|
format!("{:?}", trap).contains("Cannot wait on pending future"),
|
|
"expected get a pending future Trap from dummy executor, got: {}",
|
|
trap
|
|
);
|
|
}
|
|
|
|
fn store(engine: &Engine) -> Store<Ctx> {
|
|
Store::new(engine, Ctx)
|
|
}
|
|
|
|
// Wiggle expects the caller to have an exported memory. Wasmtime can only
|
|
// provide this if the caller is a WebAssembly module, so we need to write
|
|
// a shim module:
|
|
fn shim_module(engine: &Engine) -> Module {
|
|
Module::new(
|
|
engine,
|
|
r#"
|
|
(module
|
|
(import "atoms" "int_float_args" (func $int_float_args (param i32 f32) (result i32)))
|
|
(import "atoms" "double_int_return_float" (func $double_int_return_float (param i32 i32) (result i32)))
|
|
|
|
(memory 1)
|
|
(export "memory" (memory 0))
|
|
|
|
(func $int_float_args_shim (param i32 f32) (result i32)
|
|
local.get 0
|
|
local.get 1
|
|
call $int_float_args
|
|
)
|
|
(func $double_int_return_float_shim (param i32 i32) (result i32)
|
|
local.get 0
|
|
local.get 1
|
|
call $double_int_return_float
|
|
)
|
|
(export "int_float_args_shim" (func $int_float_args_shim))
|
|
(export "double_int_return_float_shim" (func $double_int_return_float_shim))
|
|
)
|
|
"#,
|
|
)
|
|
.unwrap()
|
|
}
|