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>
This commit is contained in:
Alex Crichton
2022-11-02 11:29:31 -05:00
committed by GitHub
parent cd53bed898
commit 2afaac5181
60 changed files with 1043 additions and 1051 deletions

View File

@@ -374,8 +374,7 @@ pub fn differential(
// falls through to checking the intermediate state otherwise.
(Err(lhs), Err(rhs)) => {
let err = rhs.downcast::<Trap>().expect("not a trap");
let poisoned = err.trap_code() == Some(TrapCode::StackOverflow)
|| lhs_engine.is_stack_overflow(&lhs);
let poisoned = err == Trap::StackOverflow || lhs_engine.is_stack_overflow(&lhs);
if poisoned {
return Ok(false);
@@ -675,14 +674,9 @@ pub fn table_ops(
.downcast::<Trap>()
.unwrap();
match trap.trap_code() {
Some(TrapCode::TableOutOfBounds) => {}
None if trap
.to_string()
.contains("all fuel consumed by WebAssembly") => {}
_ => {
panic!("unexpected trap: {}", trap);
}
match trap {
Trap::TableOutOfBounds | Trap::OutOfFuel => {}
_ => panic!("unexpected trap: {trap}"),
}
// Do a final GC after running the Wasm.

View File

@@ -5,7 +5,6 @@ use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Once;
use wasmtime::Trap;
use wasmtime::TrapCode;
pub struct V8Engine {
isolate: Rc<RefCell<v8::OwnedIsolate>>,
@@ -91,14 +90,14 @@ impl DiffEngine for V8Engine {
v8
);
};
match wasmtime.trap_code() {
Some(TrapCode::MemoryOutOfBounds) => {
match wasmtime {
Trap::MemoryOutOfBounds => {
return verify_v8(&[
"memory access out of bounds",
"data segment is out of bounds",
])
}
Some(TrapCode::UnreachableCodeReached) => {
Trap::UnreachableCodeReached => {
return verify_v8(&[
"unreachable",
// All the wasms we test use wasm-smith's
@@ -113,10 +112,10 @@ impl DiffEngine for V8Engine {
"Maximum call stack size exceeded",
]);
}
Some(TrapCode::IntegerDivisionByZero) => {
Trap::IntegerDivisionByZero => {
return verify_v8(&["divide by zero", "remainder by zero"])
}
Some(TrapCode::StackOverflow) => {
Trap::StackOverflow => {
return verify_v8(&[
"call stack size exceeded",
// Similar to the above comment in `UnreachableCodeReached`
@@ -128,15 +127,15 @@ impl DiffEngine for V8Engine {
"unreachable",
]);
}
Some(TrapCode::IndirectCallToNull) => return verify_v8(&["null function"]),
Some(TrapCode::TableOutOfBounds) => {
Trap::IndirectCallToNull => return verify_v8(&["null function"]),
Trap::TableOutOfBounds => {
return verify_v8(&[
"table initializer is out of bounds",
"table index is out of bounds",
])
}
Some(TrapCode::BadSignature) => return verify_v8(&["function signature mismatch"]),
Some(TrapCode::IntegerOverflow) | Some(TrapCode::BadConversionToInteger) => {
Trap::BadSignature => return verify_v8(&["function signature mismatch"]),
Trap::IntegerOverflow | Trap::BadConversionToInteger => {
return verify_v8(&[
"float unrepresentable in integer range",
"divide result unrepresentable",

View File

@@ -3,7 +3,7 @@
use crate::generators::{Config, DiffValue, DiffValueType};
use crate::oracles::engine::{DiffEngine, DiffInstance};
use anyhow::{Context, Error, Result};
use wasmtime::{Trap, TrapCode};
use wasmtime::Trap;
/// A wrapper for `wasmi` as a [`DiffEngine`].
pub struct WasmiEngine {
@@ -55,8 +55,8 @@ impl DiffEngine for WasmiEngine {
// Wasmtime reports as a `MemoryOutOfBounds`.
Some(wasmi::Error::Memory(msg)) => {
assert_eq!(
trap.trap_code(),
Some(TrapCode::MemoryOutOfBounds),
*trap,
Trap::MemoryOutOfBounds,
"wasmtime error did not match wasmi: {msg}"
);
return;
@@ -77,10 +77,7 @@ impl DiffEngine for WasmiEngine {
.expect(&format!("not a trap: {:?}", err)),
};
assert!(wasmi.as_code().is_some());
assert_eq!(
wasmi.as_code().map(wasmi_to_wasmtime_trap_code),
trap.trap_code(),
);
assert_eq!(wasmi_to_wasmtime_trap_code(wasmi.as_code().unwrap()), *trap);
}
fn is_stack_overflow(&self, err: &Error) -> bool {
@@ -97,18 +94,18 @@ impl DiffEngine for WasmiEngine {
}
/// Converts `wasmi` trap code to `wasmtime` trap code.
fn wasmi_to_wasmtime_trap_code(trap: wasmi::core::TrapCode) -> wasmtime::TrapCode {
use wasmi::core::TrapCode as WasmiTrapCode;
fn wasmi_to_wasmtime_trap_code(trap: wasmi::core::TrapCode) -> Trap {
use wasmi::core::TrapCode;
match trap {
WasmiTrapCode::Unreachable => TrapCode::UnreachableCodeReached,
WasmiTrapCode::MemoryAccessOutOfBounds => TrapCode::MemoryOutOfBounds,
WasmiTrapCode::TableAccessOutOfBounds => TrapCode::TableOutOfBounds,
WasmiTrapCode::ElemUninitialized => TrapCode::IndirectCallToNull,
WasmiTrapCode::DivisionByZero => TrapCode::IntegerDivisionByZero,
WasmiTrapCode::IntegerOverflow => TrapCode::IntegerOverflow,
WasmiTrapCode::InvalidConversionToInt => TrapCode::BadConversionToInteger,
WasmiTrapCode::StackOverflow => TrapCode::StackOverflow,
WasmiTrapCode::UnexpectedSignature => TrapCode::BadSignature,
TrapCode::Unreachable => Trap::UnreachableCodeReached,
TrapCode::MemoryAccessOutOfBounds => Trap::MemoryOutOfBounds,
TrapCode::TableAccessOutOfBounds => Trap::TableOutOfBounds,
TrapCode::ElemUninitialized => Trap::IndirectCallToNull,
TrapCode::DivisionByZero => Trap::IntegerDivisionByZero,
TrapCode::IntegerOverflow => Trap::IntegerOverflow,
TrapCode::InvalidConversionToInt => Trap::BadConversionToInteger,
TrapCode::StackOverflow => Trap::StackOverflow,
TrapCode::UnexpectedSignature => Trap::BadSignature,
}
}

View File

@@ -6,7 +6,7 @@ use crate::oracles::engine::DiffInstance;
use crate::oracles::{compile_module, engine::DiffEngine, StoreLimits};
use anyhow::{Context, Error, Result};
use arbitrary::Unstructured;
use wasmtime::{Extern, FuncType, Instance, Module, Store, Trap, TrapCode, Val};
use wasmtime::{Extern, FuncType, Instance, Module, Store, Trap, Val};
/// A wrapper for using Wasmtime as a [`DiffEngine`].
pub struct WasmtimeEngine {
@@ -45,18 +45,12 @@ impl DiffEngine for WasmtimeEngine {
let trap2 = err
.downcast_ref::<Trap>()
.expect(&format!("not a trap: {:?}", err));
assert_eq!(
trap.trap_code(),
trap2.trap_code(),
"{}\nis not equal to\n{}",
trap,
trap2
);
assert_eq!(trap, trap2, "{}\nis not equal to\n{}", trap, trap2);
}
fn is_stack_overflow(&self, err: &Error) -> bool {
match err.downcast_ref::<Trap>() {
Some(trap) => trap.trap_code() == Some(TrapCode::StackOverflow),
Some(trap) => *trap == Trap::StackOverflow,
None => false,
}
}

View File

@@ -1,4 +1,5 @@
use crate::generators::Stacks;
use anyhow::{bail, Result};
use wasmtime::*;
/// Run the given `Stacks` test case and assert that the host's view of the Wasm
@@ -17,7 +18,7 @@ pub fn check_stacks(stacks: Stacks) -> usize {
.func_wrap(
"host",
"check_stack",
|mut caller: Caller<'_, ()>| -> Result<(), Trap> {
|mut caller: Caller<'_, ()>| -> Result<()> {
let fuel = caller
.get_export("fuel")
.expect("should export `fuel`")
@@ -26,7 +27,7 @@ pub fn check_stacks(stacks: Stacks) -> usize {
let fuel_left = fuel.get(&mut caller).unwrap_i32();
if fuel_left == 0 {
return Err(Trap::new("out of fuel"));
bail!(Trap::OutOfFuel);
}
fuel.set(&mut caller, Val::I32(fuel_left - 1)).unwrap();
@@ -59,7 +60,7 @@ pub fn check_stacks(stacks: Stacks) -> usize {
for input in stacks.inputs().iter().copied() {
log::debug!("input: {}", input);
if let Err(trap) = run.call(&mut store, (input.into(),)) {
log::debug!("trap: {}", trap);
log::debug!("trap: {:?}", trap);
let get_stack = instance
.get_typed_func::<(), (u32, u32), _>(&mut store, "get_stack")
.expect("should export `get_stack` function as expected");
@@ -72,9 +73,10 @@ pub fn check_stacks(stacks: Stacks) -> usize {
.get_memory(&mut store, "memory")
.expect("should have `memory` export");
let host_trace = trap.trace().unwrap();
let host_trace = trap.downcast_ref::<WasmBacktrace>().unwrap().frames();
let trap = trap.downcast_ref::<Trap>().unwrap();
max_stack_depth = max_stack_depth.max(host_trace.len());
assert_stack_matches(&mut store, memory, ptr, len, host_trace, trap.trap_code());
assert_stack_matches(&mut store, memory, ptr, len, host_trace, *trap);
}
}
max_stack_depth
@@ -87,7 +89,7 @@ fn assert_stack_matches(
ptr: u32,
len: u32,
host_trace: &[FrameInfo],
trap_code: Option<TrapCode>,
trap: Trap,
) {
let mut data = vec![0; len as usize];
memory
@@ -108,7 +110,7 @@ fn assert_stack_matches(
// be able to see the exact function that triggered the stack overflow. In
// this situation the host trace is asserted to be one larger and then the
// top frame (first) of the host trace is discarded.
let host_trace = if trap_code == Some(TrapCode::StackOverflow) {
let host_trace = if trap == Trap::StackOverflow {
assert_eq!(host_trace.len(), wasm_trace.len() + 1);
&host_trace[1..]
} else {