Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Fix returning `ThrownException` alone (#13306)

Alex Crichton87764ddf5b8c
diff --git a/crates/wasmtime/src/runtime.rs b/crates/wasmtime/src/runtime.rs
index d4201b1b1b..d19e8b7824 100644
--- a/crates/wasmtime/src/runtime.rs
+++ b/crates/wasmtime/src/runtime.rs
@@ -41,7 +41,6 @@ pub(crate) mod code;
pub(crate) mod code_memory;
#[cfg(feature = "debug")]
pub(crate) mod debug;
-#[cfg(feature = "gc")]
pub(crate) mod exception;
pub(crate) mod externals;
#[cfg(feature = "async")]
@@ -89,7 +88,6 @@ pub(crate) use bug::bail_bug;
pub use code_memory::CodeMemory;
#[cfg(feature = "debug")]
pub use debug::*;
-#[cfg(feature = "gc")]
pub use exception::*;
pub use externals::*;
pub use func::*;
diff --git a/crates/wasmtime/src/runtime/gc/disabled/rooting.rs b/crates/wasmtime/src/runtime/gc/disabled/rooting.rs
index 543063f138..ccc03dcc75 100644
--- a/crates/wasmtime/src/runtime/gc/disabled/rooting.rs
+++ b/crates/wasmtime/src/runtime/gc/disabled/rooting.rs
@@ -183,7 +183,7 @@ impl<T> OwnedRooted<T>
where
T: GcRef,
{
- pub fn clone(&self, _store: impl AsContextMut) -> Self {
+ pub fn clone(&self) -> Self {
match self.inner {}
}
diff --git a/crates/wasmtime/src/runtime/store.rs b/crates/wasmtime/src/runtime/store.rs
index 6cfc1a3ea6..18f7b040ae 100644
--- a/crates/wasmtime/src/runtime/store.rs
+++ b/crates/wasmtime/src/runtime/store.rs
@@ -76,11 +76,7 @@
//! contents of `StoreOpaque`. This is an invariant that we, as the authors of
//! `wasmtime`, must uphold for the public interface to be safe.
-#[cfg(all(feature = "gc", feature = "debug"))]
-use crate::OwnedRooted;
use crate::RootSet;
-#[cfg(feature = "gc")]
-use crate::ThrownException;
use crate::error::OutOfMemory;
#[cfg(feature = "async")]
use crate::fiber;
@@ -99,10 +95,10 @@ use crate::runtime::vm::{
};
use crate::trampoline::VMHostGlobalContext;
#[cfg(feature = "debug")]
-use crate::{BreakpointState, DebugHandler, FrameDataCache};
+use crate::{BreakpointState, DebugHandler, FrameDataCache, OwnedRooted};
use crate::{Engine, Module, Val, ValRaw, module::ModuleRegistry};
#[cfg(feature = "gc")]
-use crate::{ExnRef, Rooted};
+use crate::{ExnRef, Rooted, ThrownException};
use crate::{Global, Instance, Table};
use core::convert::Infallible;
use core::fmt;
@@ -1274,9 +1270,8 @@ impl<T> Store<T> {
/// state, but should not be used as part of the ordinary
/// exception-handling flow. For the most idiomatic handling, see
/// [`StoreContextMut::throw`].
- #[cfg(feature = "gc")]
pub fn has_pending_exception(&self) -> bool {
- self.inner.pending_exception.is_some()
+ self.inner.has_pending_exception()
}
/// Return all breakpoints.
@@ -1478,9 +1473,8 @@ impl<'a, T> StoreContextMut<'a, T> {
/// Tests whether there is a pending exception.
///
/// See [`Store::has_pending_exception`] for more details.
- #[cfg(feature = "gc")]
pub fn has_pending_exception(&self) -> bool {
- self.0.inner.pending_exception.is_some()
+ self.0.inner.has_pending_exception()
}
}
@@ -2760,9 +2754,15 @@ at https://bytecodealliance.org/security.
}
/// Tests whether there is a pending exception.
- #[cfg(feature = "gc")]
pub fn has_pending_exception(&self) -> bool {
- self.pending_exception.is_some()
+ #[cfg(feature = "gc")]
+ {
+ self.pending_exception.is_some()
+ }
+ #[cfg(not(feature = "gc"))]
+ {
+ false
+ }
}
#[cfg(feature = "gc")]
@@ -2774,19 +2774,26 @@ at https://bytecodealliance.org/security.
/// Get an owned rooted reference to the pending exception,
/// without taking it off the store.
- #[cfg(all(feature = "gc", feature = "debug"))]
+ #[cfg(feature = "debug")]
pub(crate) fn pending_exception_owned_rooted(
&mut self,
- ) -> Result<Option<OwnedRooted<ExnRef>>, crate::error::OutOfMemory> {
- let mut nogc = AutoAssertNoGc::new(self);
- nogc.pending_exception
- .take()
- .map(|vmexnref| {
- let cloned = nogc.clone_gc_ref(vmexnref.as_gc_ref());
- nogc.pending_exception = Some(cloned.into_exnref_unchecked());
- OwnedRooted::new(&mut nogc, vmexnref.into())
- })
- .transpose()
+ ) -> Result<Option<OwnedRooted<crate::ExnRef>>, crate::error::OutOfMemory> {
+ #[cfg(feature = "gc")]
+ {
+ let mut nogc = AutoAssertNoGc::new(self);
+ nogc.pending_exception
+ .take()
+ .map(|vmexnref| {
+ let cloned = nogc.clone_gc_ref(vmexnref.as_gc_ref());
+ nogc.pending_exception = Some(cloned.into_exnref_unchecked());
+ OwnedRooted::new(&mut nogc, vmexnref.into())
+ })
+ .transpose()
+ }
+ #[cfg(not(feature = "gc"))]
+ {
+ Ok(None)
+ }
}
#[cfg(feature = "gc")]
diff --git a/crates/wasmtime/src/runtime/trap.rs b/crates/wasmtime/src/runtime/trap.rs
index 5ca7a58ae5..81270344ee 100644
--- a/crates/wasmtime/src/runtime/trap.rs
+++ b/crates/wasmtime/src/runtime/trap.rs
@@ -1,7 +1,5 @@
#[cfg(feature = "coredump")]
use super::coredump::WasmCoreDump;
-#[cfg(feature = "gc")]
-use crate::ThrownException;
use crate::prelude::*;
use crate::store::StoreOpaque;
use crate::{AsContext, Module};
@@ -86,8 +84,6 @@ pub(crate) fn from_runtime_box(
coredumpstack,
} = *runtime_trap;
let (mut error, pc) = match reason {
- #[cfg(feature = "gc")]
- crate::runtime::vm::TrapReason::Exception => (ThrownException.into(), None),
// For user-defined errors they're already an `crate::Error` so no
// conversion is really necessary here, but a `backtrace` may have
// been captured so it's attempted to get inserted here.
diff --git a/crates/wasmtime/src/runtime/vm/libcalls.rs b/crates/wasmtime/src/runtime/vm/libcalls.rs
index 3c50a5f7d1..00d83582e8 100644
--- a/crates/wasmtime/src/runtime/vm/libcalls.rs
+++ b/crates/wasmtime/src/runtime/vm/libcalls.rs
@@ -1698,18 +1698,14 @@ fn get_instance_id(_store: &mut dyn VMStore, instance: InstanceId) -> u32 {
}
#[cfg(feature = "gc")]
-fn throw_ref(
- store: &mut dyn VMStore,
- _instance: InstanceId,
- exnref: u32,
-) -> Result<(), TrapReason> {
+fn throw_ref(store: &mut dyn VMStore, _instance: InstanceId, exnref: u32) -> Result<()> {
let exnref = VMGcRef::from_raw_u32(exnref).ok_or_else(|| Trap::NullReference)?;
let exnref = store.unwrap_gc_store_mut().clone_gc_ref(&exnref);
let exnref = exnref
.into_exnref(&*store.unwrap_gc_store().gc_heap)
.expect("gc ref should be an exception object");
store.set_pending_exception(exnref);
- Err(TrapReason::Exception)
+ Err(crate::ThrownException.into())
}
fn breakpoint(store: &mut dyn VMStore, _instance: InstanceId) -> Result<()> {
diff --git a/crates/wasmtime/src/runtime/vm/traphandlers.rs b/crates/wasmtime/src/runtime/vm/traphandlers.rs
index e5fd3f6e09..68a470afd8 100644
--- a/crates/wasmtime/src/runtime/vm/traphandlers.rs
+++ b/crates/wasmtime/src/runtime/vm/traphandlers.rs
@@ -21,8 +21,6 @@ use crate::runtime::module::lookup_code;
use crate::runtime::store::{ExecutorRef, StoreOpaque};
use crate::runtime::vm::sys::traphandlers;
use crate::runtime::vm::{InterpreterRef, VMContext, VMStore, VMStoreContext, f32x4, f64x2, i8x16};
-#[cfg(all(feature = "debug", feature = "gc"))]
-use crate::store::AsStoreOpaque;
use crate::{EntryStoreContext, prelude::*};
use crate::{StoreContextMut, WasmBacktrace};
use core::cell::Cell;
@@ -357,7 +355,16 @@ pub struct Trap {
/// for an exception).
#[derive(Debug)]
pub enum TrapReason {
- /// A user-raised trap through `raise_user_trap`.
+ /// A user-defined error has been raised, such as through a host function
+ /// call.
+ ///
+ /// This is constructed naturally through various `From` conversions leading
+ /// into a `TrapReason`. For example host functions returning `Result<()>`
+ /// will have any errors put here.
+ ///
+ /// Note that this variant can also represent an embedder-thrown exception.
+ /// Embedder-thrown exceptions are encoded as `ThrownException.into()` which
+ /// then looks for various handlers on the stack.
User(Error),
/// A trap raised from Cranelift-generated code.
@@ -385,26 +392,10 @@ pub enum TrapReason {
/// A trap raised from a wasm libcall
Wasm(wasmtime_environ::Trap),
-
- /// An exception.
- ///
- /// Note that internally, exceptions are rooted on the Store, while
- /// when crossing the public API, exceptions are held in a
- /// `wasmtime::Exception` which contains a boxed root and implements
- /// `Error`. This choice is intentional, to keep the internal
- /// implementation lightweight and ensure the types represent only
- /// allowable states.
- #[cfg(feature = "gc")]
- Exception,
}
impl From<Error> for TrapReason {
fn from(error: Error) -> Self {
- #[cfg(feature = "gc")]
- if error.is::<ThrownException>() {
- return TrapReason::Exception;
- }
-
TrapReason::User(error)
}
}
@@ -435,12 +426,6 @@ where
match result {
Ok(x) => Ok(x),
- #[cfg(feature = "gc")]
- Err(UnwindState::UnwindToHost {
- reason: UnwindReason::Trap(TrapReason::Exception),
- backtrace: _,
- coredump_stack: _,
- }) => Err(ThrownException.into()),
Err(UnwindState::UnwindToHost {
reason: UnwindReason::Trap(reason),
backtrace,
@@ -759,49 +744,53 @@ impl CallThreadState {
#[cfg(all(feature = "std", panic = "unwind"))]
UnwindReason::Panic(err) => {
// Panics don't need backtraces. There is nowhere to attach the
- // hypothetical backtrace to and it doesn't really make sense to try
- // in the first place since this is a Rust problem rather than a
- // Wasm problem.
+ // hypothetical backtrace to and it doesn't really make sense to
+ // try in the first place since this is a Rust problem rather
+ // than a Wasm problem.
UnwindState::UnwindToHost {
reason: UnwindReason::Panic(err),
backtrace: None,
coredump_stack: None,
}
}
- // An unwind due to an already-set pending exception
- // triggers the handler-search stack-walk. We store the
- // resolved handler if one exists. In either case, the
- // exception remains rooted in the Store until we actually
- // perform the unwind, and then gets taken and becomes the
- // payload at that point.
- #[cfg(feature = "gc")]
- UnwindReason::Trap(TrapReason::Exception) => {
- // SAFETY: we are invoking `compute_handler()` while
- // Wasm is on the stack and we have re-entered via a
- // trampoline, as required by its stack-walking logic.
- let handler = unsafe { compute_handler(store) };
- match handler {
- Some(handler) => UnwindState::UnwindToWasm(handler),
- None => UnwindState::UnwindToHost {
- reason: UnwindReason::Trap(TrapReason::Exception),
+
+ UnwindReason::Trap(trap) => 'arm: {
+ // An unwind due to an already-set pending exception triggers the
+ // handler-search stack-walk. We store the resolved handler if one
+ // exists. In either case, the exception remains rooted in the Store
+ // until we actually perform the unwind, and then gets taken and
+ // becomes the payload at that point.
+ //
+ // Note that this search only happens if the store actually has a
+ // pending exception. If the embedder returned `ThrownException`
+ // without actually putting anything in the store then the lookup
+ // doesn't happen as there's nothing for wasm to catch.
+ //
+ // SAFETY: we are invoking `compute_handler()` while Wasm is on
+ // the stack and we have re-entered via a trampoline, as
+ // required by its stack-walking logic.
+ #[cfg(feature = "gc")]
+ if let TrapReason::User(err) = &trap
+ && err.is::<ThrownException>()
+ && store.has_pending_exception()
+ && let Some(handler) = unsafe { compute_handler(store) }
+ {
+ break 'arm UnwindState::UnwindToWasm(handler);
+ }
+
+ // If we are just propagating an existing trap that already has
+ // a backtrace attached to it, then there is no need to capture
+ // a new backtrace either.
+ if let TrapReason::User(err) = &trap
+ && err.downcast_ref::<WasmBacktrace>().is_some()
+ {
+ break 'arm UnwindState::UnwindToHost {
+ reason: UnwindReason::Trap(trap),
backtrace: None,
coredump_stack: None,
- },
+ };
}
- }
- // And if we are just propagating an existing trap that already has
- // a backtrace attached to it, then there is no need to capture a
- // new backtrace either.
- UnwindReason::Trap(TrapReason::User(err))
- if err.downcast_ref::<WasmBacktrace>().is_some() =>
- {
- UnwindState::UnwindToHost {
- reason: UnwindReason::Trap(TrapReason::User(err)),
- backtrace: None,
- coredump_stack: None,
- }
- }
- UnwindReason::Trap(trap) => {
+
log::trace!("Capturing backtrace and coredump for {trap:?}");
UnwindState::UnwindToHost {
reason: UnwindReason::Trap(trap),
@@ -834,45 +823,46 @@ impl CallThreadState {
#[cfg(feature = "debug")]
{
+ use crate::ThrownException;
+ use wasmtime_core::alloc::PanicOnOom;
+
let result = match &unwind {
#[cfg(feature = "gc")]
UnwindState::UnwindToWasm(_) => {
- use wasmtime_core::alloc::PanicOnOom;
-
- assert!(store.as_store_opaque().has_pending_exception());
+ assert!(store.has_pending_exception());
let exn = store
- .as_store_opaque()
.pending_exception_owned_rooted()
// TODO(#12069): handle allocation failure here
.panic_on_oom()
.expect("exception should be set when we are throwing");
store.block_on_debug_handler(crate::DebugEvent::CaughtExceptionThrown(exn))
}
- #[cfg(feature = "gc")]
- UnwindState::UnwindToHost {
- reason: UnwindReason::Trap(TrapReason::Exception),
- ..
- } => {
- use wasmtime_core::alloc::PanicOnOom;
-
- let exn = store
- .as_store_opaque()
- .pending_exception_owned_rooted()
- // TODO(#12069): handle allocation failure here
- .panic_on_oom()
- .expect("exception should be set when we are throwing");
- store.block_on_debug_handler(crate::DebugEvent::UncaughtExceptionThrown(
- exn.clone(),
- ))
- }
UnwindState::UnwindToHost {
reason: UnwindReason::Trap(TrapReason::Wasm(trap)),
..
} => store.block_on_debug_handler(crate::DebugEvent::Trap(*trap)),
+
UnwindState::UnwindToHost {
reason: UnwindReason::Trap(TrapReason::User(err)),
..
- } => store.block_on_debug_handler(crate::DebugEvent::HostcallError(err)),
+ } => {
+ // For `ThrownException` errors that indicates that we
+ // should look at the store to see if there's a pending
+ // exception there, and if so then that's a different debug
+ // event than the `HostcallError` below.
+ if err.is::<ThrownException>()
+ && let Some(exn) = store
+ .pending_exception_owned_rooted()
+ // TODO(#12069): handle allocation failure here
+ .panic_on_oom()
+ {
+ store.block_on_debug_handler(crate::DebugEvent::UncaughtExceptionThrown(
+ exn.clone(),
+ ))
+ } else {
+ store.block_on_debug_handler(crate::DebugEvent::HostcallError(err))
+ }
+ }
UnwindState::UnwindToHost {
reason: UnwindReason::Trap(TrapReason::Jit { .. }),
diff --git a/tests/all/exceptions.rs b/tests/all/exceptions.rs
index 987011c4f4..18520627ab 100644
--- a/tests/all/exceptions.rs
+++ b/tests/all/exceptions.rs
@@ -242,3 +242,55 @@ fn gc_with_exnref_global(config: &mut Config) -> Result<()> {
Ok(())
}
+
+#[wasmtime_test(wasm_features(exceptions))]
+#[cfg_attr(miri, ignore)]
+fn thrown_exception_without_throwing(config: &mut Config) -> Result<()> {
+ let engine = Engine::new(config)?;
+ let mut store = Store::new(&engine, ());
+
+ let module = Module::new(
+ &engine,
+ r#"
+ (module
+ (import "" "" (func))
+
+ (func (export "run") call 0)
+ )
+ "#,
+ )?;
+
+ let func = Func::wrap(&mut store, || -> Result<()> { Err(ThrownException.into()) });
+ let instance = Instance::new(&mut store, &module, &[func.into()])?;
+ let func = instance.get_func(&mut store, "run").unwrap();
+ let err = func.call(&mut store, &[], &mut []).unwrap_err();
+ assert!(err.is::<ThrownException>());
+
+ Ok(())
+}
+
+#[wasmtime_test(wasm_features(exceptions))]
+#[cfg_attr(miri, ignore)]
+fn wasm_exceptions_have_backtraces(config: &mut Config) -> Result<()> {
+ let engine = Engine::new(config)?;
+ let mut store = Store::new(&engine, ());
+
+ let module = Module::new(
+ &engine,
+ r#"
+ (module
+ (tag $t0)
+
+ (func (export "run") throw $t0)
+ )
+ "#,
+ )?;
+
+ let instance = Instance::new(&mut store, &module, &[])?;
+ let func = instance.get_func(&mut store, "run").unwrap();
+ let err = func.call(&mut store, &[], &mut []).unwrap_err();
+ assert!(err.is::<ThrownException>());
+ assert!(err.is::<WasmBacktrace>());
+
+ Ok(())
+}