Skip to content

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

return error instead of panicking on host stream type mismatch (#14733)

Alex Crichtonafde5b46892c
diff --git a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs
index 8c56cdf230..a2b69f0cdc 100644
--- a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs
@@ -2984,7 +2984,7 @@ impl<T> StoreContextMut<'_, T> {
transmit.read = ReadState::HostToHost {
accept: Box::new(move |input| {
let consume = consume_with_buffer.clone();
- async move { consume(Some(input.get_mut::<C::Item>())).await }.boxed()
+ async move { consume(Some(input.get_mut::<C::Item>()?)).await }.boxed()
}),
buffer: Vec::new(),
limit: 0,
diff --git a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams/buffers.rs b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams/buffers.rs
index e65fbfc28b..9f2cd16c09 100644
--- a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams/buffers.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams/buffers.rs
@@ -10,6 +10,7 @@ pub use untyped::*;
mod untyped {
use super::WriteBuffer;
use crate::vm::SendSyncPtr;
+ use crate::{Result, bail};
use core::any::TypeId;
use core::marker;
use core::mem;
@@ -62,21 +63,23 @@ mod untyped {
/// Acquires the underlying `WriteBuffer<T>` this was created with.
///
- /// # Panics
- ///
- /// Panics if `T` does not match the type that this was created with.
- pub fn get_mut<T: 'static>(&mut self) -> &mut dyn WriteBuffer<T> {
- assert_eq!(self.element_type_id, TypeId::of::<T>());
+ /// Returns an error if `T` does not match the type that this was
+ /// created with.
+ pub fn get_mut<T: 'static>(&mut self) -> Result<&mut dyn WriteBuffer<T>> {
+ if self.element_type_id != TypeId::of::<T>() {
+ bail!("host stream item type mismatch")
+ }
+
// SAFETY: the `T` has been checked with `TypeId` and this
// structure also is proof of valid existence of the original
// `&mut WriteBuffer<T>`, so taking the raw pointer back to a safe
// reference is valid.
- unsafe {
+ Ok(unsafe {
&mut *ReinterpretWriteBuffer {
untyped: self.buf.as_ptr(),
}
.typed
- }
+ })
}
}
}
diff --git a/tests/all/component_model/async.rs b/tests/all/component_model/async.rs
index 3edc8e8140..00c9b99a2d 100644
--- a/tests/all/component_model/async.rs
+++ b/tests/all/component_model/async.rs
@@ -4,6 +4,7 @@ use std::collections::HashMap;
use std::future::{self, Future};
use std::iter;
use std::mem;
+use std::ops::DerefMut;
use std::pin::{Pin, pin};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
@@ -2350,6 +2351,76 @@ async fn drop_call_async_with_queued_start() -> Result<()> {
Ok(())
}
+#[tokio::test]
+#[cfg_attr(miri, ignore)]
+async fn host_to_host_stream_buffer_type_mismatch() -> wasmtime::Result<()> {
+ // A component that echoes a `stream<list<u8>>` back to the caller.
+ const WAT: &str = r#"
+(component
+ (type $s (stream (list u8)))
+ (core module $m
+ (func (export "echo") (param i32) (result i32) local.get 0))
+ (core instance $i (instantiate $m))
+ (func (export "echo-stream") (param "s" $s) (result $s)
+ (canon lift (core func $i "echo")))
+)
+"#;
+
+ let engine = Engine::default();
+ let component = Component::new(&engine, WAT)?;
+ let mut store = Store::new(&engine, ());
+ let instance = Linker::new(&engine)
+ .instantiate_async(&mut store, &component)
+ .await?;
+
+ // Created as `Vec<u8>` items, read back as `WasmList<u8>` items.
+ let echo = instance.get_typed_func::<(StreamReader<Vec<u8>>,), (StreamReader<WasmList<u8>>,)>(
+ &mut store,
+ "echo-stream",
+ )?;
+ let input = vec![1u8, 2, 3];
+ let reader = StreamReader::new(&mut store, vec![input.clone()])?;
+ let (reader,) = echo.call_async(&mut store, (reader,)).await?;
+
+ struct Consumer(Arc<Mutex<Vec<WasmList<u8>>>>);
+
+ impl StreamConsumer<()> for Consumer {
+ type Item = WasmList<u8>;
+
+ fn poll_consume(
+ self: Pin<&mut Self>,
+ _cx: &mut Context<'_>,
+ mut store: StoreContextMut<()>,
+ mut source: Source<'_, WasmList<u8>>,
+ _finish: bool,
+ ) -> Poll<Result<StreamResult>> {
+ let mut buffer = self.0.try_lock().unwrap();
+ buffer.reserve(source.remaining(&mut store)?);
+ source.read(store, buffer.deref_mut())?;
+ Poll::Ready(Ok(StreamResult::Completed))
+ }
+ }
+
+ let buffer = Arc::new(Mutex::new(Vec::new()));
+ reader.pipe(&mut store, Consumer(buffer.clone()))?;
+
+ let error = store
+ .run_concurrent(async |_| {
+ while buffer.try_lock().unwrap().is_empty() {
+ tokio::task::yield_now().await
+ }
+ })
+ .await
+ .unwrap_err();
+
+ assert!(
+ error.to_string().contains("host stream item type mismatch"),
+ "{error}"
+ );
+
+ Ok(())
+}
+
/// Regression test for case which previously panicked when finishing a call
/// which was started before an intervening, failing call.
#[tokio::test]