A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
disallow [Typed]Func::call from async context (#14734)
Alex Crichton79a6098bc744
diff --git a/crates/wasmtime/src/runtime/component/func.rs b/crates/wasmtime/src/runtime/component/func.rsindex 9595f102dc..00f83dec9c 100644--- a/crates/wasmtime/src/runtime/component/func.rs+++ b/crates/wasmtime/src/runtime/component/func.rs@@ -247,6 +247,7 @@ impl Func {/// * The function calls a host function which returns an error/// * The `store` used requires the use of [`Func::call_async`] instead. See/// [store documentation](crate#async) for more information.+ /// * The call is recursive from within e.g. a `call_async` invocation./// * If the function is async-lifted, in which case either/// [`Self::call_async`] or [`Self::call_concurrent`] must be used.///diff --git a/crates/wasmtime/src/runtime/component/func/typed.rs b/crates/wasmtime/src/runtime/component/func/typed.rsindex 597afcfe0f..5e5ed978e9 100644--- a/crates/wasmtime/src/runtime/component/func/typed.rs+++ b/crates/wasmtime/src/runtime/component/func/typed.rs@@ -126,6 +126,7 @@ where/// instance is currently calling a host function./// * If `store` requires using [`Self::call_async`] instead, see/// [crate documentation](crate#async) for more info.+ /// * The call is recursive from within e.g. a `call_async` invocation./// * If the function is async-lifted, in which case either/// [`Self::call_async`] or [`Self::call_concurrent`] must be used.///diff --git a/crates/wasmtime/src/runtime/component/resources/any.rs b/crates/wasmtime/src/runtime/component/resources/any.rsindex 5fdc02a52a..7a2f3c696a 100644--- a/crates/wasmtime/src/runtime/component/resources/any.rs+++ b/crates/wasmtime/src/runtime/component/resources/any.rs@@ -238,6 +238,9 @@ impl ResourceAny {/// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when/// memory allocation fails. See the `OutOfMemory` type's documentation for/// details on Wasmtime's out-of-memory handling.+ ///+ /// This will also return an error if called recursively from within e.g. a+ /// `call_async` invocation.pub fn resource_drop(self, mut store: impl AsContextMut) -> Result<()> {let mut store = store.as_context_mut();store.0.validate_sync_call()?;diff --git a/crates/wasmtime/src/runtime/func.rs b/crates/wasmtime/src/runtime/func.rsindex f8c44c0d84..48ad6317cc 100644--- a/crates/wasmtime/src/runtime/func.rs+++ b/crates/wasmtime/src/runtime/func.rs@@ -943,6 +943,7 @@ impl Func {/// via [`Func::new`], for example./// * The `store` provided is configured to require `call_async` to be used/// instead, such as with epochs or fuel.+ /// * The call is recursive from within e.g. a `call_async` invocation.////// Errors typically indicate that execution of WebAssembly was halted/// mid-way and did not complete after the error condition happened.@@ -1004,6 +1005,7 @@ impl Func {/// types and such./// * Reference types like `externref` and `funcref` are valid at the/// time of this call and for the `store` specified.+ /// * The call is _not_ recursive from within e.g. a `call_async` invocation.////// These invariants are all upheld for you with [`Func::call`] and/// [`TypedFunc::call`].diff --git a/crates/wasmtime/src/runtime/store.rs b/crates/wasmtime/src/runtime/store.rsindex 573679983d..ace96cef00 100644--- a/crates/wasmtime/src/runtime/store.rs+++ b/crates/wasmtime/src/runtime/store.rs@@ -2277,11 +2277,20 @@ at https://bytecodealliance.org/security.}#[inline]- pub(crate) fn validate_sync_call(&self) -> Result<()> {+ pub(crate) fn validate_sync_call(&mut self) -> Result<()> {#[cfg(feature = "async")]if self.async_state.async_required {bail!("store configuration requires that `*_async` functions are used instead");}+ // We disallow `[Typed]Func::call` from a fiber since it can lead to+ // e.g. GC or epoch interruption which suspends the fiber, potentially+ // returning control to the embedder and allowing it to poll a top-level+ // `call_async` future from another thread, effectively and unsoundly+ // sending `!Send` data across threads. In addition, allowing such+ // recursion risks panicking on stack overflow.+ if self.can_block() {+ bail!("cannot do blocking `call` from an async context");+ }Ok(())}diff --git a/tests/all/async_functions.rs b/tests/all/async_functions.rsindex 19aed57e09..4d42c7f352 100644--- a/tests/all/async_functions.rs+++ b/tests/all/async_functions.rs@@ -1,5 +1,6 @@use std::future::Future;use std::pin::Pin;+use std::rc::Rc;use std::sync::atomic::AtomicUsize;use std::sync::atomic::Ordering;use std::sync::{Arc, Mutex};@@ -1142,3 +1143,121 @@ async fn async_gc_with_func_new_and_func_wrap() -> Result<()> {Ok(())}++#[test]+#[cfg_attr(miri, ignore)]+fn sync_call_from_fiber() -> Result<()> {+ let mut config = Config::new();+ config.wasm_gc(true);+ let engine = Engine::new(&config)?;+ let module = Module::new(+ &engine,+ r#"(module+ (type $s (struct (field i64)))+ (import "host" "f" (func $f))+ (func (export "outer") call $f)+ (func (export "inner")+ (local $i i32)+ (loop $l+ (drop (struct.new $s (i64.const 0)))+ (local.set $i (i32.add (local.get $i) (i32.const 1)))+ (br_if $l (i32.lt_u (local.get $i) (i32.const 2000000))))))"#,+ )?;+ let mut linker = Linker::<()>::new(&engine);+ linker.func_wrap("host", "f", |mut caller: Caller<'_, ()>| -> Result<()> {+ let not_send = Rc::new(());+ let before = std::thread::current().id();+ let inner = caller.get_export("inner").unwrap().into_func().unwrap();+ inner.typed::<(), ()>(&caller)?.call(&mut caller, ())?;+ // As of this writing, the above call should return an error, but in+ // case we ever _do_ support recursive `Func::call` on a fiber, the+ // following assertion should hold:+ let after = std::thread::current().id();+ _ = Rc::strong_count(¬_send);+ assert_eq!(before, after);+ Ok(())+ })?;+ let mut store = Store::new(&engine, ());+ let inst = linker.instantiate(&mut store, &module)?;+ let outer = inst.get_typed_func::<(), ()>(&mut store, "outer")?;+ let mut fut: Pin<Box<dyn Future<Output = Result<()>> + Send>> =+ Box::pin(async move { outer.call_async(&mut store, ()).await });+ if let Poll::Ready(r) = fut.as_mut().poll(&mut Context::from_waker(Waker::noop())) {+ let err = r.unwrap_err();+ assert!(+ format!("{err:?}").contains("cannot do blocking `call` from an async context"),+ "{err:?}"+ );+ return Ok(());+ }+ // As of this writing, we'll never reach this point, but see the comment+ // about supporting `Func::call` on a fiber above.+ std::thread::spawn(move || {+ loop {+ if let Poll::Ready(r) = fut.as_mut().poll(&mut Context::from_waker(Waker::noop())) {+ return r;+ }+ }+ })+ .join()+ .unwrap()?;+ Ok(())+}++#[tokio::test]+#[cfg_attr(miri, ignore)]+async fn recurse_async() -> Result<()> {+ const WAT: &str = r#"+(module+ (import "host" "reenter" (func $reenter (param i32)))+ ;; burn roughly `n` frames of stack, then call into the host+ (func $burn (param $n i32) (param $level i32)+ (local i64 i64 i64 i64 i64 i64 i64 i64)+ local.get $n+ if+ local.get $n+ i32.const 1+ i32.sub+ local.get $level+ call $burn+ else+ local.get $level+ call $reenter+ end)+ (func (export "f") (param $level i32)+ i32.const 2000+ local.get $level+ call $burn)+)+"#;++ let engine = Engine::default();+ let module = Module::new(&engine, WAT)?;+ let mut store = Store::new(&engine, None::<Func>);+ let reenter = Func::wrap(+ &mut store,+ |mut caller: Caller<'_, Option<Func>>, level: i32| -> Result<()> {+ let f = caller.data().unwrap();+ f.call(&mut caller, &[Val::I32(level + 1)], &mut [])+ },+ );+ let instance = Instance::new(&mut store, &module, &[reenter.into()])?;+ let f = instance.get_func(&mut store, "f").unwrap();+ *store.data_mut() = Some(f);++ let r = f.call(&mut store, &[Val::I32(0)], &mut []);+ let err = r.unwrap_err();+ assert!(+ format!("{err:?}").contains("call stack exhausted"),+ "{err:?}"+ );++ let r = f.call_async(&mut store, &[Val::I32(0)], &mut []).await;+ let err = r.unwrap_err();+ assert!(+ format!("{err:?}").contains("cannot do blocking `call` from an async context"),+ "{err:?}"+ );++ Ok(())+}diff --git a/tests/all/component_model/resources.rs b/tests/all/component_model/resources.rsindex 4dd4be0329..99e634615d 100644--- a/tests/all/component_model/resources.rs+++ b/tests/all/component_model/resources.rs@@ -2133,15 +2133,15 @@ mod multiple_host_borrows {run(Kind::New).await}- fn drop_val(store: &mut wasmtime::StoreContextMut<'_, ()>, val: &Val) -> Result<()> {+ async fn drop_val(store: &mut wasmtime::StoreContextMut<'_, ()>, val: &Val) -> Result<()> {match val {Val::Resource(r) => {assert!(!r.owned());- r.resource_drop(&mut *store)+ r.resource_drop_async(&mut *store).await}Val::List(vals) => {for v in vals {- drop_val(store, v)?;+ Box::pin(drop_val(store, v)).await?;}Ok(())}@@ -2162,26 +2162,32 @@ mod multiple_host_borrows {match kind {Kind::Wrap => {- root.func_wrap("two", |mut store, (a, b): (ResourceAny, ResourceAny)| {- a.resource_drop(&mut store)?;- b.resource_drop(&mut store)?;- Ok(())+ root.func_wrap_async("two", |mut store, (a, b): (ResourceAny, ResourceAny)| {+ Box::new(async move {+ a.resource_drop_async(&mut store).await?;+ b.resource_drop_async(&mut store).await?;+ Ok(())+ })})?;- root.func_wrap("list", |mut store, (list,): (Vec<ResourceAny>,)| {- assert_eq!(list.len(), 3);- for r in list {- r.resource_drop(&mut store)?;- }- Ok(())+ root.func_wrap_async("list", |mut store, (list,): (Vec<ResourceAny>,)| {+ Box::new(async move {+ assert_eq!(list.len(), 3);+ for r in list {+ r.resource_drop_async(&mut store).await?;+ }+ Ok(())+ })})?;}Kind::New => {for name in ["two", "list"] {- root.func_new(name, |mut store, _ty, params, _results| {- for p in params {- drop_val(&mut store, p)?;- }- Ok(())+ root.func_new_async(name, |mut store, _ty, params, _results| {+ Box::new(async move {+ for p in params {+ drop_val(&mut store, p).await?;+ }+ Ok(())+ })})?;}}