A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Fix a `bail_bug!` running wasm from `poll_{produce,consume}` (#14750)
Alex Crichton5af334209f6a
diff --git a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rsindex a2b69f0cdc..5bb3163fdc 100644--- a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs+++ b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs@@ -1,6 +1,8 @@use super::table::{TableDebug, TableId};use super::{Event, GlobalErrorContextRefCount, Waitable, WaitableCommon};-use crate::component::concurrent::{ConcurrentState, QualifiedThreadId, WorkItem, tls};+use crate::component::concurrent::{+ ConcurrentState, CurrentThread, QualifiedThreadId, WorkItem, tls,+};use crate::component::func::{self, LiftContext, LowerContext};use crate::component::matching::InstanceType;use crate::component::resources::{HostResourceIndex, HostResourceTables};@@ -3202,8 +3204,28 @@ async fn write<D: 'static, P: Send + 'static, T: func::Lower + 'static, B: Write}}+/// Polls a `StreamProducer` or `StreamConsumer` future once, inline, from+/// within a guest's `{stream,future}.{read,write}` intrinsic.+///+/// The producer or consumer is embedder code which doesn't belong to the+/// reading or writing guest's task, so it's polled as though from the+/// top-level host, just as it is when it's later polled from the event loop.+fn poll_inline(+ store: &mut dyn VMStore,+ future: &mut Pin<Box<dyn Future<Output = Result<StreamResult>> + Send + 'static>>,+) -> Result<Poll<Result<StreamResult>>> {+ let old_thread = store.set_thread(CurrentThread::None)?;+ let poll = tls::set(store, || {+ future+ .as_mut()+ .poll(&mut Context::from_waker(&Waker::noop()))+ });+ store.set_thread(old_thread)?;+ Ok(poll)+}+impl Instance {- /// Handle a host- or guest-initiated write by delivering the item(s) to the+ /// Handle a guest-initiated write by delivering the item(s) to the/// `StreamConsumer` for the specified stream or future.fn consume(self,@@ -3221,11 +3243,7 @@ impl Instance {cancel,cancel_waker: None,};- let poll = tls::set(store, || {- future- .as_mut()- .poll(&mut Context::from_waker(&Waker::noop()))- });+ let poll = poll_inline(store, &mut future)?;Ok(match poll {Poll::Ready(state) => {@@ -3241,8 +3259,8 @@ impl Instance {})}- /// Handle a host- or guest-initiated read by polling the `StreamProducer`- /// for the specified stream or future for items.+ /// Handle a guest-initiated read by polling the `StreamProducer` for the+ /// specified stream or future for items.fn produce(self,store: &mut dyn VMStore,@@ -3261,11 +3279,7 @@ impl Instance {cancel,cancel_waker: None,};- let poll = tls::set(store, || {- future- .as_mut()- .poll(&mut Context::from_waker(&Waker::noop()))- });+ let poll = poll_inline(store, &mut future)?;Ok(match poll {Poll::Ready(state) => {diff --git a/tests/all/component_model/async.rs b/tests/all/component_model/async.rsindex 00c9b99a2d..5df0262216 100644--- a/tests/all/component_model/async.rs+++ b/tests/all/component_model/async.rs@@ -3396,3 +3396,63 @@ async fn yield_callback_after_dropped_event_loop() -> Result<()> {store.assert_concurrent_state_empty();Ok(())}++#[tokio::test]+#[cfg_attr(miri, ignore)]+async fn start_call_from_inline_stream_producer() -> Result<()> {+ // `read`'s `stream.read` polls the host producer below inline, and the+ // producer starts a concurrent call to `thunk`.+ let component = r#"+(component+ (type $s (stream u8))+ (core module $libc (memory (export "memory") 1))+ (core instance $libc (instantiate $libc))+ (core func $stream.read (canon stream.read $s async (memory (core memory $libc "memory"))))+ (core module $m+ (import "" "stream.read" (func $stream.read (param i32 i32 i32) (result i32)))+ (func (export "thunk"))+ (func (export "read") (param $reader i32) (result i32)+ (call $stream.read (local.get $reader) (i32.const 0) (i32.const 1)))+ )+ (core instance $i (instantiate $m (with "" (instance+ (export "stream.read" (func $stream.read))+ ))))+ (func (export "thunk") (canon lift (core func $i "thunk")))+ (func (export "read") (param "s" $s) (result u32) (canon lift (core func $i "read")))+)+"#;++ struct Producer;++ impl StreamProducer<Option<TypedFunc<(), ()>>> for Producer {+ type Item = u8;+ type Buffer = Option<u8>;++ fn poll_produce<'a>(+ self: Pin<&mut Self>,+ _cx: &mut Context<'_>,+ mut store: StoreContextMut<'a, Option<TypedFunc<(), ()>>>,+ mut destination: Destination<'a, u8, Option<u8>>,+ _finish: bool,+ ) -> Poll<Result<StreamResult>> {+ let thunk = store.data().unwrap();+ // This at least shouldn't panic...+ _ = thunk.start_call_concurrent(&mut store, ())?;+ destination.set_buffer(Some(0));+ Poll::Ready(Ok(StreamResult::Completed))+ }+ }++ let engine = super::async_engine();+ let component = Component::new(&engine, component)?;+ let mut store = Store::new(&engine, None);+ let instance = Linker::new(&engine)+ .instantiate_async(&mut store, &component)+ .await?;+ *store.data_mut() = Some(instance.get_typed_func(&mut store, "thunk")?);+ let read = instance.get_typed_func::<(StreamReader<u8>,), (u32,)>(&mut store, "read")?;+ let reader = StreamReader::new(&mut store, Producer)?;+ let (code,) = read.call_async(&mut store, (reader,)).await?;+ assert_eq!(code, 1 << 4 /* COMPLETED, 1 item */);+ Ok(())+}