A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Insulate embedders against incorrect future/stream ownership (#14552)
Alex Crichtone0723760406d
diff --git a/crates/wasmtime/src/runtime/component/concurrent/future_stream_any.rs b/crates/wasmtime/src/runtime/component/concurrent/future_stream_any.rsindex 5d65b59e89..b717fbcfad 100644--- a/crates/wasmtime/src/runtime/component/concurrent/future_stream_any.rs+++ b/crates/wasmtime/src/runtime/component/concurrent/future_stream_any.rs@@ -1,9 +1,9 @@//! Implementation of [`FutureAny`] and [`StreamAny`].use crate::component::concurrent::futures_and_streams::{self, TransmitOrigin};-use crate::component::concurrent::{TableId, TransmitHandle};use crate::component::func::{LiftContext, LowerContext, bad_type_info, desc};use crate::component::matching::InstanceType;+use crate::component::resources::HostResourceIndex;use crate::component::types::{self, FutureType, StreamType};use crate::component::{ComponentInstanceId, ComponentType, FutureReader, Lift, Lower, StreamReader,@@ -33,10 +33,17 @@ use wasmtime_environ::component::{/// called then memory will not be leaked once the owning [`Store`] is dropped,/// but the resource handle will be leaked until the [`Store`] is dropped.///+/// # Cloning+///+/// Cloning a [`FutureAny`] does not duplicate the underlying future: all clones+/// refer to the same read end, whose ownership can only be transferred once.+/// After one clone has been lowered into a guest, piped, or closed, attempting+/// any of those with another clone returns an error.+////// [`Store`]: crate::Store#[derive(Debug, Clone, PartialEq)]pub struct FutureAny {- id: TableId<TransmitHandle>,+ idx: HostResourceIndex,ty: PayloadType<FutureType>,}@@ -59,7 +66,7 @@ impl FutureAny {)?;// Like `FutureReader<T>`, however, lowering "just" gets a u32.- futures_and_streams::lower_future_to_index(self.id, cx, ty)+ futures_and_streams::lower_future_to_index(self.idx, cx, ty)}/// Attempts to convert this [`FutureAny`] to a [`FutureReader<T>`]@@ -75,7 +82,7 @@ impl FutureAny {{self.ty.typecheck_host::<T>(FutureType::equivalent_payload_host::<T>)?;- Ok(FutureReader::new_(self.id))+ Ok(FutureReader::new_(self.idx))}/// Attempts to convert `reader` to a [`FutureAny`], erasing its statically@@ -93,25 +100,25 @@ impl FutureAny {T: ComponentType + 'static,{let store = store.as_context_mut();- let ty = match store.0.transmit_origin(reader.id())? {+ let ty = match store.0.transmit_origin(reader.idx())? {TransmitOrigin::Host => PayloadType::new_host::<T>(),TransmitOrigin::GuestFuture(id, ty) => PayloadType::new_guest_future(store.0, id, ty),TransmitOrigin::GuestStream(..) => bail!("not a future"),};Ok(FutureAny {- id: reader.id(),+ idx: reader.idx(),ty,})}fn lift_from_index(cx: &mut LiftContext<'_>, ty: InterfaceType, index: u32) -> Result<Self> {- let id = futures_and_streams::lift_index_to_future(cx, ty, index)?;+ let idx = futures_and_streams::lift_index_to_future(cx, ty, index)?;let InterfaceType::Future(ty) = ty else {unreachable!()};let ty = cx.types[ty].ty;Ok(FutureAny {- id,+ idx,// Note that this future might actually be a host-originating// future which means that this ascription of "the type is the// guest" may be slightly in accurate. The guest, however, has the@@ -128,13 +135,11 @@ impl FutureAny {////// # Errors///- /// Returns an error if this future has already been closed.- ///- /// # Panics- ///- /// Panics if the `store` does not own this future.+ /// Returns an error if this future has already been closed or otherwise+ /// transferred (e.g. lowered into a guest), or if it does not belong to+ /// `store`.pub fn close(&mut self, mut store: impl AsContextMut) -> Result<()> {- futures_and_streams::future_close(store.as_context_mut().0, &mut self.id)+ futures_and_streams::future_close(store.as_context_mut().0, self.idx)}}@@ -210,10 +215,17 @@ unsafe impl Lift for FutureAny {/// called then memory will not be leaked once the owning [`Store`] is dropped,/// but the resource handle will be leaked until the [`Store`] is dropped.///+/// # Cloning+///+/// Cloning a [`StreamAny`] does not duplicate the underlying stream: all clones+/// refer to the same read end, whose ownership can only be transferred once.+/// After one clone has been lowered into a guest, piped, or closed, attempting+/// any of those with another clone returns an error.+////// [`Store`]: crate::Store#[derive(Debug, Clone, PartialEq)]pub struct StreamAny {- id: TableId<TransmitHandle>,+ idx: HostResourceIndex,ty: PayloadType<StreamType>,}@@ -231,7 +243,7 @@ impl StreamAny {payload,StreamType::equivalent_payload_guest,)?;- futures_and_streams::lower_stream_to_index(self.id, cx, ty)+ futures_and_streams::lower_stream_to_index(self.idx, cx, ty)}/// Attempts to convert this [`StreamAny`] to a [`StreamReader<T>`]@@ -247,7 +259,7 @@ impl StreamAny {{self.ty.typecheck_host::<T>(StreamType::equivalent_payload_host::<T>)?;- Ok(StreamReader::new_(self.id))+ Ok(StreamReader::new_(self.idx))}/// Attempts to convert `reader` to a [`StreamAny`], erasing its statically@@ -265,25 +277,25 @@ impl StreamAny {T: ComponentType + 'static,{let store = store.as_context_mut();- let ty = match store.0.transmit_origin(reader.id())? {+ let ty = match store.0.transmit_origin(reader.idx())? {TransmitOrigin::Host => PayloadType::new_host::<T>(),TransmitOrigin::GuestStream(id, ty) => PayloadType::new_guest_stream(store.0, id, ty),TransmitOrigin::GuestFuture(..) => bail!("not a stream"),};Ok(StreamAny {- id: reader.id(),+ idx: reader.idx(),ty,})}fn lift_from_index(cx: &mut LiftContext<'_>, ty: InterfaceType, index: u32) -> Result<Self> {- let id = futures_and_streams::lift_index_to_stream(cx, ty, index)?;+ let idx = futures_and_streams::lift_index_to_stream(cx, ty, index)?;let InterfaceType::Stream(ty) = ty else {unreachable!()};let ty = cx.types[ty].ty;Ok(StreamAny {- id,+ idx,// Note that this stream might actually be a host-originating, but// see the documentation in `FutureAny::lift_from_index` for why// this should be ok.@@ -298,13 +310,11 @@ impl StreamAny {////// # Errors///- /// Returns an error if this stream has already been closed.- ///- /// # Panics- ///- /// Panics if the `store` does not own this stream.+ /// Returns an error if this stream has already been closed or otherwise+ /// transferred (e.g. lowered into a guest), or if it does not belong to+ /// `store`.pub fn close(&mut self, mut store: impl AsContextMut) -> Result<()> {- futures_and_streams::stream_close(store.as_context_mut().0, &mut self.id)+ futures_and_streams::stream_close(store.as_context_mut().0, self.idx)}}diff --git a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rsindex f3a8a82551..14e75e4488 100644--- a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs+++ b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs@@ -3,6 +3,7 @@ use super::{Event, GlobalErrorContextRefCount, Waitable, WaitableCommon};use crate::component::concurrent::{ConcurrentState, QualifiedThreadId, WorkItem, tls};use crate::component::func::{self, LiftContext, LowerContext};use crate::component::matching::InstanceType;+use crate::component::resources::{HostResourceIndex, HostResourceTables};use crate::component::types;use crate::component::values::ErrorContextAny;use crate::component::{@@ -1257,7 +1258,7 @@ pub trait FutureConsumer<D>: Send + 'static {/// end will hang indefinitely. Consider using [`GuardedFutureReader`] to/// ensure that disposal happens automatically.pub struct FutureReader<T> {- id: TableId<TransmitHandle>,+ idx: HostResourceIndex,_phantom: PhantomData<T>,}@@ -1326,26 +1327,24 @@ impl<T> FutureReader<T> {))}- pub(super) fn new_(id: TableId<TransmitHandle>) -> Self {+ pub(super) fn new_(idx: HostResourceIndex) -> Self {Self {- id,+ idx,_phantom: PhantomData,}}- pub(super) fn id(&self) -> TableId<TransmitHandle> {- self.id+ pub(super) fn idx(&self) -> HostResourceIndex {+ self.idx}/// Set the consumer that accepts the result of this future.////// # Errors///- /// Returns an error if this future has already been closed.- ///- /// # Panics- ///- /// Panics if this future does not belong to `store`.+ /// Returns an error if this future has already been closed or otherwise+ /// transferred (e.g. lowered into a guest), or if it does not belong to+ /// `store`.pub fn pipe<S: AsContextMut>(self,mut store: S,@@ -1394,13 +1393,12 @@ impl<T> FutureReader<T> {store.as_context_mut()- .set_consumer(self.id, TransmitKind::Future, Consumer(consumer))+ .set_consumer(self.idx, TransmitKind::Future, Consumer(consumer))}/// Transfer ownership of the read end of a future from a guest to the host.fn lift_from_index(cx: &mut LiftContext<'_>, ty: InterfaceType, index: u32) -> Result<Self> {- let id = lift_index_to_future(cx, ty, index)?;- Ok(Self::new_(id))+ Ok(Self::new_(lift_index_to_future(cx, ty, index)?))}/// Close this `FutureReader`.@@ -1412,16 +1410,11 @@ impl<T> FutureReader<T> {////// # Errors///- /// Returns an error if this future has already been closed.- ///- /// # Panics- ///- /// Panics if the store that the [`Accessor`] is derived from does not own- /// this future.- ///- /// [`Accessor`]: crate::component::Accessor+ /// Returns an error if this future has already been closed or otherwise+ /// transferred (e.g. lowered into a guest), or if it does not belong to+ /// `store`.pub fn close(&mut self, mut store: impl AsContextMut) -> Result<()> {- future_close(store.as_context_mut().0, &mut self.id)+ future_close(store.as_context_mut().0, self.idx)}/// Convenience method around [`Self::close`].@@ -1471,29 +1464,29 @@ impl<T> FutureReader<T> {impl<T> fmt::Debug for FutureReader<T> {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {f.debug_struct("FutureReader")- .field("id", &self.id)+ .field("idx", &self.idx).finish()}}-pub(super) fn future_close(- store: &mut StoreOpaque,- id: &mut TableId<TransmitHandle>,-) -> Result<()> {- let id = mem::replace(id, TableId::new(u32::MAX));+pub(super) fn future_close(store: &mut StoreOpaque, idx: HostResourceIndex) -> Result<()> {+ let id = store.host_reader_take(idx)?;store.host_drop_reader(id, TransmitKind::Future)}-/// Transfer ownership of the read end of a future from the host to a guest.+/// Transfer ownership of the read end of a future from a guest to the host.pub(super) fn lift_index_to_future(cx: &mut LiftContext<'_>,ty: InterfaceType,index: u32,-) -> Result<TableId<TransmitHandle>> {+) -> Result<HostResourceIndex> {match ty {InterfaceType::Future(src) => {- let (state, instance) = cx.concurrent_state_and_instance_mut();- lift_index_to_transmit(instance, state, TransmitIndex::Future(src), index)+ let id = {+ let (state, instance) = cx.concurrent_state_and_instance_mut();+ lift_index_to_transmit(instance, state, TransmitIndex::Future(src), index)?+ };+ cx.host_resource_lower_own(id.rep(), None, None)}_ => func::bad_type_info(),}@@ -1501,12 +1494,13 @@ pub(super) fn lift_index_to_future(/// Transfer ownership of the read end of a future from the host to a guest.pub(super) fn lower_future_to_index<U>(- id: TableId<TransmitHandle>,+ idx: HostResourceIndex,cx: &mut LowerContext<'_, U>,ty: InterfaceType,) -> Result<u32> {match ty {InterfaceType::Future(dst) => {+ let id = cx.store.0.host_reader_take(idx)?;cx.instance_handle().lower_transmit_to_index(cx.store.0, TransmitIndex::Future(dst), id)}@@ -1540,7 +1534,7 @@ unsafe impl<T: ComponentType> func::Lower for FutureReader<T> {ty: InterfaceType,dst: &mut MaybeUninit<Self::Lower>,) -> Result<()> {- lower_future_to_index(self.id, cx, ty)?.linear_lower_to_flat(cx, InterfaceType::U32, dst)+ lower_future_to_index(self.idx, cx, ty)?.linear_lower_to_flat(cx, InterfaceType::U32, dst)}fn linear_lower_to_memory<U>(@@ -1549,7 +1543,7 @@ unsafe impl<T: ComponentType> func::Lower for FutureReader<T> {ty: InterfaceType,offset: usize,) -> Result<()> {- lower_future_to_index(self.id, cx, ty)?.linear_lower_to_memory(+ lower_future_to_index(self.idx, cx, ty)?.linear_lower_to_memory(cx,InterfaceType::U32,offset,@@ -1641,8 +1635,11 @@ where{fn drop(&mut self) {if let Some(reader) = &mut self.reader {- // Currently this can only fail if the future is closed twice, which- // this guard prevents, so this error shouldn't happen.+ // Currently this can only fail if the future is closed twice or+ // the handle was cloned/closed elsewhere, all of which the embedder+ // is responsible for when using this guard. Hint during+ // development that's a bad idea, but otherwise ignore the error in+ // release builds.let result = reader.close_with(&self.accessor);debug_assert!(result.is_ok());}@@ -1656,7 +1653,7 @@ where/// indefinitely. Consider using [`GuardedStreamReader`] to ensure that/// disposal happens automatically.pub struct StreamReader<T> {- id: TableId<TransmitHandle>,+ idx: HostResourceIndex,_phantom: PhantomData<T>,}@@ -1687,15 +1684,15 @@ impl<T> StreamReader<T> {))}- pub(super) fn new_(id: TableId<TransmitHandle>) -> Self {+ pub(super) fn new_(idx: HostResourceIndex) -> Self {Self {- id,+ idx,_phantom: PhantomData,}}- pub(super) fn id(&self) -> TableId<TransmitHandle> {- self.id+ pub(super) fn idx(&self) -> HostResourceIndex {+ self.idx}/// Attempt to consume this object by converting it into the specified type.@@ -1721,8 +1718,9 @@ impl<T> StreamReader<T> {/// belong to the specified `store`.pub fn try_into<V: 'static>(mut self, mut store: impl AsContextMut) -> Result<V, Self> {let store = store.as_context_mut();+ let id = store.0.host_reader_rep(self.idx).unwrap();let state = store.0.concurrent_state_mut_already_forced_current_thread();- let id = state.get_mut(self.id).unwrap().state;+ let id = state.get_mut(id).unwrap().state;if let WriteState::HostReady { try_into, .. } = &state.get_mut(id).unwrap().write {match try_into(TypeId::of::<V>()) {Some(result) => {@@ -1740,11 +1738,9 @@ impl<T> StreamReader<T> {////// # Errors///- /// Returns an error if this stream has already been closed.- ///- /// # Panics- ///- /// Panics if this stream does not belong to `store`.+ /// Returns an error if this stream has already been closed or otherwise+ /// transferred (e.g. lowered into a guest), or if it does not belong to+ /// `store`.pub fn pipe<S: AsContextMut>(self,mut store: S,@@ -1755,13 +1751,12 @@ impl<T> StreamReader<T> {{store.as_context_mut()- .set_consumer(self.id, TransmitKind::Stream, consumer)+ .set_consumer(self.idx, TransmitKind::Stream, consumer)}/// Transfer ownership of the read end of a stream from a guest to the host.fn lift_from_index(cx: &mut LiftContext<'_>, ty: InterfaceType, index: u32) -> Result<Self> {- let id = lift_index_to_stream(cx, ty, index)?;- Ok(Self::new_(id))+ Ok(Self::new_(lift_index_to_stream(cx, ty, index)?))}/// Close this `StreamReader`.@@ -1771,16 +1766,11 @@ impl<T> StreamReader<T> {////// # Errors///- /// Returns an error if this stream has already been closed.- ///- /// # Panics- ///- /// Panics if the store that the [`Accessor`] is derived from does not own- /// this stream.- ///- /// [`Accessor`]: crate::component::Accessor+ /// Returns an error if this stream has already been closed or otherwise+ /// transferred (e.g. lowered into a guest), or if it does not belong to+ /// `store`.pub fn close(&mut self, mut store: impl AsContextMut) -> Result<()> {- stream_close(store.as_context_mut().0, &mut self.id)+ stream_close(store.as_context_mut().0, self.idx)}/// Convenience method around [`Self::close`].@@ -1830,16 +1820,13 @@ impl<T> StreamReader<T> {impl<T> fmt::Debug for StreamReader<T> {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {f.debug_struct("StreamReader")- .field("id", &self.id)+ .field("idx", &self.idx).finish()}}-pub(super) fn stream_close(- store: &mut StoreOpaque,- id: &mut TableId<TransmitHandle>,-) -> Result<()> {- let id = mem::replace(id, TableId::new(u32::MAX));+pub(super) fn stream_close(store: &mut StoreOpaque, idx: HostResourceIndex) -> Result<()> {+ let id = store.host_reader_take(idx)?;store.host_drop_reader(id, TransmitKind::Stream)}@@ -1848,11 +1835,14 @@ pub(super) fn lift_index_to_stream(cx: &mut LiftContext<'_>,ty: InterfaceType,index: u32,-) -> Result<TableId<TransmitHandle>> {+) -> Result<HostResourceIndex> {match ty {InterfaceType::Stream(src) => {- let (state, instance) = cx.concurrent_state_and_instance_mut();- lift_index_to_transmit(instance, state, TransmitIndex::Stream(src), index)+ let id = {+ let (state, instance) = cx.concurrent_state_and_instance_mut();+ lift_index_to_transmit(instance, state, TransmitIndex::Stream(src), index)?+ };+ cx.host_resource_lower_own(id.rep(), None, None)}_ => func::bad_type_info(),}@@ -1860,12 +1850,13 @@ pub(super) fn lift_index_to_stream(/// Transfer ownership of the read end of a stream from the host to a guest.pub(super) fn lower_stream_to_index<U>(- id: TableId<TransmitHandle>,+ idx: HostResourceIndex,cx: &mut LowerContext<'_, U>,ty: InterfaceType,) -> Result<u32> {match ty {InterfaceType::Stream(dst) => {+ let id = cx.store.0.host_reader_take(idx)?;cx.instance_handle().lower_transmit_to_index(cx.store.0, TransmitIndex::Stream(dst), id)}@@ -1899,7 +1890,7 @@ unsafe impl<T: ComponentType> func::Lower for StreamReader<T> {ty: InterfaceType,dst: &mut MaybeUninit<Self::Lower>,) -> Result<()> {- lower_stream_to_index(self.id, cx, ty)?.linear_lower_to_flat(cx, InterfaceType::U32, dst)+ lower_stream_to_index(self.idx, cx, ty)?.linear_lower_to_flat(cx, InterfaceType::U32, dst)}fn linear_lower_to_memory<U>(@@ -1908,7 +1899,7 @@ unsafe impl<T: ComponentType> func::Lower for StreamReader<T> {ty: InterfaceType,offset: usize,) -> Result<()> {- lower_stream_to_index(self.id, cx, ty)?.linear_lower_to_memory(+ lower_stream_to_index(self.idx, cx, ty)?.linear_lower_to_memory(cx,InterfaceType::U32,offset,@@ -2001,8 +1992,7 @@ where{fn drop(&mut self) {if let Some(reader) = &mut self.reader {- // Currently this can only fail if the future is closed twice, which- // this guard prevents, so this error shouldn't happen.+ // See comments in `Drop for GuardedFutureReader` for this assert.let result = reader.close_with(&self.accessor);debug_assert!(result.is_ok());}@@ -2585,14 +2575,33 @@ impl StoreOpaque {Ok(())}- pub(super) fn transmit_origin(- &mut self,- id: TableId<TransmitHandle>,- ) -> Result<TransmitOrigin> {+ pub(super) fn transmit_origin(&mut self, idx: HostResourceIndex) -> Result<TransmitOrigin> {+ let id = self.host_reader_rep(idx)?;let state = self.concurrent_state_mut()?;let state_id = state.get_mut(id)?.state;Ok(state.get_mut(state_id)?.origin)}++ /// Insert `id` within the store, returning a `HostResourceIndex` suitable+ /// to re-acquire it via the `host_reader_take` and `host_reader_rep`+ /// methods below.+ fn host_reader_insert(&mut self, id: TableId<TransmitHandle>) -> Result<HostResourceIndex> {+ HostResourceTables::new_host(self)?.host_resource_lower_own(id.rep(), None, None)+ }++ /// Removes `idx` from the store, returning the internal `id` it was+ /// created with.+ fn host_reader_take(&mut self, idx: HostResourceIndex) -> Result<TableId<TransmitHandle>> {+ let rep = HostResourceTables::new_host(self)?.host_resource_lift_own(idx)?;+ Ok(TableId::new(rep))+ }++ /// Looks up `idx` within the store, returning the internal `id` it was+ /// created with.+ fn host_reader_rep(&mut self, idx: HostResourceIndex) -> Result<TableId<TransmitHandle>> {+ let rep = HostResourceTables::new_host(self)?.host_resource_rep(idx)?;+ Ok(TableId::new(rep))+ }}impl<T> StoreContextMut<'_, T> {@@ -2600,7 +2609,7 @@ impl<T> StoreContextMut<'_, T> {mut self,kind: TransmitKind,producer: P,- ) -> Result<TableId<TransmitHandle>>+ ) -> Result<HostResourceIndex>whereP::Item: func::Lower,{@@ -2780,16 +2789,17 @@ impl<T> StoreContextMut<'_, T> {cancel: false,cancel_waker: None,};- Ok(read)+ self.0.host_reader_insert(read)}fn set_consumer<C: StreamConsumer<T>>(mut self,- id: TableId<TransmitHandle>,+ idx: HostResourceIndex,kind: TransmitKind,consumer: C,) -> Result<()> {let token = StoreToken::new(self.as_context_mut());+ let id = self.0.host_reader_take(idx)?;let state = self.0.concurrent_state_mut()?;let id = state.get_mut(id)?.state;let transmit = state.get_mut(id)?;diff --git a/crates/wasmtime/src/runtime/component/resources/host_tables.rs b/crates/wasmtime/src/runtime/component/resources/host_tables.rsindex 4835e538e0..7c315ba4da 100644--- a/crates/wasmtime/src/runtime/component/resources/host_tables.rs+++ b/crates/wasmtime/src/runtime/component/resources/host_tables.rs@@ -123,6 +123,14 @@ impl<'a> HostResourceTables<'a> {self.tables.resource_lift_own(TypedResourceIndex::Host(idx))}+ /// Validates that `idx` still refers to a live host-owned resource and+ /// returns its `rep`, without consuming it or lending it out.+ #[cfg(feature = "component-model-async")]+ pub fn host_resource_rep(&mut self, idx: HostResourceIndex) -> Result<u32> {+ let (idx, _) = self.validate_host_index(idx, false)?;+ self.tables.resource_rep(TypedResourceIndex::Host(idx))+ }+/// See [`HostResourceTables::host_resource_lift_own`].pub fn host_resource_lift_borrow(&mut self, idx: HostResourceIndex) -> Result<u32> {let (idx, _) = self.validate_host_index(idx, false)?;diff --git a/tests/all/component_model/async_dynamic.rs b/tests/all/component_model/async_dynamic.rsindex 3b0b674357..41aba1d2db 100644--- a/tests/all/component_model/async_dynamic.rs+++ b/tests/all/component_model/async_dynamic.rs@@ -1,4 +1,6 @@-use wasmtime::component::{Component, FutureAny, FutureReader, Linker, StreamAny, StreamReader};+use wasmtime::component::{+ Component, FutureAny, FutureReader, Linker, StreamAny, StreamReader, Val,+};use wasmtime::{Config, Engine, Result, Store};#[test]@@ -280,3 +282,137 @@ async fn stream_any_smoke() -> Result<()> {.await??;Ok(())}++const TAKE_FUTURES_AND_STREAMS: &str = r#"+(component+ (type $f (future u32))+ (type $s (stream u32))+ (core module $m+ (func (export "take1") (param i32))+ (func (export "take2") (param i32 i32)))+ (core instance $i (instantiate $m))+ (func (export "take1-f") (param "a" $f)+ (canon lift (core func $i "take1")))+ (func (export "take2-f") (param "a" $f) (param "b" $f)+ (canon lift (core func $i "take2")))+ (func (export "take1-s") (param "a" $s)+ (canon lift (core func $i "take1")))+ (func (export "take2-s") (param "a" $s) (param "b" $s)+ (canon lift (core func $i "take2")))+)+"#;++#[test]+#[cfg_attr(miri, ignore)]+fn future_and_stream_lowered_at_most_once() -> Result<()> {+ let mut config = Config::new();+ config.wasm_component_model_async(true);+ let engine = Engine::new(&config)?;+ let component = Component::new(&engine, TAKE_FUTURES_AND_STREAMS)?;+ let linker = Linker::new(&engine);+ let new_store = || Store::new(&engine, ());++ // Two clones of one `FutureAny` passed to the same call.+ {+ let mut store = new_store();+ let instance = linker.instantiate(&mut store, &component)?;+ let take2 = instance.get_typed_func::<(FutureAny, FutureAny), ()>(&mut store, "take2-f")?;+ let f = FutureReader::new(&mut store, async { wasmtime::error::Ok(7_u32) })?+ .try_into_future_any(&mut store)?;+ let mut g = f.clone();+ assert!(take2.call(&mut store, (f, g.clone())).is_err());+ assert!(g.close(&mut store).is_err());+ }++ // Two clones of one `StreamAny` passed to the same call.+ {+ let mut store = new_store();+ let instance = linker.instantiate(&mut store, &component)?;+ let take2 = instance.get_typed_func::<(StreamAny, StreamAny), ()>(&mut store, "take2-s")?;+ let s = StreamReader::new(&mut store, vec![7_u32])?.try_into_stream_any(&mut store)?;+ let mut t = s.clone();+ assert!(take2.call(&mut store, (s, t.clone())).is_err());+ assert!(t.close(&mut store).is_err());+ }++ // The same `Val::Future` lowered in two calls.+ {+ let mut store = new_store();+ let instance = linker.instantiate(&mut store, &component)?;+ let take1 = instance.get_func(&mut store, "take1-f").unwrap();+ let f = FutureReader::new(&mut store, async { wasmtime::error::Ok(7_u32) })?+ .try_into_future_any(&mut store)?;+ let f = Val::Future(f);+ take1.call(&mut store, &[f.clone()], &mut [])?;+ assert!(take1.call(&mut store, &[f.clone()], &mut []).is_err());+ let Val::Future(mut f) = f else {+ unreachable!()+ };+ assert!(f.close(&mut store).is_err());+ }++ // The same `Val::Stream` lowered in two calls.+ {+ let mut store = new_store();+ let instance = linker.instantiate(&mut store, &component)?;+ let take1 = instance.get_func(&mut store, "take1-s").unwrap();+ let s = StreamReader::new(&mut store, vec![7_u32])?.try_into_stream_any(&mut store)?;+ let s = Val::Stream(s);+ take1.call(&mut store, &[s.clone()], &mut [])?;+ assert!(take1.call(&mut store, &[s.clone()], &mut []).is_err());+ let Val::Stream(mut s) = s else {+ unreachable!()+ };+ assert!(s.close(&mut store).is_err());+ }++ // A `FutureReader` lowered twice by reference.+ {+ let mut store = new_store();+ let instance = linker.instantiate(&mut store, &component)?;+ let take1 = instance.get_typed_func::<(&FutureReader<u32>,), ()>(&mut store, "take1-f")?;+ let mut f = FutureReader::new(&mut store, async { wasmtime::error::Ok(7_u32) })?;+ take1.call(&mut store, (&f,))?;+ assert!(take1.call(&mut store, (&f,)).is_err());+ assert!(f.close(&mut store).is_err());+ }++ // A `StreamReader` lowered twice by reference.+ {+ let mut store = new_store();+ let instance = linker.instantiate(&mut store, &component)?;+ let take1 = instance.get_typed_func::<(&StreamReader<u32>,), ()>(&mut store, "take1-s")?;+ let mut s = StreamReader::new(&mut store, vec![7_u32])?;+ take1.call(&mut store, (&s,))?;+ assert!(take1.call(&mut store, (&s,)).is_err());+ assert!(s.close(&mut store).is_err());+ }++ // Closing clones more than once.+ {+ let mut store = new_store();+ let mut f = FutureReader::new(&mut store, async { wasmtime::error::Ok(7_u32) })?+ .try_into_future_any(&mut store)?;+ let mut g = f.clone();+ f.close(&mut store)?;+ assert!(g.close(&mut store).is_err());+ assert!(f.close(&mut store).is_err());+ }++ // A stale clone must not alias a new future which reuses the old one's+ // table slot.+ {+ let mut store = new_store();+ let instance = linker.instantiate(&mut store, &component)?;+ let take1 = instance.get_typed_func::<(&FutureAny,), ()>(&mut store, "take1-f")?;+ let f = FutureReader::new(&mut store, async { wasmtime::error::Ok(7_u32) })?+ .try_into_future_any(&mut store)?;+ f.clone().close(&mut store)?;+ let mut g = FutureReader::new(&mut store, async { wasmtime::error::Ok(8_u32) })?+ .try_into_future_any(&mut store)?;+ assert!(take1.call(&mut store, (&f,)).is_err());+ g.close(&mut store)?;+ }++ Ok(())+}