Skip to content

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

Fix some store behavior when dropping async computations (#14557)

Alex Crichton6a6cdcf30ab0
diff --git a/crates/wasmtime/src/runtime/component/concurrent.rs b/crates/wasmtime/src/runtime/component/concurrent.rs
index b111d784a2..15d2bd7699 100644
--- a/crates/wasmtime/src/runtime/component/concurrent.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent.rs
@@ -1526,7 +1526,7 @@ impl<T> StoreContextMut<'_, T> {
if let Some(item) = self.ready.take() {
match item {
WorkItem::ResumeFiber { mut fiber, .. } => {
- fiber.dispose(self.store.0)
+ fiber.dispose(self.store.0);
}
WorkItem::PushFuture(future) => {
tls::set(self.store.0, move || drop(future))
@@ -1722,13 +1722,13 @@ impl<T> StoreContextMut<'_, T> {
pub(crate) async fn start_instance(
&mut self,
instance: ModuleInstance,
+ callee: Option<RuntimeInstance>,
) -> Result<ModuleInstance> {
let (tx, rx) = oneshot::channel();
let token = StoreToken::new(self.as_context_mut());
self.0.queue_task(move |store| {
_ = tx.send(
- instance
- .start_raw(&mut token.as_context_mut(store))
+ super::instance::start_raw(&mut token.as_context_mut(store), instance, callee)
.map(|()| instance),
);
Ok(())
diff --git a/crates/wasmtime/src/runtime/component/instance.rs b/crates/wasmtime/src/runtime/component/instance.rs
index 548024c22b..c6e81058a1 100644
--- a/crates/wasmtime/src/runtime/component/instance.rs
+++ b/crates/wasmtime/src/runtime/component/instance.rs
@@ -815,18 +815,8 @@ impl<'a> Instantiator<'a> {
}
};
- let exit = if let Some(component_instance) = *component_instance {
- store.0.enter_guest_sync_call(
- false,
- RuntimeInstance {
- instance,
- index: component_instance,
- },
- )?;
- true
- } else {
- false
- };
+ let callee =
+ component_instance.map(|index| RuntimeInstance { instance, index });
// Note that the unsafety here should be ok because the
// validity of the component means that type-checks have
@@ -852,7 +842,7 @@ impl<'a> Instantiator<'a> {
if needs_startup {
if asyncness == Asyncness::No {
- instance.start_raw(store)?;
+ start_raw(store, instance, callee)?;
} else {
#[cfg(feature = "async")]
{
@@ -864,15 +854,19 @@ impl<'a> Instantiator<'a> {
// event loop in case it calls async
// functions or intrinsics, creates and
// resumes threads, etc.
- instance = store.start_instance(instance).await?;
+ instance = store.start_instance(instance, callee).await?;
} else {
- store.on_fiber(|store| instance.start_raw(store)).await??;
+ store
+ .on_fiber(|store| start_raw(store, instance, callee))
+ .await??;
}
}
#[cfg(not(feature = "component-model-async"))]
{
_ = &mut instance;
- store.on_fiber(|store| instance.start_raw(store)).await??;
+ store
+ .on_fiber(|store| start_raw(store, instance, callee))
+ .await??;
}
}
#[cfg(not(feature = "async"))]
@@ -883,10 +877,6 @@ impl<'a> Instantiator<'a> {
}
}
- if exit {
- store.0.exit_guest_sync_call()?;
- }
-
self.instance_mut(store.0).push_instance_id(instance.id())?;
}
@@ -1087,6 +1077,25 @@ impl<'a> Instantiator<'a> {
}
}
+/// Runs the start function of the core wasm `instance`.
+///
+/// If `callee` is specified then the start function is run as a sync-lifted
+/// call into that component instance.
+pub(crate) fn start_raw<T>(
+ store: &mut StoreContextMut<'_, T>,
+ instance: crate::Instance,
+ callee: Option<RuntimeInstance>,
+) -> Result<()> {
+ if let Some(callee) = callee {
+ store.0.enter_guest_sync_call(false, callee)?;
+ }
+ instance.start_raw(store)?;
+ if callee.is_some() {
+ store.0.exit_guest_sync_call()?;
+ }
+ Ok(())
+}
+
/// A "pre-instantiated" [`Instance`] which has all of its arguments already
/// supplied and is ready to instantiate.
///
diff --git a/crates/wasmtime/src/runtime/component/resources/any.rs b/crates/wasmtime/src/runtime/component/resources/any.rs
index 4d938ca89e..18b265cb44 100644
--- a/crates/wasmtime/src/runtime/component/resources/any.rs
+++ b/crates/wasmtime/src/runtime/component/resources/any.rs
@@ -325,14 +325,18 @@ impl ResourceAny {
// destructors have al been previously type-checked and are guaranteed
// to take one i32 argument and return no results, so the parameters
// here should be configured correctly.
- unsafe {
+ let result = unsafe {
crate::Func::call_unchecked_raw(
store,
dtor,
NonNull::from(&mut args),
UncaughtException::Trap,
- )?;
+ )
+ };
+ if result.is_err() {
+ store.0.set_trapped();
}
+ result?;
if slot.instance.is_some() {
store.0.exit_guest_sync_call()?;
diff --git a/crates/wasmtime/src/runtime/fiber.rs b/crates/wasmtime/src/runtime/fiber.rs
index 89c5d49b82..8511df2f6c 100644
--- a/crates/wasmtime/src/runtime/fiber.rs
+++ b/crates/wasmtime/src/runtime/fiber.rs
@@ -452,13 +452,19 @@ impl<'a> StoreFiber<'a> {
self.fiber.take().map(|f| f.into_inner().0.into_stack())
}
- pub(crate) fn dispose(&mut self, store: &mut StoreOpaque) {
+ /// Cancels this fiber, if it's still in progress, by resuming it with an
+ /// error so that it unwinds and completes.
+ ///
+ /// Returns whether the fiber was in progress and had to be cancelled.
+ pub(crate) fn dispose(&mut self, store: &mut StoreOpaque) -> bool {
if let Some(fiber) = self.fiber() {
if !fiber.done() {
let result = resume_fiber(store, self, Err(format_err!("future dropped")));
debug_assert!(result.is_ok());
+ return true;
}
}
+ false
}
#[cfg(all(feature = "component-model-async", feature = "gc"))]
@@ -1007,7 +1013,14 @@ impl<'b> Future for FiberFuture<'_, 'b> {
impl Drop for FiberFuture<'_, '_> {
fn drop(&mut self) {
if let Some(fiber) = &mut self.fiber {
- fiber.dispose(self.store);
+ let cancelled = fiber.dispose(self.store);
+
+ // If the fiber was cancelled partway through then whatever it was
+ // doing has been abandoned, and whatever it was doing may only be
+ // partially reflected within the store, so lock down the store.
+ if cancelled {
+ self.store.set_trapped();
+ }
}
}
}
diff --git a/crates/wasmtime/src/runtime/func.rs b/crates/wasmtime/src/runtime/func.rs
index 2ed8f7b2c0..f8c44c0d84 100644
--- a/crates/wasmtime/src/runtime/func.rs
+++ b/crates/wasmtime/src/runtime/func.rs
@@ -1487,7 +1487,6 @@ pub(crate) fn invoke_wasm_and_catch_traps<T>(
uncaught_exception,
closure,
);
- #[cfg(feature = "component-model")]
if result.is_err() {
store.0.set_trapped();
}
diff --git a/crates/wasmtime/src/runtime/store.rs b/crates/wasmtime/src/runtime/store.rs
index 21b54c5b69..de8b7714f9 100644
--- a/crates/wasmtime/src/runtime/store.rs
+++ b/crates/wasmtime/src/runtime/store.rs
@@ -2300,6 +2300,9 @@ at https://bytecodealliance.org/security.
// otherwise fall back to the runtime-agnostic code.
yield_now().await
}
+
+ #[cfg(not(feature = "component-model"))]
+ pub(crate) fn set_trapped(&mut self) {}
}
#[cfg(any(feature = "async", feature = "gc"))]
diff --git a/tests/all/component_model/async.rs b/tests/all/component_model/async.rs
index f2e863aaac..b3cb7dc55b 100644
--- a/tests/all/component_model/async.rs
+++ b/tests/all/component_model/async.rs
@@ -1870,3 +1870,233 @@ async fn start_function_trap_reported_faithfully() -> Result<()> {
assert_eq!(err.downcast::<Trap>()?, Trap::UnreachableCodeReached);
Ok(())
}
+
+const DROP_MID_FLIGHT_WAT: &str = r#"
+(component
+ (core func $task.return (canon task.return))
+ (core module $m
+ (import "" "task.return" (func $tr))
+ (memory 1)
+ (func (export "run") (result i32) (call $tr) (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 "run") async (canon lift (core func $i "run") async (callback (core func $i "cb"))))
+)
+"#;
+
+#[tokio::test]
+#[cfg_attr(miri, ignore)]
+async fn drop_instantiate_async_blocked_in_limiter() -> Result<()> {
+ struct Limiter {
+ block: bool,
+ }
+
+ #[async_trait::async_trait]
+ impl wasmtime::ResourceLimiterAsync for Limiter {
+ async fn memory_growing(&mut self, _: usize, _: usize, _: Option<usize>) -> Result<bool> {
+ if self.block {
+ std::future::pending::<()>().await;
+ }
+ Ok(true)
+ }
+ async fn table_growing(&mut self, _: usize, _: usize, _: Option<usize>) -> Result<bool> {
+ Ok(true)
+ }
+ }
+
+ let mut config = Config::new();
+ config.wasm_component_model_async(true);
+ let engine = Engine::new(&config)?;
+ let component = Component::new(&engine, DROP_MID_FLIGHT_WAT)?;
+ let linker = Linker::new(&engine);
+ let mut store = Store::new(&engine, Limiter { block: true });
+ store.limiter_async(|l| l);
+
+ let future = Box::pin(linker.instantiate_async(&mut store, &component));
+ assert!(PollOnce::new(future).await.is_err());
+
+ // Using the store afterwards shouldn't panic...
+ store.data_mut().block = false;
+ let instance = linker.instantiate_async(&mut store, &component).await?;
+ let run = instance.get_typed_func::<(), ()>(&mut store, "run")?;
+ store
+ .run_concurrent(async |a| run.call_concurrent(a, ()).await)
+ .await??;
+ run.call_async(&mut store, ()).await?;
+
+ Ok(())
+}
+
+#[derive(Clone, Copy, PartialEq)]
+enum BlockingCallHook {
+ Calling,
+ Returning,
+}
+
+struct BlockingCallHookHandler(Arc<Mutex<Option<BlockingCallHook>>>);
+
+#[async_trait::async_trait]
+impl<T: Send> wasmtime::CallHookHandler<T> for BlockingCallHookHandler {
+ async fn handle_call_event(
+ &self,
+ _: wasmtime::StoreHookState<'_, T>,
+ ch: wasmtime::CallHook,
+ ) -> Result<()> {
+ let which = match ch {
+ wasmtime::CallHook::CallingWasm => BlockingCallHook::Calling,
+ wasmtime::CallHook::ReturningFromWasm => BlockingCallHook::Returning,
+ _ => return Ok(()),
+ };
+ if *self.0.lock().unwrap() == Some(which) {
+ std::future::pending::<()>().await;
+ }
+ Ok(())
+ }
+}
+
+// Dropping `run_concurrent` while a guest call is blocked in an async call
+// hook abandons that call partway through, so the store must be poisoned
+// rather than left with a stale current guest task.
+async fn drop_run_concurrent_blocked_in_call_hook(which: BlockingCallHook) -> Result<()> {
+ let mut config = Config::new();
+ config.wasm_component_model_async(true);
+ let engine = Engine::new(&config)?;
+ let component = Component::new(&engine, DROP_MID_FLIGHT_WAT)?;
+ let mut store = Store::new(&engine, ());
+ let block = Arc::new(Mutex::new(None));
+ store.call_hook_async(BlockingCallHookHandler(block.clone()));
+ let linker = Linker::new(&engine);
+ let instance = linker.instantiate_async(&mut store, &component).await?;
+ let run = instance.get_typed_func::<(), ()>(&mut store, "run")?;
+
+ *block.lock().unwrap() = Some(which);
+ let future = Box::pin(store.run_concurrent(async |a| run.call_concurrent(a, ()).await));
+ assert!(PollOnce::new(future).await.is_err());
+ *block.lock().unwrap() = None;
+
+ let err = store
+ .run_concurrent(async |a| run.call_concurrent(a, ()).await)
+ .await?
+ .unwrap_err();
+ assert_eq!(
+ err.downcast_ref::<Trap>(),
+ Some(&Trap::CannotEnterComponent)
+ );
+
+ Ok(())
+}
+
+#[tokio::test]
+#[cfg_attr(miri, ignore)]
+async fn drop_run_concurrent_blocked_in_calling_hook() -> Result<()> {
+ drop_run_concurrent_blocked_in_call_hook(BlockingCallHook::Calling).await
+}
+
+#[tokio::test]
+#[cfg_attr(miri, ignore)]
+async fn drop_run_concurrent_blocked_in_returning_hook() -> Result<()> {
+ drop_run_concurrent_blocked_in_call_hook(BlockingCallHook::Returning).await
+}
+
+// Dropping `instantiate_async` while a core module's start function is blocked
+// in an async call hook abandons the start function partway through, so the
+// store must be poisoned.
+#[tokio::test]
+#[cfg_attr(miri, ignore)]
+async fn drop_instantiate_async_blocked_in_start_call_hook() -> Result<()> {
+ let mut config = Config::new();
+ config.wasm_component_model_async(true);
+ let engine = Engine::new(&config)?;
+ let with_start = Component::new(
+ &engine,
+ r#"
+(component
+ (core module $m
+ (func $start)
+ (start $start))
+ (core instance $i (instantiate $m))
+)
+ "#,
+ )?;
+ let component = Component::new(&engine, DROP_MID_FLIGHT_WAT)?;
+ let mut store = Store::new(&engine, ());
+ let block = Arc::new(Mutex::new(Some(BlockingCallHook::Calling)));
+ store.call_hook_async(BlockingCallHookHandler(block.clone()));
+ let linker = Linker::new(&engine);
+
+ let future = Box::pin(linker.instantiate_async(&mut store, &with_start));
+ assert!(PollOnce::new(future).await.is_err());
+ *block.lock().unwrap() = None;
+
+ let instance = linker.instantiate_async(&mut store, &component).await?;
+ let run = instance.get_typed_func::<(), ()>(&mut store, "run")?;
+ let err = store
+ .run_concurrent(async |a| run.call_concurrent(a, ()).await)
+ .await?
+ .unwrap_err();
+ assert_eq!(
+ err.downcast_ref::<Trap>(),
+ Some(&Trap::CannotEnterComponent)
+ );
+
+ Ok(())
+}
+
+// A call hook failing while `ResourceAny::resource_drop_async` enters the
+// guest to run a destructor must poison the store.
+#[tokio::test]
+#[cfg_attr(miri, ignore)]
+async fn resource_drop_call_hook_error() -> Result<()> {
+ let engine = Engine::default();
+ let component = Component::new(
+ &engine,
+ r#"
+(component
+ (core module $d (func (export "dtor") (param i32)))
+ (core instance $d (instantiate $d))
+ (type $r (resource (rep i32) (dtor (core func $d "dtor"))))
+ (core func $new (canon resource.new $r))
+ (core module $m
+ (import "" "new" (func $new (param i32) (result i32)))
+ (func (export "mk") (result i32) (call $new (i32.const 7)))
+ (func (export "nop")))
+ (core instance $i (instantiate $m
+ (with "" (instance (export "new" (func $new))))))
+ (export $r2 "r" (type $r))
+ (func (export "mk") (result (own $r2)) (canon lift (core func $i "mk")))
+ (func (export "nop") (canon lift (core func $i "nop")))
+)
+ "#,
+ )?;
+ let mut store = Store::new(&engine, false);
+ let instance = Linker::new(&engine)
+ .instantiate_async(&mut store, &component)
+ .await?;
+ let mk = instance.get_typed_func::<(), (ResourceAny,)>(&mut store, "mk")?;
+ let nop = instance.get_typed_func::<(), ()>(&mut store, "nop")?;
+ let (r,) = mk.call_async(&mut store, ()).await?;
+
+ store.call_hook(|store, hook| {
+ if *store.data() && matches!(hook, wasmtime::CallHook::CallingWasm) {
+ wasmtime::bail!("hook error");
+ }
+ Ok(())
+ });
+ *store.data_mut() = true;
+ let err = r.resource_drop_async(&mut store).await.unwrap_err();
+ assert_eq!(err.to_string(), "hook error");
+ *store.data_mut() = false;
+
+ let err = store
+ .run_concurrent(async |a| nop.call_concurrent(a, ()).await)
+ .await
+ .and_then(|r| r)
+ .unwrap_err();
+ assert_eq!(
+ err.downcast_ref::<Trap>(),
+ Some(&Trap::CannotEnterComponent),
+ "unexpected error: {err:?}"
+ );
+
+ Ok(())
+}