* 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>
169 lines
6.0 KiB
Rust
169 lines
6.0 KiB
Rust
/// Execute the wiggle guest conversion code to exercise it
|
|
mod convert_just_errno {
|
|
use anyhow::Result;
|
|
use wiggle_test::{impl_errno, HostMemory, WasiCtx};
|
|
|
|
/// The `errors` argument to the wiggle gives us a hook to map a rich error
|
|
/// type like this one (typical of wiggle use cases in wasi-common and beyond)
|
|
/// down to the flat error enums that witx can specify.
|
|
#[derive(Debug, thiserror::Error)]
|
|
pub enum RichError {
|
|
#[error("Invalid argument: {0}")]
|
|
InvalidArg(String),
|
|
#[error("Won't cross picket line: {0}")]
|
|
PicketLine(String),
|
|
}
|
|
|
|
// Define an errno with variants corresponding to RichError. Use it in a
|
|
// trivial function.
|
|
wiggle::from_witx!({
|
|
witx_literal: "
|
|
(typename $errno (enum (@witx tag u8) $ok $invalid_arg $picket_line))
|
|
(module $one_error_conversion
|
|
(@interface func (export \"foo\")
|
|
(param $strike u32)
|
|
(result $err (expected (error $errno)))))
|
|
",
|
|
errors: { errno => RichError },
|
|
});
|
|
|
|
impl_errno!(types::Errno);
|
|
|
|
/// When the `errors` mapping in witx is non-empty, we need to impl the
|
|
/// types::UserErrorConversion trait that wiggle generates from that mapping.
|
|
impl<'a> types::UserErrorConversion for WasiCtx<'a> {
|
|
fn errno_from_rich_error(&mut self, e: RichError) -> Result<types::Errno> {
|
|
// WasiCtx can collect a Vec<String> log so we can test this. We're
|
|
// logging the Display impl that `thiserror::Error` provides us.
|
|
self.log.borrow_mut().push(e.to_string());
|
|
// Then do the trivial mapping down to the flat enum.
|
|
match e {
|
|
RichError::InvalidArg { .. } => Ok(types::Errno::InvalidArg),
|
|
RichError::PicketLine { .. } => Ok(types::Errno::PicketLine),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<'a> one_error_conversion::OneErrorConversion for WasiCtx<'a> {
|
|
fn foo(&mut self, strike: u32) -> Result<(), RichError> {
|
|
// We use the argument to this function to exercise all of the
|
|
// possible error cases we could hit here
|
|
match strike {
|
|
0 => Ok(()),
|
|
1 => Err(RichError::PicketLine(format!("I'm not a scab"))),
|
|
_ => Err(RichError::InvalidArg(format!("out-of-bounds: {}", strike))),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn one_error_conversion_test() {
|
|
let mut ctx = WasiCtx::new();
|
|
let host_memory = HostMemory::new();
|
|
|
|
// Exercise each of the branches in `foo`.
|
|
// Start with the success case:
|
|
let r0 = one_error_conversion::foo(&mut ctx, &host_memory, 0).unwrap();
|
|
assert_eq!(
|
|
r0,
|
|
types::Errno::Ok as i32,
|
|
"Expected return value for strike=0"
|
|
);
|
|
assert!(ctx.log.borrow().is_empty(), "No error log for strike=0");
|
|
|
|
// First error case:
|
|
let r1 = one_error_conversion::foo(&mut ctx, &host_memory, 1).unwrap();
|
|
assert_eq!(
|
|
r1,
|
|
types::Errno::PicketLine as i32,
|
|
"Expected return value for strike=1"
|
|
);
|
|
assert_eq!(
|
|
ctx.log.borrow_mut().pop().expect("one log entry"),
|
|
"Won't cross picket line: I'm not a scab",
|
|
"Expected log entry for strike=1",
|
|
);
|
|
|
|
// Second error case:
|
|
let r2 = one_error_conversion::foo(&mut ctx, &host_memory, 2).unwrap();
|
|
assert_eq!(
|
|
r2,
|
|
types::Errno::InvalidArg as i32,
|
|
"Expected return value for strike=2"
|
|
);
|
|
assert_eq!(
|
|
ctx.log.borrow_mut().pop().expect("one log entry"),
|
|
"Invalid argument: out-of-bounds: 2",
|
|
"Expected log entry for strike=2",
|
|
);
|
|
}
|
|
}
|
|
|
|
/// Type-check the wiggle guest conversion code against a more complex case where
|
|
/// we use two distinct error types.
|
|
mod convert_multiple_error_types {
|
|
pub use super::convert_just_errno::RichError;
|
|
use anyhow::Result;
|
|
use wiggle_test::{impl_errno, WasiCtx};
|
|
|
|
/// Test that we can map multiple types of errors.
|
|
#[derive(Debug, thiserror::Error)]
|
|
#[allow(dead_code)]
|
|
pub enum AnotherRichError {
|
|
#[error("I've had this many cups of coffee and can't even think straight: {0}")]
|
|
TooMuchCoffee(usize),
|
|
}
|
|
|
|
// Just like the prior test, except that we have a second errno type. This should mean there
|
|
// are two functions in UserErrorConversion.
|
|
// Additionally, test that the function "baz" marked noreturn always returns a wasmtime::Trap.
|
|
wiggle::from_witx!({
|
|
witx_literal: "
|
|
(typename $errno (enum (@witx tag u8) $ok $invalid_arg $picket_line))
|
|
(typename $errno2 (enum (@witx tag u8) $ok $too_much_coffee))
|
|
(module $two_error_conversions
|
|
(@interface func (export \"foo\")
|
|
(param $strike u32)
|
|
(result $err (expected (error $errno))))
|
|
(@interface func (export \"bar\")
|
|
(param $drink u32)
|
|
(result $err (expected (error $errno2))))
|
|
(@interface func (export \"baz\")
|
|
(param $drink u32)
|
|
(@witx noreturn)))
|
|
",
|
|
errors: { errno => RichError, errno2 => AnotherRichError },
|
|
});
|
|
|
|
impl_errno!(types::Errno);
|
|
impl_errno!(types::Errno2);
|
|
|
|
// The UserErrorConversion trait will also have two methods for this test. They correspond to
|
|
// each member of the `errors` mapping.
|
|
// Bodies elided.
|
|
impl<'a> types::UserErrorConversion for WasiCtx<'a> {
|
|
fn errno_from_rich_error(&mut self, _e: RichError) -> Result<types::Errno> {
|
|
unimplemented!()
|
|
}
|
|
fn errno2_from_another_rich_error(
|
|
&mut self,
|
|
_e: AnotherRichError,
|
|
) -> Result<types::Errno2> {
|
|
unimplemented!()
|
|
}
|
|
}
|
|
|
|
// And here's the witx module trait impl, bodies elided
|
|
impl<'a> two_error_conversions::TwoErrorConversions for WasiCtx<'a> {
|
|
fn foo(&mut self, _: u32) -> Result<(), RichError> {
|
|
unimplemented!()
|
|
}
|
|
fn bar(&mut self, _: u32) -> Result<(), AnotherRichError> {
|
|
unimplemented!()
|
|
}
|
|
fn baz(&mut self, _: u32) -> anyhow::Error {
|
|
unimplemented!()
|
|
}
|
|
}
|
|
}
|