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

@@ -1,4 +1,4 @@
use anyhow::Result;
use anyhow::{anyhow, bail, Result};
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
@@ -440,7 +440,7 @@ async fn resume_separate_thread() {
let func = Func::wrap0_async(&mut store, |_| {
Box::new(async {
tokio::task::yield_now().await;
Err::<(), _>(wasmtime::Trap::new("test"))
Err::<(), _>(anyhow!("test"))
})
});
let result = Instance::new_async(&mut store, &module, &[func.into()]).await;
@@ -493,7 +493,7 @@ async fn resume_separate_thread3() {
// situation we'll set up the TLS info so it's in place while the body of
// the function executes...
let mut store = Store::new(&Engine::default(), None);
let f = Func::wrap(&mut store, move |mut caller: Caller<'_, _>| {
let f = Func::wrap(&mut store, move |mut caller: Caller<'_, _>| -> Result<()> {
// ... and the execution of this host-defined function (while the TLS
// info is initialized), will set up a recursive call into wasm. This
// recursive call will be done asynchronously so we can suspend it
@@ -536,7 +536,7 @@ async fn resume_separate_thread3() {
// ... all in all this function will need access to the original TLS
// information to raise the trap. This TLS information should be
// restored even though the asynchronous execution is suspended.
Err::<(), _>(wasmtime::Trap::new(""))
bail!("")
});
assert!(f.call(&mut store, &[], &mut []).is_err());
}
@@ -561,8 +561,12 @@ async fn recursive_async() -> Result<()> {
// ... but calls that actually stack overflow should indeed stack
// overflow
let err = overflow.call_async(&mut caller, ()).await.unwrap_err();
assert_eq!(err.trap_code(), Some(TrapCode::StackOverflow));
let err = overflow
.call_async(&mut caller, ())
.await
.unwrap_err()
.downcast::<Trap>()?;
assert_eq!(err, Trap::StackOverflow);
Ok(())
})
});

View File

