A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Turn host-thrown exceptions into traps for components (#14688)
Alex Crichton6a4ecd9fb47a
diff --git a/crates/wasmtime/src/runtime/vm/component.rs b/crates/wasmtime/src/runtime/vm/component.rsindex 94b81b9e2f..a0864b822a 100644--- a/crates/wasmtime/src/runtime/vm/component.rs+++ b/crates/wasmtime/src/runtime/vm/component.rs@@ -15,7 +15,7 @@ use crate::runtime::component::{ComponentInstanceId, RuntimeInstance};use crate::runtime::vm::instance::{InstanceLayout, OwnedInstance, OwnedVMContext};use crate::runtime::vm::vmcontext::VMFunctionBody;use crate::runtime::vm::{- HostResult, SendSyncPtr, VMArrayCallFunction, VMFuncRef, VMGlobalDefinition,+ HostResult, SendSyncPtr, UncaughtException, VMArrayCallFunction, VMFuncRef, VMGlobalDefinition,VMMemoryDefinition, VMOpaqueContext, VMStore, VMStoreRawPtr, VMTableImport, VMWasmCallFunction,ValRaw, VmPtr, VmSafe, catch_unwind_and_record_trap,};@@ -269,7 +269,7 @@ impl ComponentInstance {let store = unsafe { &mut *reference.store.0.as_ptr() };let instance = Instance::from_wasmtime(store, reference.id);- catch_unwind_and_record_trap(store, |store| f(store, instance))+ catch_unwind_and_record_trap(store, UncaughtException::Trap, |store| f(store, instance))}/// Returns the `InstanceId` associated with the `vmctx` provided.diff --git a/crates/wasmtime/src/runtime/vm/instance.rs b/crates/wasmtime/src/runtime/vm/instance.rsindex 5be8d457ec..ecc3abd5cc 100644--- a/crates/wasmtime/src/runtime/vm/instance.rs+++ b/crates/wasmtime/src/runtime/vm/instance.rs@@ -14,8 +14,8 @@ use crate::runtime::vm::vmcontext::{VMTableDefinition, VMTableImport, VMTagDefinition, VMTagImport,};use crate::runtime::vm::{- GcStore, HostResult, Imports, ModuleRuntimeInfo, SendSyncPtr, VMGcRef, VMGlobalKind, VMStore,- VMStoreRawPtr, VmPtr, VmSafe, WasmFault, catch_unwind_and_record_trap,+ GcStore, HostResult, Imports, ModuleRuntimeInfo, SendSyncPtr, UncaughtException, VMGcRef,+ VMGlobalKind, VMStore, VMStoreRawPtr, VmPtr, VmSafe, WasmFault, catch_unwind_and_record_trap,};use crate::store::{InstanceId, StoreId, StoreInstanceId, StoreOpaque, StoreResourceLimiter};use crate::vm::{VMWasmCallFunction, ValRaw};@@ -337,7 +337,9 @@ impl Instance {// Thread the `store` and `instance` through panic/trap infrastructure// back into `f`.- catch_unwind_and_record_trap(store, |store| f(store, instance))+ catch_unwind_and_record_trap(store, UncaughtException::Propagate, |store| {+ f(store, instance)+ })}/// Converts the provided `*mut VMContext` to an `Instance` pointer anddiff --git a/crates/wasmtime/src/runtime/vm/traphandlers.rs b/crates/wasmtime/src/runtime/vm/traphandlers.rsindex 25ccabd63e..64b6d8b026 100644--- a/crates/wasmtime/src/runtime/vm/traphandlers.rs+++ b/crates/wasmtime/src/runtime/vm/traphandlers.rs@@ -122,8 +122,15 @@ pub(super) unsafe fn raise_preexisting_trap(store: &mut dyn VMStore) {/// This function acts as a bridge between the two to appropriately handle/// encoding host values to Cranelift-understood ABIs via the `HostResult`/// trait.+///+/// The `uncaught_exception` parameter controls what happens when `f` throws an+/// exception (returns a `ThrownException` error). Core wasm host functions+/// propagate the exception to their wasm caller, but component host functions+/// and intrinsics are a component boundary which exceptions cannot cross, so+/// there the exception is instead turned into a trap.pub fn catch_unwind_and_record_trap<R>(store: &mut dyn VMStore,+ uncaught_exception: UncaughtException,f: impl FnOnce(&mut dyn VMStore) -> R,) -> R::Abiwhere@@ -134,7 +141,10 @@ where// (e.g. `ret` is a "false"-y value) then it's recorded in TLS for the// unwind operation that's about to happen from Cranelift-generated code.let (ret, unwind) = R::maybe_catch_unwind(store, |store| f(store));- if let Some(unwind) = unwind {+ if let Some(mut unwind) = unwind {+ if let UnwindReason::Trap(Ok(trap)) = &mut unwind {+ uncaught_exception.apply(&mut trap.reason);+ }tls::with(|info| info.unwrap().record_unwind(unwind));}ret@@ -463,6 +473,21 @@ pub enum UncaughtException {Trap,}+impl UncaughtException {+ fn apply(self, reason: &mut TrapReason) {+ #[cfg(all(feature = "gc", feature = "component-model"))]+ if self == UncaughtException::Trap+ && let TrapReason::User(err) = reason+ && err.is::<ThrownException>()+ {+ // FIXME: this throws away the entire `err` and replaces it with a+ // `Trap`, so any context on `err` is lost.+ *err = crate::Trap::UncaughtException.into();+ }+ let _ = (self, reason);+ }+}+/// Catches any wasm traps that happen within the execution of `closure`,/// returning them as a `Result`.pub fn catch_traps<T, F>(@@ -936,19 +961,7 @@ impl CallThreadState {// Handle `UncaughtException` if we've come this far (as caught// exceptions are handled above).- //- // FIXME: this throws away the entire `err` and replaces it with- // a `Trap`, so any context on `err` is lost.- #[cfg(all(feature = "gc", feature = "component-model"))]- if self.uncaught_exception == UncaughtException::Trap- && matches!(- &trap.reason,- TrapReason::User(err) if err.is::<ThrownException>()- )- {- trap.reason = TrapReason::User(crate::Trap::UncaughtException.into());- }- let _ = &self.uncaught_exception;+ self.uncaught_exception.apply(&mut trap.reason);}// If this wasn't a wasm-caught exception, then catch the exceptiondiff --git a/tests/all/component_model/import.rs b/tests/all/component_model/import.rsindex e35eaa599e..e9bf62ee80 100644--- a/tests/all/component_model/import.rs+++ b/tests/all/component_model/import.rs@@ -1251,3 +1251,54 @@ fn hostcall_fuel_limits_val() -> Result<()> {Ok(())}++#[test]+fn host_throw_is_trap() -> Result<()> {+ for concurrency in [true, false] {+ let mut config = Config::new();+ config.wasm_exceptions(true);+ config.wasm_component_model(true);+ config.concurrency_support(concurrency);+ let engine = Engine::new(&config)?;+ let component = Component::new(+ &engine,+ r#"+ (component+ (import "f" (func $f))+ (core func $f (canon lower (func $f)))+ (core module $m+ (import "" "f" (func $f))+ (func (export "run")+ (block $caught+ (try_table (catch_all $caught)+ (call $f))+ return)+ unreachable)+ )+ (core instance $i (instantiate $m+ (with "" (instance (export "f" (func $f))))+ ))+ (func (export "run") (canon lift (core func $i "run")))+ )+ "#,+ )?;+ let mut linker = Linker::<()>::new(&engine);+ linker.root().func_wrap("f", |mut store, (): ()| {+ let ty = wasmtime::TagType::new(wasmtime::FuncType::new(store.engine(), [], []));+ let tag = wasmtime::Tag::new(&mut store, &ty)?;+ let pre = wasmtime::ExnRefPre::new(&mut store, wasmtime::ExnType::from_tag_type(&ty)?);+ let exn = wasmtime::ExnRef::new(&mut store, &pre, &tag, &[])?;+ store.throw::<()>(exn)+ })?;+ let mut store = Store::new(&engine, ());+ let instance = linker.instantiate(&mut store, &component)?;+ let run = instance.get_typed_func::<(), ()>(&mut store, "run")?;+ let err = run.call(&mut store, ()).unwrap_err();+ assert_eq!(+ err.downcast_ref::<wasmtime::Trap>(),+ Some(&wasmtime::Trap::UncaughtException),+ "{err:?}",+ );+ }+ Ok(())+}