Skip to content

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

Don't propagate `ThrownException` with components (#14549)

Alex Crichton894553615544
diff --git a/crates/wasmtime/src/runtime/component/concurrent.rs b/crates/wasmtime/src/runtime/component/concurrent.rs
index 9f6e8d6fd2..0ec1699138 100644
--- a/crates/wasmtime/src/runtime/component/concurrent.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent.rs
@@ -64,7 +64,9 @@ use crate::store::{Store, StoreId, StoreInner, StoreOpaque, StoreToken};
#[cfg(feature = "gc")]
use crate::vm::GcRootsList;
use crate::vm::component::{CallContext, ComponentInstance, CurrentScope, InstanceState, Scope};
-use crate::vm::{AlwaysMut, SendSyncPtr, VMFuncRef, VMLazyThread, VMMemoryDefinition, VMStore};
+use crate::vm::{
+ AlwaysMut, SendSyncPtr, UncaughtException, VMFuncRef, VMLazyThread, VMMemoryDefinition, VMStore,
+};
use crate::{
AsContext, AsContextMut, FuncType, Result, StoreContext, StoreContextMut, ValRaw, ValType, bail,
};
@@ -2855,6 +2857,7 @@ impl Instance {
as *mut [MaybeUninit<ValRaw>] as _,
)
.unwrap(),
+ UncaughtException::Trap,
)?;
}
@@ -3170,6 +3173,7 @@ impl Instance {
&mut src[..count.max(dst.len())] as *mut [MaybeUninit<ValRaw>] as _,
)
.unwrap(),
+ UncaughtException::Trap,
)?;
}
dst.copy_from_slice(&src[..dst.len()]);
@@ -3204,6 +3208,7 @@ impl Instance {
&mut store,
return_.as_non_null(),
my_src.as_mut_slice().into(),
+ UncaughtException::Trap,
)?;
}
@@ -3271,6 +3276,7 @@ impl Instance {
&mut store,
function.as_non_null(),
params.as_mut_slice().into(),
+ UncaughtException::Trap,
)?;
}
Ok(params[0].get_u32())
diff --git a/crates/wasmtime/src/runtime/component/func.rs b/crates/wasmtime/src/runtime/component/func.rs
index 8d0eb34cf5..ae506a737a 100644
--- a/crates/wasmtime/src/runtime/component/func.rs
+++ b/crates/wasmtime/src/runtime/component/func.rs
@@ -5,7 +5,7 @@ use crate::component::types::ComponentFunc;
use crate::component::values::Val;
use crate::prelude::*;
use crate::runtime::vm::component::{ComponentInstance, InstanceFlags};
-use crate::runtime::vm::{Export, SendSyncPtr, VMFuncRef};
+use crate::runtime::vm::{Export, SendSyncPtr, UncaughtException, VMFuncRef};
use crate::store::StoreOpaque;
use crate::{AsContext, AsContextMut, StoreContextMut, ValRaw};
use core::mem::{self, MaybeUninit};
@@ -519,6 +519,7 @@ impl Func {
mem::size_of_val(space) / mem::size_of::<ValRaw>(),
))
.unwrap(),
+ UncaughtException::Trap,
)?;
}
@@ -733,6 +734,7 @@ pub(crate) unsafe fn call_post_return(
&mut store.as_context_mut(),
func,
core::slice::from_ref(&arg).into(),
+ UncaughtException::Trap,
)?;
}
diff --git a/crates/wasmtime/src/runtime/component/func/options.rs b/crates/wasmtime/src/runtime/component/func/options.rs
index 9279b538ca..ea64642b3a 100644
--- a/crates/wasmtime/src/runtime/component/func/options.rs
+++ b/crates/wasmtime/src/runtime/component/func/options.rs
@@ -6,8 +6,8 @@ use crate::component::resources::{HostResourceData, HostResourceIndex, HostResou
use crate::component::store::ComponentTaskState;
use crate::component::{Instance, ResourceType, RuntimeInstance};
use crate::prelude::*;
-use crate::runtime::vm::VMFuncRef;
use crate::runtime::vm::component::{ComponentInstance, CurrentScope, HandleTable, ResourceTables};
+use crate::runtime::vm::{UncaughtException, VMFuncRef};
use crate::store::{StoreId, StoreOpaque};
use alloc::sync::Arc;
use core::fmt;
@@ -179,7 +179,13 @@ impl<'a, T: 'static> LowerContext<'a, T> {
// Invoke the wasm malloc function using its raw and statically known
// signature.
let result = unsafe {
- ReallocFunc::call_raw(&mut StoreContextMut(store), &realloc_ty, realloc, params)?
+ ReallocFunc::call_raw(
+ &mut StoreContextMut(store),
+ &realloc_ty,
+ realloc,
+ params,
+ UncaughtException::Trap,
+ )?
};
if result % old_align != 0 {
diff --git a/crates/wasmtime/src/runtime/component/resources/any.rs b/crates/wasmtime/src/runtime/component/resources/any.rs
index 232abecd52..4d938ca89e 100644
--- a/crates/wasmtime/src/runtime/component/resources/any.rs
+++ b/crates/wasmtime/src/runtime/component/resources/any.rs
@@ -15,7 +15,7 @@ use crate::component::resources::host::{HostResource, HostResourceType};
use crate::component::resources::{HostResourceIndex, HostResourceTables};
use crate::component::{ComponentType, Lift, Lower, Resource, ResourceDynamic, ResourceType};
use crate::prelude::*;
-use crate::runtime::vm::ValRaw;
+use crate::runtime::vm::{UncaughtException, ValRaw};
use crate::{AsContextMut, StoreContextMut, Trap};
use core::mem::MaybeUninit;
use core::ptr::NonNull;
@@ -326,7 +326,12 @@ impl ResourceAny {
// to take one i32 argument and return no results, so the parameters
// here should be configured correctly.
unsafe {
- crate::Func::call_unchecked_raw(store, dtor, NonNull::from(&mut args))?;
+ crate::Func::call_unchecked_raw(
+ store,
+ dtor,
+ NonNull::from(&mut args),
+ UncaughtException::Trap,
+ )?;
}
if slot.instance.is_some() {
diff --git a/crates/wasmtime/src/runtime/func.rs b/crates/wasmtime/src/runtime/func.rs
index f4ceb3f36b..2ed8f7b2c0 100644
--- a/crates/wasmtime/src/runtime/func.rs
+++ b/crates/wasmtime/src/runtime/func.rs
@@ -1,7 +1,7 @@
use crate::error::OutOfMemory;
use crate::prelude::*;
use crate::runtime::vm::{
- self, InterpreterRef, SendSyncPtr, StoreBox, VMArrayCallHostFuncContext,
+ self, InterpreterRef, SendSyncPtr, StoreBox, UncaughtException, VMArrayCallHostFuncContext,
VMCommonStackInformation, VMContext, VMFuncRef, VMFunctionImport, VMOpaqueContext,
VMStoreContext, VmPtr,
};
@@ -1018,17 +1018,25 @@ impl Func {
// SAFETY: the safety of this function call is the same as the contract
// of this function.
- unsafe { Self::call_unchecked_raw(&mut store, func_ref, params_and_returns) }
+ unsafe {
+ Self::call_unchecked_raw(
+ &mut store,
+ func_ref,
+ params_and_returns,
+ UncaughtException::Propagate,
+ )
+ }
}
pub(crate) unsafe fn call_unchecked_raw<T>(
store: &mut StoreContextMut<'_, T>,
func_ref: NonNull<VMFuncRef>,
params_and_returns: NonNull<[ValRaw]>,
+ uncaught_exception: UncaughtException,
) -> Result<()> {
// SAFETY: the safety of this function call is the same as the contract
// of this function.
- invoke_wasm_and_catch_traps(store, |caller, vm| unsafe {
+ invoke_wasm_and_catch_traps(store, uncaught_exception, |caller, vm| unsafe {
VMFuncRef::array_call(func_ref, vm, caller, params_and_returns)
})
}
@@ -1456,6 +1464,7 @@ impl Func {
/// can pass to the called wasm function, if desired.
pub(crate) fn invoke_wasm_and_catch_traps<T>(
store: &mut StoreContextMut<'_, T>,
+ uncaught_exception: crate::runtime::vm::UncaughtException,
closure: impl FnMut(NonNull<VMContext>, Option<InterpreterRef<'_>>) -> bool,
) -> Result<()> {
// The `enter_wasm` call below will reset the store context's
@@ -1472,7 +1481,12 @@ pub(crate) fn invoke_wasm_and_catch_traps<T>(
// `previous_runtime_state` implicitly dropped here
return Err(trap);
}
- let result = crate::runtime::vm::catch_traps(store, &mut previous_runtime_state, closure);
+ let result = crate::runtime::vm::catch_traps(
+ store,
+ &mut previous_runtime_state,
+ uncaught_exception,
+ closure,
+ );
#[cfg(feature = "component-model")]
if result.is_err() {
store.0.set_trapped();
diff --git a/crates/wasmtime/src/runtime/func/typed.rs b/crates/wasmtime/src/runtime/func/typed.rs
index 068464c15f..4b1c79b69c 100644
--- a/crates/wasmtime/src/runtime/func/typed.rs
+++ b/crates/wasmtime/src/runtime/func/typed.rs
@@ -1,6 +1,6 @@
use super::invoke_wasm_and_catch_traps;
use crate::prelude::*;
-use crate::runtime::vm::VMFuncRef;
+use crate::runtime::vm::{UncaughtException, VMFuncRef};
use crate::store::{AutoAssertNoGc, StoreOpaque};
use crate::{
AsContext, AsContextMut, Engine, Func, FuncType, HeapType, NoFunc, RefType, StoreContextMut,
@@ -101,7 +101,15 @@ where
let mut store = store.as_context_mut();
store.0.validate_sync_call()?;
let func = self.func.vm_func_ref(store.0);
- unsafe { Self::call_raw(&mut store, &self.ty, func, params) }
+ unsafe {
+ Self::call_raw(
+ &mut store,
+ &self.ty,
+ func,
+ params,
+ UncaughtException::Propagate,
+ )
+ }
}
/// Invokes this WebAssembly function with the specified parameters.
@@ -140,7 +148,9 @@ where
store
.on_fiber(|store| {
let func = self.func.vm_func_ref(store.0);
- unsafe { Self::call_raw(store, &self.ty, func, params) }
+ unsafe {
+ Self::call_raw(store, &self.ty, func, params, UncaughtException::Propagate)
+ }
})
.await?
}
@@ -156,6 +166,7 @@ where
ty: &FuncType,
func: ptr::NonNull<VMFuncRef>,
params: Params,
+ uncaught_exception: UncaughtException,
) -> Result<Results> {
// double-check that params/results match for this function's type in
// debug mode.
@@ -197,7 +208,7 @@ where
// the memory go away, so the size matters here for performance.
let mut captures = (func, storage);
- let result = invoke_wasm_and_catch_traps(store, |caller, vm| {
+ let result = invoke_wasm_and_catch_traps(store, uncaught_exception, |caller, vm| {
let (func_ref, storage) = &mut captures;
let storage_len = mem::size_of_val::<Storage<_, _>>(storage) / mem::size_of::<ValRaw>();
let storage: *mut Storage<_, _> = storage;
diff --git a/crates/wasmtime/src/runtime/instance.rs b/crates/wasmtime/src/runtime/instance.rs
index 7d6a7796fa..45f1b67f5e 100644
--- a/crates/wasmtime/src/runtime/instance.rs
+++ b/crates/wasmtime/src/runtime/instance.rs
@@ -1,8 +1,8 @@
use crate::linker::{Definition, DefinitionType};
use crate::prelude::*;
use crate::runtime::vm::{
- self, Imports, ModuleRuntimeInfo, VMFuncRef, VMFunctionImport, VMGlobalImport, VMMemoryImport,
- VMStore, VMTableImport, VMTagImport,
+ self, Imports, ModuleRuntimeInfo, UncaughtException, VMFuncRef, VMFunctionImport,
+ VMGlobalImport, VMMemoryImport, VMStore, VMTableImport, VMTagImport,
};
use crate::store::{
AllocateInstanceKind, Asyncness, InstanceId, StoreInstanceId, StoreOpaque, StoreResourceLimiter,
@@ -362,9 +362,13 @@ impl Instance {
let caller_vmctx = instance.vmctx();
unsafe {
let funcref = f.vm_func_ref(store.0);
- super::func::invoke_wasm_and_catch_traps(store, |_default_caller, vm| {
- VMFuncRef::array_call(funcref, vm, caller_vmctx, NonNull::from(&mut []))
- })?;
+ super::func::invoke_wasm_and_catch_traps(
+ store,
+ UncaughtException::Propagate,
+ |_default_caller, vm| {
+ VMFuncRef::array_call(funcref, vm, caller_vmctx, NonNull::from(&mut []))
+ },
+ )?;
}
Ok(())
}
diff --git a/crates/wasmtime/src/runtime/vm/traphandlers.rs b/crates/wasmtime/src/runtime/vm/traphandlers.rs
index 41bea9418f..78d244de3f 100644
--- a/crates/wasmtime/src/runtime/vm/traphandlers.rs
+++ b/crates/wasmtime/src/runtime/vm/traphandlers.rs
@@ -452,11 +452,23 @@ where
}
}
+/// Controls what happens when a Wasm exception escapes a `catch_traps`
+/// activation without being caught by a handler on its stack.
+#[derive(Copy, Clone, PartialEq, Eq, Debug)]
+pub enum UncaughtException {
+ /// Propagate the exception to the host as a `ThrownException`.
+ Propagate,
+ /// Convert the escaping exception into a `Trap::UncaughtException`.
+ #[cfg(feature = "component-model")]
+ Trap,
+}
+
/// Catches any wasm traps that happen within the execution of `closure`,
/// returning them as a `Result`.
pub fn catch_traps<T, F>(
store: &mut StoreContextMut<'_, T>,
old_state: &mut EntryStoreContext,
+ uncaught_exception: UncaughtException,
mut closure: F,
) -> Result<()>
where
@@ -464,11 +476,14 @@ where
{
let caller = store.0.default_caller();
- let result = CallThreadState::new(store.0, old_state).with(|_cx| match store.0.executor() {
- ExecutorRef::Interpreter(r) => closure(caller, Some(r)),
- #[cfg(has_host_compiler_backend)]
- ExecutorRef::Native => closure(caller, None),
- });
+ let result =
+ CallThreadState::new(store.0, old_state, uncaught_exception).with(|_cx| {
+ match store.0.executor() {
+ ExecutorRef::Interpreter(r) => closure(caller, Some(r)),
+ #[cfg(has_host_compiler_backend)]
+ ExecutorRef::Native => closure(caller, None),
+ }
+ });
match result {
Ok(x) => Ok(x),
@@ -512,6 +527,7 @@ mod call_thread_state {
/// reached for host-code destinations and right when
/// performing the jump for Wasm-code destinations).
pub(super) unwind: Cell<Option<UnwindReason>>,
+ pub(super) uncaught_exception: UncaughtException,
#[cfg(all(has_native_signals))]
pub(super) signal_handler: Option<*const SignalHandler>,
pub(super) capture_backtrace: bool,
@@ -547,9 +563,11 @@ mod call_thread_state {
pub(super) fn new(
store: &mut StoreOpaque,
old_state: *mut EntryStoreContext,
+ uncaught_exception: UncaughtException,
) -> CallThreadState {
CallThreadState {
unwind: Cell::new(None),
+ uncaught_exception,
unwinder: store.unwinder(),
#[cfg(all(has_native_signals))]
signal_handler: store.signal_handler(),
@@ -892,6 +910,22 @@ impl CallThreadState {
trap.backtrace = self.capture_backtrace(store.vm_store_context_mut(), None);
trap.coredumpstack = self.capture_coredump(store.vm_store_context_mut(), None);
}
+
+ // 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;
}
// If this wasn't a wasm-caught exception, then catch the exception
diff --git a/tests/misc_testsuite/component-model/async/exceptions.wast b/tests/misc_testsuite/component-model/async/exceptions.wast
index 68010c0d29..ca51576829 100644
--- a/tests/misc_testsuite/component-model/async/exceptions.wast
+++ b/tests/misc_testsuite/component-model/async/exceptions.wast
@@ -1,21 +1,13 @@
;;! component_model_async = true
;;! exceptions = true
;;! reference_types = true
+;;! multi_memory = true
;; Tests for the interaction of Wasm exceptions and async lifts/lowers.
;;
-;; Unlike the sync->sync case (see `../exceptions.wast`) the fused adapters
-;; for calls involving an async lift or lower do not invoke guest code
-;; directly: the host drives the callee (and the parameter/result translation
-;; functions) itself, so an exception unwinding out of any of that guest code
-;; reaches the host, which catches it and reports an error. These tests pin
-;; that behavior: if fused-adapter codegen is ever optimized to call guest
-;; code directly on these paths, these tests will fail and the adapters
-;; involved will need exception barriers like the sync->sync one.
-;;
-;; In each case the `b` parameter selects when the exception is thrown:
-;; `false` throws in the first phase of the call (initial callee invocation)
-;; and `true` in a later phase (callback or post-yield).
+;; In all cases no matter what interleavings/etc show up, an uncaught exception
+;; from one component cannot ever be caught in another component and must show
+;; up as a form of uncaught exception trap.
;; sync->async
(component definition $A
@@ -65,9 +57,9 @@
)
(component instance $A $A)
-(assert_trap (invoke "run" (bool.const false)) "thrown Wasm exception")
+(assert_trap (invoke "run" (bool.const false)) "uncaught exception propagated out of component")
(component instance $A $A)
-(assert_trap (invoke "run" (bool.const true)) "thrown Wasm exception")
+(assert_trap (invoke "run" (bool.const true)) "uncaught exception propagated out of component")
;; async->sync
(component definition $A
@@ -141,9 +133,9 @@
)
(component instance $A $A)
-(assert_trap (invoke "run" (bool.const false)) "thrown Wasm exception")
+(assert_trap (invoke "run" (bool.const false)) "uncaught exception propagated out of component")
(component instance $A $A)
-(assert_trap (invoke "run" (bool.const true)) "thrown Wasm exception")
+(assert_trap (invoke "run" (bool.const true)) "uncaught exception propagated out of component")
;; async->async
(component definition $A
@@ -213,6 +205,238 @@
)
(component instance $A $A)
-(assert_trap (invoke "run" (bool.const false)) "thrown Wasm exception")
+(assert_trap (invoke "run" (bool.const false)) "uncaught exception propagated out of component")
(component instance $A $A)
-(assert_trap (invoke "run" (bool.const true)) "thrown Wasm exception")
+(assert_trap (invoke "run" (bool.const true)) "uncaught exception propagated out of component")
+
+;; The caller's `realloc` is invoked during the callee's `task.return` to lower
+;; a `string` result. An exception thrown by it must trap rather than unwind
+;; into the callee's `try_table`.
+(component
+ (component $C
+ (core module $libc (memory (export "mem") 1))
+ (core instance $libc (instantiate $libc))
+ (core module $m
+ (import "" "task.return" (func $task.return (param i32 i32)))
+ (import "" "mem" (memory 1))
+ (data (i32.const 100) "hi")
+ (func (export "g") (result i32)
+ (block $caught
+ (try_table (catch_all $caught)
+ (call $task.return (i32.const 100) (i32.const 2)))
+ (return (i32.const 0 (; EXIT ;))))
+ ;; the caller's exception leaked into this component
+ unreachable)
+ (func (export "cb") (param i32 i32 i32) (result i32) unreachable))
+ (core func $task.return (canon task.return (result string)
+ (memory (core memory $libc "mem"))))
+ (core instance $i (instantiate $m
+ (with "" (instance
+ (export "task.return" (func $task.return))
+ (export "mem" (memory $libc "mem"))))))
+ (func (export "g") async (result string)
+ (canon lift (core func $i "g") async
+ (memory (core memory $libc "mem"))
+ (callback (core func $i "cb")))))
+ (instance $c (instantiate $C))
+
+ (component $A
+ (import "g" (func $g async (result string)))
+ (core module $libc (memory (export "mem") 1))
+ (core instance $libc (instantiate $libc))
+ (core module $r
+ (tag $t)
+ (func (export "realloc") (param i32 i32 i32 i32) (result i32)
+ (throw $t)))
+ (core instance $r (instantiate $r))
+ (core func $g (canon lower (func $g) async
+ (memory (core memory $libc "mem"))
+ (realloc (core func $r "realloc"))))
+ (core module $m
+ (import "" "g" (func $g (param i32) (result i32)))
+ (func (export "run") (result i32)
+ (call $g (i32.const 16))))
+ (core instance $i
+ (instantiate $m (with "" (instance (export "g" (func $g))))))
+ (func (export "run") (result u32) (canon lift (core func $i "run"))))
+ (instance $a (instantiate $A (with "g" (func $c "g"))))
+ (export "run" (func $a "run")))
+
+(assert_trap (invoke "run") "uncaught exception propagated out of component")
+
+;; The callee's `realloc` is invoked when the caller's call lowers a `string`
+;; parameter into the callee. An exception thrown by it must trap rather than
+;; unwind into the caller's `try_table`.
+(component
+ (component $C
+ (core module $libc (memory (export "mem") 1))
+ (core instance $libc (instantiate $libc))
+ (core module $r
+ (tag $t)
+ (func (export "realloc") (param i32 i32 i32 i32) (result i32)
+ (throw $t)))
+ (core instance $r (instantiate $r))
+ (core func $task.return (canon task.return))
+ (core module $m
+ (import "" "task.return" (func $task.return))
+ (func (export "g") (param i32 i32) (result i32)
+ (call $task.return)
+ (i32.const 0 (; EXIT ;)))
+ (func (export "cb") (param i32 i32 i32) (result i32) unreachable))
+ (core instance $i (instantiate $m
+ (with "" (instance (export "task.return" (func $task.return))))))
+ (func (export "g") async (param "s" string)
+ (canon lift (core func $i "g") async
+ (memory (core memory $libc "mem"))
+ (realloc (core func $r "realloc"))
+ (callback (core func $i "cb")))))
+ (instance $c (instantiate $C))
+
+ (component $A
+ (import "g" (func $g async (param "s" string)))
+ (core module $libc
+ (memory (export "mem") 1)
+ (data (i32.const 0x100) "hello"))
+ (core instance $libc (instantiate $libc))
+ (core func $g (canon lower (func $g) async
+ (memory (core memory $libc "mem"))))
+ (core module $m
+ (import "" "g" (func $g (param i32 i32) (result i32)))
+ (func (export "run") (result i32)
+ (block $caught
+ (try_table (catch_all $caught)
+ (drop (call $g (i32.const 0x100) (i32.const 5))))
+ (return (i32.const 42 (; no leak ;))))
+ ;; the callee's exception leaked into this component
+ unreachable))
+ (core instance $i (instantiate $m
+ (with "" (instance (export "g" (func $g))))))
+ (func (export "run") (result u32) (canon lift (core func $i "run"))))
+ (instance $a (instantiate $A (with "g" (func $c "g"))))
+ (export "run" (func $a "run")))
+
+(assert_trap (invoke "run") "uncaught exception propagated out of component")
+
+;; A sync-lift `post-return` function that throws. The host runs it after the
+;; export returns; an exception escaping it is not caught by anything on the
+;; stack, so it must become an "uncaught exception" trap. (This path is sync,
+;; but the same `call_post_return` is used when a sync-lifted export is driven
+;; by the async event loop.)
+(component
+ (core module $r
+ (tag $t)
+ (func (export "post-return") (param i32)
+ (throw $t)))
+ (core instance $r (instantiate $r))
+ (core module $m
+ (func (export "g") (result i32) (i32.const 0)))
+ (core instance $i (instantiate $m))
+ (func (export "g") (result u32)
+ (canon lift (core func $i "g")
+ (post-return (core func $r "post-return")))))
+
+(assert_trap (invoke "g") "uncaught exception propagated out of component")
+
+;; The callee's `realloc`, invoked by the host to lower a `string` argument
+;; into the callee, throws. This lowering runs in host Rust code
+;; (`LowerContext::realloc`), not a fused adapter, so the exception must be
+;; converted to a trap there.
+(component
+ (core module $r
+ (tag $t)
+ (func (export "realloc") (param i32 i32 i32 i32) (result i32)
+ (throw $t)))
+ (core instance $r (instantiate $r))
+ (core module $libc (memory (export "mem") 1))
+ (core instance $libc (instantiate $libc))
+ (core module $m
+ (func (export "g") (param i32 i32) (result i32) (i32.const 0)))
+ (core instance $i (instantiate $m))
+ (func (export "g") (param "s" string) (result u32)
+ (canon lift (core func $i "g")
+ (memory (core memory $libc "mem"))
+ (realloc (core func $r "realloc")))))
+
+(assert_trap (invoke "g" (str.const "hello"))
+ "uncaught exception propagated out of component")
+
+;; The reader's `realloc` is invoked by the host while a `stream.write` copies a
+;; `string` into the reader. An exception thrown by it must trap rather than
+;; unwind into the writer's `try_table`. Unlike the adapter cases above this
+;; `realloc` runs in host Rust code (the stream copy), not inside an adapter.
+;; The reader stays alive (yields) so its read is still pending when the write
+;; drives the copy.
+(component
+ (component $C
+ (core module $libc (memory (export "mem") 1))
+ (core instance $libc (instantiate $libc))
+ (type $ST (stream string))
+ (core module $r
+ (tag $t)
+ (func (export "realloc") (param i32 i32 i32 i32) (result i32)
+ (throw $t)))
+ (core instance $r (instantiate $r))
+ (core func $stream.read
+ (canon stream.read $ST async (memory (core memory $libc "mem"))
+ (realloc (core func $r "realloc"))))
+ (core module $m
+ (import "" "stream.read"
+ (func $stream.read (param i32 i32 i32) (result i32)))
+ (func (export "start") (param i32) (result i32)
+ (drop
+ (call $stream.read (local.get 0) (i32.const 0x100) (i32.const 1)))
+ (i32.const 1 (; CALLBACK_CODE_YIELD, stay alive ;)))
+ (func (export "cb") (param i32 i32 i32) (result i32)
+ (i32.const 1 (; CALLBACK_CODE_YIELD ;))))
+ (core instance $i
+ (instantiate $m
+ (with "" (instance (export "stream.read" (func $stream.read))))))
+ (func (export "start") async (param "s" (stream string))
+ (canon lift (core func $i "start") async
+ (callback (core func $i "cb")))))
+
+ (component $D
+ (import "start" (func $start async (param "s" (stream string))))
+ (core module $libc
+ (memory (export "mem") 1)
+ (data (i32.const 0x200) "hi"))
+ (core instance $libc (instantiate $libc))
+ (type $ST (stream string))
+ (core func $start (canon lower (func $start) async))
+ (core func $stream.new (canon stream.new $ST))
+ (core func $stream.write
+ (canon stream.write $ST async (memory (core memory $libc "mem"))))
+ (core module $m
+ (import "" "mem" (memory 1))
+ (import "" "start" (func $start (param i32) (result i32)))
+ (import "" "stream.new" (func $stream.new (result i64)))
+ (import "" "stream.write"
+ (func $stream.write (param i32 i32 i32) (result i32)))
+ (func (export "run") (result i32)
+ (local $s i64) (local $r i32) (local $w i32)
+ (local.set $s (call $stream.new))
+ (local.set $r (i32.wrap_i64 (local.get $s)))
+ (local.set $w (i32.wrap_i64 (i64.shr_u (local.get $s) (i64.const 32))))
+ (drop (call $start (local.get $r)))
+ (i32.store (i32.const 0x100) (i32.const 0x200))
+ (i32.store (i32.const 0x104) (i32.const 2))
+ (block $caught
+ (try_table (catch_all $caught)
+ (drop
+ (call $stream.write (local.get $w) (i32.const 0x100)
+ (i32.const 1))))
+ (return (i32.const 42)))
+ ;; the reader's exception leaked into this component
+ unreachable))
+ (core instance $i (instantiate $m (with "" (instance
+ (export "mem" (memory $libc "mem"))
+ (export "start" (func $start))
+ (export "stream.new" (func $stream.new))
+ (export "stream.write" (func $stream.write))))))
+ (func (export "run") (result u32) (canon lift (core func $i "run"))))
+
+ (instance $c (instantiate $C))
+ (instance $d (instantiate $D (with "start" (func $c "start"))))
+ (func (export "run") (alias export $d "run")))
+
+(assert_trap (invoke "run") "uncaught exception propagated out of component")
diff --git a/tests/misc_testsuite/component-model/exceptions.wast b/tests/misc_testsuite/component-model/exceptions.wast
index 631150748d..ab866eded1 100644
--- a/tests/misc_testsuite/component-model/exceptions.wast
+++ b/tests/misc_testsuite/component-model/exceptions.wast
@@ -235,3 +235,15 @@
(export "run" (func $b "run"))
)
(assert_trap (invoke "run") "uncaught exception propagated out of component")
+
+;; A sync-lifted export whose own body throws with no handler. Invoking it
+;; directly must trap with an uncaught exception rather than letting the
+;; exception unwind out of the component to the host.
+(component
+ (core module $m
+ (tag $t)
+ (func (export "run") (throw $t)))
+ (core instance $i (instantiate $m))
+ (func (export "run") (canon lift (core func $i "run"))))
+
+(assert_trap (invoke "run") "uncaught exception propagated out of component")