@@ -1,4 +1,4 @@
use anyhow::Error;
use anyhow::{bail, Error, Result};
use std::future::Future;
use std::pin::Pin;
use std::task::{self, Poll};
@@ -424,12 +424,12 @@ fn trapping() -> Result<(), Error> {
linker.func_wrap(
"host",
"f",
|mut caller: Caller<State>, action: i32, recur: i32| -> Result<(), Trap> {
|mut caller: Caller<State>, action: i32, recur: i32| -> Result<()> {
assert_eq!(caller.data().context.last(), Some(&Context::Host));
assert_eq!(caller.data().calls_into_host, caller.data().calls_into_wasm);
match action {
TRAP_IN_F => return Err(Trap::new("trapping in f")),
TRAP_IN_F => bail!("trapping in f"),
TRAP_NEXT_CALL_HOST => caller.data_mut().trap_next_call_host = true,
TRAP_NEXT_RETURN_HOST => caller.data_mut().trap_next_return_host = true,
TRAP_NEXT_CALL_WASM => caller.data_mut().trap_next_call_wasm = true,
@@ -485,7 +485,7 @@ fn trapping() -> Result<(), Error> {
};
let (s, e) = run(TRAP_IN_F, false);
assert!(e.unwrap().to_string().starts_with("trapping in f"));
assert!(format!("{:?}", e.unwrap()).contains("trapping in f"));
assert_eq!(s.calls_into_host, 1);
assert_eq!(s.returns_from_host, 1);
assert_eq!(s.calls_into_wasm, 1);
@@ -501,10 +501,7 @@ fn trapping() -> Result<(), Error> {
// trap in next call to host. recur, so the second call into host traps:
let (s, e) = run(TRAP_NEXT_CALL_HOST, true);
assert!(e
.unwrap()
.to_string()
.starts_with("call_hook: trapping on CallingHost"));
assert!(format!("{:?}", e.unwrap()).contains("call_hook: trapping on CallingHost"));
assert_eq!(s.calls_into_host, 2);
assert_eq!(s.returns_from_host, 1);
assert_eq!(s.calls_into_wasm, 2);
@@ -512,10 +509,7 @@ fn trapping() -> Result<(), Error> {
// trap in the return from host. should trap right away, without recursion
let (s, e) = run(TRAP_NEXT_RETURN_HOST, false);
assert!(e
.unwrap()
.to_string()
.starts_with("call_hook: trapping on ReturningFromHost"));
assert!(format!("{:?}", e.unwrap()).contains("call_hook: trapping on ReturningFromHost"));
assert_eq!(s.calls_into_host, 1);
assert_eq!(s.returns_from_host, 1);
assert_eq!(s.calls_into_wasm, 1);
@@ -531,10 +525,7 @@ fn trapping() -> Result<(), Error> {
// trap in next call to wasm. recur, so the second call into wasm traps:
let (s, e) = run(TRAP_NEXT_CALL_WASM, true);
assert!(e
.unwrap()
.to_string()
.starts_with("call_hook: trapping on CallingWasm"));
assert!(format!("{:?}", e.unwrap()).contains("call_hook: trapping on CallingWasm"));
assert_eq!(s.calls_into_host, 1);
assert_eq!(s.returns_from_host, 1);
assert_eq!(s.calls_into_wasm, 2);
@@ -542,10 +533,7 @@ fn trapping() -> Result<(), Error> {
// trap in the return from wasm. should trap right away, without recursion
let (s, e) = run(TRAP_NEXT_RETURN_WASM, false);
assert!(e
.unwrap()
.to_string()
.starts_with("call_hook: trapping on ReturningFromWasm"));
assert!(format!("{:?}", e.unwrap()).contains("call_hook: trapping on ReturningFromWasm"));
assert_eq!(s.calls_into_host, 1);
assert_eq!(s.returns_from_host, 1);
assert_eq!(s.calls_into_wasm, 1);
@@ -560,11 +548,7 @@ async fn basic_async_hook() -> Result<(), Error> {
#[async_trait::async_trait]
impl CallHookHandler<State> for HandlerR {
async fn handle_call_event(
&self,
obj: &mut State,
ch: CallHook,
) -> Result<(), wasmtime::Trap> {
async fn handle_call_event(&self, obj: &mut State, ch: CallHook) -> Result<()> {
State::call_hook(obj, ch)
}
}
@@ -638,13 +622,9 @@ async fn timeout_async_hook() -> Result<(), Error> {
#[async_trait::async_trait]
impl CallHookHandler<State> for HandlerR {
async fn handle_call_event(
&self,
obj: &mut State,
ch: CallHook,
) -> Result<(), wasmtime::Trap> {
async fn handle_call_event(&self, obj: &mut State, ch: CallHook) -> Result<()> {
if obj.calls_into_host > 200 {
return Err(wasmtime::Trap::new("timeout"));
bail!("timeout");
}
match ch {
@@ -718,11 +698,7 @@ async fn drop_suspended_async_hook() -> Result<(), Error> {
#[async_trait::async_trait]
impl CallHookHandler<u32> for Handler {
async fn handle_call_event(
&self,
state: &mut u32,
_ch: CallHook,
) -> Result<(), wasmtime::Trap> {
async fn handle_call_event(&self, state: &mut u32, _ch: CallHook) -> Result<()> {
assert_eq!(*state, 0);
*state += 1;
let _dec = Decrement(state);
@@ -861,12 +837,12 @@ impl Default for State {
impl State {
// This implementation asserts that hooks are always called in a stack-like manner.
fn call_hook(&mut self, s: CallHook) -> Result<(), Trap> {
fn call_hook(&mut self, s: CallHook) -> Result<()> {
match s {
CallHook::CallingHost => {
self.calls_into_host += 1;
if self.trap_next_call_host {
return Err(Trap::new("call_hook: trapping on CallingHost"));
bail!("call_hook: trapping on CallingHost");
} else {
self.context.push(Context::Host);
}
@@ -875,7 +851,7 @@ impl State {
Some(Context::Host) => {
self.returns_from_host += 1;
if self.trap_next_return_host {
return Err(Trap::new("call_hook: trapping on ReturningFromHost"));
bail!("call_hook: trapping on ReturningFromHost");
}
}
c => panic!(
@@ -886,7 +862,7 @@ impl State {
CallHook::CallingWasm => {
self.calls_into_wasm += 1;
if self.trap_next_call_wasm {
return Err(Trap::new("call_hook: trapping on CallingWasm"));
bail!("call_hook: trapping on CallingWasm");
} else {
self.context.push(Context::Wasm);
}
@@ -895,7 +871,7 @@ impl State {
Some(Context::Wasm) => {
self.returns_from_wasm += 1;
if self.trap_next_return_wasm {
return Err(Trap::new("call_hook: trapping on ReturningFromWasm"));
bail!("call_hook: trapping on ReturningFromWasm");
}
}
c => panic!(

View File

@@ -252,11 +252,7 @@ fn exit125_wasi_snapshot1() -> Result<()> {
fn exit126_wasi_snapshot0() -> Result<()> {
let wasm = build_wasm("tests/all/cli_tests/exit126_wasi_snapshot0.wat")?;
let output = run_wasmtime_for_output(&[wasm.path().to_str().unwrap(), "--disable-cache"])?;
if cfg!(windows) {
assert_eq!(output.status.code().unwrap(), 3);
} else {
assert_eq!(output.status.code().unwrap(), 128 + libc::SIGABRT);
}
assert_eq!(output.status.code().unwrap(), 1);
assert!(output.stdout.is_empty());
assert!(String::from_utf8_lossy(&output.stderr).contains("invalid exit status"));
Ok(())
@@ -267,11 +263,7 @@ fn exit126_wasi_snapshot0() -> Result<()> {
fn exit126_wasi_snapshot1() -> Result<()> {
let wasm = build_wasm("tests/all/cli_tests/exit126_wasi_snapshot1.wat")?;
let output = run_wasmtime_for_output(&[wasm.path().to_str().unwrap(), "--disable-cache"])?;
if cfg!(windows) {
assert_eq!(output.status.code().unwrap(), 3);
} else {
assert_eq!(output.status.code().unwrap(), 128 + libc::SIGABRT);
}
assert_eq!(output.status.code().unwrap(), 1);
assert!(output.stdout.is_empty());
assert!(String::from_utf8_lossy(&output.stderr).contains("invalid exit status"));
Ok(())

View File

@@ -1,6 +1,6 @@
use anyhow::Result;
use wasmtime::component::*;
use wasmtime::{Store, StoreContextMut, Trap, TrapCode};
use wasmtime::{Store, StoreContextMut, Trap};
/// This is super::func::thunks, except with an async store.
#[tokio::test]
@@ -38,7 +38,7 @@ async fn smoke() -> Result<()> {
.call_async(&mut store, ())
.await
.unwrap_err();
assert!(err.downcast::<Trap>()?.trap_code() == Some(TrapCode::UnreachableCodeReached));
assert_eq!(err.downcast::<Trap>()?, Trap::UnreachableCodeReached);
Ok(())
}

View File

@@ -3,7 +3,7 @@ use anyhow::Result;
use std::rc::Rc;
use std::sync::Arc;
use wasmtime::component::*;
use wasmtime::{Store, StoreContextMut, Trap, TrapCode};
use wasmtime::{Store, StoreContextMut, Trap};
const CANON_32BIT_NAN: u32 = 0b01111111110000000000000000000000;
const CANON_64BIT_NAN: u64 = 0b0111111111111000000000000000000000000000000000000000000000000000;
@@ -37,7 +37,7 @@ fn thunks() -> Result<()> {
.get_typed_func::<(), (), _>(&mut store, "thunk-trap")?
.call(&mut store, ())
.unwrap_err();
assert!(err.downcast::<Trap>()?.trap_code() == Some(TrapCode::UnreachableCodeReached));
assert_eq!(err.downcast::<Trap>()?, Trap::UnreachableCodeReached);
Ok(())
}
@@ -1099,7 +1099,7 @@ fn some_traps() -> Result<()> {
.call(&mut store, (&[],))
.unwrap_err()
.downcast::<Trap>()?;
assert_eq!(err.trap_code(), Some(TrapCode::UnreachableCodeReached));
assert_eq!(err, Trap::UnreachableCodeReached);
// This should fail when calling the allocator function for the argument
let err = instance(&mut store)?
@@ -1107,7 +1107,7 @@ fn some_traps() -> Result<()> {
.call(&mut store, ("",))
.unwrap_err()
.downcast::<Trap>()?;
assert_eq!(err.trap_code(), Some(TrapCode::UnreachableCodeReached));
assert_eq!(err, Trap::UnreachableCodeReached);
// This should fail when calling the allocator function for the space
// to store the arguments (before arguments are even lowered)
@@ -1119,7 +1119,7 @@ fn some_traps() -> Result<()> {
.call(&mut store, ("", "", "", "", "", "", "", "", "", ""))
.unwrap_err()
.downcast::<Trap>()?;
assert_eq!(err.trap_code(), Some(TrapCode::UnreachableCodeReached));
assert_eq!(err, Trap::UnreachableCodeReached);
// Assert that when the base pointer returned by malloc is out of bounds
// that errors are reported as such. Both empty and lists with contents
@@ -2375,8 +2375,8 @@ fn errors_that_poison_instance() -> Result<()> {
Err(e) => e,
};
assert_eq!(
err.downcast::<Trap>().unwrap().trap_code(),
Some(TrapCode::UnreachableCodeReached)
err.downcast::<Trap>().unwrap(),
Trap::UnreachableCodeReached
);
}

View File

@@ -2,7 +2,7 @@ use super::REALLOC_AND_FREE;
use anyhow::Result;
use std::ops::Deref;
use wasmtime::component::*;
use wasmtime::{Store, StoreContextMut, Trap};
use wasmtime::{Store, StoreContextMut, WasmBacktrace};
#[test]
fn can_compile() -> Result<()> {
@@ -256,15 +256,13 @@ fn attempt_to_leave_during_malloc() -> Result<()> {
.instantiate(&mut store, &component)?
.get_typed_func::<(), (), _>(&mut store, "run")?
.call(&mut store, ())
.unwrap_err()
.downcast::<Trap>()?;
.unwrap_err();
assert!(
trap.to_string().contains("cannot leave component instance"),
"bad trap: {}",
trap,
format!("{trap:?}").contains("cannot leave component instance"),
"bad trap: {trap:?}",
);
let trace = trap.trace().unwrap();
let trace = trap.downcast_ref::<WasmBacktrace>().unwrap().frames();
assert_eq!(trace.len(), 4);
// This was our entry point...
@@ -294,12 +292,10 @@ fn attempt_to_leave_during_malloc() -> Result<()> {
.instantiate(&mut store, &component)?
.get_typed_func::<(&str,), (), _>(&mut store, "take-string")?
.call(&mut store, ("x",))
.unwrap_err()
.downcast::<Trap>()?;
.unwrap_err();
assert!(
trap.to_string().contains("cannot leave component instance"),
"bad trap: {}",
trap,
format!("{trap:?}").contains("cannot leave component instance"),
"bad trap: {trap:?}",
);
Ok(())
}
@@ -344,10 +340,8 @@ fn attempt_to_reenter_during_host() -> Result<()> {
let func = store.data_mut().func.take().unwrap();
let trap = func.call(&mut store, ()).unwrap_err();
assert!(
trap.to_string()
.contains("cannot reenter component instance"),
"bad trap: {}",
trap,
format!("{trap:?}").contains("cannot reenter component instance"),
"bad trap: {trap:?}",
);
Ok(())
},
@@ -372,10 +366,8 @@ fn attempt_to_reenter_during_host() -> Result<()> {
let func = store.data_mut().func.take().unwrap();
let trap = func.call(&mut store, &[], &mut []).unwrap_err();
assert!(
trap.to_string()
.contains("cannot reenter component instance"),
"bad trap: {}",
trap,
format!("{trap:?}").contains("cannot reenter component instance"),
"bad trap: {trap:?}",
);
Ok(())
},
@@ -733,16 +725,22 @@ fn bad_import_alignment() -> Result<()> {
.instantiate(&mut store, &component)?
.get_typed_func::<(), (), _>(&mut store, "unaligned-retptr")?
.call(&mut store, ())
.unwrap_err()
.downcast::<Trap>()?;
assert!(trap.to_string().contains("pointer not aligned"), "{}", trap);
.unwrap_err();
assert!(
format!("{:?}", trap).contains("pointer not aligned"),
"{}",
trap
);
let trap = linker
.instantiate(&mut store, &component)?
.get_typed_func::<(), (), _>(&mut store, "unaligned-argptr")?
.call(&mut store, ())
.unwrap_err()
.downcast::<Trap>()?;
assert!(trap.to_string().contains("pointer not aligned"), "{}", trap);
.unwrap_err();
assert!(
format!("{:?}", trap).contains("pointer not aligned"),
"{}",
trap
);
Ok(())
}

View File

@@ -1,6 +1,6 @@
use anyhow::Result;
use wasmtime::component::*;
use wasmtime::{Store, StoreContextMut, Trap, TrapCode};
use wasmtime::{Store, StoreContextMut, Trap};
#[test]
fn invalid_api() -> Result<()> {
@@ -284,7 +284,7 @@ fn trap_in_post_return_poisons_instance() -> Result<()> {
let f = instance.get_typed_func::<(), (), _>(&mut store, "f")?;
f.call(&mut store, ())?;
let trap = f.post_return(&mut store).unwrap_err().downcast::<Trap>()?;
assert_eq!(trap.trap_code(), Some(TrapCode::UnreachableCodeReached));
assert_eq!(trap, Trap::UnreachableCodeReached);
let err = f.call(&mut store, ()).unwrap_err();
assert!(
err.to_string()

View File

@@ -1,7 +1,7 @@
use super::REALLOC_AND_FREE;
use anyhow::Result;
use wasmtime::component::{Component, Linker};
use wasmtime::{Engine, Store, StoreContextMut, Trap, TrapCode};
use wasmtime::{Engine, Store, StoreContextMut, Trap};
const UTF16_TAG: u32 = 1 << 31;
@@ -248,7 +248,7 @@ fn test_ptr_out_of_bounds(engine: &Engine, src: &str, dst: &str) -> Result<()> {
.err()
.unwrap()
.downcast::<Trap>()?;
assert_eq!(trap.trap_code(), Some(TrapCode::UnreachableCodeReached));
assert_eq!(trap, Trap::UnreachableCodeReached);
Ok(())
};
@@ -322,7 +322,7 @@ fn test_ptr_overflow(engine: &Engine, src: &str, dst: &str) -> Result<()> {
.call(&mut store, (size,))
.unwrap_err()
.downcast::<Trap>()?;
assert_eq!(trap.trap_code(), Some(TrapCode::UnreachableCodeReached));
assert_eq!(trap, Trap::UnreachableCodeReached);
Ok(())
};
@@ -422,7 +422,7 @@ fn test_realloc_oob(engine: &Engine, src: &str, dst: &str) -> Result<()> {
let instance = Linker::new(engine).instantiate(&mut store, &component)?;
let func = instance.get_typed_func::<(), (), _>(&mut store, "f")?;
let trap = func.call(&mut store, ()).unwrap_err().downcast::<Trap>()?;
assert_eq!(trap.trap_code(), Some(TrapCode::UnreachableCodeReached));
assert_eq!(trap, Trap::UnreachableCodeReached);
Ok(())
}
@@ -498,9 +498,8 @@ fn test_invalid_string_encoding(
let trap = test_raw_when_encoded(engine, src, dst, bytes, len)?.unwrap();
let src = src.replace("latin1+", "");
assert!(
trap.to_string()
.contains(&format!("invalid {src} encoding")),
"bad error: {}",
format!("{:?}", trap).contains(&format!("invalid {src} encoding")),
"bad error: {:?}",
trap,
);
Ok(())
@@ -524,7 +523,7 @@ fn test_raw_when_encoded(
dst: &str,
bytes: &[u8],
len: u32,
) -> Result<Option<Trap>> {
) -> Result<Option<anyhow::Error>> {
let component = format!(
r#"
(component
@@ -574,6 +573,6 @@ fn test_raw_when_encoded(
let func = instance.get_typed_func::<(&[u8], u32), (), _>(&mut store, "f")?;
match func.call(&mut store, (bytes, len)) {
Ok(_) => Ok(None),
Err(e) => Ok(Some(e.downcast()?)),
Err(e) => Ok(Some(e)),
}
}

View File

@@ -170,12 +170,7 @@ mod tests {
let trap = invoke_export(&mut store, instance, "read_out_of_bounds")
.unwrap_err()
.downcast::<Trap>()?;
assert!(
trap.to_string()
.contains("wasm trap: out of bounds memory access"),
"bad trap message: {:?}",
trap.to_string()
);
assert_eq!(trap, Trap::MemoryOutOfBounds);
}
// these invoke wasmtime_call_trampoline from callable.rs
@@ -192,10 +187,11 @@ mod tests {
let read_out_of_bounds_func =
instance.get_typed_func::<(), i32, _>(&mut store, "read_out_of_bounds")?;
println!("calling read_out_of_bounds...");
let trap = read_out_of_bounds_func.call(&mut store, ()).unwrap_err();
assert!(trap
.to_string()
.contains("wasm trap: out of bounds memory access"));
let trap = read_out_of_bounds_func
.call(&mut store, ())
.unwrap_err()
.downcast::<Trap>()?;
assert_eq!(trap, Trap::MemoryOutOfBounds);
}
Ok(())
}

View File

@@ -117,7 +117,7 @@ fn iloop() {
store.add_fuel(10_000).unwrap();
let error = Instance::new(&mut store, &module, &[]).err().unwrap();
assert!(
error.to_string().contains("all fuel consumed"),
format!("{:?}", error).contains("all fuel consumed"),
"bad error: {}",
error
);
@@ -173,8 +173,11 @@ fn host_function_consumes_all() {
let export = instance
.get_typed_func::<(), (), _>(&mut store, "")
.unwrap();
let trap = export.call(&mut store, ()).err().unwrap().to_string();
assert!(trap.contains("all fuel consumed"), "bad error: {}", trap);
let trap = export.call(&mut store, ()).unwrap_err();
assert!(
format!("{trap:?}").contains("all fuel consumed"),
"bad error: {trap:?}"
);
}
#[test]

View File

@@ -1,4 +1,4 @@
use anyhow::Result;
use anyhow::{bail, Result};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst};
use std::sync::Arc;
use wasmtime::*;
@@ -17,15 +17,13 @@ fn func_constructors() {
Func::wrap(&mut store, || -> Option<ExternRef> { None });
Func::wrap(&mut store, || -> Option<Func> { None });
Func::wrap(&mut store, || -> Result<(), Trap> { loop {} });
Func::wrap(&mut store, || -> Result<i32, Trap> { loop {} });
Func::wrap(&mut store, || -> Result<i64, Trap> { loop {} });
Func::wrap(&mut store, || -> Result<f32, Trap> { loop {} });
Func::wrap(&mut store, || -> Result<f64, Trap> { loop {} });
Func::wrap(&mut store, || -> Result<Option<ExternRef>, Trap> {
loop {}
});
Func::wrap(&mut store, || -> Result<Option<Func>, Trap> { loop {} });
Func::wrap(&mut store, || -> Result<()> { loop {} });
Func::wrap(&mut store, || -> Result<i32> { loop {} });
Func::wrap(&mut store, || -> Result<i64> { loop {} });
Func::wrap(&mut store, || -> Result<f32> { loop {} });
Func::wrap(&mut store, || -> Result<f64> { loop {} });
Func::wrap(&mut store, || -> Result<Option<ExternRef>> { loop {} });
Func::wrap(&mut store, || -> Result<Option<Func>> { loop {} });
}
#[test]
@@ -222,15 +220,9 @@ fn import_works() -> Result<()> {
#[test]
fn trap_smoke() -> Result<()> {
let mut store = Store::<()>::default();
let f = Func::wrap(&mut store, || -> Result<(), Trap> {
Err(Trap::new("test"))
});
let err = f
.call(&mut store, &[], &mut [])
.unwrap_err()
.downcast::<Trap>()?;
let f = Func::wrap(&mut store, || -> Result<()> { bail!("test") });
let err = f.call(&mut store, &[], &mut []).unwrap_err();
assert!(err.to_string().contains("test"));
assert!(err.i32_exit_status().is_none());
Ok(())
}
@@ -244,11 +236,8 @@ fn trap_import() -> Result<()> {
)?;
let mut store = Store::<()>::default();
let module = Module::new(store.engine(), &wasm)?;
let import = Func::wrap(&mut store, || -> Result<(), Trap> { Err(Trap::new("foo")) });
let trap = Instance::new(&mut store, &module, &[import.into()])
.err()
.unwrap()
.downcast::<Trap>()?;
let import = Func::wrap(&mut store, || -> Result<()> { bail!("foo") });
let trap = Instance::new(&mut store, &module, &[import.into()]).unwrap_err();
assert!(trap.to_string().contains("foo"));
Ok(())
}
@@ -451,10 +440,7 @@ fn func_write_nothing() -> anyhow::Result<()> {
let mut store = Store::<()>::default();
let ty = FuncType::new(None, Some(ValType::I32));
let f = Func::new(&mut store, ty, |_, _, _| Ok(()));
let err = f
.call(&mut store, &[], &mut [Val::I32(0)])
.unwrap_err()
.downcast::<Trap>()?;
let err = f.call(&mut store, &[], &mut [Val::I32(0)]).unwrap_err();
assert!(err
.to_string()
.contains("function attempted to return an incompatible value"));
@@ -488,7 +474,7 @@ fn return_cross_store_value() -> anyhow::Result<()> {
let run = instance.get_func(&mut store1, "run").unwrap();
let result = run.call(&mut store1, &[], &mut [Val::I32(0)]);
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("cross-`Store`"));
assert!(format!("{:?}", result.unwrap_err()).contains("cross-`Store`"));
Ok(())
}
@@ -620,9 +606,9 @@ fn trap_doesnt_leak() -> anyhow::Result<()> {
// test that `Func::wrap` is correct
let canary1 = Canary::default();
let dtor1_run = canary1.0.clone();
let f1 = Func::wrap(&mut store, move || -> Result<(), Trap> {
let f1 = Func::wrap(&mut store, move || -> Result<()> {
drop(&canary1);
Err(Trap::new(""))
bail!("")
});
assert!(f1.typed::<(), (), _>(&store)?.call(&mut store, ()).is_err());
assert!(f1.call(&mut store, &[], &mut []).is_err());
@@ -632,7 +618,7 @@ fn trap_doesnt_leak() -> anyhow::Result<()> {
let dtor2_run = canary2.0.clone();
let f2 = Func::new(&mut store, FuncType::new(None, None), move |_, _, _| {
drop(&canary2);
Err(Trap::new(""))
bail!("")
});
assert!(f2.typed::<(), (), _>(&store)?.call(&mut store, ()).is_err());
assert!(f2.call(&mut store, &[], &mut []).is_err());

View File

@@ -1,7 +1,8 @@
use anyhow::Result;
use anyhow::{bail, Result};
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
use wasmtime::*;
use wasmtime_wasi::sync::WasiCtxBuilder;
use wasmtime_wasi::I32Exit;
#[test]
#[should_panic = "cannot use `func_new_async` without enabling async support"]
@@ -33,13 +34,13 @@ fn wrap_func() -> Result<()> {
linker.func_wrap("m3", "", || -> Option<ExternRef> { None })?;
linker.func_wrap("m3", "f", || -> Option<Func> { None })?;
linker.func_wrap("", "f1", || -> Result<(), Trap> { loop {} })?;
linker.func_wrap("", "f2", || -> Result<i32, Trap> { loop {} })?;
linker.func_wrap("", "f3", || -> Result<i64, Trap> { loop {} })?;
linker.func_wrap("", "f4", || -> Result<f32, Trap> { loop {} })?;
linker.func_wrap("", "f5", || -> Result<f64, Trap> { loop {} })?;
linker.func_wrap("", "f6", || -> Result<Option<ExternRef>, Trap> { loop {} })?;
linker.func_wrap("", "f7", || -> Result<Option<Func>, Trap> { loop {} })?;
linker.func_wrap("", "f1", || -> Result<()> { loop {} })?;
linker.func_wrap("", "f2", || -> Result<i32> { loop {} })?;
linker.func_wrap("", "f3", || -> Result<i64> { loop {} })?;
linker.func_wrap("", "f4", || -> Result<f32> { loop {} })?;
linker.func_wrap("", "f5", || -> Result<f64> { loop {} })?;
linker.func_wrap("", "f6", || -> Result<Option<ExternRef>> { loop {} })?;
linker.func_wrap("", "f7", || -> Result<Option<Func>> { loop {} })?;
Ok(())
}
@@ -444,19 +445,15 @@ fn call_wasm_many_args() -> Result<()> {
fn trap_smoke() -> Result<()> {
let engine = Engine::default();
let mut linker = Linker::<()>::new(&engine);
linker.func_wrap("", "", || -> Result<(), Trap> { Err(Trap::new("test")) })?;
linker.func_wrap("", "", || -> Result<()> { bail!("test") })?;
let mut store = Store::new(&engine, ());
let f = linker.get(&mut store, "", "").unwrap().into_func().unwrap();
let err = f
.call(&mut store, &[], &mut [])
.unwrap_err()
.downcast::<Trap>()?;
let err = f.call(&mut store, &[], &mut []).unwrap_err();
assert!(err.to_string().contains("test"));
assert!(err.i32_exit_status().is_none());
Ok(())
}
@@ -472,16 +469,12 @@ fn trap_import() -> Result<()> {
let engine = Engine::default();
let mut linker = Linker::new(&engine);
linker.func_wrap("", "", || -> Result<(), Trap> { Err(Trap::new("foo")) })?;
linker.func_wrap("", "", || -> Result<()> { bail!("foo") })?;
let module = Module::new(&engine, &wasm)?;
let mut store = Store::new(&engine, ());
let trap = linker
.instantiate(&mut store, &module)
.err()
.unwrap()
.downcast::<Trap>()?;
let trap = linker.instantiate(&mut store, &module).unwrap_err();
assert!(trap.to_string().contains("foo"));
@@ -607,10 +600,7 @@ fn func_return_nothing() -> Result<()> {
let mut store = Store::new(&engine, ());
let f = linker.get(&mut store, "", "").unwrap().into_func().unwrap();
let err = f
.call(&mut store, &[], &mut [Val::I32(0)])
.unwrap_err()
.downcast::<Trap>()?;
let err = f.call(&mut store, &[], &mut [Val::I32(0)]).unwrap_err();
assert!(err
.to_string()
.contains("function attempted to return an incompatible value"));
@@ -725,8 +715,11 @@ fn wasi_imports() -> Result<()> {
let instance = linker.instantiate(&mut store, &module)?;
let start = instance.get_typed_func::<(), (), _>(&mut store, "_start")?;
let trap = start.call(&mut store, ()).unwrap_err();
assert_eq!(trap.i32_exit_status(), Some(123));
let exit = start
.call(&mut store, ())
.unwrap_err()
.downcast::<I32Exit>()?;
assert_eq!(exit.0, 123);
Ok(())
}

View File

@@ -31,12 +31,8 @@ fn loops_interruptable() -> anyhow::Result<()> {
let instance = Instance::new(&mut store, &module, &[])?;
let iloop = instance.get_typed_func::<(), (), _>(&mut store, "loop")?;
store.engine().increment_epoch();
let trap = iloop.call(&mut store, ()).unwrap_err();
assert!(
trap.trap_code().unwrap() == TrapCode::Interrupt,
"bad message: {}",
trap
);
let trap = iloop.call(&mut store, ()).unwrap_err().downcast::<Trap>()?;
assert_eq!(trap, Trap::Interrupt);
Ok(())
}
@@ -48,12 +44,8 @@ fn functions_interruptable() -> anyhow::Result<()> {
let instance = Instance::new(&mut store, &module, &[func.into()])?;
let iloop = instance.get_typed_func::<(), (), _>(&mut store, "loop")?;
store.engine().increment_epoch();
let trap = iloop.call(&mut store, ()).unwrap_err();
assert!(
trap.trap_code().unwrap() == TrapCode::Interrupt,
"{}",
trap.to_string()
);
let trap = iloop.call(&mut store, ()).unwrap_err().downcast::<Trap>()?;
assert_eq!(trap, Trap::Interrupt);
Ok(())
}
@@ -98,15 +90,11 @@ fn loop_interrupt_from_afar() -> anyhow::Result<()> {
// Enter the infinitely looping function and assert that our interrupt
// handle does indeed actually interrupt the function.
let iloop = instance.get_typed_func::<(), (), _>(&mut store, "loop")?;
let trap = iloop.call(&mut store, ()).unwrap_err();
let trap = iloop.call(&mut store, ()).unwrap_err().downcast::<Trap>()?;
STOP.store(true, SeqCst);
thread.join().unwrap();
assert!(HITS.load(SeqCst) > NUM_HITS);
assert!(
trap.trap_code().unwrap() == TrapCode::Interrupt,
"bad message: {}",
trap.to_string()
);
assert_eq!(trap, Trap::Interrupt);
Ok(())
}
@@ -138,14 +126,10 @@ fn function_interrupt_from_afar() -> anyhow::Result<()> {
// Enter the infinitely looping function and assert that our interrupt
// handle does indeed actually interrupt the function.
let iloop = instance.get_typed_func::<(), (), _>(&mut store, "loop")?;
let trap = iloop.call(&mut store, ()).unwrap_err();
let trap = iloop.call(&mut store, ()).unwrap_err().downcast::<Trap>()?;
STOP.store(true, SeqCst);
thread.join().unwrap();
assert!(HITS.load(SeqCst) > NUM_HITS);
assert!(
trap.trap_code().unwrap() == TrapCode::Interrupt,
"bad message: {}",
trap.to_string()
);
assert_eq!(trap, Trap::Interrupt);
Ok(())
}

View File

@@ -82,10 +82,7 @@ fn test_returns_incorrect_type() -> Result<()> {
let mut result = [Val::I32(0)];
let trap = run_func
.call(&mut store, &[], &mut result)
.expect_err("the execution should fail")
.downcast::<Trap>()?;
assert!(trap
.to_string()
.contains("function attempted to return an incompatible value"));
.expect_err("the execution should fail");
assert!(format!("{:?}", trap).contains("function attempted to return an incompatible value"));
Ok(())
}

View File

@@ -32,7 +32,7 @@ fn link_twice_bad() -> Result<()> {
linker.func_wrap("f", "", || {})?;
assert!(linker.func_wrap("f", "", || {}).is_err());
assert!(linker
.func_wrap("f", "", || -> Result<(), Trap> { loop {} })
.func_wrap("f", "", || -> Result<()> { loop {} })
.is_err());
// globals

View File

@@ -167,20 +167,32 @@ fn memory_guard_page_trap() -> Result<()> {
let m = instance.get_memory(&mut store, "m").unwrap();
let f = instance.get_typed_func::<i32, (), _>(&mut store, "f")?;
let trap = f.call(&mut store, 0).expect_err("function should trap");
assert!(trap.to_string().contains("out of bounds"));
let trap = f
.call(&mut store, 0)
.expect_err("function should trap")
.downcast::<Trap>()?;
assert_eq!(trap, Trap::MemoryOutOfBounds);
let trap = f.call(&mut store, 1).expect_err("function should trap");
assert!(trap.to_string().contains("out of bounds"));
let trap = f
.call(&mut store, 1)
.expect_err("function should trap")
.downcast::<Trap>()?;
assert_eq!(trap, Trap::MemoryOutOfBounds);
m.grow(&mut store, 1).expect("memory should grow");
f.call(&mut store, 0).expect("function should not trap");
let trap = f.call(&mut store, 65536).expect_err("function should trap");
assert!(trap.to_string().contains("out of bounds"));
let trap = f
.call(&mut store, 65536)
.expect_err("function should trap")
.downcast::<Trap>()?;
assert_eq!(trap, Trap::MemoryOutOfBounds);
let trap = f.call(&mut store, 65537).expect_err("function should trap");
assert!(trap.to_string().contains("out of bounds"));
let trap = f
.call(&mut store, 65537)
.expect_err("function should trap")
.downcast::<Trap>()?;
assert_eq!(trap, Trap::MemoryOutOfBounds);
m.grow(&mut store, 1).expect("memory should grow");
f.call(&mut store, 65536).expect("function should not trap");

View File

@@ -28,12 +28,8 @@ fn host_always_has_some_stack() -> anyhow::Result<()> {
// Make sure that our function traps and the trap says that the call stack
// has been exhausted.
let trap = foo.call(&mut store, ()).unwrap_err();
assert!(
trap.to_string().contains("call stack exhausted"),
"{}",
trap.to_string()
);
let trap = foo.call(&mut store, ()).unwrap_err().downcast::<Trap>()?;
assert_eq!(trap, Trap::StackOverflow);
// Additionally, however, and this is the crucial test, make sure that the
// host function actually completed. If HITS is 1 then we entered but didn't

View File

@@ -1,4 +1,4 @@
use anyhow::Result;
use anyhow::{bail, Error, Result};
use std::panic::{self, AssertUnwindSafe};
use std::process::Command;
use wasmtime::*;
@@ -15,7 +15,75 @@ fn test_trap_return() -> Result<()> {
let module = Module::new(store.engine(), wat)?;
let hello_type = FuncType::new(None, None);
let hello_func = Func::new(&mut store, hello_type, |_, _, _| Err(Trap::new("test 123")));
let hello_func = Func::new(&mut store, hello_type, |_, _, _| bail!("test 123"));
let instance = Instance::new(&mut store, &module, &[hello_func.into()])?;
let run_func = instance.get_typed_func::<(), (), _>(&mut store, "run")?;
let e = run_func.call(&mut store, ()).unwrap_err();
assert!(format!("{e:?}").contains("test 123"));
assert!(
e.downcast_ref::<WasmBacktrace>().is_some(),
"error should contain a WasmBacktrace"
);
Ok(())
}
#[test]
fn test_anyhow_error_return() -> Result<()> {
let mut store = Store::<()>::default();
let wat = r#"
(module
(func $hello (import "" "hello"))
(func (export "run") (call $hello))
)
"#;
let module = Module::new(store.engine(), wat)?;
let hello_type = FuncType::new(None, None);
let hello_func = Func::new(&mut store, hello_type, |_, _, _| {
Err(anyhow::Error::msg("test 1234"))
});
let instance = Instance::new(&mut store, &module, &[hello_func.into()])?;
let run_func = instance.get_typed_func::<(), (), _>(&mut store, "run")?;
let e = run_func.call(&mut store, ()).unwrap_err();
assert!(!e.to_string().contains("test 1234"));
assert!(format!("{:?}", e).contains("Caused by:\n test 1234"));
assert!(e.downcast_ref::<Trap>().is_none());
assert!(e.downcast_ref::<WasmBacktrace>().is_some());
Ok(())
}
#[test]
fn test_trap_return_downcast() -> Result<()> {
let mut store = Store::<()>::default();
let wat = r#"
(module
(func $hello (import "" "hello"))
(func (export "run") (call $hello))
)
"#;
#[derive(Debug)]
struct MyTrap;
impl std::fmt::Display for MyTrap {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "my trap")
}
}
impl std::error::Error for MyTrap {}
let module = Module::new(store.engine(), wat)?;
let hello_type = FuncType::new(None, None);
let hello_func = Func::new(&mut store, hello_type, |_, _, _| {
Err(anyhow::Error::from(MyTrap))
});
let instance = Instance::new(&mut store, &module, &[hello_func.into()])?;
let run_func = instance.get_typed_func::<(), (), _>(&mut store, "run")?;
@@ -24,7 +92,19 @@ fn test_trap_return() -> Result<()> {
.call(&mut store, ())
.err()
.expect("error calling function");
assert!(e.to_string().contains("test 123"));
let dbg = format!("{:?}", e);
println!("{}", dbg);
assert!(!e.to_string().contains("my trap"));
assert!(dbg.contains("Caused by:\n my trap"));
e.downcast_ref::<MyTrap>()
.expect("error downcasts to MyTrap");
let bt = e
.downcast_ref::<WasmBacktrace>()
.expect("error downcasts to WasmBacktrace");
assert_eq!(bt.frames().len(), 1);
println!("{:?}", bt);
Ok(())
}
@@ -43,12 +123,9 @@ fn test_trap_trace() -> Result<()> {
let instance = Instance::new(&mut store, &module, &[])?;
let run_func = instance.get_typed_func::<(), (), _>(&mut store, "run")?;
let e = run_func
.call(&mut store, ())
.err()
.expect("error calling function");
let e = run_func.call(&mut store, ()).unwrap_err();
let trace = e.trace().expect("backtrace is available");
let trace = e.downcast_ref::<WasmBacktrace>().unwrap().frames();
assert_eq!(trace.len(), 2);
assert_eq!(trace[0].module_name().unwrap(), "hello_mod");
assert_eq!(trace[0].func_index(), 1);
@@ -60,11 +137,7 @@ fn test_trap_trace() -> Result<()> {
assert_eq!(trace[1].func_name(), None);
assert_eq!(trace[1].func_offset(), Some(1));
assert_eq!(trace[1].module_offset(), Some(0x21));
assert!(
e.to_string().contains("unreachable"),
"wrong message: {}",
e.to_string()
);
assert_eq!(e.downcast::<Trap>()?, Trap::UnreachableCodeReached);
Ok(())
}
@@ -123,11 +196,9 @@ fn test_trap_through_host() -> Result<()> {
&module,
&[host_func_a.into(), host_func_b.into()],
)?;
let a = instance
.get_typed_func::<(), (), _>(&mut store, "a")
.unwrap();
let a = instance.get_typed_func::<(), (), _>(&mut store, "a")?;
let err = a.call(&mut store, ()).unwrap_err();
let trace = err.trace().expect("backtrace is available");
let trace = err.downcast_ref::<WasmBacktrace>().unwrap().frames();
assert_eq!(trace.len(), 3);
assert_eq!(trace[0].func_name(), Some("c"));
assert_eq!(trace[1].func_name(), Some("b"));
@@ -153,12 +224,8 @@ fn test_trap_backtrace_disabled() -> Result<()> {
let instance = Instance::new(&mut store, &module, &[])?;
let run_func = instance.get_typed_func::<(), (), _>(&mut store, "run")?;
let e = run_func
.call(&mut store, ())
.err()
.expect("error calling function");
assert!(e.trace().is_none(), "backtraces should be disabled");
let e = run_func.call(&mut store, ()).unwrap_err();
assert!(e.downcast_ref::<WasmBacktrace>().is_none());
Ok(())
}
@@ -174,24 +241,21 @@ fn test_trap_trace_cb() -> Result<()> {
"#;
let fn_type = FuncType::new(None, None);
let fn_func = Func::new(&mut store, fn_type, |_, _, _| Err(Trap::new("cb throw")));
let fn_func = Func::new(&mut store, fn_type, |_, _, _| bail!("cb throw"));
let module = Module::new(store.engine(), wat)?;
let instance = Instance::new(&mut store, &module, &[fn_func.into()])?;
let run_func = instance.get_typed_func::<(), (), _>(&mut store, "run")?;
let e = run_func
.call(&mut store, ())
.err()
.expect("error calling function");
let e = run_func.call(&mut store, ()).unwrap_err();
let trace = e.trace().expect("backtrace is available");
let trace = e.downcast_ref::<WasmBacktrace>().unwrap().frames();
assert_eq!(trace.len(), 2);
assert_eq!(trace[0].module_name().unwrap(), "hello_mod");
assert_eq!(trace[0].func_index(), 2);
assert_eq!(trace[1].module_name().unwrap(), "hello_mod");
assert_eq!(trace[1].func_index(), 1);
assert!(e.to_string().contains("cb throw"));
assert!(format!("{e:?}").contains("cb throw"));
Ok(())
}
@@ -209,19 +273,16 @@ fn test_trap_stack_overflow() -> Result<()> {
let instance = Instance::new(&mut store, &module, &[])?;
let run_func = instance.get_typed_func::<(), (), _>(&mut store, "run")?;
let e = run_func
.call(&mut store, ())
.err()
.expect("error calling function");
let e = run_func.call(&mut store, ()).unwrap_err();
let trace = e.trace().expect("backtrace is available");
let trace = e.downcast_ref::<WasmBacktrace>().unwrap().frames();
assert!(trace.len() >= 32);
for i in 0..trace.len() {
assert_eq!(trace[i].module_name().unwrap(), "rec_mod");
assert_eq!(trace[i].func_index(), 0);
assert_eq!(trace[i].func_name(), Some("run"));
}
assert!(e.to_string().contains("call stack exhausted"));
assert_eq!(e.downcast::<Trap>()?, Trap::StackOverflow);
Ok(())
}
@@ -242,19 +303,18 @@ fn trap_display_pretty() -> Result<()> {
let instance = Instance::new(&mut store, &module, &[])?;
let run_func = instance.get_typed_func::<(), (), _>(&mut store, "bar")?;
let e = run_func
.call(&mut store, ())
.err()
.expect("error calling function");
let e = run_func.call(&mut store, ()).unwrap_err();
assert_eq!(
e.to_string(),
format!("{:?}", e),
"\
wasm trap: wasm `unreachable` instruction executed
wasm backtrace:
error while executing at wasm backtrace:
0: 0x23 - m!die
1: 0x27 - m!<wasm function 1>
2: 0x2c - m!foo
3: 0x31 - m!<wasm function 3>
Caused by:
wasm trap: wasm `unreachable` instruction executed\
"
);
Ok(())
@@ -287,21 +347,20 @@ fn trap_display_multi_module() -> Result<()> {
let instance = Instance::new(&mut store, &module, &[bar])?;
let bar2 = instance.get_typed_func::<(), (), _>(&mut store, "bar2")?;
let e = bar2
.call(&mut store, ())
.err()
.expect("error calling function");
let e = bar2.call(&mut store, ()).unwrap_err();
assert_eq!(
e.to_string(),
format!("{e:?}"),
"\
wasm trap: wasm `unreachable` instruction executed
wasm backtrace:
error while executing at wasm backtrace:
0: 0x23 - a!die
1: 0x27 - a!<wasm function 1>
2: 0x2c - a!foo
3: 0x31 - a!<wasm function 3>
4: 0x29 - b!middle
5: 0x2e - b!<wasm function 2>
Caused by:
wasm trap: wasm `unreachable` instruction executed\
"
);
Ok(())
@@ -321,15 +380,9 @@ fn trap_start_function_import() -> Result<()> {
let module = Module::new(store.engine(), &binary)?;
let sig = FuncType::new(None, None);
let func = Func::new(&mut store, sig, |_, _, _| Err(Trap::new("user trap")));
let err = Instance::new(&mut store, &module, &[func.into()])
.err()
.unwrap();
assert!(err
.downcast_ref::<Trap>()
.unwrap()
.to_string()
.contains("user trap"));
let func = Func::new(&mut store, sig, |_, _, _| bail!("user trap"));
let err = Instance::new(&mut store, &module, &[func.into()]).unwrap_err();
assert!(format!("{err:?}").contains("user trap"));
Ok(())
}
@@ -417,7 +470,7 @@ fn rust_catch_panic_import() -> Result<()> {
let instance = Instance::new(&mut store, &module, &[panic.into(), catch_panic.into()])?;
let run = instance.get_typed_func::<(), (), _>(&mut store, "run")?;
let trap = run.call(&mut store, ()).unwrap_err();
let trace = trap.trace().unwrap();
let trace = trap.downcast_ref::<WasmBacktrace>().unwrap().frames();
assert_eq!(trace.len(), 1);
assert_eq!(trace[0].func_index(), 3);
assert_eq!(num_panics.load(std::sync::atomic::Ordering::SeqCst), 2);
@@ -536,18 +589,20 @@ fn start_trap_pretty() -> Result<()> {
let module = Module::new(store.engine(), wat)?;
let e = match Instance::new(&mut store, &module, &[]) {
Ok(_) => panic!("expected failure"),
Err(e) => e.downcast::<Trap>()?,
Err(e) => e,
};
assert_eq!(
e.to_string(),
format!("{e:?}"),
"\
wasm trap: wasm `unreachable` instruction executed
wasm backtrace:
error while executing at wasm backtrace:
0: 0x1d - m!die
1: 0x21 - m!<wasm function 1>
2: 0x26 - m!foo
3: 0x2b - m!start
Caused by:
wasm trap: wasm `unreachable` instruction executed\
"
);
Ok(())
@@ -568,15 +623,15 @@ fn present_after_module_drop() -> Result<()> {
assert_trap(func.call(&mut store, ()).unwrap_err());
return Ok(());
fn assert_trap(t: Trap) {
println!("{}", t);
let trace = t.trace().expect("backtrace is available");
fn assert_trap(t: Error) {
println!("{:?}", t);
let trace = t.downcast_ref::<WasmBacktrace>().unwrap().frames();
assert_eq!(trace.len(), 1);
assert_eq!(trace[0].func_index(), 0);
}
}
fn assert_trap_code(wat: &str, code: wasmtime::TrapCode) {
fn assert_trap_code(wat: &str, code: wasmtime::Trap) {
let mut store = Store::<()>::default();
let module = Module::new(store.engine(), wat).unwrap();
@@ -585,7 +640,7 @@ fn assert_trap_code(wat: &str, code: wasmtime::TrapCode) {
Err(e) => e,
};
let trap = err.downcast_ref::<Trap>().unwrap();
assert_eq!(trap.trap_code(), Some(code));
assert_eq!(*trap, code);
}
#[test]
@@ -598,7 +653,7 @@ fn heap_out_of_bounds_trap() {
(start $start)
)
"#,
TrapCode::MemoryOutOfBounds,
Trap::MemoryOutOfBounds,
);
assert_trap_code(
@@ -609,7 +664,7 @@ fn heap_out_of_bounds_trap() {
(start $start)
)
"#,
TrapCode::MemoryOutOfBounds,
Trap::MemoryOutOfBounds,
);
}
@@ -660,13 +715,11 @@ fn parse_dwarf_info() -> Result<()> {
);
linker.module(&mut store, "", &module)?;
let run = linker.get_default(&mut store, "")?;
let trap = run
.call(&mut store, &[], &mut [])
.unwrap_err()
.downcast::<Trap>()?;
let trap = run.call(&mut store, &[], &mut []).unwrap_err();
let mut found = false;
for frame in trap.trace().expect("backtrace is available") {
let frames = trap.downcast_ref::<WasmBacktrace>().unwrap().frames();
for frame in frames {
for symbol in frame.symbols() {
if let Some(file) = symbol.file() {
if file.ends_with("input.rs") {
@@ -698,16 +751,15 @@ fn no_hint_even_with_dwarf_info() -> Result<()> {
)
"#,
)?;
let trap = Instance::new(&mut store, &module, &[])
.err()
.unwrap()
.downcast::<Trap>()?;
let trap = Instance::new(&mut store, &module, &[]).unwrap_err();
assert_eq!(
trap.to_string(),
format!("{trap:?}"),
"\
wasm trap: wasm `unreachable` instruction executed
wasm backtrace:
error while executing at wasm backtrace:
0: 0x1a - <unknown>!start
Caused by:
wasm trap: wasm `unreachable` instruction executed\
"
);
Ok(())
@@ -732,17 +784,16 @@ fn hint_with_dwarf_info() -> Result<()> {
)
"#,
)?;
let trap = Instance::new(&mut store, &module, &[])
.err()
.unwrap()
.downcast::<Trap>()?;
let trap = Instance::new(&mut store, &module, &[]).unwrap_err();
assert_eq!(
trap.to_string(),
format!("{trap:?}"),
"\
wasm trap: wasm `unreachable` instruction executed
wasm backtrace:
error while executing at wasm backtrace:
0: 0x1a - <unknown>!start
note: using the `WASMTIME_BACKTRACE_DETAILS=1` environment variable to may show more debugging information
Caused by:
wasm trap: wasm `unreachable` instruction executed\
"
);
Ok(())
@@ -794,12 +845,9 @@ fn traps_without_address_map() -> Result<()> {
let instance = Instance::new(&mut store, &module, &[])?;
let run_func = instance.get_typed_func::<(), (), _>(&mut store, "run")?;
let e = run_func
.call(&mut store, ())
.err()
.expect("error calling function");
let e = run_func.call(&mut store, ()).unwrap_err();
let trace = e.trace().expect("backtrace is available");
let trace = e.downcast_ref::<WasmBacktrace>().unwrap().frames();
assert_eq!(trace.len(), 2);
assert_eq!(trace[0].func_name(), Some("hello"));
assert_eq!(trace[0].func_index(), 1);
@@ -846,16 +894,13 @@ fn catch_trap_calling_across_stores() -> Result<()> {
.get_typed_func::<(), (), _>(&mut data.child_store, "trap")
.expect("trap function should be exported");
let trap = func
.call(&mut data.child_store, ())
.err()
.expect("should trap");
let trap = func.call(&mut data.child_store, ()).unwrap_err();
assert!(
trap.to_string().contains("unreachable"),
"trap should contain 'unreachable', got: {trap}"
format!("{trap:?}").contains("unreachable"),
"trap should contain 'unreachable', got: {trap:?}"
);
let trace = trap.trace().unwrap();
let trace = trap.downcast_ref::<WasmBacktrace>().unwrap().frames();
assert_eq!(trace.len(), 1);
assert_eq!(trace[0].func_name(), Some("trap"));
@@ -965,7 +1010,7 @@ async fn async_then_sync_trap() -> Result<()> {
.unwrap();
let trap = a.call_async(&mut async_store, ()).await.unwrap_err();
let trace = trap.trace().unwrap();
let trace = trap.downcast_ref::<WasmBacktrace>().unwrap().frames();
// We don't support cross-store or cross-engine symbolication currently, so
// the other frames are ignored.
assert_eq!(trace.len(), 1);
@@ -1022,25 +1067,21 @@ async fn sync_then_async_trap() -> Result<()> {
let sync_module = Module::new(sync_store.engine(), wat)?;
let mut sync_linker = Linker::new(sync_store.engine());
sync_linker.func_wrap(
"",
"b",
move |mut caller: Caller<SyncCtx>| -> Result<(), Trap> {
log::info!("Called `b`...");
let async_instance = caller.data().async_instance;
let async_store = &mut caller.data_mut().async_store;
sync_linker.func_wrap("", "b", move |mut caller: Caller<SyncCtx>| -> Result<()> {
log::info!("Called `b`...");
let async_instance = caller.data().async_instance;
let async_store = &mut caller.data_mut().async_store;
log::info!("Calling `c`...");
let c = async_instance
.get_typed_func::<(), (), _>(&mut *async_store, "c")
.unwrap();
tokio::task::block_in_place(|| {
tokio::runtime::Handle::current()
.block_on(async move { c.call_async(async_store, ()).await })
})?;
Ok(())
},
)?;
log::info!("Calling `c`...");
let c = async_instance
.get_typed_func::<(), (), _>(&mut *async_store, "c")
.unwrap();
tokio::task::block_in_place(|| {
tokio::runtime::Handle::current()
.block_on(async move { c.call_async(async_store, ()).await })
})?;
Ok(())
})?;
let sync_instance = sync_linker.instantiate(&mut sync_store, &sync_module)?;
@@ -1050,7 +1091,7 @@ async fn sync_then_async_trap() -> Result<()> {
.unwrap();
let trap = a.call(&mut sync_store, ()).unwrap_err();
let trace = trap.trace().unwrap();
let trace = trap.downcast_ref::<WasmBacktrace>().unwrap().frames();
// We don't support cross-store or cross-engine symbolication currently, so
// the other frames are ignored.
assert_eq!(trace.len(), 1);