Skip to main content

wasmtime/runtime/component/
concurrent.rs

1//! Runtime support for the Component Model Async ABI.
2//!
3//! This module and its submodules provide host runtime support for Component
4//! Model Async features such as async-lifted exports, async-lowered imports,
5//! streams, futures, and related intrinsics.  See [the Async
6//! Explainer](https://github.com/WebAssembly/component-model/blob/main/design/mvp/Concurrency.md)
7//! for a high-level overview.
8//!
9//! At the core of this support is an event loop which schedules and switches
10//! between guest tasks and any host tasks they create.  Each
11//! `Store` will have at most one event loop running at any given
12//! time, and that loop may be suspended and resumed by the host embedder using
13//! e.g. `StoreContextMut::run_concurrent`.  The `StoreContextMut::poll_until`
14//! function contains the loop itself, while the
15//! `StoreOpaque::concurrent_state` field holds its state.
16//!
17//! # Public API Overview
18//!
19//! ## Top-level API (e.g. kicking off host->guest calls and driving the event loop)
20//!
21//! - `[Typed]Func::call_concurrent`: Start a host->guest call to an
22//! async-lifted or sync-lifted import, creating a guest task.
23//!
24//! - `StoreContextMut::run_concurrent`: Run the event loop for the specified
25//! instance, allowing any and all tasks belonging to that instance to make
26//! progress.
27//!
28//! - `StoreContextMut::spawn`: Run a background task as part of the event loop
29//! for the specified instance.
30//!
31//! - `{Future,Stream}Reader::new`: Create a new Component Model `future` or
32//! `stream` which may be passed to the guest.  This takes a
33//! `{Future,Stream}Producer` implementation which will be polled for items when
34//! the consumer requests them.
35//!
36//! - `{Future,Stream}Reader::pipe`: Consume a `future` or `stream` by
37//! connecting it to a `{Future,Stream}Consumer` which will consume any items
38//! produced by the write end.
39//!
40//! ## Host Task API (e.g. implementing concurrent host functions and background tasks)
41//!
42//! - `LinkerInstance::func_wrap_concurrent`: Register a concurrent host
43//! function with the linker.  That function will take an `Accessor` as its
44//! first parameter, which provides access to the store between (but not across)
45//! await points.
46//!
47//! - `Accessor::with`: Access the store and its associated data.
48//!
49//! - `Accessor::spawn`: Run a background task as part of the event loop for the
50//! store.  This is equivalent to `StoreContextMut::spawn` but more convenient to use
51//! in host functions.
52
53use self::error_contexts::GlobalErrorContextRefCount;
54use crate::bail_bug;
55use crate::component::func::{Func, call_post_return};
56use crate::component::{
57    HasData, HasSelf, Instance, Resource, ResourceTable, ResourceTableError, RuntimeInstance,
58};
59use crate::fiber::{self, StoreFiber, StoreFiberYield};
60use crate::hash_set::HashSet;
61#[cfg(feature = "gc")]
62use crate::module::ModuleRegistry;
63use crate::prelude::*;
64use crate::store::{Store, StoreId, StoreInner, StoreOpaque, StoreToken};
65#[cfg(feature = "gc")]
66use crate::vm::GcRootsList;
67use crate::vm::component::{CallContext, ComponentInstance, InstanceState};
68use crate::vm::{AlwaysMut, SendSyncPtr, VMFuncRef, VMLazyThread, VMMemoryDefinition, VMStore};
69use crate::{
70    AsContext, AsContextMut, FuncType, Result, StoreContext, StoreContextMut, ValRaw, ValType, bail,
71};
72use alloc::borrow::ToOwned;
73use alloc::collections::{BTreeMap, BTreeSet, VecDeque};
74use core::any::Any;
75use core::cell::UnsafeCell;
76use core::fmt;
77use core::future;
78use core::future::Future;
79use core::marker::PhantomData;
80use core::mem::{self, ManuallyDrop, MaybeUninit};
81use core::ops::DerefMut;
82use core::pin::{Pin, pin};
83use core::ptr::{self, NonNull};
84use core::task::{Context, Poll, Waker};
85use futures::channel::oneshot;
86use futures::stream::{FuturesUnordered, StreamExt};
87use futures_and_streams::{FlatAbi, ReturnCode, TransmitHandle, TransmitIndex};
88use table::{TableDebug, TableId};
89use wasmtime_environ::component::{
90    CanonicalAbiInfo, CanonicalOptions, CanonicalOptionsDataModel, MAX_FLAT_PARAMS,
91    MAX_FLAT_RESULTS, OptionsIndex, PREPARE_ASYNC_NO_RESULT, PREPARE_ASYNC_WITH_RESULT,
92    RuntimeComponentInstanceIndex, RuntimeTableIndex, StringEncoding,
93    TypeComponentGlobalErrorContextTableIndex, TypeComponentLocalErrorContextTableIndex,
94    TypeFuncIndex, TypeFutureTableIndex, TypeStreamTableIndex, TypeTupleIndex,
95};
96use wasmtime_environ::packed_option::ReservedValue;
97use wasmtime_environ::{NUM_COMPONENT_CONTEXT_SLOTS, Trap};
98#[cfg(feature = "gc")]
99use wasmtime_unwinder::Unwind;
100
101pub use abort::JoinHandle;
102pub use func::{FuncCallConcurrent, TypedFuncCallConcurrent};
103pub use future_stream_any::{FutureAny, StreamAny};
104pub use futures_and_streams::{
105    Destination, DirectDestination, DirectSource, ErrorContext, FutureConsumer, FutureProducer,
106    FutureReader, GuardedFutureReader, GuardedStreamReader, ReadBuffer, Source, StreamConsumer,
107    StreamProducer, StreamReader, StreamResult, VecBuffer, WriteBuffer,
108};
109pub(crate) use futures_and_streams::{ResourcePair, lower_error_context_to_index};
110
111mod abort;
112mod error_contexts;
113mod func;
114mod future_stream_any;
115mod futures_and_streams;
116pub(crate) mod table;
117pub(crate) mod tls;
118
119/// Constant defined in the Component Model spec to indicate that the async
120/// intrinsic (e.g. `future.write`) has not yet completed.
121const BLOCKED: u32 = 0xffff_ffff;
122
123/// Corresponds to `CallState` in the upstream spec.
124#[derive(Clone, Copy, Eq, PartialEq, Debug)]
125pub enum Status {
126    Starting = 0,
127    Started = 1,
128    Returned = 2,
129    StartCancelled = 3,
130    ReturnCancelled = 4,
131}
132
133impl Status {
134    /// Packs this status and the optional `waitable` provided into a 32-bit
135    /// result that the canonical ABI requires.
136    ///
137    /// The low 4 bits are reserved for the status while the upper 28 bits are
138    /// the waitable, if present.
139    pub fn pack(self, waitable: Option<u32>) -> u32 {
140        assert!(matches!(self, Status::Returned) == waitable.is_none());
141        let waitable = waitable.unwrap_or(0);
142        assert!(waitable < (1 << 28));
143        (waitable << 4) | (self as u32)
144    }
145}
146
147/// Corresponds to `EventCode` in the Component Model spec, plus related payload
148/// data.
149#[derive(Clone, Copy, Debug)]
150enum Event {
151    None,
152    Subtask {
153        status: Status,
154    },
155    StreamRead {
156        code: ReturnCode,
157        pending: Option<(TypeStreamTableIndex, u32)>,
158    },
159    StreamWrite {
160        code: ReturnCode,
161        pending: Option<(TypeStreamTableIndex, u32)>,
162    },
163    FutureRead {
164        code: ReturnCode,
165        pending: Option<(TypeFutureTableIndex, u32)>,
166    },
167    FutureWrite {
168        code: ReturnCode,
169        pending: Option<(TypeFutureTableIndex, u32)>,
170    },
171    Cancelled,
172}
173
174impl Event {
175    /// Lower this event to core Wasm integers for delivery to the guest.
176    ///
177    /// Note that the waitable handle, if any, is assumed to be lowered
178    /// separately.
179    fn parts(self) -> (u32, u32) {
180        const EVENT_NONE: u32 = 0;
181        const EVENT_SUBTASK: u32 = 1;
182        const EVENT_STREAM_READ: u32 = 2;
183        const EVENT_STREAM_WRITE: u32 = 3;
184        const EVENT_FUTURE_READ: u32 = 4;
185        const EVENT_FUTURE_WRITE: u32 = 5;
186        const EVENT_CANCELLED: u32 = 6;
187        match self {
188            Event::None => (EVENT_NONE, 0),
189            Event::Cancelled => (EVENT_CANCELLED, 0),
190            Event::Subtask { status } => (EVENT_SUBTASK, status as u32),
191            Event::StreamRead { code, .. } => (EVENT_STREAM_READ, code.encode()),
192            Event::StreamWrite { code, .. } => (EVENT_STREAM_WRITE, code.encode()),
193            Event::FutureRead { code, .. } => (EVENT_FUTURE_READ, code.encode()),
194            Event::FutureWrite { code, .. } => (EVENT_FUTURE_WRITE, code.encode()),
195        }
196    }
197}
198
199/// Corresponds to `CallbackCode` in the spec.
200mod callback_code {
201    pub const EXIT: u32 = 0;
202    pub const YIELD: u32 = 1;
203    pub const WAIT: u32 = 2;
204}
205
206/// A flag indicating that the callee is an async-lowered export.
207///
208/// This may be passed to the `async-start` intrinsic from a fused adapter.
209const START_FLAG_ASYNC_CALLEE: u32 = wasmtime_environ::component::START_FLAG_ASYNC_CALLEE as u32;
210
211/// Provides access to either store data (via the `get` method) or the store
212/// itself (via [`AsContext`]/[`AsContextMut`]), as well as the component
213/// instance to which the current host task belongs.
214///
215/// See [`Accessor::with`] for details.
216pub struct Access<'a, T: 'static, D: HasData + ?Sized = HasSelf<T>> {
217    store: StoreContextMut<'a, T>,
218    get_data: fn(&mut T) -> D::Data<'_>,
219}
220
221impl<'a, T, D> Access<'a, T, D>
222where
223    D: HasData + ?Sized,
224    T: 'static,
225{
226    /// Creates a new [`Access`] from its component parts.
227    pub fn new(store: StoreContextMut<'a, T>, get_data: fn(&mut T) -> D::Data<'_>) -> Self {
228        Self { store, get_data }
229    }
230
231    /// Get mutable access to the store data.
232    pub fn data_mut(&mut self) -> &mut T {
233        self.store.data_mut()
234    }
235
236    /// Get mutable access to the store data.
237    pub fn get(&mut self) -> D::Data<'_> {
238        (self.get_data)(self.data_mut())
239    }
240
241    /// Spawn a background task.
242    ///
243    /// See [`Accessor::spawn`] for details.
244    pub fn spawn(&mut self, task: impl AccessorTask<T, D>) -> Result<JoinHandle>
245    where
246        T: 'static,
247    {
248        let accessor = Accessor {
249            get_data: self.get_data,
250            token: StoreToken::new(self.store.as_context_mut()),
251        };
252        self.store
253            .as_context_mut()
254            .spawn_with_accessor(accessor, task)
255    }
256
257    /// Returns the getter this accessor is using to project from `T` into
258    /// `D::Data`.
259    pub fn getter(&self) -> fn(&mut T) -> D::Data<'_> {
260        self.get_data
261    }
262}
263
264impl<'a, T, D> AsContext for Access<'a, T, D>
265where
266    D: HasData + ?Sized,
267    T: 'static,
268{
269    type Data = T;
270
271    fn as_context(&self) -> StoreContext<'_, T> {
272        self.store.as_context()
273    }
274}
275
276impl<'a, T, D> AsContextMut for Access<'a, T, D>
277where
278    D: HasData + ?Sized,
279    T: 'static,
280{
281    fn as_context_mut(&mut self) -> StoreContextMut<'_, T> {
282        self.store.as_context_mut()
283    }
284}
285
286/// Provides scoped mutable access to store data in the context of a concurrent
287/// host task future.
288///
289/// This allows multiple host task futures to execute concurrently and access
290/// the store between (but not across) `await` points.
291///
292/// # Rationale
293///
294/// This structure is sort of like `&mut T` plus a projection from `&mut T` to
295/// `D::Data<'_>`. The problem this is solving, however, is that it does not
296/// literally store these values. The basic problem is that when a concurrent
297/// host future is being polled it has access to `&mut T` (and the whole
298/// `Store`) but when it's not being polled it does not have access to these
299/// values. This reflects how the store is only ever polling one future at a
300/// time so the store is effectively being passed between futures.
301///
302/// Rust's `Future` trait, however, has no means of passing a `Store`
303/// temporarily between futures. The [`Context`](core::task::Context) type does
304/// not have the ability to attach arbitrary information to it at this time.
305/// This type, [`Accessor`], is used to bridge this expressivity gap.
306///
307/// The [`Accessor`] type here represents the ability to acquire, temporarily in
308/// a synchronous manner, the current store. The [`Accessor::with`] function
309/// yields an [`Access`] which can be used to access [`StoreContextMut`], `&mut
310/// T`, or `D::Data<'_>`. Note though that [`Accessor::with`] intentionally does
311/// not take an `async` closure as its argument, instead it's a synchronous
312/// closure which must complete during on run of `Future::poll`. This reflects
313/// how the store is temporarily made available while a host future is being
314/// polled.
315///
316/// # Implementation
317///
318/// This type does not actually store `&mut T` nor `StoreContextMut<T>`, and
319/// this type additionally doesn't even have a lifetime parameter. This is
320/// instead a representation of proof of the ability to acquire these while a
321/// future is being polled. Wasmtime will, when it polls a host future,
322/// configure ambient state such that the `Accessor` that a future closes over
323/// will work and be able to access the store.
324///
325/// This has a number of implications for users such as:
326///
327/// * It's intentional that `Accessor` cannot be cloned, it needs to stay within
328///   the lifetime of a single future.
329/// * A future is expected to, however, close over an `Accessor` and keep it
330///   alive probably for the duration of the entire future.
331/// * Different host futures will be given different `Accessor`s, and that's
332///   intentional.
333/// * The `Accessor` type is `Send` and `Sync` irrespective of `T` which
334///   alleviates some otherwise required bounds to be written down.
335///
336/// # Using `Accessor` in `Drop`
337///
338/// The methods on `Accessor` are only expected to work in the context of
339/// `Future::poll` and are not guaranteed to work in `Drop`. This is because a
340/// host future can be dropped at any time throughout the system and Wasmtime
341/// store context is not necessarily available at that time. It's recommended to
342/// not use `Accessor` methods in anything connected to a `Drop` implementation
343/// as they will panic and have unintended results. If you run into this though
344/// feel free to file an issue on the Wasmtime repository.
345pub struct Accessor<T: 'static, D = HasSelf<T>>
346where
347    D: HasData + ?Sized,
348{
349    token: StoreToken<T>,
350    get_data: fn(&mut T) -> D::Data<'_>,
351}
352
353/// A helper trait to take any type of accessor-with-data in functions.
354///
355/// This trait is similar to [`AsContextMut`] except that it's used when
356/// working with an [`Accessor`] instead of a [`StoreContextMut`]. The
357/// [`Accessor`] is the main type used in concurrent settings and is passed to
358/// functions such as [`Func::call_concurrent`].
359///
360/// This trait is implemented for [`Accessor`] and `&T` where `T` implements
361/// this trait. This effectively means that regardless of the `D` in
362/// `Accessor<T, D>` it can still be passed to a function which just needs a
363/// store accessor.
364///
365/// Acquiring an [`Accessor`] can be done through
366/// [`StoreContextMut::run_concurrent`] for example or in a host function
367/// through
368/// [`Linker::func_wrap_concurrent`](crate::component::LinkerInstance::func_wrap_concurrent).
369pub trait AsAccessor {
370    /// The `T` in `Store<T>` that this accessor refers to.
371    type Data: 'static;
372
373    /// The `D` in `Accessor<T, D>`, or the projection out of
374    /// `Self::Data`.
375    type AccessorData: HasData + ?Sized;
376
377    /// Returns the accessor that this is referring to.
378    fn as_accessor(&self) -> &Accessor<Self::Data, Self::AccessorData>;
379}
380
381impl<T: AsAccessor + ?Sized> AsAccessor for &T {
382    type Data = T::Data;
383    type AccessorData = T::AccessorData;
384
385    fn as_accessor(&self) -> &Accessor<Self::Data, Self::AccessorData> {
386        T::as_accessor(self)
387    }
388}
389
390impl<T, D: HasData + ?Sized> AsAccessor for Accessor<T, D> {
391    type Data = T;
392    type AccessorData = D;
393
394    fn as_accessor(&self) -> &Accessor<T, D> {
395        self
396    }
397}
398
399// Note that it is intentional at this time that `Accessor` does not actually
400// store `&mut T` or anything similar. This distinctly enables the `Accessor`
401// structure to be both `Send` and `Sync` regardless of what `T` is (or `D` for
402// that matter). This is used to ergonomically simplify bindings where the
403// majority of the time `Accessor` is closed over in a future which then needs
404// to be `Send` and `Sync`. To avoid needing to write `T: Send` everywhere (as
405// you already have to write `T: 'static`...) it helps to avoid this.
406//
407// Note as well that `Accessor` doesn't actually store its data at all. Instead
408// it's more of a "proof" of what can be accessed from TLS. API design around
409// `Accessor` and functions like `Linker::func_wrap_concurrent` are
410// intentionally made to ensure that `Accessor` is ideally only used in the
411// context that TLS variables are actually set. For example host functions are
412// given `&Accessor`, not `Accessor`, and this prevents them from persisting
413// the value outside of a future. Within the future the TLS variables are all
414// guaranteed to be set while the future is being polled.
415//
416// Finally though this is not an ironclad guarantee, but nor does it need to be.
417// The TLS APIs are designed to panic or otherwise model usage where they're
418// called recursively or similar. It's hoped that code cannot be constructed to
419// actually hit this at runtime but this is not a safety requirement at this
420// time.
421const _: () = {
422    const fn assert<T: Send + Sync>() {}
423    assert::<Accessor<UnsafeCell<u32>>>();
424};
425
426impl<T> Accessor<T> {
427    /// Creates a new `Accessor` backed by the specified functions.
428    ///
429    /// - `get`: used to retrieve the store
430    ///
431    /// - `get_data`: used to "project" from the store's associated data to
432    /// another type (e.g. a field of that data or a wrapper around it).
433    ///
434    /// - `spawn`: used to queue spawned background tasks to be run later
435    pub(crate) fn new(token: StoreToken<T>) -> Self {
436        Self {
437            token,
438            get_data: |x| x,
439        }
440    }
441}
442
443impl<T, D> Accessor<T, D>
444where
445    D: HasData + ?Sized,
446{
447    /// Run the specified closure, passing it mutable access to the store.
448    ///
449    /// This function is one of the main building blocks of the [`Accessor`]
450    /// type. This yields synchronous, blocking, access to the store via an
451    /// [`Access`]. The [`Access`] implements [`AsContextMut`] in addition to
452    /// providing the ability to access `D` via [`Access::get`]. Note that the
453    /// `fun` here is given only temporary access to the store and `T`/`D`
454    /// meaning that the return value `R` here is not allowed to capture borrows
455    /// into the two. If access is needed to data within `T` or `D` outside of
456    /// this closure then it must be `clone`d out, for example.
457    ///
458    /// # Panics
459    ///
460    /// This function will panic if it is call recursively with any other
461    /// accessor already in scope. For example if `with` is called within `fun`,
462    /// then this function will panic. It is up to the embedder to ensure that
463    /// this does not happen.
464    pub fn with<R>(&self, fun: impl FnOnce(Access<'_, T, D>) -> R) -> R {
465        tls::get(|vmstore| {
466            fun(Access {
467                store: self.token.as_context_mut(vmstore),
468                get_data: self.get_data,
469            })
470        })
471    }
472
473    /// Returns the getter this accessor is using to project from `T` into
474    /// `D::Data`.
475    pub fn getter(&self) -> fn(&mut T) -> D::Data<'_> {
476        self.get_data
477    }
478
479    /// Changes this accessor to access `D2` instead of the current type
480    /// parameter `D`.
481    ///
482    /// This changes the underlying data access from `T` to `D2::Data<'_>`.
483    ///
484    /// # Panics
485    ///
486    /// When using this API the returned value is disconnected from `&self` and
487    /// the lifetime binding the `self` argument. An `Accessor` only works
488    /// within the context of the closure or async closure that it was
489    /// originally given to, however. This means that due to the fact that the
490    /// returned value has no lifetime connection it's possible to use the
491    /// accessor outside of `&self`, the original accessor, and panic.
492    ///
493    /// The returned value should only be used within the scope of the original
494    /// `Accessor` that `self` refers to.
495    pub fn with_getter<D2: HasData>(
496        &self,
497        get_data: fn(&mut T) -> D2::Data<'_>,
498    ) -> Accessor<T, D2> {
499        Accessor {
500            token: self.token,
501            get_data,
502        }
503    }
504
505    /// Spawn a background task which will receive an `&Accessor<T, D>` and
506    /// run concurrently with any other tasks in progress for the current
507    /// store.
508    ///
509    /// This is particularly useful for host functions which return a `stream`
510    /// or `future` such that the code to write to the write end of that
511    /// `stream` or `future` must run after the function returns.
512    ///
513    /// The returned [`JoinHandle`] may be used to cancel the task.
514    ///
515    /// # Panics
516    ///
517    /// Panics if called within a closure provided to the [`Accessor::with`]
518    /// function. This can only be called outside an active invocation of
519    /// [`Accessor::with`].
520    pub fn spawn(&self, task: impl AccessorTask<T, D>) -> Result<JoinHandle>
521    where
522        T: 'static,
523    {
524        let accessor = self.clone_for_spawn();
525        self.with(|mut access| access.as_context_mut().spawn_with_accessor(accessor, task))
526    }
527
528    fn clone_for_spawn(&self) -> Self {
529        Self {
530            token: self.token,
531            get_data: self.get_data,
532        }
533    }
534
535    /// Polls to see if this store contains any "interesting" tasks still within
536    /// it.
537    ///
538    /// Returns `Poll::Ready(())` if there are no more interesting tasks, and
539    /// otherwise returns `Poll::Pending`. If pending is returned then whenever
540    /// the last remaining "interesting" task has exited the provided context's
541    /// waker will be notified. Note that only the waker passed to the last call
542    /// to `poll_no_interesting_tasks` for the store will be notified, so this
543    /// is only appropriate to use once-at-a-time per store.
544    ///
545    /// The component model specification, as of this current date, does not
546    /// have a distinction between "interesting" tasks and not. The current
547    /// intention is that in a future revision of the component model this will
548    /// be distinguished at the component ABI level where tasks will be able to
549    /// flag themselves as "interesting" optionally. Additionally extra work can
550    /// be opted-in to being "interesting".
551    ///
552    /// For now what this means is that all component model tasks within this
553    /// store are considered interesting. This specifically includes the entire
554    /// duration of a task, so even all of the time after a task has returned
555    /// but before it has exited. This means that this function is, today,
556    /// effectively a proxy for "are there any more tasks still running in this
557    /// store". This can be used by embedders to determine whether there's any
558    /// more work going on, even in the background, for a particular guest.
559    /// Hosts can use this as a signal that the guest wants to stay alive a
560    /// little longer, even after a task has returned.
561    ///
562    /// In the future this predicate won't include all tasks in this store. Some
563    /// tasks will be able to flag themselves as not interesting, meaning that
564    /// when this returns ready it'd be possible that there are still tasks
565    /// remaining in the store.
566    ///
567    /// Note that at this time spawned threads within a task are always
568    /// considered uninteresting. If this function returns ready, then spawned
569    /// threads may still be in the store.
570    pub fn poll_no_interesting_tasks(&self, cx: &mut Context<'_>) -> Poll<()> {
571        self.with(|mut access| {
572            let store = access.as_context_mut().0;
573            let state = store.concurrent_state_mut_without_forcing_current_thread();
574            if state.interesting_tasks == 0 {
575                Poll::Ready(())
576            } else {
577                state.interesting_tasks_empty_waker = Some(cx.waker().clone());
578                Poll::Pending
579            }
580        })
581    }
582
583    /// Poll to see if the component instance corresponding to the specified
584    /// function is ready to run a concurrent call without queuing it (i.e. does
585    /// not have backpressure enabled and does not have a sync call in
586    /// progress).
587    ///
588    /// Returns `Poll::Ready(())` if the component instance is ready to run a
589    /// concurrent call, and otherwise returns `Poll::Pending`.  If pending is
590    /// returned then whenever the instance becomes ready for a call the
591    /// provided context's waker will be notified.  Note that only the waker
592    /// passed to the last call to `poll_ready_for_concurrent_call` for the
593    /// store will be notified (regardless of whether the same or different
594    /// `Func` is specified relative to earlier calls), so this is only
595    /// appropriate to use once-at-a-time per store.  Also note that the waker
596    /// may be notified when _any_ instance becomes callable (i.e. not
597    /// necessarily the last one polled), so this function must be called again
598    /// to determine if the instance of interest is ready.
599    pub fn poll_ready_for_concurrent_call(&self, func: Func, cx: &mut Context<'_>) -> Poll<()> {
600        self.with(|mut access| {
601            let store = access.as_context_mut().0;
602            let (_, _, _, raw_options) = func.abi_info(store);
603            let instance = func.instance().runtime_instance(raw_options.instance);
604            let state = store.instance_state(instance).concurrent_state();
605            if state.backpressure == 0 {
606                Poll::Ready(())
607            } else {
608                store
609                    .concurrent_state_mut_without_forcing_current_thread()
610                    .ready_for_concurrent_call_waker = Some(cx.waker().clone());
611                Poll::Pending
612            }
613        })
614    }
615}
616
617/// Represents a task which may be provided to `Accessor::spawn`,
618/// `Accessor::forward`, or `StorecContextMut::spawn`.
619// TODO: Replace this with `core::ops::AsyncFnOnce` when that becomes a viable
620// option.
621//
622// As of this writing, it's not possible to specify e.g. `Send` and `Sync`
623// bounds on the `Future` type returned by an `AsyncFnOnce`.  Also, using `F:
624// Future<Output = Result<()>> + Send + Sync, FN: FnOnce(&Accessor<T>) -> F +
625// Send + Sync + 'static` fails with a type mismatch error when we try to pass
626// it an async closure (e.g. `async move |_| { ... }`).  So this seems to be the
627// best we can do for the time being.
628pub trait AccessorTask<T, D = HasSelf<T>>: Send + 'static
629where
630    D: HasData + ?Sized,
631{
632    /// Run the task.
633    fn run(self, accessor: &Accessor<T, D>) -> impl Future<Output = Result<()>> + Send;
634}
635
636/// Represents parameter and result metadata for the caller side of a
637/// guest->guest call orchestrated by a fused adapter.
638enum CallerInfo {
639    /// Metadata for a call to an async-lowered import
640    Async {
641        params: Vec<ValRaw>,
642        has_result: bool,
643    },
644    /// Metadata for a call to an sync-lowered import
645    Sync {
646        params: Vec<ValRaw>,
647        result_count: u32,
648    },
649}
650
651/// Indicates how a guest task is waiting on a waitable set.
652enum WaitMode {
653    /// The guest task is waiting using `task.wait`
654    Fiber(StoreFiber<'static>),
655    /// The guest task is waiting via a callback declared as part of an
656    /// async-lifted export.
657    Callback(Instance),
658}
659
660/// Represents the reason a fiber is suspending itself.
661#[derive(Debug)]
662enum SuspendReason {
663    /// The fiber is waiting for an event to be delivered to the specified
664    /// waitable set or task.
665    Waiting {
666        set: TableId<WaitableSet>,
667        thread: QualifiedThreadId,
668        skip_may_block_check: bool,
669    },
670    /// The fiber has finished handling its most recent work item and is waiting
671    /// for another (or to be dropped if it is no longer needed).
672    NeedWork,
673    /// The fiber is yielding and should be resumed once other tasks have had a
674    /// chance to run.
675    Yielding {
676        thread: QualifiedThreadId,
677        cancellable: bool,
678        skip_may_block_check: bool,
679    },
680    /// The fiber was explicitly suspended with a call to `thread.suspend` or `thread.switch-to`.
681    ExplicitlySuspending {
682        thread: QualifiedThreadId,
683        skip_may_block_check: bool,
684    },
685}
686
687/// Represents a pending call into guest code for a given guest task.
688enum GuestCallKind {
689    /// Indicates there's an event to deliver to the task, possibly related to a
690    /// waitable set the task has been waiting on or polling.
691    DeliverEvent {
692        /// The instance to which the task belongs.
693        instance: Instance,
694        /// The waitable set the event belongs to, if any.
695        ///
696        /// If this is `None` the event will be waiting in the
697        /// `GuestTask::event` field for the task.
698        set: Option<TableId<WaitableSet>>,
699    },
700    /// Indicates that a new guest task call is pending and may be executed
701    /// using the specified closure.
702    ///
703    /// If the closure returns `Ok(Some(call))`, the `call` should be run
704    /// immediately using `handle_guest_call`.
705    StartImplicit(Box<dyn FnOnce(&mut dyn VMStore) -> Result<Option<GuestCall>> + Send + Sync>),
706    StartExplicit(Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send + Sync>),
707}
708
709impl fmt::Debug for GuestCallKind {
710    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
711        match self {
712            Self::DeliverEvent { instance, set } => f
713                .debug_struct("DeliverEvent")
714                .field("instance", instance)
715                .field("set", set)
716                .finish(),
717            Self::StartImplicit(_) => f.debug_tuple("StartImplicit").finish(),
718            Self::StartExplicit(_) => f.debug_tuple("StartExplicit").finish(),
719        }
720    }
721}
722
723/// The target of a suspension intrinsic.
724#[derive(Copy, Clone, Debug)]
725pub enum SuspensionTarget {
726    SomeSuspended(u32),
727    Some(u32),
728    None,
729}
730
731impl SuspensionTarget {
732    fn is_none(&self) -> bool {
733        matches!(self, SuspensionTarget::None)
734    }
735    fn is_some(&self) -> bool {
736        !self.is_none()
737    }
738}
739
740/// Represents a pending call into guest code for a given guest thread.
741#[derive(Debug)]
742struct GuestCall {
743    thread: QualifiedThreadId,
744    kind: GuestCallKind,
745}
746
747impl GuestCall {
748    /// Returns whether or not the call is ready to run.
749    ///
750    /// A call will not be ready to run if either:
751    ///
752    /// - the (sub-)component instance to be called has already been entered and
753    /// cannot be reentered until an in-progress call completes
754    ///
755    /// - the call is for a not-yet started task and the (sub-)component
756    /// instance to be called has backpressure enabled
757    fn is_ready(&self, store: &mut StoreOpaque) -> Result<bool> {
758        let instance = store
759            .concurrent_state_mut()?
760            .get_mut(self.thread.task)?
761            .instance;
762        let state = store.instance_state(instance).concurrent_state();
763
764        let ready = match &self.kind {
765            GuestCallKind::DeliverEvent { .. } => !state.do_not_enter,
766            GuestCallKind::StartImplicit(_) => !(state.do_not_enter || state.backpressure > 0),
767            GuestCallKind::StartExplicit(_) => true,
768        };
769        log::trace!(
770            "call {self:?} ready? {ready} (do_not_enter: {}; backpressure: {})",
771            state.do_not_enter,
772            state.backpressure
773        );
774        Ok(ready)
775    }
776}
777
778/// Job to be run on a worker fiber.
779enum WorkerItem {
780    GuestCall(GuestCall),
781    Function(AlwaysMut<Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send>>),
782}
783
784/// Represents a pending work item to be handled by the event loop for a given
785/// component instance.
786enum WorkItem {
787    /// A host task to be pushed to `ConcurrentState::futures`.
788    PushFuture(AlwaysMut<HostTaskFuture>),
789    /// A fiber to resume.
790    ResumeFiber(StoreFiber<'static>),
791    /// A thread to resume.
792    ResumeThread(RuntimeComponentInstanceIndex, QualifiedThreadId),
793    /// A pending call into guest code for a given guest task.
794    GuestCall(RuntimeComponentInstanceIndex, GuestCall),
795    /// A job to run on a worker fiber.
796    WorkerFunction(AlwaysMut<Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send>>),
797}
798
799impl fmt::Debug for WorkItem {
800    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
801        match self {
802            Self::PushFuture(_) => f.debug_tuple("PushFuture").finish(),
803            Self::ResumeFiber(_) => f.debug_tuple("ResumeFiber").finish(),
804            Self::ResumeThread(instance, thread) => f
805                .debug_tuple("ResumeThread")
806                .field(instance)
807                .field(thread)
808                .finish(),
809            Self::GuestCall(instance, call) => f
810                .debug_tuple("GuestCall")
811                .field(instance)
812                .field(call)
813                .finish(),
814            Self::WorkerFunction(_) => f.debug_tuple("WorkerFunction").finish(),
815        }
816    }
817}
818
819/// Whether a suspension intrinsic was cancelled or completed
820#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
821pub(crate) enum WaitResult {
822    Cancelled,
823    Completed,
824}
825
826/// Poll the specified future until it completes on behalf of a guest->host call
827/// using a sync-lowered import.
828///
829/// This is similar to `Instance::first_poll` except it's for sync-lowered
830/// imports, meaning we don't need to handle cancellation and we can block the
831/// caller until the task completes, at which point the caller can handle
832/// lowering the result to the guest's stack and linear memory.
833pub(crate) fn poll_and_block<R: Send + Sync + 'static>(
834    store: &mut dyn VMStore,
835    host_task: EnteredHostTask,
836    future: impl Future<Output = Result<R>> + Send + 'static,
837) -> Result<R> {
838    let task = store.current_host_thread()?;
839
840    // Wrap the future in a closure which will take care of stashing the result
841    // in `GuestTask::result` and resuming this fiber when the host task
842    // completes.
843    let mut future = Box::pin(async move {
844        let result = future.await?;
845        tls::get(move |store| {
846            let state = store.concurrent_state_mut()?;
847            let host_state = &mut state.get_mut(task)?.state;
848            assert!(matches!(host_state, HostTaskState::CalleeStarted));
849            *host_state = HostTaskState::CalleeFinished(Box::new(result));
850
851            Waitable::Host(task).set_event(
852                state,
853                Some(Event::Subtask {
854                    status: Status::Returned,
855                }),
856            )?;
857
858            Ok(())
859        })
860    }) as HostTaskFuture;
861
862    // Finally, poll the future.  We can use a dummy `Waker` here because we'll
863    // add the future to `ConcurrentState::futures` and poll it automatically
864    // from the event loop if it doesn't complete immediately here.
865    let poll = tls::set(store, || {
866        future
867            .as_mut()
868            .poll(&mut Context::from_waker(&Waker::noop()))
869    });
870
871    let caller = match host_task {
872        Some(pair) => pair.1,
873        None => bail_bug!("host task wasn't created but should have been"),
874    };
875
876    match poll {
877        // It completed immediately; check the result and delete the task.
878        Poll::Ready(result) => result?,
879
880        // It did not complete immediately; add it to
881        // `ConcurrentState::futures` so it will be polled via the event loop;
882        // then use `GuestThread::sync_call_set` to wait for the task to
883        // complete, suspending the current fiber until it does so.
884        Poll::Pending => {
885            let state = store.concurrent_state_mut()?;
886            state.push_future(future);
887
888            let set = state.get_mut(caller.thread)?.sync_call_set;
889            Waitable::Host(task).join(state, Some(set))?;
890
891            store.suspend(SuspendReason::Waiting {
892                set,
893                thread: caller,
894                skip_may_block_check: false,
895            })?;
896
897            // Remove the `task` from the `sync_call_set` to ensure that when
898            // this function returns and the task is deleted that there are no
899            // more lingering references to this host task.
900            Waitable::Host(task).join(store.concurrent_state_mut()?, None)?;
901        }
902    }
903
904    // Retrieve and return the result.
905    let host_state = &mut store.concurrent_state_mut()?.get_mut(task)?.state;
906    match mem::replace(host_state, HostTaskState::CalleeDone { cancelled: false }) {
907        HostTaskState::CalleeFinished(result) => Ok(match result.downcast() {
908            Ok(result) => *result,
909            Err(_) => bail_bug!("host task finished with wrong type of result"),
910        }),
911        _ => bail_bug!("unexpected host task state after completion"),
912    }
913}
914
915/// Execute the specified guest call.
916fn handle_guest_call(store: &mut dyn VMStore, call: GuestCall) -> Result<()> {
917    let mut next = Some(call);
918    while let Some(call) = next.take() {
919        match call.kind {
920            GuestCallKind::DeliverEvent { instance, set } => {
921                let (event, waitable) =
922                    match instance.get_event(store, call.thread.task, set, true)? {
923                        Some(pair) => pair,
924                        None => bail_bug!("delivering non-present event"),
925                    };
926                let state = store.concurrent_state_mut()?;
927                let task = state.get_mut(call.thread.task)?;
928                let runtime_instance = task.instance;
929                let handle = waitable.map(|(_, v)| v).unwrap_or(0);
930
931                log::trace!(
932                    "use callback to deliver event {event:?} to {:?} for {waitable:?}",
933                    call.thread,
934                );
935
936                let old_thread = store.set_thread(call.thread)?;
937                log::trace!(
938                    "GuestCallKind::DeliverEvent: replaced {old_thread:?} with {:?} as current thread",
939                    call.thread
940                );
941
942                store.enter_instance(runtime_instance);
943
944                let Some(callback) = store
945                    .concurrent_state_mut()?
946                    .get_mut(call.thread.task)?
947                    .callback
948                    .take()
949                else {
950                    bail_bug!("guest task callback field not present")
951                };
952
953                let code = callback(store, event, handle)?;
954
955                store
956                    .concurrent_state_mut()?
957                    .get_mut(call.thread.task)?
958                    .callback = Some(callback);
959
960                store.exit_instance(runtime_instance)?;
961
962                store.set_thread(old_thread)?;
963
964                next = instance.handle_callback_code(
965                    store,
966                    call.thread,
967                    runtime_instance.index,
968                    code,
969                )?;
970
971                log::trace!(
972                    "GuestCallKind::DeliverEvent: restored {old_thread:?} as current thread"
973                );
974            }
975            GuestCallKind::StartImplicit(fun) => {
976                next = fun(store)?;
977            }
978            GuestCallKind::StartExplicit(fun) => {
979                fun(store)?;
980            }
981        }
982    }
983
984    Ok(())
985}
986
987impl<T> Store<T> {
988    /// Convenience wrapper for [`StoreContextMut::run_concurrent`].
989    pub async fn run_concurrent<R>(&mut self, fun: impl AsyncFnOnce(&Accessor<T>) -> R) -> Result<R>
990    where
991        T: Send + 'static,
992    {
993        ensure!(
994            self.as_context().0.concurrency_support(),
995            "cannot use `run_concurrent` when Config::concurrency_support disabled",
996        );
997        self.as_context_mut().run_concurrent(fun).await
998    }
999
1000    #[doc(hidden)]
1001    pub fn assert_concurrent_state_empty(&mut self) {
1002        self.as_context_mut().assert_concurrent_state_empty();
1003    }
1004
1005    #[doc(hidden)]
1006    pub fn concurrent_state_table_size(&mut self) -> usize {
1007        self.as_context_mut().concurrent_state_table_size()
1008    }
1009
1010    /// Convenience wrapper for [`StoreContextMut::spawn`].
1011    pub fn spawn(&mut self, task: impl AccessorTask<T, HasSelf<T>>) -> Result<JoinHandle>
1012    where
1013        T: 'static,
1014    {
1015        self.as_context_mut().spawn(task)
1016    }
1017}
1018
1019impl<T> StoreContextMut<'_, T> {
1020    /// Assert that all the relevant tables and queues in the concurrent state
1021    /// for this store are empty.
1022    ///
1023    /// This is for sanity checking in integration tests
1024    /// (e.g. `component-async-tests`) that the relevant state has been cleared
1025    /// after each test concludes.  This should help us catch leaks, e.g. guest
1026    /// tasks which haven't been deleted despite having completed and having
1027    /// been dropped by their supertasks.
1028    ///
1029    /// Only intended for use in Wasmtime's own testing.
1030    #[doc(hidden)]
1031    pub fn assert_concurrent_state_empty(self) {
1032        let store = self.0;
1033        store
1034            .store_data_mut()
1035            .components
1036            .assert_instance_states_empty();
1037        let state = store.concurrent_state_mut().unwrap();
1038        assert!(
1039            state.table.get_mut().is_empty(),
1040            "non-empty table: {:?}",
1041            state.table.get_mut()
1042        );
1043        assert!(state.high_priority.is_empty());
1044        assert!(state.low_priority.is_empty());
1045        assert!(state.unforced_current_thread.is_none());
1046        assert!(state.futures_mut().unwrap().is_empty());
1047        assert!(state.global_error_context_ref_counts.is_empty());
1048    }
1049
1050    /// Helper function to perform tests over the size of the concurrent state
1051    /// table which can be useful for detecting leaks.
1052    ///
1053    /// Only intended for use in Wasmtime's own testing.
1054    #[doc(hidden)]
1055    pub fn concurrent_state_table_size(&mut self) -> usize {
1056        self.0
1057            .concurrent_state_mut()
1058            .unwrap()
1059            .table
1060            .get_mut()
1061            .iter_mut()
1062            .count()
1063    }
1064
1065    /// Spawn a background task to run as part of this instance's event loop.
1066    ///
1067    /// The task will receive an `&Accessor<U>` and run concurrently with
1068    /// any other tasks in progress for the instance.
1069    ///
1070    /// Note that the task will only make progress if and when the event loop
1071    /// for this instance is run.
1072    ///
1073    /// The returned [`JoinHandle`] may be used to cancel the task.
1074    pub fn spawn(mut self, task: impl AccessorTask<T>) -> Result<JoinHandle>
1075    where
1076        T: 'static,
1077    {
1078        let accessor = Accessor::new(StoreToken::new(self.as_context_mut()));
1079        self.spawn_with_accessor(accessor, task)
1080    }
1081
1082    /// Internal implementation of `spawn` functions where a `store` is
1083    /// available along with an `Accessor`.
1084    fn spawn_with_accessor<D>(
1085        self,
1086        accessor: Accessor<T, D>,
1087        task: impl AccessorTask<T, D>,
1088    ) -> Result<JoinHandle>
1089    where
1090        T: 'static,
1091        D: HasData + ?Sized,
1092    {
1093        // Create an "abortable future" here where internally the future will
1094        // hook calls to poll and possibly spawn more background tasks on each
1095        // iteration.
1096        let (handle, future) = JoinHandle::run(async move { task.run(&accessor).await });
1097        self.0
1098            .concurrent_state_mut()?
1099            .push_future(Box::pin(async move { future.await.unwrap_or(Ok(())) }));
1100        Ok(handle)
1101    }
1102
1103    /// Run the specified closure `fun` to completion as part of this store's
1104    /// event loop.
1105    ///
1106    /// This will run `fun` as part of this store's event loop until it
1107    /// yields a result.  `fun` is provided an [`Accessor`], which provides
1108    /// controlled access to the store and its data.
1109    ///
1110    /// This function can be used to invoke [`Func::call_concurrent`] for
1111    /// example within the async closure provided here.
1112    ///
1113    /// This function will unconditionally return an error if
1114    /// [`Config::concurrency_support`] is disabled.
1115    ///
1116    /// [`Config::concurrency_support`]: crate::Config::concurrency_support
1117    ///
1118    /// # Store-blocking behavior
1119    ///
1120    /// At this time there are certain situations in which the `Future` returned
1121    /// by the `AsyncFnOnce` passed to this function will not be polled for an
1122    /// extended period of time, despite one or more `Waker::wake` events having
1123    /// occurred for the task to which it belongs.  This can manifest as the
1124    /// `Future` seeming to be "blocked" or "locked up", but is actually due to
1125    /// the `Store` being held by e.g. a blocking host function, preventing the
1126    /// `Future` from being polled. A canonical example of this is when the
1127    /// `fun` provided to this function attempts to set a timeout for an
1128    /// invocation of a wasm function. In this situation the async closure is
1129    /// waiting both on (a) the wasm computation to finish, and (b) the timeout
1130    /// to elapse. At this time this setup will not always work and the timeout
1131    /// may not reliably fire.
1132    ///
1133    /// This function will not block the current thread and as such is always
1134    /// suitable to run in an `async` context, but the current implementation of
1135    /// Wasmtime can lead to situations where a certain wasm computation is
1136    /// required to make progress the closure to make progress. This is an
1137    /// artifact of Wasmtime's historical implementation of `async` functions
1138    /// and is the topic of [#11869] and [#11870]. In the timeout example from
1139    /// above it means that Wasmtime can get "wedged" for a bit where (a) must
1140    /// progress for a readiness notification of (b) to get delivered.
1141    ///
1142    /// This effectively means that it's not possible to reliably perform a
1143    /// "select" operation within the `fun` closure, which timeouts for example
1144    /// are based on. Fixing this requires some relatively major refactoring
1145    /// work within Wasmtime itself. This is a known pitfall otherwise and one
1146    /// that is intended to be fixed one day. In the meantime it's recommended
1147    /// to apply timeouts or such to the entire `run_concurrent` call itself
1148    /// rather than internally.
1149    ///
1150    /// [#11869]: https://github.com/bytecodealliance/wasmtime/issues/11869
1151    /// [#11870]: https://github.com/bytecodealliance/wasmtime/issues/11870
1152    ///
1153    /// # Example
1154    ///
1155    /// ```
1156    /// # use {
1157    /// #   wasmtime::{
1158    /// #     error::{Result},
1159    /// #     component::{ Component, Linker, Resource, ResourceTable},
1160    /// #     Config, Engine, Store
1161    /// #   },
1162    /// # };
1163    /// #
1164    /// # struct MyResource(u32);
1165    /// # struct Ctx { table: ResourceTable }
1166    /// #
1167    /// # async fn foo() -> Result<()> {
1168    /// # let mut config = Config::new();
1169    /// # let engine = Engine::new(&config)?;
1170    /// # let mut store = Store::new(&engine, Ctx { table: ResourceTable::new() });
1171    /// # let mut linker = Linker::new(&engine);
1172    /// # let component = Component::new(&engine, "")?;
1173    /// # let instance = linker.instantiate_async(&mut store, &component).await?;
1174    /// # let foo = instance.get_typed_func::<(Resource<MyResource>,), (Resource<MyResource>,)>(&mut store, "foo")?;
1175    /// # let bar = instance.get_typed_func::<(u32,), ()>(&mut store, "bar")?;
1176    /// store.run_concurrent(async |accessor| -> wasmtime::Result<_> {
1177    ///    let resource = accessor.with(|mut access| access.get().table.push(MyResource(42)))?;
1178    ///    let (another_resource,) = foo.call_concurrent(accessor, (resource,)).await?;
1179    ///    let value = accessor.with(|mut access| access.get().table.delete(another_resource))?;
1180    ///    bar.call_concurrent(accessor, (value.0,)).await?;
1181    ///    Ok(())
1182    /// }).await??;
1183    /// # Ok(())
1184    /// # }
1185    /// ```
1186    pub async fn run_concurrent<R>(self, fun: impl AsyncFnOnce(&Accessor<T>) -> R) -> Result<R>
1187    where
1188        T: Send + 'static,
1189    {
1190        ensure!(
1191            self.0.concurrency_support(),
1192            "cannot use `run_concurrent` when Config::concurrency_support disabled",
1193        );
1194        self.do_run_concurrent(fun, false).await
1195    }
1196
1197    pub(super) async fn run_concurrent_trap_on_idle<R>(
1198        self,
1199        fun: impl AsyncFnOnce(&Accessor<T>) -> R,
1200    ) -> Result<R>
1201    where
1202        T: Send + 'static,
1203    {
1204        self.do_run_concurrent(fun, true).await
1205    }
1206
1207    async fn do_run_concurrent<R>(
1208        mut self,
1209        fun: impl AsyncFnOnce(&Accessor<T>) -> R,
1210        trap_on_idle: bool,
1211    ) -> Result<R>
1212    where
1213        T: Send + 'static,
1214    {
1215        debug_assert!(self.0.concurrency_support());
1216        check_recursive_run();
1217        let token = StoreToken::new(self.as_context_mut());
1218
1219        struct Dropper<'a, T: 'static, V> {
1220            store: StoreContextMut<'a, T>,
1221            value: ManuallyDrop<V>,
1222        }
1223
1224        impl<'a, T, V> Drop for Dropper<'a, T, V> {
1225            fn drop(&mut self) {
1226                tls::set(self.store.0, || {
1227                    // SAFETY: Here we drop the value without moving it for the
1228                    // first and only time -- per the contract for `Drop::drop`,
1229                    // this code won't run again, and the `value` field will no
1230                    // longer be accessible.
1231                    unsafe { ManuallyDrop::drop(&mut self.value) }
1232                });
1233            }
1234        }
1235
1236        let accessor = &Accessor::new(token);
1237        let dropper = &mut Dropper {
1238            store: self,
1239            value: ManuallyDrop::new(fun(accessor)),
1240        };
1241        // SAFETY: We never move `dropper` nor its `value` field.
1242        let future = unsafe { Pin::new_unchecked(dropper.value.deref_mut()) };
1243
1244        dropper
1245            .store
1246            .as_context_mut()
1247            .poll_until(future, trap_on_idle)
1248            .await
1249    }
1250
1251    /// Run this store's event loop.
1252    ///
1253    /// The returned future will resolve when the specified future completes or,
1254    /// if `trap_on_idle` is true, when the event loop can't make further
1255    /// progress.
1256    async fn poll_until<R>(
1257        mut self,
1258        mut future: Pin<&mut impl Future<Output = R>>,
1259        trap_on_idle: bool,
1260    ) -> Result<R>
1261    where
1262        T: Send + 'static,
1263    {
1264        struct Reset<'a, T: 'static> {
1265            store: StoreContextMut<'a, T>,
1266            futures: Option<FuturesUnordered<HostTaskFuture>>,
1267        }
1268
1269        impl<'a, T> Drop for Reset<'a, T> {
1270            fn drop(&mut self) {
1271                if let Some(futures) = self.futures.take() {
1272                    *self
1273                        .store
1274                        .0
1275                        .concurrent_state_mut_already_forced_current_thread()
1276                        .futures
1277                        .get_mut() = Some(futures);
1278                }
1279            }
1280        }
1281
1282        loop {
1283            // Take `ConcurrentState::futures` out of the store so we can poll
1284            // it while also safely giving any of the futures inside access to
1285            // `self`.
1286            let futures = self.0.concurrent_state_mut()?.futures.get_mut().take();
1287            let mut reset = Reset {
1288                store: self.as_context_mut(),
1289                futures,
1290            };
1291            let mut next = match reset.futures.as_mut() {
1292                Some(f) => pin!(f.next()),
1293                None => bail_bug!("concurrent state missing futures field"),
1294            };
1295
1296            enum PollResult<R> {
1297                Complete(R),
1298                ProcessWork {
1299                    ready: Vec<WorkItem>,
1300                    low_priority: bool,
1301                },
1302            }
1303
1304            let result = future::poll_fn(|cx| {
1305                // First, poll the future we were passed as an argument and
1306                // return immediately if it's ready.
1307                if let Poll::Ready(value) = tls::set(reset.store.0, || future.as_mut().poll(cx)) {
1308                    return Poll::Ready(Ok(PollResult::Complete(value)));
1309                }
1310
1311                // Next, poll `ConcurrentState::futures` (which includes any
1312                // pending host tasks and/or background tasks), returning
1313                // immediately if one of them fails.
1314                let next = match tls::set(reset.store.0, || next.as_mut().poll(cx)) {
1315                    Poll::Ready(Some(output)) => {
1316                        match output {
1317                            Err(e) => return Poll::Ready(Err(e)),
1318                            Ok(()) => {}
1319                        }
1320                        Poll::Ready(true)
1321                    }
1322                    Poll::Ready(None) => Poll::Ready(false),
1323                    Poll::Pending => Poll::Pending,
1324                };
1325
1326                // Next, collect the next batch of work items to process, if
1327                // any.  This will be either all of the high-priority work
1328                // items, or if there are none, a single low-priority work item.
1329                let state = reset.store.0.concurrent_state_mut()?;
1330                let mut ready = mem::take(&mut state.high_priority);
1331                let mut low_priority = false;
1332                if ready.is_empty() {
1333                    if let Some(item) = state.low_priority.pop_back() {
1334                        ready.push(item);
1335                        low_priority = true;
1336                    }
1337                }
1338                if !ready.is_empty() {
1339                    return Poll::Ready(Ok(PollResult::ProcessWork {
1340                        ready,
1341                        low_priority,
1342                    }));
1343                }
1344
1345                // Finally, if we have nothing else to do right now, determine what to do
1346                // based on whether there are any pending futures in
1347                // `ConcurrentState::futures`.
1348                return match next {
1349                    Poll::Ready(true) => {
1350                        // In this case, one of the futures in
1351                        // `ConcurrentState::futures` completed
1352                        // successfully, so we return now and continue
1353                        // the outer loop in case there is another one
1354                        // ready to complete.
1355                        Poll::Ready(Ok(PollResult::ProcessWork {
1356                            ready: Vec::new(),
1357                            low_priority: false,
1358                        }))
1359                    }
1360                    Poll::Ready(false) => {
1361                        // Poll the future we were passed one last time
1362                        // in case one of `ConcurrentState::futures` had
1363                        // the side effect of unblocking it.
1364                        if let Poll::Ready(value) =
1365                            tls::set(reset.store.0, || future.as_mut().poll(cx))
1366                        {
1367                            Poll::Ready(Ok(PollResult::Complete(value)))
1368                        } else {
1369                            // In this case, there are no more pending
1370                            // futures in `ConcurrentState::futures`,
1371                            // there are no remaining work items, _and_
1372                            // the future we were passed as an argument
1373                            // still hasn't completed.
1374                            if trap_on_idle {
1375                                // `trap_on_idle` is true, so we exit
1376                                // immediately.
1377                                Poll::Ready(Err(Trap::AsyncDeadlock.into()))
1378                            } else {
1379                                // `trap_on_idle` is false, so we assume
1380                                // that future will wake up and give us
1381                                // more work to do when it's ready to.
1382                                Poll::Pending
1383                            }
1384                        }
1385                    }
1386                    // There is at least one pending future in
1387                    // `ConcurrentState::futures` and we have nothing
1388                    // else to do but wait for now, so we return
1389                    // `Pending`.
1390                    Poll::Pending => Poll::Pending,
1391                };
1392            })
1393            .await;
1394
1395            // Put the `ConcurrentState::futures` back into the store before we
1396            // return or handle any work items since one or more of those items
1397            // might append more futures.
1398            drop(reset);
1399
1400            match result? {
1401                // The future we were passed as an argument completed, so we
1402                // return the result.
1403                PollResult::Complete(value) => break Ok(value),
1404                // The future we were passed has not yet completed, so handle
1405                // any work items and then loop again.
1406                PollResult::ProcessWork {
1407                    ready,
1408                    low_priority,
1409                } => {
1410                    struct Dispose<'a, T: 'static, I: Iterator<Item = WorkItem>> {
1411                        store: StoreContextMut<'a, T>,
1412                        ready: I,
1413                    }
1414
1415                    impl<'a, T, I: Iterator<Item = WorkItem>> Drop for Dispose<'a, T, I> {
1416                        fn drop(&mut self) {
1417                            while let Some(item) = self.ready.next() {
1418                                match item {
1419                                    WorkItem::ResumeFiber(mut fiber) => fiber.dispose(self.store.0),
1420                                    WorkItem::PushFuture(future) => {
1421                                        tls::set(self.store.0, move || drop(future))
1422                                    }
1423                                    _ => {}
1424                                }
1425                            }
1426                        }
1427                    }
1428
1429                    let mut dispose = Dispose {
1430                        store: self.as_context_mut(),
1431                        ready: ready.into_iter(),
1432                    };
1433
1434                    // If we're about to run a low-priority task, first yield to
1435                    // the executor.  This ensures that it won't be starved of
1436                    // the ability to e.g. update the readiness of sockets,
1437                    // etc. which the guest may be using `thread.yield` along
1438                    // with `waitable-set.poll` to monitor in a CPU-heavy loop.
1439                    //
1440                    // This works for e.g. `thread.yield` and callbacks which
1441                    // return `CALLBACK_CODE_YIELD` because we queue a low
1442                    // priority item to resume the task (i.e. resume the thread
1443                    // or call the callback, respectively) just prior to
1444                    // suspending it.  Indeed, as of this writing those are the
1445                    // _only_ situations we queue low-priority tasks.
1446                    // Therefore, we interpret the guest's request to yield as
1447                    // meaning "yield to other guest tasks _and_/_or_ host
1448                    // operations such as updating socket readiness", the latter
1449                    // being the async runtime's responsibility.
1450                    //
1451                    // In the future, if this ends up causing measurable
1452                    // performance issues, this could be optimized such that we
1453                    // only yield periodically (e.g. for batches of low priority
1454                    // items) and not for each and every idividual item.
1455                    if low_priority {
1456                        dispose.store.0.yield_now().await
1457                    }
1458
1459                    while let Some(item) = dispose.ready.next() {
1460                        dispose
1461                            .store
1462                            .as_context_mut()
1463                            .handle_work_item(item)
1464                            .await?;
1465                    }
1466                }
1467            }
1468        }
1469    }
1470
1471    /// Handle the specified work item, possibly resuming a fiber if applicable.
1472    async fn handle_work_item(self, item: WorkItem) -> Result<()>
1473    where
1474        T: Send,
1475    {
1476        log::trace!("handle work item {item:?}");
1477        match item {
1478            WorkItem::PushFuture(future) => {
1479                self.0
1480                    .concurrent_state_mut()?
1481                    .futures_mut()?
1482                    .push(future.into_inner());
1483            }
1484            WorkItem::ResumeFiber(fiber) => {
1485                self.0.resume_fiber(fiber).await?;
1486            }
1487            WorkItem::ResumeThread(_, thread) => {
1488                if let GuestThreadState::Ready { fiber, .. } = mem::replace(
1489                    &mut self.0.concurrent_state_mut()?.get_mut(thread.thread)?.state,
1490                    GuestThreadState::Running,
1491                ) {
1492                    self.0.resume_fiber(fiber).await?;
1493                } else {
1494                    bail_bug!("cannot resume non-pending thread {thread:?}");
1495                }
1496            }
1497            WorkItem::GuestCall(_, call) => {
1498                if call.is_ready(self.0)? {
1499                    self.run_on_worker(WorkerItem::GuestCall(call)).await?;
1500                } else {
1501                    let state = self.0.concurrent_state_mut()?;
1502                    let task = state.get_mut(call.thread.task)?;
1503                    if !task.starting_sent {
1504                        task.starting_sent = true;
1505                        if let GuestCallKind::StartImplicit(_) = &call.kind {
1506                            Waitable::Guest(call.thread.task).set_event(
1507                                state,
1508                                Some(Event::Subtask {
1509                                    status: Status::Starting,
1510                                }),
1511                            )?;
1512                        }
1513                    }
1514
1515                    let instance = state.get_mut(call.thread.task)?.instance;
1516                    self.0
1517                        .instance_state(instance)
1518                        .concurrent_state()
1519                        .pending
1520                        .insert(call.thread, call.kind);
1521                }
1522            }
1523            WorkItem::WorkerFunction(fun) => {
1524                self.run_on_worker(WorkerItem::Function(fun)).await?;
1525            }
1526        }
1527
1528        Ok(())
1529    }
1530
1531    /// Execute the specified guest call on a worker fiber.
1532    async fn run_on_worker(self, item: WorkerItem) -> Result<()>
1533    where
1534        T: Send,
1535    {
1536        let worker = if let Some(fiber) = self.0.concurrent_state_mut()?.worker.take() {
1537            fiber
1538        } else {
1539            fiber::make_fiber(self.0, move |store| {
1540                loop {
1541                    let Some(item) = store.concurrent_state_mut()?.worker_item.take() else {
1542                        bail_bug!("worker_item not present when resuming fiber")
1543                    };
1544                    match item {
1545                        WorkerItem::GuestCall(call) => handle_guest_call(store, call)?,
1546                        WorkerItem::Function(fun) => fun.into_inner()(store)?,
1547                    }
1548
1549                    store.suspend(SuspendReason::NeedWork)?;
1550                }
1551            })?
1552        };
1553
1554        let worker_item = &mut self.0.concurrent_state_mut()?.worker_item;
1555        assert!(worker_item.is_none());
1556        *worker_item = Some(item);
1557
1558        self.0.resume_fiber(worker).await
1559    }
1560
1561    /// Wrap the specified host function in a future which will call it, passing
1562    /// it an `&Accessor<T>`.
1563    ///
1564    /// See the `Accessor` documentation for details.
1565    pub(crate) fn wrap_call<F, R>(self, closure: F) -> impl Future<Output = Result<R>> + 'static
1566    where
1567        T: 'static,
1568        F: FnOnce(&Accessor<T>) -> Pin<Box<dyn Future<Output = Result<R>> + Send + '_>>
1569            + Send
1570            + Sync
1571            + 'static,
1572        R: Send + Sync + 'static,
1573    {
1574        let token = StoreToken::new(self);
1575        async move {
1576            let mut accessor = Accessor::new(token);
1577            closure(&mut accessor).await
1578        }
1579    }
1580
1581    /// Returns an iterator over the current async call stack defined by the
1582    /// component model.
1583    ///
1584    /// This can be used, for example to correlate a host import call with which
1585    /// root export task originally called it.
1586    ///
1587    /// Tasks are yielded "youngest first" where the first item in the iterator
1588    /// is the current task, and the last item in the iterator is the original
1589    /// call.
1590    pub fn async_call_stack(&mut self) -> Result<impl Iterator<Item = GuestTaskId>> {
1591        let mut cur = Some(self.0.current_thread()?);
1592        let state = self.0.concurrent_state_mut()?;
1593        Ok(core::iter::from_fn(move || {
1594            while let Some(t) = cur {
1595                cur = state.parent(t);
1596                if let Some(task) = t.guest_task() {
1597                    return Some(GuestTaskId(task));
1598                }
1599            }
1600
1601            None
1602        }))
1603    }
1604}
1605
1606/// Return value of [`StoreOpaque::host_task_create`].
1607///
1608/// This is an `Option` to handle the dynamic `store.concurrency_support()`
1609/// property, and when set this returns the host task that was created in
1610/// addition to the previously running guest thread.
1611pub type EnteredHostTask = Option<(TableId<HostTask>, QualifiedThreadId)>;
1612
1613impl StoreOpaque {
1614    /// Returns the currently-running thread, promoting any deferred lazy thread
1615    /// into a fully-materialized `CurrentThread`.
1616    #[inline]
1617    pub(crate) fn current_thread(&mut self) -> Result<CurrentThread> {
1618        // Without concurrency support there is nothing to force.
1619        if !self.concurrency_support() {
1620            return Ok(CurrentThread::None);
1621        }
1622
1623        // If the JIT-visible current thread isn't a deferred thread then
1624        // `ConcurrentState` is already up to date.
1625        if !self
1626            .vm_store_context_mut()
1627            .current_thread_mut()
1628            .is_deferred()
1629        {
1630            return Ok(self
1631                .concurrent_state_mut_already_forced_current_thread()
1632                .unforced_current_thread);
1633        }
1634
1635        self.force_deferred_current_thread()
1636    }
1637
1638    /// Slow path of [`Self::current_thread`]: promote the deferred lazy
1639    /// thread into a fully-materialized `CurrentThread`.
1640    #[cold]
1641    fn force_deferred_current_thread(&mut self) -> Result<CurrentThread> {
1642        // The component instance whose adapters pushed the deferred frames; all
1643        // frames in a guest-to-guest, sync-to-sync call chain of fused adapters
1644        // live within a single `wasmtime::component::Instance` (because
1645        // cross-`wasmtime::component::Instance` calls don't go through fused
1646        // adapters), and guest code only ever runs as a guest thread, so the
1647        // chain's base thread is already materialized in `ConcurrentState` and
1648        // we can get the `ComponentInstanceId` shared by the whole chain from
1649        // here.
1650        let state = self.concurrent_state_mut_without_forcing_current_thread();
1651        let id = match state.unforced_current_thread.guest_task() {
1652            Some(task) => state.get_mut(task)?.instance.instance,
1653            None => bail_bug!("deferred component-model thread with non-guest base"),
1654        };
1655
1656        // Collect the deferred frames pushed inline by fused adapters, walking
1657        // the `parent` chain from innermost to the base.
1658        let mut frames = Vec::new();
1659        let mut cur = *self.vm_store_context_mut().current_thread_mut();
1660        while let Some(ptr) = cur.as_deferred() {
1661            // SAFETY: `ptr` points at a `VMDeferredThread` living in a fused
1662            // adapter's stack frame that is suspended below us on the stack
1663            // (mid-call, waiting for this nested call to return), so the
1664            // referent is still valid and exclusively ours to read.
1665            let deferred = unsafe { ptr.as_non_null().as_ref() };
1666            frames.push((
1667                deferred.callee_async != 0,
1668                deferred.callee_instance,
1669                deferred.saved_context,
1670            ));
1671            cur = deferred.parent;
1672        }
1673
1674        // Mark the current thread forced *before* replaying so that any
1675        // reentrant `force_current_thread` call short-circuits via the
1676        // non-deferred path above.
1677        *self.vm_store_context_mut().current_thread_mut() = VMLazyThread::forced();
1678
1679        // Save the current context, as we need to overwrite it while replaying
1680        // below.
1681        let current_context = *self.vm_store_context_mut().component_context_mut();
1682
1683        // Replay the deferred `enter_guest_sync_call`s outermost-first so that
1684        // the resulting `ConcurrentState` matches what the non-deferred path
1685        // would have otherwise produced.
1686        for (callee_async, callee_instance, saved_context) in frames.into_iter().rev() {
1687            // Restore the caller's context slots so that we save the correct
1688            // values into the caller's thread, exactly as the non-deferred path
1689            // would have on entry.
1690            *self.vm_store_context_mut().component_context_mut() = saved_context;
1691            let callee = RuntimeInstance {
1692                instance: id,
1693                index: RuntimeComponentInstanceIndex::from_u32(callee_instance),
1694            };
1695            self.enter_guest_sync_call(None, callee_async, callee)?;
1696        }
1697
1698        // Replaying done; restore the current context.
1699        *self.vm_store_context_mut().component_context_mut() = current_context;
1700
1701        Ok(self
1702            .concurrent_state_mut_without_forcing_current_thread()
1703            .unforced_current_thread)
1704    }
1705
1706    fn current_guest_thread(&mut self) -> Result<QualifiedThreadId> {
1707        match self.current_thread()?.guest() {
1708            Some(id) => Ok(*id),
1709            None => bail_bug!("current thread is not a guest thread"),
1710        }
1711    }
1712
1713    fn current_host_thread(&mut self) -> Result<TableId<HostTask>> {
1714        match self.current_thread()?.host() {
1715            Some(id) => Ok(id),
1716            None => bail_bug!("current thread is not a host thread"),
1717        }
1718    }
1719
1720    /// Returns whether there's a pending cancellation on the current guest thread,
1721    /// consuming the event if so.
1722    fn take_pending_cancellation(&mut self) -> Result<bool> {
1723        let thread = self.current_guest_thread()?;
1724        let task = self.concurrent_state_mut()?.get_mut(thread.task)?;
1725        if let Some(Event::Cancelled) = task.event {
1726            task.event.take();
1727            return Ok(true);
1728        }
1729        Ok(false)
1730    }
1731
1732    /// Push a `GuestTask` onto the task stack for either a sync-to-sync,
1733    /// guest-to-guest call or a sync host-to-guest call.
1734    ///
1735    /// This task will only be used for the purpose of handling calls to
1736    /// intrinsic functions; both parameter lowering and result lifting are
1737    /// assumed to be taken care of elsewhere.
1738    ///
1739    /// NB: for sync-to-sync, guest-to-guest calls we delay task construction in
1740    /// fused adapters, see `StoreOpaque::current_thread`, `VMDeferredThread`,
1741    /// and `lower_fact_enter_sync_call`. Make sure all this stuff stays in
1742    /// sync!
1743    pub(crate) fn enter_guest_sync_call(
1744        &mut self,
1745        guest_caller: Option<RuntimeInstance>,
1746        callee_async: bool,
1747        callee: RuntimeInstance,
1748    ) -> Result<()> {
1749        log::trace!("enter sync call {callee:?}");
1750        if !self.concurrency_support() {
1751            return self.enter_call_not_concurrent();
1752        }
1753
1754        let thread = self.current_thread()?;
1755        let state = self.concurrent_state_mut()?;
1756        let instance = if let Some(task) = thread.guest_task() {
1757            Some(state.get_mut(task)?.instance)
1758        } else {
1759            None
1760        };
1761        if guest_caller.is_some() {
1762            debug_assert_eq!(instance, guest_caller);
1763        }
1764        let guest_thread = GuestTask::new(
1765            state,
1766            Box::new(move |_, _| bail_bug!("cannot lower params in sync call")),
1767            LiftResult {
1768                lift: Box::new(move |_, _| bail_bug!("cannot lift result in sync call")),
1769                ty: TypeTupleIndex::reserved_value(),
1770                memory: None,
1771                string_encoding: StringEncoding::Utf8,
1772            },
1773            if let Some(thread) = thread.guest() {
1774                Caller::Guest { thread: *thread }
1775            } else {
1776                Caller::Host {
1777                    tx: None,
1778                    host_future_present: false,
1779                    caller: thread,
1780                }
1781            },
1782            None,
1783            callee,
1784            callee_async,
1785        )?;
1786
1787        Instance::from_wasmtime(self, callee.instance).add_guest_thread_to_instance_table(
1788            guest_thread.thread,
1789            self,
1790            callee.index,
1791        )?;
1792        self.set_thread(guest_thread)?;
1793
1794        Ok(())
1795    }
1796
1797    /// Pop a `GuestTask` previously pushed using `enter_sync_call`.
1798    ///
1799    /// NB: for sync-to-sync, guest-to-guest calls we delay task construction in
1800    /// fused adapters and then when the call returns we check to see if the
1801    /// task's contruction was forced and if not avoid calling out of the JIT
1802    /// code to this function. See `lower_fact_exit_sync_call`. Make sure all
1803    /// this stuff stays in sync!
1804    pub(crate) fn exit_guest_sync_call(&mut self) -> Result<()> {
1805        if !self.concurrency_support() {
1806            return Ok(self.exit_call_not_concurrent());
1807        }
1808        let thread = match self.set_thread(CurrentThread::None)?.guest() {
1809            Some(t) => *t,
1810            None => bail_bug!("expected task when exiting"),
1811        };
1812        let task = self.concurrent_state_mut()?.get_mut(thread.task)?;
1813        let instance = task.instance;
1814        let caller = match &task.caller {
1815            &Caller::Guest { thread } => thread.into(),
1816            &Caller::Host { caller, .. } => caller,
1817        };
1818        task.lift_result = None;
1819        task.exited = true;
1820        self.set_thread(caller)?;
1821
1822        log::trace!("exit sync call {instance:?}");
1823        self.cleanup_thread(thread, instance, CleanupTask::Yes)?;
1824
1825        Ok(())
1826    }
1827
1828    /// Similar to `enter_guest_sync_call` except for when the guest makes a
1829    /// transition to the host.
1830    ///
1831    /// FIXME: this is called for all guest->host transitions and performs some
1832    /// relatively expensive table manipulations. This would ideally be
1833    /// optimized to avoid the full allocation of a `HostTask` in at least some
1834    /// situations.
1835    pub(crate) fn host_task_create(&mut self) -> Result<EnteredHostTask> {
1836        if !self.concurrency_support() {
1837            self.enter_call_not_concurrent()?;
1838            return Ok(None);
1839        }
1840        let caller = self.current_guest_thread()?;
1841        let state = self.concurrent_state_mut()?;
1842        let task = state.push(HostTask::new(caller.task, HostTaskState::CalleeStarted))?;
1843        log::trace!("new host task {task:?}");
1844        self.set_thread(task)?;
1845        Ok(Some((task, caller)))
1846    }
1847
1848    /// Dual of `host_task_create` and signifies that the host has finished and
1849    /// will be cleaned up.
1850    ///
1851    /// Note that this isn't invoked when the host is invoked asynchronously and
1852    /// the host isn't complete yet. In that situation the host task persists
1853    /// and will be cleaned up separately in `subtask_drop`
1854    pub(crate) fn host_task_delete(&mut self, task: EnteredHostTask) -> Result<()> {
1855        match task {
1856            Some((task, caller)) => {
1857                self.set_thread(caller)?;
1858                log::trace!("delete host task {task:?}");
1859                self.concurrent_state_mut()?.delete(task)?;
1860            }
1861            None => {
1862                self.exit_call_not_concurrent();
1863            }
1864        }
1865        Ok(())
1866    }
1867
1868    /// Determine whether the specified instance may be entered from the host.
1869    ///
1870    /// We return `true` here only if all of the following hold:
1871    ///
1872    /// - The top-level instance is not already on the current task's call stack.
1873    /// - The instance is not in need of a post-return function call.
1874    /// - `self` has not been poisoned due to a trap.
1875    pub(crate) fn may_enter(&mut self, instance: RuntimeInstance) -> Result<bool> {
1876        if self.trapped() {
1877            return Ok(false);
1878        }
1879        if !self.concurrency_support() {
1880            return Ok(true);
1881        }
1882        let mut cur = Some(self.current_thread()?);
1883        let state = self.concurrent_state_mut()?;
1884        while let Some(t) = cur {
1885            if let Some(task) = t.guest_task() {
1886                let task = state.get_mut(task)?;
1887                // Note that we only compare top-level instance IDs here.
1888                // The idea is that the host is not allowed to recursively
1889                // enter a top-level instance even if the specific leaf
1890                // instance is not on the stack. This the behavior defined
1891                // in the spec, and it allows us to elide runtime checks in
1892                // guest-to-guest adapters.
1893                if task.instance.instance == instance.instance {
1894                    return Ok(false);
1895                }
1896            }
1897            cur = state.parent(t);
1898        }
1899        Ok(true)
1900    }
1901
1902    /// Helper function to retrieve the `InstanceState` for the
1903    /// specified instance.
1904    fn instance_state(&mut self, instance: RuntimeInstance) -> &mut InstanceState {
1905        self.component_instance_mut(instance.instance)
1906            .instance_state(instance.index)
1907    }
1908
1909    /// Configure the currently running `thread`.
1910    ///
1911    /// This will save off any state necessary for the previous thread, if
1912    /// applicable, and then it'll additionally update state for `thread` if
1913    /// needed too.
1914    fn set_thread(&mut self, thread: impl Into<CurrentThread>) -> Result<CurrentThread> {
1915        let thread = thread.into();
1916        let state = self.concurrent_state_mut()?;
1917        let old_thread = mem::replace(&mut state.unforced_current_thread, thread);
1918
1919        // First thing to do after swapping threads is updating the context
1920        // slots for this thread within the store. This restores the behavior of
1921        // `context.{get,set}`. This involves taking the old state out of the
1922        // store, saving it in the thread that's being swapped from, and doing
1923        // the inverse for the new thread. When debug assertions are enabled
1924        // this also leaves behind sentinel values to try to uncover bugs where
1925        // this may be forgotten.
1926        if let Some(old_thread) = old_thread.guest() {
1927            let old_context = *self.vm_store_context_mut().component_context_mut();
1928            self.concurrent_state_mut()?
1929                .get_mut(old_thread.thread)?
1930                .context = old_context;
1931        }
1932        if cfg!(debug_assertions) {
1933            *self.vm_store_context_mut().component_context_mut() =
1934                [u32::MAX; NUM_COMPONENT_CONTEXT_SLOTS];
1935        }
1936        if let Some(thread) = thread.guest() {
1937            let thread = self.concurrent_state_mut()?.get_mut(thread.thread)?;
1938            let context = thread.context;
1939            if cfg!(debug_assertions) {
1940                thread.context = [u32::MAX; NUM_COMPONENT_CONTEXT_SLOTS];
1941            }
1942            *self.vm_store_context_mut().component_context_mut() = context;
1943        }
1944
1945        // Each time we switch threads, we conservatively set `task_may_block`
1946        // to `false` for the component instance we're switching away from (if
1947        // any), meaning it will be `false` for any new thread created for that
1948        // instance unless explicitly set otherwise.
1949        //
1950        // Additionally if we're switching to a new thread, set its component
1951        // instance's `task_may_block` according to where it left off.
1952        let state = self.concurrent_state_mut()?;
1953        if let Some(old_task) = old_thread.guest_task() {
1954            let instance = state.get_mut(old_task)?.instance.instance;
1955            self.component_instance_mut(instance)
1956                .set_task_may_block(false)
1957        }
1958
1959        if thread.guest_task().is_some() {
1960            self.set_task_may_block()?;
1961        }
1962
1963        // Keep the JIT-visible current-thread pointer in sync.
1964        *self.vm_store_context_mut().current_thread_mut() = if thread.is_none() {
1965            VMLazyThread::none()
1966        } else {
1967            VMLazyThread::forced()
1968        };
1969
1970        Ok(old_thread)
1971    }
1972
1973    /// Set the global variable representing whether the current task may block
1974    /// prior to entering Wasm code.
1975    fn set_task_may_block(&mut self) -> Result<()> {
1976        let guest_thread = self.current_guest_thread()?;
1977        let state = self.concurrent_state_mut()?;
1978        let instance = state.get_mut(guest_thread.task)?.instance.instance;
1979        let may_block = self.concurrent_state_mut()?.may_block(guest_thread.task)?;
1980        self.component_instance_mut(instance)
1981            .set_task_may_block(may_block);
1982        Ok(())
1983    }
1984
1985    pub(crate) fn check_blocking(&mut self) -> Result<()> {
1986        if !self.concurrency_support() {
1987            return Ok(());
1988        }
1989        let task = self.current_guest_thread()?.task;
1990        let state = self.concurrent_state_mut()?;
1991        let instance = state.get_mut(task)?.instance.instance;
1992        let task_may_block = self.component_instance(instance).get_task_may_block();
1993
1994        if task_may_block {
1995            Ok(())
1996        } else {
1997            Err(Trap::CannotBlockSyncTask.into())
1998        }
1999    }
2000
2001    /// Record that we're about to enter a (sub-)component instance which does
2002    /// not support more than one concurrent, stackful activation, meaning it
2003    /// cannot be entered again until the next call returns.
2004    fn enter_instance(&mut self, instance: RuntimeInstance) {
2005        log::trace!("enter {instance:?}");
2006        self.instance_state(instance)
2007            .concurrent_state()
2008            .do_not_enter = true;
2009    }
2010
2011    /// Record that we've exited a (sub-)component instance previously entered
2012    /// with `Self::enter_instance` and then calls `Self::partition_pending`.
2013    /// See the documentation for the latter for details.
2014    fn exit_instance(&mut self, instance: RuntimeInstance) -> Result<()> {
2015        log::trace!("exit {instance:?}");
2016        self.instance_state(instance)
2017            .concurrent_state()
2018            .do_not_enter = false;
2019        self.partition_pending(instance)
2020    }
2021
2022    /// Iterate over `InstanceState::pending`, moving any ready items into the
2023    /// "high priority" work item queue.
2024    ///
2025    /// Also, notify `ConcurrentState::ready_for_concurrent_call_waker` if
2026    /// present.
2027    ///
2028    /// See `GuestCall::is_ready` for details.
2029    fn partition_pending(&mut self, instance: RuntimeInstance) -> Result<()> {
2030        for (thread, kind) in
2031            mem::take(&mut self.instance_state(instance).concurrent_state().pending).into_iter()
2032        {
2033            let call = GuestCall { thread, kind };
2034            if call.is_ready(self)? {
2035                self.concurrent_state_mut()?
2036                    .push_high_priority(WorkItem::GuestCall(instance.index, call));
2037            } else {
2038                self.instance_state(instance)
2039                    .concurrent_state()
2040                    .pending
2041                    .insert(call.thread, call.kind);
2042            }
2043        }
2044
2045        if let Some(waker) = self
2046            .concurrent_state_mut()?
2047            .ready_for_concurrent_call_waker
2048            .take()
2049        {
2050            waker.wake();
2051        }
2052
2053        Ok(())
2054    }
2055
2056    /// Implements the `backpressure.{inc,dec}` intrinsics.
2057    pub(crate) fn backpressure_modify(
2058        &mut self,
2059        caller_instance: RuntimeInstance,
2060        modify: impl FnOnce(u16) -> Option<u16>,
2061    ) -> Result<()> {
2062        let state = self.instance_state(caller_instance).concurrent_state();
2063        let old = state.backpressure;
2064        let new = modify(old).ok_or_else(|| Trap::BackpressureOverflow)?;
2065        state.backpressure = new;
2066
2067        if old > 0 && new == 0 {
2068            // Backpressure was previously enabled and is now disabled; move any
2069            // newly-eligible guest calls to the "high priority" queue.
2070            self.partition_pending(caller_instance)?;
2071        }
2072
2073        Ok(())
2074    }
2075
2076    /// Resume the specified fiber, giving it exclusive access to the specified
2077    /// store.
2078    async fn resume_fiber(&mut self, fiber: StoreFiber<'static>) -> Result<()> {
2079        let old_thread = self.current_thread()?;
2080        log::trace!("resume_fiber: save current thread {old_thread:?}");
2081
2082        let fiber = fiber::resolve_or_release(self, fiber).await?;
2083
2084        self.set_thread(old_thread)?;
2085
2086        let state = self.concurrent_state_mut()?;
2087
2088        if let Some(ot) = old_thread.guest() {
2089            state.get_mut(ot.thread)?.state = GuestThreadState::Running;
2090        }
2091        log::trace!("resume_fiber: restore current thread {old_thread:?}");
2092
2093        if let Some(mut fiber) = fiber {
2094            log::trace!("resume_fiber: suspend reason {:?}", &state.suspend_reason);
2095            // See the `SuspendReason` documentation for what each case means.
2096            let reason = match state.suspend_reason.take() {
2097                Some(r) => r,
2098                None => bail_bug!("suspend reason missing when resuming fiber"),
2099            };
2100            match reason {
2101                SuspendReason::NeedWork => {
2102                    if state.worker.is_none() {
2103                        state.worker = Some(fiber);
2104                    } else {
2105                        fiber.dispose(self);
2106                    }
2107                }
2108                SuspendReason::Yielding {
2109                    thread,
2110                    cancellable,
2111                    ..
2112                } => {
2113                    state.get_mut(thread.thread)?.state =
2114                        GuestThreadState::Ready { fiber, cancellable };
2115                    let instance = state.get_mut(thread.task)?.instance.index;
2116                    state.push_low_priority(WorkItem::ResumeThread(instance, thread));
2117                }
2118                SuspendReason::ExplicitlySuspending { thread, .. } => {
2119                    state.get_mut(thread.thread)?.state = GuestThreadState::Suspended(fiber);
2120                }
2121                SuspendReason::Waiting { set, thread, .. } => {
2122                    let old = state
2123                        .get_mut(set)?
2124                        .waiting
2125                        .insert(thread, WaitMode::Fiber(fiber));
2126                    assert!(old.is_none());
2127                }
2128            };
2129        } else {
2130            log::trace!("resume_fiber: fiber has exited");
2131        }
2132
2133        Ok(())
2134    }
2135
2136    /// Suspend the current fiber, storing the reason in
2137    /// `ConcurrentState::suspend_reason` to indicate the conditions under which
2138    /// it should be resumed.
2139    ///
2140    /// See the `SuspendReason` documentation for details.
2141    fn suspend(&mut self, reason: SuspendReason) -> Result<()> {
2142        log::trace!("suspend fiber: {reason:?}");
2143
2144        // If we're yielding or waiting on behalf of a guest thread, we'll need to
2145        // pop the call context which manages resource borrows before suspending
2146        // and then push it again once we've resumed.
2147        let task = match &reason {
2148            SuspendReason::Yielding { thread, .. }
2149            | SuspendReason::Waiting { thread, .. }
2150            | SuspendReason::ExplicitlySuspending { thread, .. } => Some(thread.task),
2151            SuspendReason::NeedWork => None,
2152        };
2153
2154        let old_guest_thread = if task.is_some() {
2155            self.current_thread()?
2156        } else {
2157            CurrentThread::None
2158        };
2159
2160        // We should not have reached here unless either there's no current
2161        // task, or the current task is permitted to block.  In addition, we
2162        // special-case `thread.switch-to` and waiting for a subtask to go from
2163        // `starting` to `started`, both of which we consider non-blocking
2164        // operations despite requiring a suspend.
2165        debug_assert!(
2166            matches!(
2167                reason,
2168                SuspendReason::ExplicitlySuspending {
2169                    skip_may_block_check: true,
2170                    ..
2171                } | SuspendReason::Waiting {
2172                    skip_may_block_check: true,
2173                    ..
2174                } | SuspendReason::Yielding {
2175                    skip_may_block_check: true,
2176                    ..
2177                }
2178            ) || old_guest_thread
2179                .guest_task()
2180                .map(|task| self.concurrent_state_mut()?.may_block(task))
2181                .transpose()?
2182                .unwrap_or(true)
2183        );
2184
2185        let suspend_reason = &mut self.concurrent_state_mut()?.suspend_reason;
2186        assert!(suspend_reason.is_none());
2187        *suspend_reason = Some(reason);
2188
2189        self.with_blocking(|_, cx| cx.suspend(StoreFiberYield::ReleaseStore))?;
2190
2191        if task.is_some() {
2192            self.set_thread(old_guest_thread)?;
2193        }
2194
2195        Ok(())
2196    }
2197
2198    fn wait_for_event(&mut self, waitable: Waitable) -> Result<()> {
2199        let caller = self.current_guest_thread()?;
2200        let state = self.concurrent_state_mut()?;
2201
2202        waitable.trap_if_in_waitable_set(state)?;
2203
2204        let set = state.get_mut(caller.thread)?.sync_call_set;
2205        waitable.join(state, Some(set))?;
2206        self.suspend(SuspendReason::Waiting {
2207            set,
2208            thread: caller,
2209            skip_may_block_check: false,
2210        })?;
2211        let state = self.concurrent_state_mut()?;
2212        waitable.join(state, None)
2213    }
2214
2215    /// Cleans up the data structures backing the `guest_thread` specified,
2216    /// removing it from the internal tables of `runtime_instance` as well.
2217    ///
2218    /// This function is used whenever a guest thread has fully exited and
2219    /// completed. This'll clean up the associated `GuestThread` structure and
2220    /// related resources it contains.
2221    ///
2222    /// Other functionality that this implements is:
2223    ///
2224    /// * This will perform conditional cleanup of the `GuestTask` that owns
2225    ///   this thread if `cleanup_task` is `CleanupTask::Yes`.
2226    /// * If there are no more threads in the `GuestTask` that this thread is
2227    ///   associated with, and if the task hasn't produced a result (e.g. it's not
2228    ///   returned or cancelled), then a trap will be raised that a result
2229    ///   wasn't ever produced.
2230    /// * If this task is finished, meaning the top-level thread exited and
2231    ///   additionally it's been returned or cancelled, then this will handle
2232    ///   management of the store's "active interesting tasks" counter.
2233    ///
2234    /// Effectively this is intended to be a "narrow waist" through which many
2235    /// destruction operations are funneled through.
2236    fn cleanup_thread(
2237        &mut self,
2238        guest_thread: QualifiedThreadId,
2239        runtime_instance: RuntimeInstance,
2240        cleanup_task: CleanupTask,
2241    ) -> Result<()> {
2242        let state = self.concurrent_state_mut()?;
2243        let thread_data = state.get_mut(guest_thread.thread)?;
2244        let sync_call_set = thread_data.sync_call_set;
2245        if let Some(guest_id) = thread_data.instance_rep {
2246            self.instance_state(runtime_instance)
2247                .thread_handle_table()
2248                .guest_thread_remove(guest_id)?;
2249        }
2250        let state = self.concurrent_state_mut()?;
2251
2252        // Clean up any pending subtasks in the sync_call_set
2253        for waitable in mem::take(&mut state.get_mut(sync_call_set)?.ready) {
2254            if let Some(Event::Subtask {
2255                status: Status::Returned | Status::ReturnCancelled,
2256            }) = waitable.common(state)?.event
2257            {
2258                waitable.delete_from(state)?;
2259            }
2260        }
2261
2262        state.delete(guest_thread.thread)?;
2263        state.delete(sync_call_set)?;
2264        let task = state.get_mut(guest_thread.task)?;
2265        task.threads.remove(&guest_thread.thread);
2266
2267        if task.threads.is_empty() && !task.returned_or_cancelled() {
2268            bail!(Trap::NoAsyncResult);
2269        }
2270        let ready_to_delete = task.ready_to_delete();
2271
2272        if !task.decremented_interesting_task_count && task.exited && task.returned_or_cancelled() {
2273            task.decremented_interesting_task_count = true;
2274
2275            debug_assert!(state.interesting_tasks > 0);
2276            state.interesting_tasks -= 1;
2277            if state.interesting_tasks == 0
2278                && let Some(waker) = state.interesting_tasks_empty_waker.take()
2279            {
2280                waker.wake();
2281            }
2282        }
2283
2284        match cleanup_task {
2285            CleanupTask::Yes => {
2286                if ready_to_delete {
2287                    Waitable::Guest(guest_thread.task).delete_from(state)?;
2288                }
2289            }
2290            CleanupTask::No => {}
2291        }
2292
2293        Ok(())
2294    }
2295
2296    /// Performs cancellation of the `guest_task` specified with the
2297    /// precondition that the task hasn't lowered its parameters.
2298    ///
2299    /// In this situation the task hasn't ever been started meaning it hasn't
2300    /// actually run any wasm code yet. This requires cleaning up metadata such
2301    /// as thread information attached to the task.
2302    ///
2303    /// The main two entrypoints for this function are:
2304    ///
2305    /// * Task cancellation via `subtask.cancel`, the intrinsic.
2306    /// * Dropping a host `call_async` future which needs to cancel the task
2307    ///   because it cannot reference its parameters any more.
2308    fn cancel_guest_subtask_without_lowered_parameters(
2309        &mut self,
2310        caller_instance: RuntimeInstance,
2311        guest_task: TableId<GuestTask>,
2312    ) -> Result<()> {
2313        let concurrent_state = self.concurrent_state_mut()?;
2314        let task = concurrent_state.get_mut(guest_task)?;
2315        assert!(!task.already_lowered_parameters());
2316        // The task is in a `starting` state, meaning it hasn't run at
2317        // all yet.  Here we update its fields to indicate that it is
2318        // ready to delete immediately once `subtask.drop` is called.
2319        task.lower_params = None;
2320        task.lift_result = None;
2321        task.exited = true;
2322        let instance = task.instance;
2323
2324        // Clean up the thread within this task as it's now never going
2325        // to run.
2326        assert_eq!(1, task.threads.len());
2327        let thread = *task.threads.iter().next().unwrap();
2328        self.cleanup_thread(
2329            QualifiedThreadId {
2330                task: guest_task,
2331                thread,
2332            },
2333            caller_instance,
2334            CleanupTask::No,
2335        )?;
2336
2337        // Not yet started; cancel and remove from pending
2338        let pending = &mut self.instance_state(instance).concurrent_state().pending;
2339        let pending_count = pending.len();
2340        pending.retain(|thread, _| thread.task != guest_task);
2341        // If there were no pending threads for this task, we're in an error state
2342        if pending.len() == pending_count {
2343            bail!(Trap::SubtaskCancelAfterTerminal);
2344        }
2345        Ok(())
2346    }
2347
2348    /// Used by `ResourceTables` to record the scope of a borrow to get undone
2349    /// in the future.
2350    pub(crate) fn current_scope_id(&mut self) -> Result<Option<u32>> {
2351        if !self.concurrency_support() {
2352            return self.current_scope_id_not_concurrent();
2353        }
2354        let (bits, is_host) = match self.current_thread()? {
2355            CurrentThread::Guest(id) => (id.task.rep(), false),
2356            CurrentThread::GuestTask(id) => (id.rep(), false),
2357            CurrentThread::Host(id) => (id.rep(), true),
2358            CurrentThread::None => return Ok(None),
2359        };
2360        assert_eq!((bits << 1) >> 1, bits);
2361        Ok(Some((bits << 1) | u32::from(is_host)))
2362    }
2363}
2364
2365enum CleanupTask {
2366    Yes,
2367    No,
2368}
2369
2370impl Instance {
2371    /// Get the next pending event for the specified task and (optional)
2372    /// waitable set, along with the waitable handle if applicable.
2373    fn get_event(
2374        self,
2375        store: &mut StoreOpaque,
2376        guest_task: TableId<GuestTask>,
2377        set: Option<TableId<WaitableSet>>,
2378        cancellable: bool,
2379    ) -> Result<Option<(Event, Option<(Waitable, u32)>)>> {
2380        let state = store.concurrent_state_mut()?;
2381
2382        let event = &mut state.get_mut(guest_task)?.event;
2383        if let Some(ev) = event
2384            && (cancellable || !matches!(ev, Event::Cancelled))
2385        {
2386            log::trace!("deliver event {ev:?} to {guest_task:?}");
2387            let ev = *ev;
2388            *event = None;
2389            return Ok(Some((ev, None)));
2390        }
2391
2392        let set = match set {
2393            Some(set) => set,
2394            None => return Ok(None),
2395        };
2396        let waitable = match state.get_mut(set)?.ready.pop_first() {
2397            Some(v) => v,
2398            None => return Ok(None),
2399        };
2400
2401        let common = waitable.common(state)?;
2402        let handle = match common.handle {
2403            Some(h) => h,
2404            None => bail_bug!("handle not set when delivering event"),
2405        };
2406        let event = match common.event.take() {
2407            Some(e) => e,
2408            None => bail_bug!("event not set when delivering event"),
2409        };
2410
2411        log::trace!(
2412            "deliver event {event:?} to {guest_task:?} for {waitable:?} (handle {handle}); set {set:?}"
2413        );
2414
2415        waitable.on_delivery(store, self, event)?;
2416
2417        Ok(Some((event, Some((waitable, handle)))))
2418    }
2419
2420    /// Handle the `CallbackCode` returned from an async-lifted export or its
2421    /// callback.
2422    ///
2423    /// If this returns `Ok(Some(call))`, then `call` should be run immediately
2424    /// using `handle_guest_call`.
2425    fn handle_callback_code(
2426        self,
2427        store: &mut StoreOpaque,
2428        guest_thread: QualifiedThreadId,
2429        runtime_instance: RuntimeComponentInstanceIndex,
2430        code: u32,
2431    ) -> Result<Option<GuestCall>> {
2432        let (code, set) = unpack_callback_code(code);
2433
2434        log::trace!("received callback code from {guest_thread:?}: {code} (set: {set})");
2435
2436        let state = store.concurrent_state_mut()?;
2437
2438        let get_set = |store: &mut StoreOpaque, handle| -> Result<_> {
2439            let set = store
2440                .instance_state(self.runtime_instance(runtime_instance))
2441                .handle_table()
2442                .waitable_set_rep(handle)?;
2443
2444            Ok(TableId::<WaitableSet>::new(set))
2445        };
2446
2447        Ok(match code {
2448            callback_code::EXIT => {
2449                log::trace!("implicit thread {guest_thread:?} completed");
2450                let task = store.concurrent_state_mut()?.get_mut(guest_thread.task)?;
2451                task.exited = true;
2452                task.callback = None;
2453                store.cleanup_thread(
2454                    guest_thread,
2455                    self.runtime_instance(runtime_instance),
2456                    CleanupTask::Yes,
2457                )?;
2458                None
2459            }
2460            callback_code::YIELD => {
2461                let task = state.get_mut(guest_thread.task)?;
2462                // If an `Event::Cancelled` is pending, we'll deliver that;
2463                // otherwise, we'll deliver `Event::None`.  Note that
2464                // `GuestTask::event` is only ever set to one of those two
2465                // `Event` variants.
2466                if let Some(event) = task.event {
2467                    assert!(matches!(event, Event::None | Event::Cancelled));
2468                } else {
2469                    task.event = Some(Event::None);
2470                }
2471                let call = GuestCall {
2472                    thread: guest_thread,
2473                    kind: GuestCallKind::DeliverEvent {
2474                        instance: self,
2475                        set: None,
2476                    },
2477                };
2478                if state.may_block(guest_thread.task)? {
2479                    // Push this thread onto the "low priority" queue so it runs
2480                    // after any other threads have had a chance to run.
2481                    state.push_low_priority(WorkItem::GuestCall(runtime_instance, call));
2482                    None
2483                } else {
2484                    // Yielding in a non-blocking context is defined as a no-op
2485                    // according to the spec, so we must run this thread
2486                    // immediately without allowing any others to run.
2487                    Some(call)
2488                }
2489            }
2490            callback_code::WAIT => {
2491                // The task may only return `WAIT` if it was created for a call
2492                // to an async export).  Otherwise, we'll trap.
2493                state.check_blocking_for(guest_thread.task)?;
2494
2495                let set = get_set(store, set)?;
2496                let state = store.concurrent_state_mut()?;
2497
2498                if state.get_mut(guest_thread.task)?.event.is_some()
2499                    || !state.get_mut(set)?.ready.is_empty()
2500                {
2501                    // An event is immediately available; deliver it ASAP.
2502                    state.push_high_priority(WorkItem::GuestCall(
2503                        runtime_instance,
2504                        GuestCall {
2505                            thread: guest_thread,
2506                            kind: GuestCallKind::DeliverEvent {
2507                                instance: self,
2508                                set: Some(set),
2509                            },
2510                        },
2511                    ));
2512                } else {
2513                    // No event is immediately available.
2514                    //
2515                    // We're waiting, so register to be woken up when an event
2516                    // is published for this waitable set.
2517                    //
2518                    // Here we also set `GuestTask::wake_on_cancel` which allows
2519                    // `subtask.cancel` to interrupt the wait.
2520                    let old = state
2521                        .get_mut(guest_thread.thread)?
2522                        .wake_on_cancel
2523                        .replace(set);
2524                    if !old.is_none() {
2525                        bail_bug!("thread unexpectedly had wake_on_cancel set");
2526                    }
2527                    let old = state
2528                        .get_mut(set)?
2529                        .waiting
2530                        .insert(guest_thread, WaitMode::Callback(self));
2531                    if !old.is_none() {
2532                        bail_bug!("set's waiting set already had this thread registered");
2533                    }
2534                }
2535                None
2536            }
2537            _ => bail!(Trap::UnsupportedCallbackCode),
2538        })
2539    }
2540
2541    /// Add the specified guest call to the "high priority" work item queue, to
2542    /// be started as soon as backpressure and/or reentrance rules allow.
2543    ///
2544    /// SAFETY: The raw pointer arguments must be valid references to guest
2545    /// functions (with the appropriate signatures) when the closures queued by
2546    /// this function are called.
2547    unsafe fn queue_call<T: 'static>(
2548        self,
2549        mut store: StoreContextMut<T>,
2550        guest_thread: QualifiedThreadId,
2551        callee: SendSyncPtr<VMFuncRef>,
2552        param_count: usize,
2553        result_count: usize,
2554        async_: bool,
2555        callback: Option<SendSyncPtr<VMFuncRef>>,
2556        post_return: Option<SendSyncPtr<VMFuncRef>>,
2557    ) -> Result<()> {
2558        /// Return a closure which will call the specified function in the scope
2559        /// of the specified task.
2560        ///
2561        /// This will use `GuestTask::lower_params` to lower the parameters, but
2562        /// will not lift the result; instead, it returns a
2563        /// `[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]` from which the result, if
2564        /// any, may be lifted.  Note that an async-lifted export will have
2565        /// returned its result using the `task.return` intrinsic (or not
2566        /// returned a result at all, in the case of `task.cancel`), in which
2567        /// case the "result" of this call will either be a callback code or
2568        /// nothing.
2569        ///
2570        /// SAFETY: `callee` must be a valid `*mut VMFuncRef` at the time when
2571        /// the returned closure is called.
2572        unsafe fn make_call<T: 'static>(
2573            store: StoreContextMut<T>,
2574            guest_thread: QualifiedThreadId,
2575            callee: SendSyncPtr<VMFuncRef>,
2576            param_count: usize,
2577            result_count: usize,
2578        ) -> impl FnOnce(&mut dyn VMStore) -> Result<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>
2579        + Send
2580        + Sync
2581        + 'static
2582        + use<T> {
2583            let token = StoreToken::new(store);
2584            move |store: &mut dyn VMStore| {
2585                let mut storage = [MaybeUninit::uninit(); MAX_FLAT_PARAMS];
2586
2587                store
2588                    .concurrent_state_mut()?
2589                    .get_mut(guest_thread.thread)?
2590                    .state = GuestThreadState::Running;
2591                let task = store.concurrent_state_mut()?.get_mut(guest_thread.task)?;
2592                let lower = match task.lower_params.take() {
2593                    Some(l) => l,
2594                    None => bail_bug!("lower_params missing"),
2595                };
2596
2597                lower(store, &mut storage[..param_count])?;
2598
2599                let mut store = token.as_context_mut(store);
2600
2601                // SAFETY: Per the contract documented in `make_call's`
2602                // documentation, `callee` must be a valid pointer.
2603                unsafe {
2604                    crate::Func::call_unchecked_raw(
2605                        &mut store,
2606                        callee.as_non_null(),
2607                        NonNull::new(
2608                            &mut storage[..param_count.max(result_count)]
2609                                as *mut [MaybeUninit<ValRaw>] as _,
2610                        )
2611                        .unwrap(),
2612                    )?;
2613                }
2614
2615                Ok(storage)
2616            }
2617        }
2618
2619        // SAFETY: Per the contract described in this function documentation,
2620        // the `callee` pointer which `call` closes over must be valid when
2621        // called by the closure we queue below.
2622        let call = unsafe {
2623            make_call(
2624                store.as_context_mut(),
2625                guest_thread,
2626                callee,
2627                param_count,
2628                result_count,
2629            )
2630        };
2631
2632        let callee_instance = store
2633            .0
2634            .concurrent_state_mut()?
2635            .get_mut(guest_thread.task)?
2636            .instance;
2637
2638        let fun = if callback.is_some() {
2639            assert!(async_);
2640
2641            Box::new(move |store: &mut dyn VMStore| {
2642                self.add_guest_thread_to_instance_table(
2643                    guest_thread.thread,
2644                    store,
2645                    callee_instance.index,
2646                )?;
2647                let old_thread = store.set_thread(guest_thread)?;
2648                log::trace!(
2649                    "stackless call: replaced {old_thread:?} with {guest_thread:?} as current thread"
2650                );
2651
2652                store.enter_instance(callee_instance);
2653
2654                // SAFETY: See the documentation for `make_call` to review the
2655                // contract we must uphold for `call` here.
2656                //
2657                // Per the contract described in the `queue_call`
2658                // documentation, the `callee` pointer which `call` closes
2659                // over must be valid.
2660                let storage = call(store)?;
2661
2662                store.exit_instance(callee_instance)?;
2663
2664                store.set_thread(old_thread)?;
2665                let state = store.concurrent_state_mut()?;
2666                if let Some(t) = old_thread.guest() {
2667                    state.get_mut(t.thread)?.state = GuestThreadState::Running;
2668                }
2669                log::trace!("stackless call: restored {old_thread:?} as current thread");
2670
2671                // SAFETY: `wasmparser` will have validated that the callback
2672                // function returns a `i32` result.
2673                let code = unsafe { storage[0].assume_init() }.get_i32() as u32;
2674
2675                self.handle_callback_code(store, guest_thread, callee_instance.index, code)
2676            })
2677                as Box<dyn FnOnce(&mut dyn VMStore) -> Result<Option<GuestCall>> + Send + Sync>
2678        } else {
2679            let token = StoreToken::new(store.as_context_mut());
2680            Box::new(move |store: &mut dyn VMStore| {
2681                self.add_guest_thread_to_instance_table(
2682                    guest_thread.thread,
2683                    store,
2684                    callee_instance.index,
2685                )?;
2686                let old_thread = store.set_thread(guest_thread)?;
2687                log::trace!(
2688                    "sync/async-stackful call: replaced {old_thread:?} with {guest_thread:?} as current thread",
2689                );
2690                let flags = self.id().get(store).instance_flags(callee_instance.index);
2691
2692                // Unless this is a callback-less (i.e. stackful)
2693                // async-lifted export, we need to record that the instance
2694                // cannot be entered until the call returns.
2695                if !async_ {
2696                    store.enter_instance(callee_instance);
2697                }
2698
2699                // SAFETY: See the documentation for `make_call` to review the
2700                // contract we must uphold for `call` here.
2701                //
2702                // Per the contract described in the `queue_call`
2703                // documentation, the `callee` pointer which `call` closes
2704                // over must be valid.
2705                let storage = call(store)?;
2706
2707                if !async_ {
2708                    // This is a sync-lifted export, so now is when we lift the
2709                    // result, optionally call the post-return function, if any,
2710                    // and finally notify any current or future waiters that the
2711                    // subtask has returned.
2712
2713                    let lift = {
2714                        store.exit_instance(callee_instance)?;
2715
2716                        let state = store.concurrent_state_mut()?;
2717                        if !state.get_mut(guest_thread.task)?.result.is_none() {
2718                            bail_bug!("task has already produced a result");
2719                        }
2720
2721                        match state.get_mut(guest_thread.task)?.lift_result.take() {
2722                            Some(lift) => lift,
2723                            None => bail_bug!("lift_result field is missing"),
2724                        }
2725                    };
2726
2727                    // SAFETY: `result_count` represents the number of core Wasm
2728                    // results returned, per `wasmparser`.
2729                    let result = (lift.lift)(store, unsafe {
2730                        mem::transmute::<&[MaybeUninit<ValRaw>], &[ValRaw]>(
2731                            &storage[..result_count],
2732                        )
2733                    })?;
2734
2735                    let post_return_arg = match result_count {
2736                        0 => ValRaw::i32(0),
2737                        // SAFETY: `result_count` represents the number of
2738                        // core Wasm results returned, per `wasmparser`.
2739                        1 => unsafe { storage[0].assume_init() },
2740                        _ => unreachable!(),
2741                    };
2742
2743                    unsafe {
2744                        call_post_return(
2745                            token.as_context_mut(store),
2746                            post_return.map(|v| v.as_non_null()),
2747                            post_return_arg,
2748                            flags,
2749                        )?;
2750                    }
2751
2752                    self.task_complete(store, guest_thread.task, result, Status::Returned)?;
2753                }
2754
2755                store.set_thread(old_thread)?;
2756
2757                store
2758                    .concurrent_state_mut()?
2759                    .get_mut(guest_thread.task)?
2760                    .exited = true;
2761
2762                // This is a callback-less call, so the implicit thread has now completed
2763                store.cleanup_thread(guest_thread, callee_instance, CleanupTask::Yes)?;
2764                Ok(None)
2765            })
2766        };
2767
2768        store
2769            .0
2770            .concurrent_state_mut()?
2771            .push_high_priority(WorkItem::GuestCall(
2772                callee_instance.index,
2773                GuestCall {
2774                    thread: guest_thread,
2775                    kind: GuestCallKind::StartImplicit(fun),
2776                },
2777            ));
2778
2779        Ok(())
2780    }
2781
2782    /// Prepare (but do not start) a guest->guest call.
2783    ///
2784    /// This is called from fused adapter code generated in
2785    /// `wasmtime_environ::fact::trampoline::Compiler`.  `start` and `return_`
2786    /// are synthesized Wasm functions which move the parameters from the caller
2787    /// to the callee and the result from the callee to the caller,
2788    /// respectively.  The adapter will call `Self::start_call` immediately
2789    /// after calling this function.
2790    ///
2791    /// SAFETY: All the pointer arguments must be valid pointers to guest
2792    /// entities (and with the expected signatures for the function references
2793    /// -- see `wasmtime_environ::fact::trampoline::Compiler` for details).
2794    unsafe fn prepare_call<T: 'static>(
2795        self,
2796        mut store: StoreContextMut<T>,
2797        start: NonNull<VMFuncRef>,
2798        return_: NonNull<VMFuncRef>,
2799        caller_instance: RuntimeComponentInstanceIndex,
2800        callee_instance: RuntimeComponentInstanceIndex,
2801        task_return_type: TypeTupleIndex,
2802        callee_async: bool,
2803        memory: *mut VMMemoryDefinition,
2804        string_encoding: StringEncoding,
2805        caller_info: CallerInfo,
2806    ) -> Result<()> {
2807        if let (CallerInfo::Sync { .. }, true) = (&caller_info, callee_async) {
2808            // A task may only call an async-typed function via a sync lower if
2809            // it was created by a call to an async export.  Otherwise, we'll
2810            // trap.
2811            store.0.check_blocking()?;
2812        }
2813
2814        enum ResultInfo {
2815            Heap { results: u32 },
2816            Stack { result_count: u32 },
2817        }
2818
2819        let result_info = match &caller_info {
2820            CallerInfo::Async {
2821                has_result: true,
2822                params,
2823            } => ResultInfo::Heap {
2824                results: match params.last() {
2825                    Some(r) => r.get_u32(),
2826                    None => bail_bug!("retptr missing"),
2827                },
2828            },
2829            CallerInfo::Async {
2830                has_result: false, ..
2831            } => ResultInfo::Stack { result_count: 0 },
2832            CallerInfo::Sync {
2833                result_count,
2834                params,
2835            } if *result_count > u32::try_from(MAX_FLAT_RESULTS)? => ResultInfo::Heap {
2836                results: match params.last() {
2837                    Some(r) => r.get_u32(),
2838                    None => bail_bug!("arg ptr missing"),
2839                },
2840            },
2841            CallerInfo::Sync { result_count, .. } => ResultInfo::Stack {
2842                result_count: *result_count,
2843            },
2844        };
2845
2846        let sync_caller = matches!(caller_info, CallerInfo::Sync { .. });
2847
2848        // Create a new guest task for the call, closing over the `start` and
2849        // `return_` functions to lift the parameters and lower the result,
2850        // respectively.
2851        let start = SendSyncPtr::new(start);
2852        let return_ = SendSyncPtr::new(return_);
2853        let token = StoreToken::new(store.as_context_mut());
2854        let old_thread = store.0.current_guest_thread()?;
2855        let state = store.0.concurrent_state_mut()?;
2856
2857        debug_assert_eq!(
2858            state.get_mut(old_thread.task)?.instance,
2859            self.runtime_instance(caller_instance)
2860        );
2861
2862        let guest_thread = GuestTask::new(
2863            state,
2864            Box::new(move |store, dst| {
2865                let mut store = token.as_context_mut(store);
2866                assert!(dst.len() <= MAX_FLAT_PARAMS);
2867                // The `+ 1` here accounts for the return pointer, if any:
2868                let mut src = [MaybeUninit::uninit(); MAX_FLAT_PARAMS + 1];
2869                let count = match caller_info {
2870                    // Async callers, if they have a result, use the last
2871                    // parameter as a return pointer so chop that off if
2872                    // relevant here.
2873                    CallerInfo::Async { params, has_result } => {
2874                        let params = &params[..params.len() - usize::from(has_result)];
2875                        for (param, src) in params.iter().zip(&mut src) {
2876                            src.write(*param);
2877                        }
2878                        params.len()
2879                    }
2880
2881                    // Sync callers forward everything directly.
2882                    CallerInfo::Sync { params, .. } => {
2883                        for (param, src) in params.iter().zip(&mut src) {
2884                            src.write(*param);
2885                        }
2886                        params.len()
2887                    }
2888                };
2889                // SAFETY: `start` is a valid `*mut VMFuncRef` from
2890                // `wasmtime-cranelift`-generated fused adapter code.  Based on
2891                // how it was constructed (see
2892                // `wasmtime_environ::fact::trampoline::Compiler::compile_async_start_adapter`
2893                // for details) we know it takes count parameters and returns
2894                // `dst.len()` results.
2895                unsafe {
2896                    crate::Func::call_unchecked_raw(
2897                        &mut store,
2898                        start.as_non_null(),
2899                        NonNull::new(
2900                            &mut src[..count.max(dst.len())] as *mut [MaybeUninit<ValRaw>] as _,
2901                        )
2902                        .unwrap(),
2903                    )?;
2904                }
2905                dst.copy_from_slice(&src[..dst.len()]);
2906                let task = store.0.current_guest_thread()?.task;
2907                let state = store.0.concurrent_state_mut()?;
2908                Waitable::Guest(task).set_event(
2909                    state,
2910                    Some(Event::Subtask {
2911                        status: Status::Started,
2912                    }),
2913                )?;
2914                Ok(())
2915            }),
2916            LiftResult {
2917                lift: Box::new(move |store, src| {
2918                    // SAFETY: See comment in closure passed as `lower_params`
2919                    // parameter above.
2920                    let mut store = token.as_context_mut(store);
2921                    let mut my_src = src.to_owned(); // TODO: use stack to avoid allocation?
2922                    if let ResultInfo::Heap { results } = &result_info {
2923                        my_src.push(ValRaw::u32(*results));
2924                    }
2925
2926                    // Execute the `return_` hook, generated by Wasmtime's FACT
2927                    // compiler, in the context of the old thread. The old
2928                    // thread, this thread's caller, may have `realloc`
2929                    // callbacks invoked for example and those need the correct
2930                    // context set for the current thread.
2931                    let prev = store.0.set_thread(old_thread)?;
2932
2933                    // SAFETY: `return_` is a valid `*mut VMFuncRef` from
2934                    // `wasmtime-cranelift`-generated fused adapter code.  Based
2935                    // on how it was constructed (see
2936                    // `wasmtime_environ::fact::trampoline::Compiler::compile_async_return_adapter`
2937                    // for details) we know it takes `src.len()` parameters and
2938                    // returns up to 1 result.
2939                    unsafe {
2940                        crate::Func::call_unchecked_raw(
2941                            &mut store,
2942                            return_.as_non_null(),
2943                            my_src.as_mut_slice().into(),
2944                        )?;
2945                    }
2946
2947                    // Restore the previous current thread after the
2948                    // lifting/lowering has returned.
2949                    store.0.set_thread(prev)?;
2950
2951                    let thread = store.0.current_guest_thread()?;
2952                    let state = store.0.concurrent_state_mut()?;
2953                    if sync_caller {
2954                        state.get_mut(thread.task)?.sync_result = SyncResult::Produced(
2955                            if let ResultInfo::Stack { result_count } = &result_info {
2956                                match result_count {
2957                                    0 => None,
2958                                    1 => Some(my_src[0]),
2959                                    _ => unreachable!(),
2960                                }
2961                            } else {
2962                                None
2963                            },
2964                        );
2965                    }
2966                    Ok(Box::new(DummyResult) as Box<dyn Any + Send + Sync>)
2967                }),
2968                ty: task_return_type,
2969                memory: NonNull::new(memory).map(SendSyncPtr::new),
2970                string_encoding,
2971            },
2972            Caller::Guest { thread: old_thread },
2973            None,
2974            self.runtime_instance(callee_instance),
2975            callee_async,
2976        )?;
2977
2978        // Make the new thread the current one so that `Self::start_call` knows
2979        // which one to start.
2980        store.0.set_thread(guest_thread)?;
2981        log::trace!("pushed {guest_thread:?} as current thread; old thread was {old_thread:?}");
2982
2983        Ok(())
2984    }
2985
2986    /// Call the specified callback function for an async-lifted export.
2987    ///
2988    /// SAFETY: `function` must be a valid reference to a guest function of the
2989    /// correct signature for a callback.
2990    unsafe fn call_callback<T>(
2991        self,
2992        mut store: StoreContextMut<T>,
2993        function: SendSyncPtr<VMFuncRef>,
2994        event: Event,
2995        handle: u32,
2996    ) -> Result<u32> {
2997        let (ordinal, result) = event.parts();
2998        let params = &mut [
2999            ValRaw::u32(ordinal),
3000            ValRaw::u32(handle),
3001            ValRaw::u32(result),
3002        ];
3003        // SAFETY: `func` is a valid `*mut VMFuncRef` from either
3004        // `wasmtime-cranelift`-generated fused adapter code or
3005        // `component::Options`.  Per `wasmparser` callback signature
3006        // validation, we know it takes three parameters and returns one.
3007        unsafe {
3008            crate::Func::call_unchecked_raw(
3009                &mut store,
3010                function.as_non_null(),
3011                params.as_mut_slice().into(),
3012            )?;
3013        }
3014        Ok(params[0].get_u32())
3015    }
3016
3017    /// Start a guest->guest call previously prepared using
3018    /// `Self::prepare_call`.
3019    ///
3020    /// This is called from fused adapter code generated in
3021    /// `wasmtime_environ::fact::trampoline::Compiler`.  The adapter will call
3022    /// this function immediately after calling `Self::prepare_call`.
3023    ///
3024    /// SAFETY: The `*mut VMFuncRef` arguments must be valid pointers to guest
3025    /// functions with the appropriate signatures for the current guest task.
3026    /// If this is a call to an async-lowered import, the actual call may be
3027    /// deferred and run after this function returns, in which case the pointer
3028    /// arguments must also be valid when the call happens.
3029    unsafe fn start_call<T: 'static>(
3030        self,
3031        mut store: StoreContextMut<T>,
3032        callback: *mut VMFuncRef,
3033        post_return: *mut VMFuncRef,
3034        callee: NonNull<VMFuncRef>,
3035        param_count: u32,
3036        result_count: u32,
3037        flags: u32,
3038        storage: Option<&mut [MaybeUninit<ValRaw>]>,
3039    ) -> Result<u32> {
3040        let token = StoreToken::new(store.as_context_mut());
3041        let async_caller = storage.is_none();
3042        let guest_thread = store.0.current_guest_thread()?;
3043        let state = store.0.concurrent_state_mut()?;
3044        let callee_async = state.get_mut(guest_thread.task)?.async_function;
3045        let callee = SendSyncPtr::new(callee);
3046        let param_count = usize::try_from(param_count)?;
3047        assert!(param_count <= MAX_FLAT_PARAMS);
3048        let result_count = usize::try_from(result_count)?;
3049        assert!(result_count <= MAX_FLAT_RESULTS);
3050
3051        let task = state.get_mut(guest_thread.task)?;
3052        if let Some(callback) = NonNull::new(callback) {
3053            // We're calling an async-lifted export with a callback, so store
3054            // the callback and related context as part of the task so we can
3055            // call it later when needed.
3056            let callback = SendSyncPtr::new(callback);
3057            task.callback = Some(Box::new(move |store, event, handle| {
3058                let store = token.as_context_mut(store);
3059                unsafe { self.call_callback::<T>(store, callback, event, handle) }
3060            }));
3061        }
3062
3063        let Caller::Guest { thread: caller } = &task.caller else {
3064            // As of this writing, `start_call` is only used for guest->guest
3065            // calls.
3066            bail_bug!("start_call unexpectedly invoked for host->guest call");
3067        };
3068        let caller = *caller;
3069        let caller_instance = state.get_mut(caller.task)?.instance;
3070
3071        // Queue the call as a "high priority" work item.
3072        unsafe {
3073            self.queue_call(
3074                store.as_context_mut(),
3075                guest_thread,
3076                callee,
3077                param_count,
3078                result_count,
3079                (flags & START_FLAG_ASYNC_CALLEE) != 0,
3080                NonNull::new(callback).map(SendSyncPtr::new),
3081                NonNull::new(post_return).map(SendSyncPtr::new),
3082            )?;
3083        }
3084
3085        let state = store.0.concurrent_state_mut()?;
3086
3087        // Use the caller's `GuestThread::sync_call_set` to register interest in
3088        // the subtask...
3089        let guest_waitable = Waitable::Guest(guest_thread.task);
3090        let old_set = guest_waitable.common(state)?.set;
3091        let set = state.get_mut(caller.thread)?.sync_call_set;
3092        guest_waitable.join(state, Some(set))?;
3093
3094        store.0.set_thread(CurrentThread::None)?;
3095
3096        // ... and suspend this fiber temporarily while we wait for it to start.
3097        //
3098        // Note that we _could_ call the callee directly using the current fiber
3099        // rather than suspend this one, but that would make reasoning about the
3100        // event loop more complicated and is probably only worth doing if
3101        // there's a measurable performance benefit.  In addition, it would mean
3102        // blocking the caller if the callee calls a blocking sync-lowered
3103        // import, and as of this writing the spec says we must not do that.
3104        //
3105        // Alternatively, the fused adapter code could be modified to call the
3106        // callee directly without calling a host-provided intrinsic at all (in
3107        // which case it would need to do its own, inline backpressure checks,
3108        // etc.).  Again, we'd want to see a measurable performance benefit
3109        // before committing to such an optimization.  And again, we'd need to
3110        // update the spec to allow that.
3111        let (status, waitable) = loop {
3112            store.0.suspend(SuspendReason::Waiting {
3113                set,
3114                thread: caller,
3115                // Normally, `StoreOpaque::suspend` would assert it's being
3116                // called from a context where blocking is allowed.  However, if
3117                // `async_caller` is `true`, we'll only "block" long enough for
3118                // the callee to start, i.e. we won't repeat this loop, so we
3119                // tell `suspend` it's okay even if we're not allowed to block.
3120                // Alternatively, if the callee is not an async function, then
3121                // we know it won't block anyway.
3122                skip_may_block_check: async_caller || !callee_async,
3123            })?;
3124
3125            let state = store.0.concurrent_state_mut()?;
3126
3127            log::trace!("taking event for {:?}", guest_thread.task);
3128            let event = guest_waitable.take_event(state)?;
3129            let Some(Event::Subtask { status }) = event else {
3130                bail_bug!("subtasks should only get subtask events, got {event:?}")
3131            };
3132
3133            log::trace!("status {status:?} for {:?}", guest_thread.task);
3134
3135            if status == Status::Returned {
3136                // It returned, so we can stop waiting.
3137                break (status, None);
3138            } else if async_caller {
3139                // It hasn't returned yet, but the caller is calling via an
3140                // async-lowered import, so we generate a handle for the task
3141                // waitable and return the status.
3142                let handle = store
3143                    .0
3144                    .instance_state(caller_instance)
3145                    .handle_table()
3146                    .subtask_insert_guest(guest_thread.task.rep())?;
3147                store
3148                    .0
3149                    .concurrent_state_mut()?
3150                    .get_mut(guest_thread.task)?
3151                    .common
3152                    .handle = Some(handle);
3153                break (status, Some(handle));
3154            } else {
3155                // The callee hasn't returned yet, and the caller is calling via
3156                // a sync-lowered import, so we loop and keep waiting until the
3157                // callee returns.
3158            }
3159        };
3160
3161        guest_waitable.join(store.0.concurrent_state_mut()?, old_set)?;
3162
3163        // Reset the current thread to point to the caller as it resumes control.
3164        store.0.set_thread(caller)?;
3165        store
3166            .0
3167            .concurrent_state_mut()?
3168            .get_mut(caller.thread)?
3169            .state = GuestThreadState::Running;
3170        log::trace!("popped current thread {guest_thread:?}; new thread is {caller:?}");
3171
3172        if let Some(storage) = storage {
3173            // The caller used a sync-lowered import to call an async-lifted
3174            // export, in which case the result, if any, has been stashed in
3175            // `GuestTask::sync_result`.
3176            let state = store.0.concurrent_state_mut()?;
3177            let task = state.get_mut(guest_thread.task)?;
3178            if let Some(result) = task.sync_result.take()? {
3179                if let Some(result) = result {
3180                    storage[0] = MaybeUninit::new(result);
3181                }
3182
3183                if task.exited && task.ready_to_delete() {
3184                    Waitable::Guest(guest_thread.task).delete_from(state)?;
3185                }
3186            }
3187        }
3188
3189        Ok(status.pack(waitable))
3190    }
3191
3192    /// Poll the specified future once on behalf of a guest->host call using an
3193    /// async-lowered import.
3194    ///
3195    /// If it returns `Ready`, return `Ok(None)`.  Otherwise, if it returns
3196    /// `Pending`, add it to the set of futures to be polled as part of this
3197    /// instance's event loop until it completes, and then return
3198    /// `Ok(Some(handle))` where `handle` is the waitable handle to return.
3199    ///
3200    /// Whether the future returns `Ready` immediately or later, the `lower`
3201    /// function will be used to lower the result, if any, into the guest caller's
3202    /// stack and linear memory. The `lower` function is invoked with `None` if
3203    /// the future is cancelled.
3204    pub(crate) fn first_poll<T: 'static, R: Send + 'static>(
3205        self,
3206        mut store: StoreContextMut<'_, T>,
3207        host_task: EnteredHostTask,
3208        future: impl Future<Output = Result<R>> + Send + 'static,
3209        lower: impl FnOnce(StoreContextMut<T>, Option<R>, bool) -> Result<()> + Send + 'static,
3210    ) -> Result<u32> {
3211        let token = StoreToken::new(store.as_context_mut());
3212        let task = store.0.current_host_thread()?;
3213        let state = store.0.concurrent_state_mut()?;
3214
3215        // Create an abortable future which hooks calls to poll and manages call
3216        // context state for the future.
3217        let (join_handle, future) = JoinHandle::run(future);
3218        {
3219            let state = &mut state.get_mut(task)?.state;
3220            assert!(matches!(state, HostTaskState::CalleeStarted));
3221            *state = HostTaskState::CalleeRunning(join_handle);
3222        }
3223
3224        let mut future = Box::pin(future);
3225
3226        // Finally, poll the future.  We can use a dummy `Waker` here because
3227        // we'll add the future to `ConcurrentState::futures` and poll it
3228        // automatically from the event loop if it doesn't complete immediately
3229        // here.
3230        let poll = tls::set(store.0, || {
3231            future
3232                .as_mut()
3233                .poll(&mut Context::from_waker(&Waker::noop()))
3234        });
3235
3236        match poll {
3237            // It finished immediately; lower the result and delete the task.
3238            Poll::Ready(result) => {
3239                let result = result.transpose()?;
3240                lower(store.as_context_mut(), result, true)?;
3241                return Ok(Status::Returned.pack(None));
3242            }
3243
3244            // Future isn't ready yet, so fall through.
3245            Poll::Pending => {}
3246        }
3247
3248        // It hasn't finished yet; add the future to
3249        // `ConcurrentState::futures` so it will be polled by the event
3250        // loop and allocate a waitable handle to return to the guest.
3251
3252        // Wrap the future in a closure responsible for lowering the result into
3253        // the guest's stack and memory, as well as notifying any waiters that
3254        // the task returned.
3255        let future = Box::pin(async move {
3256            let result = match future.await {
3257                Some(result) => Some(result?),
3258                None => None,
3259            };
3260            let on_complete = move |store: &mut dyn VMStore| {
3261                // Restore the `current_thread` to be the host so `lower` knows
3262                // how to manipulate borrows and knows which scope of borrows
3263                // to check.
3264                let mut store = token.as_context_mut(store);
3265                let old = store.0.set_thread(task)?;
3266
3267                let status = if result.is_some() {
3268                    Status::Returned
3269                } else {
3270                    Status::ReturnCancelled
3271                };
3272
3273                lower(store.as_context_mut(), result, false)?;
3274                let state = store.0.concurrent_state_mut()?;
3275                match &mut state.get_mut(task)?.state {
3276                    // The task is already flagged as finished because it was
3277                    // cancelled. No need to transition further.
3278                    HostTaskState::CalleeDone { .. } => {}
3279
3280                    // Otherwise transition this task to the done state.
3281                    other => *other = HostTaskState::CalleeDone { cancelled: false },
3282                }
3283                Waitable::Host(task).set_event(state, Some(Event::Subtask { status }))?;
3284
3285                store.0.set_thread(old)?;
3286                Ok(())
3287            };
3288
3289            // Here we schedule a task to run on a worker fiber to do the
3290            // lowering since it may involve a call to the guest's realloc
3291            // function. This is necessary because calling the guest while
3292            // there are host embedder frames on the stack is unsound.
3293            tls::get(move |store| {
3294                store
3295                    .concurrent_state_mut()?
3296                    .push_high_priority(WorkItem::WorkerFunction(AlwaysMut::new(Box::new(
3297                        on_complete,
3298                    ))));
3299                Ok(())
3300            })
3301        });
3302
3303        // Make this task visible to the guest and then record what it
3304        // was made visible as.
3305        let caller = match host_task {
3306            Some(pair) => pair.1,
3307            None => bail_bug!("host task wasn't created but should have been"),
3308        };
3309        let state = store.0.concurrent_state_mut()?;
3310        state.push_future(future);
3311        let instance = state.get_mut(caller.task)?.instance;
3312        let handle = store
3313            .0
3314            .instance_state(instance)
3315            .handle_table()
3316            .subtask_insert_host(task.rep())?;
3317        store.0.concurrent_state_mut()?.get_mut(task)?.common.handle = Some(handle);
3318        log::trace!("assign {task:?} handle {handle} for {caller:?} instance {instance:?}");
3319
3320        // Restore the currently running thread to this host task's
3321        // caller. Note that the host task isn't deallocated as it's
3322        // within the store and will get deallocated later.
3323        store.0.set_thread(caller)?;
3324        Ok(Status::Started.pack(Some(handle)))
3325    }
3326
3327    /// Implements the `task.return` intrinsic, lifting the result for the
3328    /// current guest task.
3329    pub(crate) fn task_return(
3330        self,
3331        store: &mut dyn VMStore,
3332        ty: TypeTupleIndex,
3333        options: OptionsIndex,
3334        storage: &[ValRaw],
3335    ) -> Result<()> {
3336        let guest_thread = store.current_guest_thread()?;
3337        let state = store.concurrent_state_mut()?;
3338        let lift = state
3339            .get_mut(guest_thread.task)?
3340            .lift_result
3341            .take()
3342            .ok_or_else(|| Trap::TaskCancelOrReturnTwice)?;
3343        if !state.get_mut(guest_thread.task)?.result.is_none() {
3344            bail_bug!("task result unexpectedly already set");
3345        }
3346
3347        let CanonicalOptions {
3348            string_encoding,
3349            data_model,
3350            ..
3351        } = &self.id().get(store).component().env_component().options[options];
3352
3353        let invalid = ty != lift.ty
3354            || string_encoding != &lift.string_encoding
3355            || match data_model {
3356                CanonicalOptionsDataModel::LinearMemory(opts) => match opts.memory {
3357                    Some(memory) => {
3358                        let expected = lift.memory.map(|v| v.as_ptr()).unwrap_or(ptr::null_mut());
3359                        let actual = self.id().get(store).runtime_memory(memory);
3360                        expected != actual.as_ptr()
3361                    }
3362                    // Memory not specified, meaning it didn't need to be
3363                    // specified per validation, so not invalid.
3364                    None => false,
3365                },
3366                // Always invalid as this isn't supported.
3367                CanonicalOptionsDataModel::Gc { .. } => true,
3368            };
3369
3370        if invalid {
3371            bail!(Trap::TaskReturnInvalid);
3372        }
3373
3374        log::trace!("task.return for {guest_thread:?}");
3375
3376        let result = (lift.lift)(store, storage)?;
3377        self.task_complete(store, guest_thread.task, result, Status::Returned)
3378    }
3379
3380    /// Implements the `task.cancel` intrinsic.
3381    pub(crate) fn task_cancel(self, store: &mut StoreOpaque) -> Result<()> {
3382        let guest_thread = store.current_guest_thread()?;
3383        let state = store.concurrent_state_mut()?;
3384        let task = state.get_mut(guest_thread.task)?;
3385        if !task.cancel_sent {
3386            bail!(Trap::TaskCancelNotCancelled);
3387        }
3388        _ = task
3389            .lift_result
3390            .take()
3391            .ok_or_else(|| Trap::TaskCancelOrReturnTwice)?;
3392
3393        if !task.result.is_none() {
3394            bail_bug!("task result should not bet set yet");
3395        }
3396
3397        log::trace!("task.cancel for {guest_thread:?}");
3398
3399        self.task_complete(
3400            store,
3401            guest_thread.task,
3402            Box::new(DummyResult),
3403            Status::ReturnCancelled,
3404        )
3405    }
3406
3407    /// Complete the specified guest task (i.e. indicate that it has either
3408    /// returned a (possibly empty) result or cancelled itself).
3409    ///
3410    /// This will return any resource borrows and notify any current or future
3411    /// waiters that the task has completed.
3412    fn task_complete(
3413        self,
3414        store: &mut StoreOpaque,
3415        guest_task: TableId<GuestTask>,
3416        result: Box<dyn Any + Send + Sync>,
3417        status: Status,
3418    ) -> Result<()> {
3419        store
3420            .component_resource_tables(Some(self))?
3421            .validate_scope_exit()?;
3422
3423        let state = store.concurrent_state_mut()?;
3424        let task = state.get_mut(guest_task)?;
3425
3426        if let Caller::Host { tx, .. } = &mut task.caller {
3427            if let Some(tx) = tx.take() {
3428                _ = tx.send(result);
3429            }
3430        } else {
3431            task.result = Some(result);
3432            Waitable::Guest(guest_task).set_event(state, Some(Event::Subtask { status }))?;
3433        }
3434
3435        Ok(())
3436    }
3437
3438    /// Implements the `waitable-set.new` intrinsic.
3439    pub(crate) fn waitable_set_new(
3440        self,
3441        store: &mut StoreOpaque,
3442        caller_instance: RuntimeComponentInstanceIndex,
3443    ) -> Result<u32> {
3444        let set = store.concurrent_state_mut()?.push(WaitableSet::default())?;
3445        let handle = store
3446            .instance_state(self.runtime_instance(caller_instance))
3447            .handle_table()
3448            .waitable_set_insert(set.rep())?;
3449        log::trace!("new waitable set {set:?} (handle {handle})");
3450        Ok(handle)
3451    }
3452
3453    /// Implements the `waitable-set.drop` intrinsic.
3454    pub(crate) fn waitable_set_drop(
3455        self,
3456        store: &mut StoreOpaque,
3457        caller_instance: RuntimeComponentInstanceIndex,
3458        set: u32,
3459    ) -> Result<()> {
3460        let rep = store
3461            .instance_state(self.runtime_instance(caller_instance))
3462            .handle_table()
3463            .waitable_set_remove(set)?;
3464
3465        log::trace!("drop waitable set {rep} (handle {set})");
3466
3467        // Note that we're careful to check for waiters _before_ deleting the
3468        // set to avoid dropping any waiters in `WaitMode::Fiber(_)`, which
3469        // would panic.  See `drop-waitable-set-with-waiters.wast` for details.
3470        if !store
3471            .concurrent_state_mut()?
3472            .get_mut(TableId::<WaitableSet>::new(rep))?
3473            .waiting
3474            .is_empty()
3475        {
3476            bail!(Trap::WaitableSetDropHasWaiters);
3477        }
3478
3479        store
3480            .concurrent_state_mut()?
3481            .delete(TableId::<WaitableSet>::new(rep))?;
3482
3483        Ok(())
3484    }
3485
3486    /// Implements the `waitable.join` intrinsic.
3487    pub(crate) fn waitable_join(
3488        self,
3489        store: &mut StoreOpaque,
3490        caller_instance: RuntimeComponentInstanceIndex,
3491        waitable_handle: u32,
3492        set_handle: u32,
3493    ) -> Result<()> {
3494        let mut instance = self.id().get_mut(store);
3495        let waitable =
3496            Waitable::from_instance(instance.as_mut(), caller_instance, waitable_handle)?;
3497
3498        let set = if set_handle == 0 {
3499            None
3500        } else {
3501            let set = instance.instance_states().0[caller_instance]
3502                .handle_table()
3503                .waitable_set_rep(set_handle)?;
3504
3505            let state = store.concurrent_state_mut()?;
3506            if let Some(old) = waitable.common(state)?.set
3507                && state.get_mut(old)?.is_sync_call_set
3508            {
3509                bail!(Trap::WaitableSyncAndAsync);
3510            }
3511
3512            Some(TableId::<WaitableSet>::new(set))
3513        };
3514
3515        log::trace!(
3516            "waitable {waitable:?} (handle {waitable_handle}) join set {set:?} (handle {set_handle})",
3517        );
3518
3519        waitable.join(store.concurrent_state_mut()?, set)
3520    }
3521
3522    /// Implements the `subtask.drop` intrinsic.
3523    pub(crate) fn subtask_drop(
3524        self,
3525        store: &mut StoreOpaque,
3526        caller_instance: RuntimeComponentInstanceIndex,
3527        task_id: u32,
3528    ) -> Result<()> {
3529        self.waitable_join(store, caller_instance, task_id, 0)?;
3530
3531        let (rep, is_host) = store
3532            .instance_state(self.runtime_instance(caller_instance))
3533            .handle_table()
3534            .subtask_remove(task_id)?;
3535
3536        let concurrent_state = store.concurrent_state_mut()?;
3537        let (waitable, delete) = if is_host {
3538            let id = TableId::<HostTask>::new(rep);
3539            let task = concurrent_state.get_mut(id)?;
3540            match &task.state {
3541                HostTaskState::CalleeRunning(_) => bail!(Trap::SubtaskDropNotResolved),
3542                HostTaskState::CalleeDone { .. } => {}
3543                HostTaskState::CalleeStarted | HostTaskState::CalleeFinished(_) => {
3544                    bail_bug!("invalid state for callee in `subtask.drop`")
3545                }
3546            }
3547            (Waitable::Host(id), true)
3548        } else {
3549            let id = TableId::<GuestTask>::new(rep);
3550            let task = concurrent_state.get_mut(id)?;
3551            if task.lift_result.is_some() {
3552                bail!(Trap::SubtaskDropNotResolved);
3553            }
3554            (
3555                Waitable::Guest(id),
3556                concurrent_state.get_mut(id)?.ready_to_delete(),
3557            )
3558        };
3559
3560        waitable.common(concurrent_state)?.handle = None;
3561
3562        // If this subtask has an event that means that the terminal status of
3563        // this subtask wasn't yet received so it can't be dropped yet.
3564        if waitable.take_event(concurrent_state)?.is_some() {
3565            bail!(Trap::SubtaskDropNotResolved);
3566        }
3567
3568        if delete {
3569            waitable.delete_from(concurrent_state)?;
3570        }
3571
3572        log::trace!("subtask_drop {waitable:?} (handle {task_id})");
3573        Ok(())
3574    }
3575
3576    /// Implements the `waitable-set.wait` intrinsic.
3577    pub(crate) fn waitable_set_wait(
3578        self,
3579        store: &mut StoreOpaque,
3580        options: OptionsIndex,
3581        set: u32,
3582        payload: u32,
3583    ) -> Result<u32> {
3584        if !self.options(store, options).async_ {
3585            // The caller may only call `waitable-set.wait` from an async task
3586            // (i.e. a task created via a call to an async export).
3587            // Otherwise, we'll trap.
3588            store.check_blocking()?;
3589        }
3590
3591        let &CanonicalOptions {
3592            cancellable,
3593            instance: caller_instance,
3594            ..
3595        } = &self.id().get(store).component().env_component().options[options];
3596        let rep = store
3597            .instance_state(self.runtime_instance(caller_instance))
3598            .handle_table()
3599            .waitable_set_rep(set)?;
3600
3601        self.waitable_check(
3602            store,
3603            cancellable,
3604            WaitableCheck::Wait,
3605            WaitableCheckParams {
3606                set: TableId::new(rep),
3607                options,
3608                payload,
3609            },
3610        )
3611    }
3612
3613    /// Implements the `waitable-set.poll` intrinsic.
3614    pub(crate) fn waitable_set_poll(
3615        self,
3616        store: &mut StoreOpaque,
3617        options: OptionsIndex,
3618        set: u32,
3619        payload: u32,
3620    ) -> Result<u32> {
3621        let &CanonicalOptions {
3622            cancellable,
3623            instance: caller_instance,
3624            ..
3625        } = &self.id().get(store).component().env_component().options[options];
3626        let rep = store
3627            .instance_state(self.runtime_instance(caller_instance))
3628            .handle_table()
3629            .waitable_set_rep(set)?;
3630
3631        self.waitable_check(
3632            store,
3633            cancellable,
3634            WaitableCheck::Poll,
3635            WaitableCheckParams {
3636                set: TableId::new(rep),
3637                options,
3638                payload,
3639            },
3640        )
3641    }
3642
3643    /// Implements the `thread.index` intrinsic.
3644    pub(crate) fn thread_index(&self, store: &mut dyn VMStore) -> Result<u32> {
3645        let thread_id = store.current_guest_thread()?.thread;
3646        match store
3647            .concurrent_state_mut()?
3648            .get_mut(thread_id)?
3649            .instance_rep
3650        {
3651            Some(r) => Ok(r),
3652            None => bail_bug!("thread should have instance_rep by now"),
3653        }
3654    }
3655
3656    /// Implements the `thread.new-indirect` intrinsic.
3657    pub(crate) fn thread_new_indirect<T: 'static>(
3658        self,
3659        mut store: StoreContextMut<T>,
3660        runtime_instance: RuntimeComponentInstanceIndex,
3661        _func_ty_idx: TypeFuncIndex, // currently unused
3662        start_func_table_idx: RuntimeTableIndex,
3663        start_func_idx: u32,
3664        context: i32,
3665    ) -> Result<u32> {
3666        log::trace!("creating new thread");
3667
3668        let start_func_ty = FuncType::new(store.engine(), [ValType::I32], []);
3669        let (instance, registry) = self.id().get_mut_and_registry(store.0);
3670        let callee = instance
3671            .index_runtime_func_table(registry, start_func_table_idx, start_func_idx as u64)?
3672            .ok_or_else(|| Trap::ThreadNewIndirectUninitialized)?;
3673        if callee.type_index(store.0) != start_func_ty.type_index() {
3674            bail!(Trap::ThreadNewIndirectInvalidType);
3675        }
3676
3677        let token = StoreToken::new(store.as_context_mut());
3678        let start_func = Box::new(
3679            move |store: &mut dyn VMStore, guest_thread: QualifiedThreadId| -> Result<()> {
3680                let old_thread = store.set_thread(guest_thread)?;
3681                log::trace!(
3682                    "thread start: replaced {old_thread:?} with {guest_thread:?} as current thread"
3683                );
3684
3685                let mut store = token.as_context_mut(store);
3686                let mut params = [ValRaw::i32(context)];
3687                // Use call_unchecked rather than call or call_async, as we don't want to run the function
3688                // on a separate fiber if we're running in an async store.
3689                unsafe { callee.call_unchecked(store.as_context_mut(), &mut params)? };
3690
3691                store.0.set_thread(old_thread)?;
3692
3693                store.0.cleanup_thread(
3694                    guest_thread,
3695                    self.runtime_instance(runtime_instance),
3696                    CleanupTask::Yes,
3697                )?;
3698                log::trace!("explicit thread {guest_thread:?} completed");
3699                let state = store.0.concurrent_state_mut()?;
3700                if let Some(t) = old_thread.guest() {
3701                    state.get_mut(t.thread)?.state = GuestThreadState::Running;
3702                }
3703                log::trace!("thread start: restored {old_thread:?} as current thread");
3704
3705                Ok(())
3706            },
3707        );
3708
3709        let current_thread = store.0.current_guest_thread()?;
3710        let state = store.0.concurrent_state_mut()?;
3711        let parent_task = current_thread.task;
3712
3713        let new_thread = GuestThread::new_explicit(state, parent_task, start_func)?;
3714        let thread_id = state.push(new_thread)?;
3715        state.get_mut(parent_task)?.threads.insert(thread_id);
3716
3717        log::trace!("new thread with id {thread_id:?} created");
3718
3719        self.add_guest_thread_to_instance_table(thread_id, store.0, runtime_instance)
3720    }
3721
3722    pub(crate) fn resume_thread(
3723        self,
3724        store: &mut StoreOpaque,
3725        runtime_instance: RuntimeComponentInstanceIndex,
3726        thread_idx: u32,
3727        high_priority: bool,
3728        allow_ready: bool,
3729    ) -> Result<()> {
3730        let thread_id =
3731            GuestThread::from_instance(self.id().get_mut(store), runtime_instance, thread_idx)?;
3732        let state = store.concurrent_state_mut()?;
3733        let guest_thread = QualifiedThreadId::qualify(state, thread_id)?;
3734        let thread = state.get_mut(guest_thread.thread)?;
3735
3736        match mem::replace(&mut thread.state, GuestThreadState::Running) {
3737            GuestThreadState::NotStartedExplicit(start_func) => {
3738                log::trace!("starting thread {guest_thread:?}");
3739                let guest_call = WorkItem::GuestCall(
3740                    runtime_instance,
3741                    GuestCall {
3742                        thread: guest_thread,
3743                        kind: GuestCallKind::StartExplicit(Box::new(move |store| {
3744                            start_func(store, guest_thread)
3745                        })),
3746                    },
3747                );
3748                store
3749                    .concurrent_state_mut()?
3750                    .push_work_item(guest_call, high_priority);
3751            }
3752            GuestThreadState::Suspended(fiber) => {
3753                log::trace!("resuming thread {thread_id:?} that was suspended");
3754                store
3755                    .concurrent_state_mut()?
3756                    .push_work_item(WorkItem::ResumeFiber(fiber), high_priority);
3757            }
3758            GuestThreadState::Ready { fiber, cancellable } if allow_ready => {
3759                log::trace!("resuming thread {thread_id:?} that was ready");
3760                thread.state = GuestThreadState::Ready { fiber, cancellable };
3761                store
3762                    .concurrent_state_mut()?
3763                    .promote_thread_work_item(guest_thread);
3764            }
3765            other => {
3766                thread.state = other;
3767                bail!(Trap::CannotResumeThread);
3768            }
3769        }
3770        Ok(())
3771    }
3772
3773    fn add_guest_thread_to_instance_table(
3774        self,
3775        thread_id: TableId<GuestThread>,
3776        store: &mut StoreOpaque,
3777        runtime_instance: RuntimeComponentInstanceIndex,
3778    ) -> Result<u32> {
3779        let guest_id = store
3780            .instance_state(self.runtime_instance(runtime_instance))
3781            .thread_handle_table()
3782            .guest_thread_insert(thread_id.rep())?;
3783        store
3784            .concurrent_state_mut()?
3785            .get_mut(thread_id)?
3786            .instance_rep = Some(guest_id);
3787        Ok(guest_id)
3788    }
3789
3790    /// Helper function for the `thread.yield`, `thread.yield-to-suspended`, `thread.suspend`,
3791    /// `thread.suspend-to`, and `thread.suspend-to-suspended` intrinsics.
3792    pub(crate) fn suspension_intrinsic(
3793        self,
3794        store: &mut StoreOpaque,
3795        caller: RuntimeComponentInstanceIndex,
3796        cancellable: bool,
3797        yielding: bool,
3798        to_thread: SuspensionTarget,
3799    ) -> Result<WaitResult> {
3800        let guest_thread = store.current_guest_thread()?;
3801        if to_thread.is_none() {
3802            let state = store.concurrent_state_mut()?;
3803            if yielding {
3804                // This is a `thread.yield` call
3805                if !state.may_block(guest_thread.task)? {
3806                    // In a non-blocking context, a `thread.yield` may trigger
3807                    // other threads in the same component instance to run.
3808                    if !state.promote_instance_local_thread_work_item(caller) {
3809                        // No other threads are runnable, so just return
3810                        return Ok(WaitResult::Completed);
3811                    }
3812                }
3813            } else {
3814                // The caller may only call `thread.suspend` from an async task
3815                // (i.e. a task created via a call to an async export).
3816                // Otherwise, we'll trap.
3817                store.check_blocking()?;
3818            }
3819        }
3820
3821        // There could be a pending cancellation from a previous uncancellable wait
3822        if cancellable && store.take_pending_cancellation()? {
3823            return Ok(WaitResult::Cancelled);
3824        }
3825
3826        match to_thread {
3827            SuspensionTarget::SomeSuspended(thread) => {
3828                self.resume_thread(store, caller, thread, true, false)?
3829            }
3830            SuspensionTarget::Some(thread) => {
3831                self.resume_thread(store, caller, thread, true, true)?
3832            }
3833            SuspensionTarget::None => { /* nothing to do */ }
3834        }
3835
3836        let reason = if yielding {
3837            SuspendReason::Yielding {
3838                thread: guest_thread,
3839                cancellable,
3840                // Tell `StoreOpaque::suspend` it's okay to suspend here since
3841                // we're handling a `thread.yield-to-suspended` call; otherwise it would
3842                // panic if we called it in a non-blocking context.
3843                skip_may_block_check: to_thread.is_some(),
3844            }
3845        } else {
3846            SuspendReason::ExplicitlySuspending {
3847                thread: guest_thread,
3848                // Tell `StoreOpaque::suspend` it's okay to suspend here since
3849                // we're handling a `thread.suspend-to(-suspended)` call; otherwise it would
3850                // panic if we called it in a non-blocking context.
3851                skip_may_block_check: to_thread.is_some(),
3852            }
3853        };
3854
3855        store.suspend(reason)?;
3856
3857        if cancellable && store.take_pending_cancellation()? {
3858            Ok(WaitResult::Cancelled)
3859        } else {
3860            Ok(WaitResult::Completed)
3861        }
3862    }
3863
3864    /// Helper function for the `waitable-set.wait` and `waitable-set.poll` intrinsics.
3865    fn waitable_check(
3866        self,
3867        store: &mut StoreOpaque,
3868        cancellable: bool,
3869        check: WaitableCheck,
3870        params: WaitableCheckParams,
3871    ) -> Result<u32> {
3872        let guest_thread = store.current_guest_thread()?;
3873
3874        log::trace!("waitable check for {guest_thread:?}; set {:?}", params.set);
3875
3876        let state = store.concurrent_state_mut()?;
3877        let task = state.get_mut(guest_thread.task)?;
3878
3879        // If we're waiting, and there are no events immediately available,
3880        // suspend the fiber until that changes.
3881        match &check {
3882            WaitableCheck::Wait => {
3883                let set = params.set;
3884
3885                if (task.event.is_none()
3886                    || (matches!(task.event, Some(Event::Cancelled)) && !cancellable))
3887                    && state.get_mut(set)?.ready.is_empty()
3888                {
3889                    if cancellable {
3890                        let old = state
3891                            .get_mut(guest_thread.thread)?
3892                            .wake_on_cancel
3893                            .replace(set);
3894                        if !old.is_none() {
3895                            bail_bug!("thread unexpectedly in a prior wake_on_cancel set");
3896                        }
3897                    }
3898
3899                    store.suspend(SuspendReason::Waiting {
3900                        set,
3901                        thread: guest_thread,
3902                        skip_may_block_check: false,
3903                    })?;
3904                }
3905            }
3906            WaitableCheck::Poll => {}
3907        }
3908
3909        log::trace!(
3910            "waitable check for {guest_thread:?}; set {:?}, part two",
3911            params.set
3912        );
3913
3914        // Deliver any pending events to the guest and return.
3915        let event = self.get_event(store, guest_thread.task, Some(params.set), cancellable)?;
3916
3917        let (ordinal, handle, result) = match &check {
3918            WaitableCheck::Wait => {
3919                let (event, waitable) = match event {
3920                    Some(p) => p,
3921                    None => bail_bug!("event expected to be present"),
3922                };
3923                let handle = waitable.map(|(_, v)| v).unwrap_or(0);
3924                let (ordinal, result) = event.parts();
3925                (ordinal, handle, result)
3926            }
3927            WaitableCheck::Poll => {
3928                if let Some((event, waitable)) = event {
3929                    let handle = waitable.map(|(_, v)| v).unwrap_or(0);
3930                    let (ordinal, result) = event.parts();
3931                    (ordinal, handle, result)
3932                } else {
3933                    log::trace!(
3934                        "no events ready to deliver via waitable-set.poll to {:?}; set {:?}",
3935                        guest_thread.task,
3936                        params.set
3937                    );
3938                    let (ordinal, result) = Event::None.parts();
3939                    (ordinal, 0, result)
3940                }
3941            }
3942        };
3943        let memory = self.options_memory_mut(store, params.options);
3944        let ptr = crate::component::func::validate_inbounds_dynamic(
3945            &CanonicalAbiInfo::POINTER_PAIR,
3946            memory,
3947            &ValRaw::u32(params.payload),
3948        )?;
3949        memory[ptr + 0..][..4].copy_from_slice(&handle.to_le_bytes());
3950        memory[ptr + 4..][..4].copy_from_slice(&result.to_le_bytes());
3951        Ok(ordinal)
3952    }
3953
3954    /// Implements the `subtask.cancel` intrinsic.
3955    pub(crate) fn subtask_cancel(
3956        self,
3957        store: &mut StoreOpaque,
3958        caller_instance: RuntimeComponentInstanceIndex,
3959        async_: bool,
3960        task_id: u32,
3961    ) -> Result<u32> {
3962        if !async_ {
3963            // The caller may only sync call `subtask.cancel` from an async task
3964            // (i.e. a task created via a call to an async export).  Otherwise,
3965            // we'll trap.
3966            store.check_blocking()?;
3967        }
3968
3969        let (rep, is_host) = store
3970            .instance_state(self.runtime_instance(caller_instance))
3971            .handle_table()
3972            .subtask_rep(task_id)?;
3973        let waitable = if is_host {
3974            Waitable::Host(TableId::<HostTask>::new(rep))
3975        } else {
3976            Waitable::Guest(TableId::<GuestTask>::new(rep))
3977        };
3978        let concurrent_state = store.concurrent_state_mut()?;
3979
3980        log::trace!("subtask_cancel {waitable:?} (handle {task_id})");
3981
3982        if !async_ {
3983            waitable.trap_if_in_waitable_set(concurrent_state)?;
3984        }
3985
3986        let needs_block;
3987        if let Waitable::Host(host_task) = waitable {
3988            let state = &mut concurrent_state.get_mut(host_task)?.state;
3989            match mem::replace(state, HostTaskState::CalleeDone { cancelled: true }) {
3990                // If the callee is still running, signal an abort is requested.
3991                //
3992                // After cancelling this falls through to block waiting for the
3993                // host task to actually finish assuming that `async_` is false.
3994                // This blocking behavior resolves the race of `handle.abort()`
3995                // with the task actually getting cancelled or finishing.
3996                HostTaskState::CalleeRunning(handle) => {
3997                    handle.abort();
3998                    needs_block = true;
3999                }
4000
4001                // Cancellation was already requested, so fail as the task can't
4002                // be cancelled twice.
4003                HostTaskState::CalleeDone { cancelled } => {
4004                    if cancelled {
4005                        bail!(Trap::SubtaskCancelAfterTerminal);
4006                    } else {
4007                        // The callee is already done so there's no need to
4008                        // block further for an event.
4009                        needs_block = false;
4010                    }
4011                }
4012
4013                // These states should not be possible for a subtask that's
4014                // visible from the guest, so trap here.
4015                HostTaskState::CalleeStarted | HostTaskState::CalleeFinished(_) => {
4016                    bail_bug!("invalid states for host callee")
4017                }
4018            }
4019        } else {
4020            let guest_task = TableId::<GuestTask>::new(rep);
4021            let task = concurrent_state.get_mut(guest_task)?;
4022            if !task.already_lowered_parameters() {
4023                store.cancel_guest_subtask_without_lowered_parameters(
4024                    self.runtime_instance(caller_instance),
4025                    guest_task,
4026                )?;
4027                return Ok(Status::StartCancelled as u32);
4028            } else if !task.returned_or_cancelled() {
4029                // Started, but not yet returned or cancelled; send the
4030                // `CANCELLED` event
4031                task.cancel_sent = true;
4032                // Note that this might overwrite an event that was set earlier
4033                // (e.g. `Event::None` if the task is yielding, or
4034                // `Event::Cancelled` if it was already cancelled), but that's
4035                // okay -- this should supersede the previous state.
4036                task.event = Some(Event::Cancelled);
4037                let runtime_instance = task.instance.index;
4038                for thread in task.threads.clone() {
4039                    let thread = QualifiedThreadId {
4040                        task: guest_task,
4041                        thread,
4042                    };
4043                    let thread_mut = concurrent_state.get_mut(thread.thread)?;
4044                    if let Some(set) = thread_mut.wake_on_cancel.take() {
4045                        // The thread is in a cancellable wait, so wake it up:
4046                        let item = match concurrent_state.get_mut(set)?.waiting.remove(&thread) {
4047                            Some(WaitMode::Fiber(fiber)) => WorkItem::ResumeFiber(fiber),
4048                            Some(WaitMode::Callback(instance)) => WorkItem::GuestCall(
4049                                runtime_instance,
4050                                GuestCall {
4051                                    thread,
4052                                    kind: GuestCallKind::DeliverEvent {
4053                                        instance,
4054                                        set: None,
4055                                    },
4056                                },
4057                            ),
4058                            None => bail_bug!("thread not present in wake_on_cancel set"),
4059                        };
4060                        concurrent_state.push_high_priority(item);
4061
4062                        let caller = store.current_guest_thread()?;
4063                        store.suspend(SuspendReason::Yielding {
4064                            thread: caller,
4065                            cancellable: false,
4066                            // `subtask.cancel` is not allowed to be called in a
4067                            // sync context, so we cannot skip the may-block check.
4068                            skip_may_block_check: false,
4069                        })?;
4070                        break;
4071                    } else if let GuestThreadState::Ready {
4072                        cancellable: true, ..
4073                    } = &thread_mut.state
4074                    {
4075                        // The thread is in a cancellable yield, so yield back
4076                        // to it.
4077                        concurrent_state.promote_thread_work_item(thread);
4078                        let caller = store.current_guest_thread()?;
4079                        store.suspend(SuspendReason::Yielding {
4080                            thread: caller,
4081                            cancellable: false,
4082                            skip_may_block_check: false,
4083                        })?;
4084                        break;
4085                    }
4086                }
4087
4088                // Guest tasks need to block if they have not yet returned or
4089                // cancelled, even as a result of the event delivery above.
4090                needs_block = !store
4091                    .concurrent_state_mut()?
4092                    .get_mut(guest_task)?
4093                    .returned_or_cancelled()
4094            } else {
4095                needs_block = false;
4096            }
4097        };
4098
4099        // If we need to block waiting on the terminal status of this subtask
4100        // then return immediately in `async` mode, or otherwise wait for the
4101        // event to get signaled through the store.
4102        if needs_block {
4103            if async_ {
4104                return Ok(BLOCKED);
4105            }
4106
4107            // Wait for this waitable to get signaled with its terminal status
4108            // from the completion callback enqueued by `first_poll`. Once
4109            // that's done fall through to the sahred
4110            store.wait_for_event(waitable)?;
4111
4112            // .. fall through to determine what event's in store for us.
4113        }
4114
4115        let event = waitable.take_event(store.concurrent_state_mut()?)?;
4116        if let Some(Event::Subtask {
4117            status: status @ (Status::Returned | Status::ReturnCancelled),
4118        }) = event
4119        {
4120            Ok(status as u32)
4121        } else {
4122            bail!(Trap::SubtaskCancelAfterTerminal);
4123        }
4124    }
4125}
4126
4127/// Trait representing component model ABI async intrinsics and fused adapter
4128/// helper functions.
4129///
4130/// SAFETY (callers): Most of the methods in this trait accept raw pointers,
4131/// which must be valid for at least the duration of the call (and possibly for
4132/// as long as the relevant guest task exists, in the case of `*mut VMFuncRef`
4133/// pointers used for async calls).
4134pub trait VMComponentAsyncStore {
4135    /// A helper function for fused adapter modules involving calls where the
4136    /// one of the caller or callee is async.
4137    ///
4138    /// This helper is not used when the caller and callee both use the sync
4139    /// ABI, only when at least one is async is this used.
4140    unsafe fn prepare_call(
4141        &mut self,
4142        instance: Instance,
4143        memory: *mut VMMemoryDefinition,
4144        start: NonNull<VMFuncRef>,
4145        return_: NonNull<VMFuncRef>,
4146        caller_instance: RuntimeComponentInstanceIndex,
4147        callee_instance: RuntimeComponentInstanceIndex,
4148        task_return_type: TypeTupleIndex,
4149        callee_async: bool,
4150        string_encoding: StringEncoding,
4151        result_count: u32,
4152        storage: *mut ValRaw,
4153        storage_len: usize,
4154    ) -> Result<()>;
4155
4156    /// A helper function for fused adapter modules involving calls where the
4157    /// caller is sync-lowered but the callee is async-lifted.
4158    unsafe fn sync_start(
4159        &mut self,
4160        instance: Instance,
4161        callback: *mut VMFuncRef,
4162        callee: NonNull<VMFuncRef>,
4163        param_count: u32,
4164        storage: *mut MaybeUninit<ValRaw>,
4165        storage_len: usize,
4166    ) -> Result<()>;
4167
4168    /// A helper function for fused adapter modules involving calls where the
4169    /// caller is async-lowered.
4170    unsafe fn async_start(
4171        &mut self,
4172        instance: Instance,
4173        callback: *mut VMFuncRef,
4174        post_return: *mut VMFuncRef,
4175        callee: NonNull<VMFuncRef>,
4176        param_count: u32,
4177        result_count: u32,
4178        flags: u32,
4179    ) -> Result<u32>;
4180
4181    /// The `future.write` intrinsic.
4182    fn future_write(
4183        &mut self,
4184        instance: Instance,
4185        caller: RuntimeComponentInstanceIndex,
4186        ty: TypeFutureTableIndex,
4187        options: OptionsIndex,
4188        future: u32,
4189        address: u32,
4190    ) -> Result<u32>;
4191
4192    /// The `future.read` intrinsic.
4193    fn future_read(
4194        &mut self,
4195        instance: Instance,
4196        caller: RuntimeComponentInstanceIndex,
4197        ty: TypeFutureTableIndex,
4198        options: OptionsIndex,
4199        future: u32,
4200        address: u32,
4201    ) -> Result<u32>;
4202
4203    /// The `future.drop-writable` intrinsic.
4204    fn future_drop_writable(
4205        &mut self,
4206        instance: Instance,
4207        ty: TypeFutureTableIndex,
4208        writer: u32,
4209    ) -> Result<()>;
4210
4211    /// The `stream.write` intrinsic.
4212    fn stream_write(
4213        &mut self,
4214        instance: Instance,
4215        caller: RuntimeComponentInstanceIndex,
4216        ty: TypeStreamTableIndex,
4217        options: OptionsIndex,
4218        stream: u32,
4219        address: u32,
4220        count: u32,
4221    ) -> Result<u32>;
4222
4223    /// The `stream.read` intrinsic.
4224    fn stream_read(
4225        &mut self,
4226        instance: Instance,
4227        caller: RuntimeComponentInstanceIndex,
4228        ty: TypeStreamTableIndex,
4229        options: OptionsIndex,
4230        stream: u32,
4231        address: u32,
4232        count: u32,
4233    ) -> Result<u32>;
4234
4235    /// The "fast-path" implementation of the `stream.write` intrinsic for
4236    /// "flat" (i.e. memcpy-able) payloads.
4237    fn flat_stream_write(
4238        &mut self,
4239        instance: Instance,
4240        caller: RuntimeComponentInstanceIndex,
4241        ty: TypeStreamTableIndex,
4242        options: OptionsIndex,
4243        payload_size: u32,
4244        payload_align: u32,
4245        stream: u32,
4246        address: u32,
4247        count: u32,
4248    ) -> Result<u32>;
4249
4250    /// The "fast-path" implementation of the `stream.read` intrinsic for "flat"
4251    /// (i.e. memcpy-able) payloads.
4252    fn flat_stream_read(
4253        &mut self,
4254        instance: Instance,
4255        caller: RuntimeComponentInstanceIndex,
4256        ty: TypeStreamTableIndex,
4257        options: OptionsIndex,
4258        payload_size: u32,
4259        payload_align: u32,
4260        stream: u32,
4261        address: u32,
4262        count: u32,
4263    ) -> Result<u32>;
4264
4265    /// The `stream.drop-writable` intrinsic.
4266    fn stream_drop_writable(
4267        &mut self,
4268        instance: Instance,
4269        ty: TypeStreamTableIndex,
4270        writer: u32,
4271    ) -> Result<()>;
4272
4273    /// The `error-context.debug-message` intrinsic.
4274    fn error_context_debug_message(
4275        &mut self,
4276        instance: Instance,
4277        ty: TypeComponentLocalErrorContextTableIndex,
4278        options: OptionsIndex,
4279        err_ctx_handle: u32,
4280        debug_msg_address: u32,
4281    ) -> Result<()>;
4282
4283    /// The `thread.new-indirect` intrinsic
4284    fn thread_new_indirect(
4285        &mut self,
4286        instance: Instance,
4287        caller: RuntimeComponentInstanceIndex,
4288        func_ty_idx: TypeFuncIndex,
4289        start_func_table_idx: RuntimeTableIndex,
4290        start_func_idx: u32,
4291        context: i32,
4292    ) -> Result<u32>;
4293}
4294
4295/// SAFETY: See trait docs.
4296impl<T: 'static> VMComponentAsyncStore for StoreInner<T> {
4297    unsafe fn prepare_call(
4298        &mut self,
4299        instance: Instance,
4300        memory: *mut VMMemoryDefinition,
4301        start: NonNull<VMFuncRef>,
4302        return_: NonNull<VMFuncRef>,
4303        caller_instance: RuntimeComponentInstanceIndex,
4304        callee_instance: RuntimeComponentInstanceIndex,
4305        task_return_type: TypeTupleIndex,
4306        callee_async: bool,
4307        string_encoding: StringEncoding,
4308        result_count_or_max_if_async: u32,
4309        storage: *mut ValRaw,
4310        storage_len: usize,
4311    ) -> Result<()> {
4312        // SAFETY: The `wasmtime_cranelift`-generated code that calls
4313        // this method will have ensured that `storage` is a valid
4314        // pointer containing at least `storage_len` items.
4315        let params = unsafe { core::slice::from_raw_parts(storage, storage_len) }.to_vec();
4316
4317        unsafe {
4318            instance.prepare_call(
4319                StoreContextMut(self),
4320                start,
4321                return_,
4322                caller_instance,
4323                callee_instance,
4324                task_return_type,
4325                callee_async,
4326                memory,
4327                string_encoding,
4328                match result_count_or_max_if_async {
4329                    PREPARE_ASYNC_NO_RESULT => CallerInfo::Async {
4330                        params,
4331                        has_result: false,
4332                    },
4333                    PREPARE_ASYNC_WITH_RESULT => CallerInfo::Async {
4334                        params,
4335                        has_result: true,
4336                    },
4337                    result_count => CallerInfo::Sync {
4338                        params,
4339                        result_count,
4340                    },
4341                },
4342            )
4343        }
4344    }
4345
4346    unsafe fn sync_start(
4347        &mut self,
4348        instance: Instance,
4349        callback: *mut VMFuncRef,
4350        callee: NonNull<VMFuncRef>,
4351        param_count: u32,
4352        storage: *mut MaybeUninit<ValRaw>,
4353        storage_len: usize,
4354    ) -> Result<()> {
4355        unsafe {
4356            instance
4357                .start_call(
4358                    StoreContextMut(self),
4359                    callback,
4360                    ptr::null_mut(),
4361                    callee,
4362                    param_count,
4363                    1,
4364                    START_FLAG_ASYNC_CALLEE,
4365                    // SAFETY: The `wasmtime_cranelift`-generated code that calls
4366                    // this method will have ensured that `storage` is a valid
4367                    // pointer containing at least `storage_len` items.
4368                    Some(core::slice::from_raw_parts_mut(storage, storage_len)),
4369                )
4370                .map(drop)
4371        }
4372    }
4373
4374    unsafe fn async_start(
4375        &mut self,
4376        instance: Instance,
4377        callback: *mut VMFuncRef,
4378        post_return: *mut VMFuncRef,
4379        callee: NonNull<VMFuncRef>,
4380        param_count: u32,
4381        result_count: u32,
4382        flags: u32,
4383    ) -> Result<u32> {
4384        unsafe {
4385            instance.start_call(
4386                StoreContextMut(self),
4387                callback,
4388                post_return,
4389                callee,
4390                param_count,
4391                result_count,
4392                flags,
4393                None,
4394            )
4395        }
4396    }
4397
4398    fn future_write(
4399        &mut self,
4400        instance: Instance,
4401        caller: RuntimeComponentInstanceIndex,
4402        ty: TypeFutureTableIndex,
4403        options: OptionsIndex,
4404        future: u32,
4405        address: u32,
4406    ) -> Result<u32> {
4407        instance
4408            .guest_write(
4409                StoreContextMut(self),
4410                caller,
4411                TransmitIndex::Future(ty),
4412                options,
4413                None,
4414                future,
4415                address,
4416                1,
4417            )
4418            .map(|result| result.encode())
4419    }
4420
4421    fn future_read(
4422        &mut self,
4423        instance: Instance,
4424        caller: RuntimeComponentInstanceIndex,
4425        ty: TypeFutureTableIndex,
4426        options: OptionsIndex,
4427        future: u32,
4428        address: u32,
4429    ) -> Result<u32> {
4430        instance
4431            .guest_read(
4432                StoreContextMut(self),
4433                caller,
4434                TransmitIndex::Future(ty),
4435                options,
4436                None,
4437                future,
4438                address,
4439                1,
4440            )
4441            .map(|result| result.encode())
4442    }
4443
4444    fn stream_write(
4445        &mut self,
4446        instance: Instance,
4447        caller: RuntimeComponentInstanceIndex,
4448        ty: TypeStreamTableIndex,
4449        options: OptionsIndex,
4450        stream: u32,
4451        address: u32,
4452        count: u32,
4453    ) -> Result<u32> {
4454        instance
4455            .guest_write(
4456                StoreContextMut(self),
4457                caller,
4458                TransmitIndex::Stream(ty),
4459                options,
4460                None,
4461                stream,
4462                address,
4463                count,
4464            )
4465            .map(|result| result.encode())
4466    }
4467
4468    fn stream_read(
4469        &mut self,
4470        instance: Instance,
4471        caller: RuntimeComponentInstanceIndex,
4472        ty: TypeStreamTableIndex,
4473        options: OptionsIndex,
4474        stream: u32,
4475        address: u32,
4476        count: u32,
4477    ) -> Result<u32> {
4478        instance
4479            .guest_read(
4480                StoreContextMut(self),
4481                caller,
4482                TransmitIndex::Stream(ty),
4483                options,
4484                None,
4485                stream,
4486                address,
4487                count,
4488            )
4489            .map(|result| result.encode())
4490    }
4491
4492    fn future_drop_writable(
4493        &mut self,
4494        instance: Instance,
4495        ty: TypeFutureTableIndex,
4496        writer: u32,
4497    ) -> Result<()> {
4498        instance.guest_drop_writable(self, TransmitIndex::Future(ty), writer)
4499    }
4500
4501    fn flat_stream_write(
4502        &mut self,
4503        instance: Instance,
4504        caller: RuntimeComponentInstanceIndex,
4505        ty: TypeStreamTableIndex,
4506        options: OptionsIndex,
4507        payload_size: u32,
4508        payload_align: u32,
4509        stream: u32,
4510        address: u32,
4511        count: u32,
4512    ) -> Result<u32> {
4513        instance
4514            .guest_write(
4515                StoreContextMut(self),
4516                caller,
4517                TransmitIndex::Stream(ty),
4518                options,
4519                Some(FlatAbi {
4520                    size: payload_size,
4521                    align: payload_align,
4522                }),
4523                stream,
4524                address,
4525                count,
4526            )
4527            .map(|result| result.encode())
4528    }
4529
4530    fn flat_stream_read(
4531        &mut self,
4532        instance: Instance,
4533        caller: RuntimeComponentInstanceIndex,
4534        ty: TypeStreamTableIndex,
4535        options: OptionsIndex,
4536        payload_size: u32,
4537        payload_align: u32,
4538        stream: u32,
4539        address: u32,
4540        count: u32,
4541    ) -> Result<u32> {
4542        instance
4543            .guest_read(
4544                StoreContextMut(self),
4545                caller,
4546                TransmitIndex::Stream(ty),
4547                options,
4548                Some(FlatAbi {
4549                    size: payload_size,
4550                    align: payload_align,
4551                }),
4552                stream,
4553                address,
4554                count,
4555            )
4556            .map(|result| result.encode())
4557    }
4558
4559    fn stream_drop_writable(
4560        &mut self,
4561        instance: Instance,
4562        ty: TypeStreamTableIndex,
4563        writer: u32,
4564    ) -> Result<()> {
4565        instance.guest_drop_writable(self, TransmitIndex::Stream(ty), writer)
4566    }
4567
4568    fn error_context_debug_message(
4569        &mut self,
4570        instance: Instance,
4571        ty: TypeComponentLocalErrorContextTableIndex,
4572        options: OptionsIndex,
4573        err_ctx_handle: u32,
4574        debug_msg_address: u32,
4575    ) -> Result<()> {
4576        instance.error_context_debug_message(
4577            StoreContextMut(self),
4578            ty,
4579            options,
4580            err_ctx_handle,
4581            debug_msg_address,
4582        )
4583    }
4584
4585    fn thread_new_indirect(
4586        &mut self,
4587        instance: Instance,
4588        caller: RuntimeComponentInstanceIndex,
4589        func_ty_idx: TypeFuncIndex,
4590        start_func_table_idx: RuntimeTableIndex,
4591        start_func_idx: u32,
4592        context: i32,
4593    ) -> Result<u32> {
4594        instance.thread_new_indirect(
4595            StoreContextMut(self),
4596            caller,
4597            func_ty_idx,
4598            start_func_table_idx,
4599            start_func_idx,
4600            context,
4601        )
4602    }
4603}
4604
4605type HostTaskFuture = Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>;
4606
4607/// Represents the state of a pending host task.
4608///
4609/// This is used to represent tasks when the guest calls into the host.
4610pub(crate) struct HostTask {
4611    common: WaitableCommon,
4612
4613    /// The calling guest task of this host task. Note that this is only used
4614    /// for backtrace purposes and is additionally not updated when the guest
4615    /// task finishes.
4616    ///
4617    /// TODO: this field should probably get deleted entirely and the
4618    /// backtrace-purposes here should move to an auxiliary table.
4619    caller: TableId<GuestTask>,
4620
4621    /// State of borrows/etc the host needs to track. Used when the guest passes
4622    /// borrows to the host, for example.
4623    call_context: CallContext,
4624
4625    state: HostTaskState,
4626}
4627
4628enum HostTaskState {
4629    /// A host task has been created and it's considered "started".
4630    ///
4631    /// The host task has yet to enter `first_poll` or `poll_and_block` which
4632    /// is where this will get updated further.
4633    CalleeStarted,
4634
4635    /// State used for tasks in `first_poll` meaning that the guest did an async
4636    /// lower of a host async function which is blocked. The specified handle is
4637    /// linked to the future in the main `FuturesUnordered` of a store which is
4638    /// used to cancel it if the guest requests cancellation.
4639    CalleeRunning(JoinHandle),
4640
4641    /// Terminal state used for tasks in `poll_and_block` to store the result of
4642    /// their computation. Note that this state is not used for tasks in
4643    /// `first_poll`.
4644    CalleeFinished(LiftedResult),
4645
4646    /// Terminal state for host tasks meaning that the task was cancelled or the
4647    /// result was taken.
4648    CalleeDone { cancelled: bool },
4649}
4650
4651impl HostTask {
4652    fn new(caller: TableId<GuestTask>, state: HostTaskState) -> Self {
4653        Self {
4654            common: WaitableCommon::default(),
4655            call_context: CallContext::default(),
4656            caller,
4657            state,
4658        }
4659    }
4660}
4661
4662impl TableDebug for HostTask {
4663    fn type_name() -> &'static str {
4664        "HostTask"
4665    }
4666}
4667
4668type CallbackFn = Box<dyn Fn(&mut dyn VMStore, Event, u32) -> Result<u32> + Send + Sync + 'static>;
4669
4670/// Represents the caller of a given guest task.
4671enum Caller {
4672    /// The host called the guest task.
4673    Host {
4674        /// If present, may be used to deliver the result.
4675        tx: Option<oneshot::Sender<LiftedResult>>,
4676        /// If true, there's a host future that must be dropped before the task
4677        /// can be deleted.
4678        host_future_present: bool,
4679        /// Represents the caller of the host function which called back into a
4680        /// guest. Note that this thread could belong to an entirely unrelated
4681        /// top-level component instance than the one the host called into.
4682        caller: CurrentThread,
4683    },
4684    /// Another guest thread called the guest task
4685    Guest {
4686        /// The id of the caller
4687        thread: QualifiedThreadId,
4688    },
4689}
4690
4691/// Represents a closure and related canonical ABI parameters required to
4692/// validate a `task.return` call at runtime and lift the result.
4693struct LiftResult {
4694    lift: RawLift,
4695    ty: TypeTupleIndex,
4696    memory: Option<SendSyncPtr<VMMemoryDefinition>>,
4697    string_encoding: StringEncoding,
4698}
4699
4700/// The table ID for a guest thread, qualified by the task to which it belongs.
4701///
4702/// This exists to minimize table lookups and the necessity to pass stores around mutably
4703/// for the common case of identifying the task to which a thread belongs.
4704#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
4705pub(crate) struct QualifiedThreadId {
4706    task: TableId<GuestTask>,
4707    thread: TableId<GuestThread>,
4708}
4709
4710impl QualifiedThreadId {
4711    fn qualify(
4712        state: &mut ConcurrentState,
4713        thread: TableId<GuestThread>,
4714    ) -> Result<QualifiedThreadId> {
4715        Ok(QualifiedThreadId {
4716            task: state.get_mut(thread)?.parent_task,
4717            thread,
4718        })
4719    }
4720}
4721
4722impl fmt::Debug for QualifiedThreadId {
4723    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4724        f.debug_tuple("QualifiedThreadId")
4725            .field(&self.task.rep())
4726            .field(&self.thread.rep())
4727            .finish()
4728    }
4729}
4730
4731enum GuestThreadState {
4732    NotStartedImplicit,
4733    NotStartedExplicit(
4734        Box<dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync>,
4735    ),
4736    Running,
4737    Suspended(StoreFiber<'static>),
4738    Ready {
4739        fiber: StoreFiber<'static>,
4740        cancellable: bool,
4741    },
4742    Completed,
4743}
4744pub struct GuestThread {
4745    /// Context-local state used to implement the `context.{get,set}`
4746    /// intrinsics.
4747    context: [u32; NUM_COMPONENT_CONTEXT_SLOTS],
4748    /// The owning guest task.
4749    parent_task: TableId<GuestTask>,
4750    /// If present, indicates that the thread is currently waiting on the
4751    /// specified set but may be cancelled and woken immediately.
4752    wake_on_cancel: Option<TableId<WaitableSet>>,
4753    /// The execution state of this guest thread
4754    state: GuestThreadState,
4755    /// The index of this thread in the component instance's handle table.
4756    /// This must always be `Some` after initialization.
4757    instance_rep: Option<u32>,
4758    /// Scratch waitable set used to watch subtasks during synchronous calls.
4759    sync_call_set: TableId<WaitableSet>,
4760}
4761
4762impl GuestThread {
4763    /// Retrieve the `GuestThread` corresponding to the specified guest-visible
4764    /// handle.
4765    fn from_instance(
4766        state: Pin<&mut ComponentInstance>,
4767        caller_instance: RuntimeComponentInstanceIndex,
4768        guest_thread: u32,
4769    ) -> Result<TableId<Self>> {
4770        let rep = state.instance_states().0[caller_instance]
4771            .thread_handle_table()
4772            .guest_thread_rep(guest_thread)?;
4773        Ok(TableId::new(rep))
4774    }
4775
4776    fn new_implicit(state: &mut ConcurrentState, parent_task: TableId<GuestTask>) -> Result<Self> {
4777        let sync_call_set = state.push(WaitableSet {
4778            is_sync_call_set: true,
4779            ..WaitableSet::default()
4780        })?;
4781        Ok(Self {
4782            context: [0; NUM_COMPONENT_CONTEXT_SLOTS],
4783            parent_task,
4784            wake_on_cancel: None,
4785            state: GuestThreadState::NotStartedImplicit,
4786            instance_rep: None,
4787            sync_call_set,
4788        })
4789    }
4790
4791    fn new_explicit(
4792        state: &mut ConcurrentState,
4793        parent_task: TableId<GuestTask>,
4794        start_func: Box<
4795            dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync,
4796        >,
4797    ) -> Result<Self> {
4798        let sync_call_set = state.push(WaitableSet {
4799            is_sync_call_set: true,
4800            ..WaitableSet::default()
4801        })?;
4802        Ok(Self {
4803            context: [0; NUM_COMPONENT_CONTEXT_SLOTS],
4804            parent_task,
4805            wake_on_cancel: None,
4806            state: GuestThreadState::NotStartedExplicit(start_func),
4807            instance_rep: None,
4808            sync_call_set,
4809        })
4810    }
4811}
4812
4813impl TableDebug for GuestThread {
4814    fn type_name() -> &'static str {
4815        "GuestThread"
4816    }
4817}
4818
4819enum SyncResult {
4820    NotProduced,
4821    Produced(Option<ValRaw>),
4822    Taken,
4823}
4824
4825impl SyncResult {
4826    fn take(&mut self) -> Result<Option<Option<ValRaw>>> {
4827        Ok(match mem::replace(self, SyncResult::Taken) {
4828            SyncResult::NotProduced => None,
4829            SyncResult::Produced(val) => Some(val),
4830            SyncResult::Taken => {
4831                bail_bug!("attempted to take a synchronous result that was already taken")
4832            }
4833        })
4834    }
4835}
4836
4837#[derive(Debug)]
4838enum HostFutureState {
4839    NotApplicable,
4840    Live,
4841    Dropped,
4842}
4843
4844/// Represents a pending guest task.
4845pub(crate) struct GuestTask {
4846    /// See `WaitableCommon`
4847    common: WaitableCommon,
4848    /// Closure to lower the parameters passed to this task.
4849    lower_params: Option<RawLower>,
4850    /// See `LiftResult`
4851    lift_result: Option<LiftResult>,
4852    /// A place to stash the type-erased lifted result if it can't be delivered
4853    /// immediately.
4854    result: Option<LiftedResult>,
4855    /// Closure to call the callback function for an async-lifted export, if
4856    /// provided.
4857    callback: Option<CallbackFn>,
4858    /// See `Caller`
4859    caller: Caller,
4860    /// Borrow state for this task.
4861    ///
4862    /// Keeps track of `borrow<T>` received to this task to ensure that
4863    /// everything is dropped by the time it exits.
4864    call_context: CallContext,
4865    /// A place to stash the lowered result for a sync-to-async call until it
4866    /// can be returned to the caller.
4867    sync_result: SyncResult,
4868    /// Whether or not the task has been cancelled (i.e. whether the task is
4869    /// permitted to call `task.cancel`).
4870    cancel_sent: bool,
4871    /// Whether or not we've sent a `Status::Starting` event to any current or
4872    /// future waiters for this waitable.
4873    starting_sent: bool,
4874    /// The runtime instance to which the exported function for this guest task
4875    /// belongs.
4876    ///
4877    /// Note that the task may do a sync->sync call via a fused adapter which
4878    /// results in that task executing code in a different instance, and it may
4879    /// call host functions and intrinsics from that other instance.
4880    instance: RuntimeInstance,
4881    /// If present, a pending `Event::None` or `Event::Cancelled` to be
4882    /// delivered to this task.
4883    event: Option<Event>,
4884    /// Whether or not the task has exited.
4885    exited: bool,
4886    /// Threads belonging to this task
4887    threads: HashSet<TableId<GuestThread>>,
4888    /// The state of the host future that represents an async task, which must
4889    /// be dropped before we can delete the task.
4890    host_future_state: HostFutureState,
4891    /// Indicates whether this task was created for a call to an async-lifted
4892    /// export.
4893    async_function: bool,
4894
4895    decremented_interesting_task_count: bool,
4896}
4897
4898impl GuestTask {
4899    fn already_lowered_parameters(&self) -> bool {
4900        // We reset `lower_params` after we lower the parameters
4901        self.lower_params.is_none()
4902    }
4903
4904    fn returned_or_cancelled(&self) -> bool {
4905        // We reset `lift_result` after we return or exit
4906        self.lift_result.is_none()
4907    }
4908
4909    fn ready_to_delete(&self) -> bool {
4910        let threads_completed = self.threads.is_empty();
4911        let has_sync_result = matches!(self.sync_result, SyncResult::Produced(_));
4912        let pending_completion_event = matches!(
4913            self.common.event,
4914            Some(Event::Subtask {
4915                status: Status::Returned | Status::ReturnCancelled
4916            })
4917        );
4918        let ready = threads_completed
4919            && !has_sync_result
4920            && !pending_completion_event
4921            && !matches!(self.host_future_state, HostFutureState::Live);
4922        log::trace!(
4923            "ready to delete? {ready} (threads_completed: {}, has_sync_result: {}, pending_completion_event: {}, host_future_state: {:?})",
4924            threads_completed,
4925            has_sync_result,
4926            pending_completion_event,
4927            self.host_future_state
4928        );
4929        ready
4930    }
4931
4932    fn new(
4933        state: &mut ConcurrentState,
4934        lower_params: RawLower,
4935        lift_result: LiftResult,
4936        caller: Caller,
4937        callback: Option<CallbackFn>,
4938        instance: RuntimeInstance,
4939        async_function: bool,
4940    ) -> Result<QualifiedThreadId> {
4941        let host_future_state = match &caller {
4942            Caller::Guest { .. } => HostFutureState::NotApplicable,
4943            Caller::Host {
4944                host_future_present,
4945                ..
4946            } => {
4947                if *host_future_present {
4948                    HostFutureState::Live
4949                } else {
4950                    HostFutureState::NotApplicable
4951                }
4952            }
4953        };
4954        let task = state.push(Self {
4955            common: WaitableCommon::default(),
4956            lower_params: Some(lower_params),
4957            lift_result: Some(lift_result),
4958            result: None,
4959            callback,
4960            caller,
4961            call_context: CallContext::default(),
4962            sync_result: SyncResult::NotProduced,
4963            cancel_sent: false,
4964            starting_sent: false,
4965            instance,
4966            event: None,
4967            exited: false,
4968            threads: HashSet::new(),
4969            host_future_state,
4970            async_function,
4971            decremented_interesting_task_count: false,
4972        })?;
4973        let new_thread = GuestThread::new_implicit(state, task)?;
4974        let thread = state.push(new_thread)?;
4975        state.get_mut(task)?.threads.insert(thread);
4976        state.interesting_tasks += 1;
4977        Ok(QualifiedThreadId { task, thread })
4978    }
4979}
4980
4981impl TableDebug for GuestTask {
4982    fn type_name() -> &'static str {
4983        "GuestTask"
4984    }
4985}
4986
4987/// Represents state common to all kinds of waitables.
4988#[derive(Default)]
4989struct WaitableCommon {
4990    /// The currently pending event for this waitable, if any.
4991    event: Option<Event>,
4992    /// The set to which this waitable belongs, if any.
4993    set: Option<TableId<WaitableSet>>,
4994    /// The handle with which the guest refers to this waitable, if any.
4995    handle: Option<u32>,
4996}
4997
4998/// Represents a Component Model Async `waitable`.
4999#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
5000enum Waitable {
5001    /// A host task
5002    Host(TableId<HostTask>),
5003    /// A guest task
5004    Guest(TableId<GuestTask>),
5005    /// The read or write end of a stream or future
5006    Transmit(TableId<TransmitHandle>),
5007}
5008
5009impl Waitable {
5010    /// Retrieve the `Waitable` corresponding to the specified guest-visible
5011    /// handle.
5012    fn from_instance(
5013        state: Pin<&mut ComponentInstance>,
5014        caller_instance: RuntimeComponentInstanceIndex,
5015        waitable: u32,
5016    ) -> Result<Self> {
5017        use crate::runtime::vm::component::Waitable;
5018
5019        let (waitable, kind) = state.instance_states().0[caller_instance]
5020            .handle_table()
5021            .waitable_rep(waitable)?;
5022
5023        Ok(match kind {
5024            Waitable::Subtask { is_host: true } => Self::Host(TableId::new(waitable)),
5025            Waitable::Subtask { is_host: false } => Self::Guest(TableId::new(waitable)),
5026            Waitable::Stream | Waitable::Future => Self::Transmit(TableId::new(waitable)),
5027        })
5028    }
5029
5030    /// Retrieve the host-visible identifier for this `Waitable`.
5031    fn rep(&self) -> u32 {
5032        match self {
5033            Self::Host(id) => id.rep(),
5034            Self::Guest(id) => id.rep(),
5035            Self::Transmit(id) => id.rep(),
5036        }
5037    }
5038
5039    /// Move this `Waitable` to the specified set (when `set` is `Some(_)`) or
5040    /// remove it from any set it may currently belong to (when `set` is
5041    /// `None`).
5042    fn join(&self, state: &mut ConcurrentState, set: Option<TableId<WaitableSet>>) -> Result<()> {
5043        log::trace!("waitable {self:?} join set {set:?}");
5044
5045        let old = mem::replace(&mut self.common(state)?.set, set);
5046
5047        if let Some(old) = old {
5048            match *self {
5049                Waitable::Host(id) => state.remove_child(id, old),
5050                Waitable::Guest(id) => state.remove_child(id, old),
5051                Waitable::Transmit(id) => state.remove_child(id, old),
5052            }?;
5053
5054            state.get_mut(old)?.ready.remove(self);
5055        }
5056
5057        if let Some(set) = set {
5058            match *self {
5059                Waitable::Host(id) => state.add_child(id, set),
5060                Waitable::Guest(id) => state.add_child(id, set),
5061                Waitable::Transmit(id) => state.add_child(id, set),
5062            }?;
5063
5064            if self.common(state)?.event.is_some() {
5065                self.mark_ready(state)?;
5066            }
5067        }
5068
5069        Ok(())
5070    }
5071
5072    /// Retrieve mutable access to the `WaitableCommon` for this `Waitable`.
5073    fn common<'a>(&self, state: &'a mut ConcurrentState) -> Result<&'a mut WaitableCommon> {
5074        Ok(match self {
5075            Self::Host(id) => &mut state.get_mut(*id)?.common,
5076            Self::Guest(id) => &mut state.get_mut(*id)?.common,
5077            Self::Transmit(id) => &mut state.get_mut(*id)?.common,
5078        })
5079    }
5080
5081    /// Trap if this waitable is currently a member of a waitable set.
5082    ///
5083    /// A synchronous stream/future/subtask operation may end up blocking on
5084    /// this waitable, so it is not allowed to run while the waitable is also
5085    /// being watched by a waitable set.
5086    fn trap_if_in_waitable_set(&self, state: &mut ConcurrentState) -> Result<()> {
5087        if self.common(state)?.set.is_some() {
5088            bail!(Trap::WaitableSyncAndAsync);
5089        }
5090        Ok(())
5091    }
5092
5093    /// Set or clear the pending event for this waitable and either deliver it
5094    /// to the first waiter, if any, or mark it as ready to be delivered to the
5095    /// next waiter that arrives.
5096    fn set_event(&self, state: &mut ConcurrentState, event: Option<Event>) -> Result<()> {
5097        log::trace!("set event for {self:?}: {event:?}");
5098        self.common(state)?.event = event;
5099        self.mark_ready(state)
5100    }
5101
5102    /// Take the pending event from this waitable, leaving `None` in its place.
5103    fn take_event(&self, state: &mut ConcurrentState) -> Result<Option<Event>> {
5104        let common = self.common(state)?;
5105        let event = common.event.take();
5106        if let Some(set) = self.common(state)?.set {
5107            state.get_mut(set)?.ready.remove(self);
5108        }
5109
5110        Ok(event)
5111    }
5112
5113    /// Deliver the current event for this waitable to the first waiter, if any,
5114    /// or else mark it as ready to be delivered to the next waiter that
5115    /// arrives.
5116    fn mark_ready(&self, state: &mut ConcurrentState) -> Result<()> {
5117        if let Some(set) = self.common(state)?.set {
5118            state.get_mut(set)?.ready.insert(*self);
5119            if let Some((thread, mode)) = state.get_mut(set)?.waiting.pop_first() {
5120                let wake_on_cancel = state.get_mut(thread.thread)?.wake_on_cancel.take();
5121                assert!(wake_on_cancel.is_none() || wake_on_cancel == Some(set));
5122
5123                let item = match mode {
5124                    WaitMode::Fiber(fiber) => WorkItem::ResumeFiber(fiber),
5125                    WaitMode::Callback(instance) => WorkItem::GuestCall(
5126                        state.get_mut(thread.task)?.instance.index,
5127                        GuestCall {
5128                            thread,
5129                            kind: GuestCallKind::DeliverEvent {
5130                                instance,
5131                                set: Some(set),
5132                            },
5133                        },
5134                    ),
5135                };
5136                state.push_high_priority(item);
5137            }
5138        }
5139        Ok(())
5140    }
5141
5142    /// Remove this waitable from the instance's rep table.
5143    fn delete_from(&self, state: &mut ConcurrentState) -> Result<()> {
5144        match self {
5145            Self::Host(task) => {
5146                log::trace!("delete host task {task:?}");
5147                state.delete(*task)?;
5148            }
5149            Self::Guest(task) => {
5150                log::trace!("delete guest task {task:?}");
5151                let task = state.delete(*task)?;
5152
5153                // When a guest task is created it increments the
5154                // `ConcurrentState::interesting_tasks` counter, and that needs
5155                // to be paired with a decrement. There are a few situations in
5156                // which the decrement needs to happen which don't all funnel
5157                // through here, so in lieu of that at least try to catch issues
5158                // where we forgot to do a decrement.
5159                debug_assert!(task.decremented_interesting_task_count);
5160            }
5161            Self::Transmit(task) => {
5162                state.delete(*task)?;
5163            }
5164        }
5165
5166        Ok(())
5167    }
5168}
5169
5170impl fmt::Debug for Waitable {
5171    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5172        match self {
5173            Self::Host(id) => write!(f, "{id:?}"),
5174            Self::Guest(id) => write!(f, "{id:?}"),
5175            Self::Transmit(id) => write!(f, "{id:?}"),
5176        }
5177    }
5178}
5179
5180/// Represents a Component Model Async `waitable-set`.
5181#[derive(Default)]
5182struct WaitableSet {
5183    /// Which waitables in this set have pending events, if any.
5184    ready: BTreeSet<Waitable>,
5185    /// Which guest threads are currently waiting on this set, if any.
5186    waiting: BTreeMap<QualifiedThreadId, WaitMode>,
5187    /// Whether this set is a synthetic, internal one meant for handling
5188    /// synchronous calls.
5189    is_sync_call_set: bool,
5190}
5191
5192impl TableDebug for WaitableSet {
5193    fn type_name() -> &'static str {
5194        "WaitableSet"
5195    }
5196}
5197
5198/// Type-erased closure to lower the parameters for a guest task.
5199type RawLower =
5200    Box<dyn FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync>;
5201
5202/// Type-erased closure to lift the result for a guest task.
5203type RawLift = Box<
5204    dyn FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
5205>;
5206
5207/// Type erased result of a guest task which may be downcast to the expected
5208/// type by a host caller (or simply ignored in the case of a guest caller; see
5209/// `DummyResult`).
5210type LiftedResult = Box<dyn Any + Send + Sync>;
5211
5212/// Used to return a result from a `LiftFn` when the actual result has already
5213/// been lowered to a guest task's stack and linear memory.
5214struct DummyResult;
5215
5216/// Represents the Component Model Async state of a (sub-)component instance.
5217#[derive(Default)]
5218pub struct ConcurrentInstanceState {
5219    /// Whether backpressure is set for this instance (enabled if >0)
5220    backpressure: u16,
5221    /// Whether this instance can be entered
5222    do_not_enter: bool,
5223    /// Pending calls for this instance which require `Self::backpressure` to be
5224    /// `true` and/or `Self::do_not_enter` to be false before they can proceed.
5225    pending: BTreeMap<QualifiedThreadId, GuestCallKind>,
5226}
5227
5228impl ConcurrentInstanceState {
5229    pub fn pending_is_empty(&self) -> bool {
5230        self.pending.is_empty()
5231    }
5232}
5233
5234#[derive(Debug, Copy, Clone)]
5235pub(crate) enum CurrentThread {
5236    /// The currently running thread is a guest, identified here with its
5237    /// task/thread id combo.
5238    Guest(QualifiedThreadId),
5239    /// The currently running thread is a host task.
5240    Host(TableId<HostTask>),
5241    /// A bit of a kludge to get `StoreOpaque::parent` working with backtraces
5242    /// and this serves as the parent node of a `Host` task. This ideally would
5243    /// get removed in favor of separate backtrace storage.
5244    GuestTask(TableId<GuestTask>),
5245    /// There is no currently running thread.
5246    None,
5247}
5248
5249impl CurrentThread {
5250    fn guest(&self) -> Option<&QualifiedThreadId> {
5251        match self {
5252            Self::Guest(id) => Some(id),
5253            _ => None,
5254        }
5255    }
5256
5257    fn guest_task(&self) -> Option<TableId<GuestTask>> {
5258        match self {
5259            Self::Guest(id) => Some(id.task),
5260            Self::GuestTask(id) => Some(*id),
5261            _ => None,
5262        }
5263    }
5264
5265    fn host(&self) -> Option<TableId<HostTask>> {
5266        match self {
5267            Self::Host(id) => Some(*id),
5268            _ => None,
5269        }
5270    }
5271
5272    fn is_none(&self) -> bool {
5273        matches!(self, Self::None)
5274    }
5275}
5276
5277impl From<QualifiedThreadId> for CurrentThread {
5278    fn from(id: QualifiedThreadId) -> Self {
5279        Self::Guest(id)
5280    }
5281}
5282
5283impl From<TableId<HostTask>> for CurrentThread {
5284    fn from(id: TableId<HostTask>) -> Self {
5285        Self::Host(id)
5286    }
5287}
5288
5289/// Represents the Component Model Async state of a store.
5290pub struct ConcurrentState {
5291    /// The currently running thread, if any.
5292    ///
5293    /// Note that we lazily materialize threads on-demand and this field is not
5294    /// necessarily up-to-date. The `StoreOpaque::current_thread` method should
5295    /// be preferred over directly accessing this field.
5296    unforced_current_thread: CurrentThread,
5297
5298    /// The set of pending host and background tasks, if any.
5299    ///
5300    /// See `ComponentInstance::poll_until` for where we temporarily take this
5301    /// out, poll it, then put it back to avoid any mutable aliasing hazards.
5302    futures: AlwaysMut<Option<FuturesUnordered<HostTaskFuture>>>,
5303    /// The table of waitables, waitable sets, etc.
5304    table: AlwaysMut<ResourceTable>,
5305    /// The "high priority" work queue for this store's event loop.
5306    high_priority: Vec<WorkItem>,
5307    /// The "low priority" work queue for this store's event loop.
5308    low_priority: VecDeque<WorkItem>,
5309    /// A place to stash the reason a fiber is suspending so that the code which
5310    /// resumed it will know under what conditions the fiber should be resumed
5311    /// again.
5312    suspend_reason: Option<SuspendReason>,
5313    /// A cached fiber which is waiting for work to do.
5314    ///
5315    /// This helps us avoid creating a new fiber for each `GuestCall` work item.
5316    worker: Option<StoreFiber<'static>>,
5317    /// A place to stash the work item for which we're resuming a worker fiber.
5318    worker_item: Option<WorkerItem>,
5319
5320    /// Reference counts for all component error contexts
5321    ///
5322    /// NOTE: it is possible the global ref count to be *greater* than the sum of
5323    /// (sub)component ref counts as tracked by `error_context_tables`, for
5324    /// example when the host holds one or more references to error contexts.
5325    ///
5326    /// The key of this primary map is often referred to as the "rep" (i.e. host-side
5327    /// component-wide representation) of the index into concurrent state for a given
5328    /// stored `ErrorContext`.
5329    ///
5330    /// Stated another way, `TypeComponentGlobalErrorContextTableIndex` is essentially the same
5331    /// as a `TableId<ErrorContextState>`.
5332    global_error_context_ref_counts:
5333        BTreeMap<TypeComponentGlobalErrorContextTableIndex, GlobalErrorContextRefCount>,
5334
5335    /// The number of "interesting tasks" currently executing in the store.
5336    ///
5337    /// This tracks the concept of a component instance lifetime as defined in
5338    /// https://github.com/WebAssembly/component-model/pull/643. Specifically
5339    /// all tasks currently increment this counter which then gets decremented
5340    /// when they exit. In the future some tasks might not increment this
5341    /// counter, but for now all do.
5342    ///
5343    /// This is used to implement `Accessor::poll_no_interesting_tasks` to
5344    /// inform the embedder when all tasks have completed. This is then
5345    /// used in wasmtime-wasi-http, for example, to know when an instance is
5346    /// idle.
5347    interesting_tasks: usize,
5348
5349    /// Single waker to notify when `interesting_tasks` reaches 0.
5350    ///
5351    /// Used in the implementation of `Accessor::poll_no_interesting_tasks`.
5352    interesting_tasks_empty_waker: Option<Waker>,
5353
5354    /// Single waker to notify when a component instance goes from
5355    /// not-concurrently-callable to concurrently-callable.
5356    ///
5357    /// Used in the implementation of `Accessor::poll_ready_for_concurrent_call`.
5358    ready_for_concurrent_call_waker: Option<Waker>,
5359}
5360
5361impl Default for ConcurrentState {
5362    fn default() -> Self {
5363        Self {
5364            unforced_current_thread: CurrentThread::None,
5365            table: AlwaysMut::new(ResourceTable::new()),
5366            futures: AlwaysMut::new(Some(FuturesUnordered::new())),
5367            high_priority: Vec::new(),
5368            low_priority: VecDeque::new(),
5369            suspend_reason: None,
5370            worker: None,
5371            worker_item: None,
5372            global_error_context_ref_counts: BTreeMap::new(),
5373            interesting_tasks: 0,
5374            interesting_tasks_empty_waker: None,
5375            ready_for_concurrent_call_waker: None,
5376        }
5377    }
5378}
5379
5380impl ConcurrentState {
5381    /// Take ownership of any fibers and futures owned by this object.
5382    ///
5383    /// This should be used when disposing of the `Store` containing this object
5384    /// in order to gracefully resolve any and all fibers using
5385    /// `StoreFiber::dispose`.  This is necessary to avoid possible
5386    /// use-after-free bugs due to fibers which may still have access to the
5387    /// `Store`.
5388    ///
5389    /// Additionally, the futures collected with this function should be dropped
5390    /// within a `tls::set` call, which will ensure than any futures closing
5391    /// over an `&Accessor` will have access to the store when dropped, allowing
5392    /// e.g. `WithAccessor[AndValue]` instances to be disposed of without
5393    /// panicking.
5394    ///
5395    /// Note that this will leave the object in an inconsistent and unusable
5396    /// state, so it should only be used just prior to dropping it.
5397    pub(crate) fn take_fibers_and_futures(
5398        &mut self,
5399        fibers: &mut Vec<StoreFiber<'static>>,
5400        futures: &mut Vec<FuturesUnordered<HostTaskFuture>>,
5401    ) {
5402        for entry in self.table.get_mut().iter_mut() {
5403            if let Some(set) = entry.downcast_mut::<WaitableSet>() {
5404                for mode in mem::take(&mut set.waiting).into_values() {
5405                    if let WaitMode::Fiber(fiber) = mode {
5406                        fibers.push(fiber);
5407                    }
5408                }
5409            } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
5410                if let GuestThreadState::Suspended(fiber) | GuestThreadState::Ready { fiber, .. } =
5411                    mem::replace(&mut thread.state, GuestThreadState::Completed)
5412                {
5413                    fibers.push(fiber);
5414                }
5415            }
5416        }
5417
5418        if let Some(fiber) = self.worker.take() {
5419            fibers.push(fiber);
5420        }
5421
5422        let mut handle_item = |item| match item {
5423            WorkItem::ResumeFiber(fiber) => {
5424                fibers.push(fiber);
5425            }
5426            WorkItem::PushFuture(future) => {
5427                self.futures
5428                    .get_mut()
5429                    .as_mut()
5430                    .unwrap()
5431                    .push(future.into_inner());
5432            }
5433            WorkItem::ResumeThread(..) | WorkItem::GuestCall(..) | WorkItem::WorkerFunction(..) => {
5434            }
5435        };
5436
5437        for item in mem::take(&mut self.high_priority) {
5438            handle_item(item);
5439        }
5440        for item in mem::take(&mut self.low_priority) {
5441            handle_item(item);
5442        }
5443
5444        if let Some(them) = self.futures.get_mut().take() {
5445            futures.push(them);
5446        }
5447    }
5448
5449    #[cfg(feature = "gc")]
5450    pub(crate) fn trace_fiber_roots(
5451        &mut self,
5452        modules: &ModuleRegistry,
5453        unwind: &dyn Unwind,
5454        gc_roots_list: &mut GcRootsList,
5455    ) {
5456        let ConcurrentState {
5457            table,
5458            worker,
5459            high_priority,
5460            low_priority,
5461
5462            // TODO(cm-gc): This field contains `ValRaw`s, but they are never GC
5463            // references because the component model doesn't support GC yet. We
5464            // will need to trace these somehow when it does.
5465            futures: _,
5466
5467            // These fields do not contain GC references.
5468            worker_item: _,
5469            unforced_current_thread: _,
5470            suspend_reason: _,
5471            global_error_context_ref_counts: _,
5472            interesting_tasks: _,
5473            interesting_tasks_empty_waker: _,
5474            ready_for_concurrent_call_waker: _,
5475        } = self;
5476
5477        for entry in table.get_mut().iter_mut() {
5478            if let Some(set) = entry.downcast_mut::<WaitableSet>() {
5479                for mode in set.waiting.values_mut() {
5480                    if let WaitMode::Fiber(fiber) = mode {
5481                        fiber.trace_gc_roots(modules, unwind, gc_roots_list);
5482                    }
5483                }
5484            } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
5485                if let GuestThreadState::Suspended(fiber) | GuestThreadState::Ready { fiber, .. } =
5486                    &mut thread.state
5487                {
5488                    fiber.trace_gc_roots(modules, unwind, gc_roots_list);
5489                }
5490            }
5491        }
5492
5493        if let Some(fiber) = worker {
5494            fiber.trace_gc_roots(modules, unwind, gc_roots_list);
5495        }
5496
5497        let mut handle_item = |item: &mut WorkItem| match item {
5498            WorkItem::ResumeFiber(fiber) => {
5499                fiber.trace_gc_roots(modules, unwind, gc_roots_list);
5500            }
5501            WorkItem::PushFuture(_future) => {
5502                // TODO(cm-gc): once futures can contain GC roots, we will need
5503                // to trace them.
5504            }
5505            WorkItem::ResumeThread(..) | WorkItem::GuestCall(..) | WorkItem::WorkerFunction(..) => {
5506            }
5507        };
5508
5509        for item in high_priority {
5510            handle_item(item);
5511        }
5512        for item in low_priority {
5513            handle_item(item);
5514        }
5515    }
5516
5517    fn push<V: Send + Sync + 'static>(
5518        &mut self,
5519        value: V,
5520    ) -> Result<TableId<V>, ResourceTableError> {
5521        self.table.get_mut().push(value).map(TableId::from)
5522    }
5523
5524    fn get_mut<V: 'static>(&mut self, id: TableId<V>) -> Result<&mut V, ResourceTableError> {
5525        self.table.get_mut().get_mut(&Resource::from(id))
5526    }
5527
5528    pub fn add_child<T: 'static, U: 'static>(
5529        &mut self,
5530        child: TableId<T>,
5531        parent: TableId<U>,
5532    ) -> Result<(), ResourceTableError> {
5533        self.table
5534            .get_mut()
5535            .add_child(Resource::from(child), Resource::from(parent))
5536    }
5537
5538    pub fn remove_child<T: 'static, U: 'static>(
5539        &mut self,
5540        child: TableId<T>,
5541        parent: TableId<U>,
5542    ) -> Result<(), ResourceTableError> {
5543        self.table
5544            .get_mut()
5545            .remove_child(Resource::from(child), Resource::from(parent))
5546    }
5547
5548    fn delete<V: 'static>(&mut self, id: TableId<V>) -> Result<V, ResourceTableError> {
5549        self.table.get_mut().delete(Resource::from(id))
5550    }
5551
5552    fn push_future(&mut self, future: HostTaskFuture) {
5553        // Note that we can't directly push to `ConcurrentState::futures` here
5554        // since this may be called from a future that's being polled inside
5555        // `Self::poll_until`, which temporarily removes the `FuturesUnordered`
5556        // so it has exclusive access while polling it.  Therefore, we push a
5557        // work item to the "high priority" queue, which will actually push to
5558        // `ConcurrentState::futures` later.
5559        self.push_high_priority(WorkItem::PushFuture(AlwaysMut::new(future)));
5560    }
5561
5562    fn push_high_priority(&mut self, item: WorkItem) {
5563        log::trace!("push high priority: {item:?}");
5564        self.high_priority.push(item);
5565    }
5566
5567    fn push_low_priority(&mut self, item: WorkItem) {
5568        log::trace!("push low priority: {item:?}");
5569        self.low_priority.push_front(item);
5570    }
5571
5572    fn push_work_item(&mut self, item: WorkItem, high_priority: bool) {
5573        if high_priority {
5574            self.push_high_priority(item);
5575        } else {
5576            self.push_low_priority(item);
5577        }
5578    }
5579
5580    fn promote_instance_local_thread_work_item(
5581        &mut self,
5582        current_instance: RuntimeComponentInstanceIndex,
5583    ) -> bool {
5584        self.promote_work_items_matching(|item: &WorkItem| match item {
5585            WorkItem::ResumeThread(instance, _) | WorkItem::GuestCall(instance, _) => {
5586                *instance == current_instance
5587            }
5588            _ => false,
5589        })
5590    }
5591
5592    fn promote_thread_work_item(&mut self, thread: QualifiedThreadId) -> bool {
5593        self.promote_work_items_matching(|item: &WorkItem| match item {
5594            WorkItem::ResumeThread(_, t) | WorkItem::GuestCall(_, GuestCall { thread: t, .. }) => {
5595                *t == thread
5596            }
5597            _ => false,
5598        })
5599    }
5600
5601    fn promote_work_items_matching<F>(&mut self, mut predicate: F) -> bool
5602    where
5603        F: FnMut(&WorkItem) -> bool,
5604    {
5605        // If there's a high-priority work item to resume the current guest thread,
5606        // we don't need to promote anything, but we return true to indicate that
5607        // work is pending for the current instance.
5608        if self.high_priority.iter().any(&mut predicate) {
5609            true
5610        }
5611        // Otherwise, look for a low-priority work item that matches the current
5612        // instance and promote it to high-priority.
5613        else if let Some(idx) = self.low_priority.iter().position(&mut predicate) {
5614            let item = self.low_priority.remove(idx).unwrap();
5615            self.push_high_priority(item);
5616            true
5617        } else {
5618            false
5619        }
5620    }
5621
5622    fn check_blocking_for(&mut self, task: TableId<GuestTask>) -> Result<()> {
5623        if self.may_block(task)? {
5624            Ok(())
5625        } else {
5626            Err(Trap::CannotBlockSyncTask.into())
5627        }
5628    }
5629
5630    fn may_block(&mut self, task: TableId<GuestTask>) -> Result<bool> {
5631        let task = self.get_mut(task)?;
5632        Ok(task.async_function || task.returned_or_cancelled())
5633    }
5634
5635    /// Used by `ResourceTables` to acquire the current `CallContext` for the
5636    /// specified task.
5637    ///
5638    /// The `task` is bit-packed as returned by `current_call_context_scope_id`
5639    /// below.
5640    pub fn call_context(&mut self, task: u32) -> Result<&mut CallContext> {
5641        let (task, is_host) = (task >> 1, task & 1 == 1);
5642        if is_host {
5643            let task: TableId<HostTask> = TableId::new(task);
5644            Ok(&mut self.get_mut(task)?.call_context)
5645        } else {
5646            let task: TableId<GuestTask> = TableId::new(task);
5647            Ok(&mut self.get_mut(task)?.call_context)
5648        }
5649    }
5650
5651    fn futures_mut(&mut self) -> Result<&mut FuturesUnordered<HostTaskFuture>> {
5652        match self.futures.get_mut().as_mut() {
5653            Some(f) => Ok(f),
5654            None => bail_bug!("futures field of concurrent state is currently taken"),
5655        }
5656    }
5657
5658    pub(crate) fn table(&mut self) -> &mut ResourceTable {
5659        self.table.get_mut()
5660    }
5661
5662    /// Returns the parent thread, if any, of `cur`.
5663    fn parent(&mut self, cur: CurrentThread) -> Option<CurrentThread> {
5664        let task = match cur {
5665            CurrentThread::GuestTask(task) => task,
5666            CurrentThread::Guest(thread) => thread.task,
5667            CurrentThread::Host(id) => {
5668                return Some(CurrentThread::GuestTask(self.get_mut(id).ok()?.caller));
5669            }
5670            CurrentThread::None => return None,
5671        };
5672        let task = self.get_mut(task).ok()?;
5673        Some(match task.caller {
5674            Caller::Host { caller, .. } => caller,
5675            Caller::Guest { thread } => thread.into(),
5676        })
5677    }
5678}
5679
5680/// Provide a type hint to compiler about the shape of a parameter lower
5681/// closure.
5682fn for_any_lower<
5683    F: FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync,
5684>(
5685    fun: F,
5686) -> F {
5687    fun
5688}
5689
5690/// Provide a type hint to compiler about the shape of a result lift closure.
5691fn for_any_lift<
5692    F: FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
5693>(
5694    fun: F,
5695) -> F {
5696    fun
5697}
5698
5699fn check_ambient_store(id: StoreId) {
5700    let message = "\
5701        `Future`s which depend on asynchronous component tasks, streams, or \
5702        futures to complete may only be polled from the event loop of the \
5703        store to which they belong.  Please use \
5704        `StoreContextMut::{run_concurrent,spawn}` to poll or await them.\
5705    ";
5706    tls::try_get(|store| {
5707        let matched = match store {
5708            tls::TryGet::Some(store) => store.id() == id,
5709            tls::TryGet::Taken | tls::TryGet::None => false,
5710        };
5711
5712        if !matched {
5713            panic!("{message}")
5714        }
5715    });
5716}
5717
5718/// Assert that `StoreContextMut::run_concurrent` has not been called from
5719/// within an store's event loop.
5720fn check_recursive_run() {
5721    tls::try_get(|store| {
5722        if !matches!(store, tls::TryGet::None) {
5723            panic!("Recursive `StoreContextMut::run_concurrent` calls not supported")
5724        }
5725    });
5726}
5727
5728fn unpack_callback_code(code: u32) -> (u32, u32) {
5729    (code & 0xF, code >> 4)
5730}
5731
5732/// Helper struct for packaging parameters to be passed to
5733/// `ComponentInstance::waitable_check` for calls to `waitable-set.wait` or
5734/// `waitable-set.poll`.
5735struct WaitableCheckParams {
5736    set: TableId<WaitableSet>,
5737    options: OptionsIndex,
5738    payload: u32,
5739}
5740
5741/// Indicates whether `ComponentInstance::waitable_check` is being called for
5742/// `waitable-set.wait` or `waitable-set.poll`.
5743enum WaitableCheck {
5744    Wait,
5745    Poll,
5746}
5747
5748/// An identifier representing a guest task within a component.
5749///
5750/// This can be acquired by calling [`Func::start_call_concurrent`] or
5751/// [`TypedFunc::start_call_concurrent`] and then using the
5752/// [`FuncCallConcurrent::task`] accessor, for example. This can then be
5753/// reflected on with [`StoreContextMut::async_call_stack`].
5754///
5755/// [`TypedFunc::start_call_concurrent`]: crate::component::TypedFunc::start_call_concurrent
5756#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
5757pub struct GuestTaskId(TableId<GuestTask>);
5758
5759/// Represents a guest task called from the host, prepared using `prepare_call`.
5760pub(crate) struct PreparedCall<R> {
5761    /// The guest export to be called
5762    handle: Func,
5763    /// The guest thread created by `prepare_call`
5764    thread: QualifiedThreadId,
5765    /// The number of lowered core Wasm parameters to pass to the call.
5766    param_count: usize,
5767    /// The `oneshot::Receiver` to which the result of the call will be
5768    /// delivered when it is available.
5769    rx: oneshot::Receiver<LiftedResult>,
5770    /// The instance that this call is prepared for.
5771    runtime_instance: RuntimeInstance,
5772    _phantom: PhantomData<R>,
5773}
5774
5775impl<R> PreparedCall<R> {
5776    /// Get a copy of the `TaskId` for this `PreparedCall`.
5777    pub(crate) fn task_id(&self) -> TaskId {
5778        TaskId {
5779            task: self.thread.task,
5780            runtime_instance: self.runtime_instance,
5781        }
5782    }
5783}
5784
5785/// Represents a task created by `prepare_call`.
5786pub(crate) struct TaskId {
5787    task: TableId<GuestTask>,
5788    runtime_instance: RuntimeInstance,
5789}
5790
5791impl TaskId {
5792    /// The host future for an async task was dropped. If the parameters have not been lowered yet,
5793    /// it is no longer valid to do so, as the lowering closure would see a dangling pointer. In this case,
5794    /// we delete the task eagerly. Otherwise, there may be running threads, or ones that are suspended
5795    /// and can be resumed by other tasks for this component, so we mark the future as dropped
5796    /// and delete the task when all threads are done.
5797    pub(crate) fn host_future_dropped(&self, store: &mut StoreOpaque) -> Result<()> {
5798        let task = store.concurrent_state_mut()?.get_mut(self.task)?;
5799        let delete = if !task.already_lowered_parameters() {
5800            store.cancel_guest_subtask_without_lowered_parameters(
5801                self.runtime_instance,
5802                self.task,
5803            )?;
5804            true
5805        } else {
5806            task.host_future_state = HostFutureState::Dropped;
5807            task.ready_to_delete()
5808        };
5809        if delete {
5810            Waitable::Guest(self.task).delete_from(store.concurrent_state_mut()?)?
5811        }
5812        Ok(())
5813    }
5814}
5815
5816/// Prepare a call to the specified exported Wasm function, providing functions
5817/// for lowering the parameters and lifting the result.
5818///
5819/// To enqueue the returned `PreparedCall` in the `ComponentInstance`'s event
5820/// loop, use `queue_call`.
5821pub(crate) fn prepare_call<T, R>(
5822    mut store: StoreContextMut<T>,
5823    handle: Func,
5824    param_count: usize,
5825    host_future_present: bool,
5826    lower_params: impl FnOnce(Func, StoreContextMut<T>, &mut [MaybeUninit<ValRaw>]) -> Result<()>
5827    + Send
5828    + Sync
5829    + 'static,
5830    lift_result: impl FnOnce(Func, &mut StoreOpaque, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>>
5831    + Send
5832    + Sync
5833    + 'static,
5834) -> Result<PreparedCall<R>> {
5835    let (options, _flags, ty, raw_options) = handle.abi_info(store.0);
5836
5837    let instance = handle.instance().id().get(store.0);
5838    let options = &instance.component().env_component().options[options];
5839    let ty = &instance.component().types()[ty];
5840    let async_function = ty.async_;
5841    let task_return_type = ty.results;
5842    let component_instance = raw_options.instance;
5843    let callback = options.callback.map(|i| instance.runtime_callback(i));
5844    let memory = options
5845        .memory()
5846        .map(|i| instance.runtime_memory(i))
5847        .map(SendSyncPtr::new);
5848    let string_encoding = options.string_encoding;
5849    let token = StoreToken::new(store.as_context_mut());
5850    let caller = store.0.current_thread()?;
5851    let state = store.0.concurrent_state_mut()?;
5852
5853    let (tx, rx) = oneshot::channel();
5854
5855    let instance = handle.instance().runtime_instance(component_instance);
5856    let thread = GuestTask::new(
5857        state,
5858        Box::new(for_any_lower(move |store, params| {
5859            lower_params(handle, token.as_context_mut(store), params)
5860        })),
5861        LiftResult {
5862            lift: Box::new(for_any_lift(move |store, result| {
5863                lift_result(handle, store, result)
5864            })),
5865            ty: task_return_type,
5866            memory,
5867            string_encoding,
5868        },
5869        Caller::Host {
5870            tx: Some(tx),
5871            host_future_present,
5872            caller,
5873        },
5874        callback.map(|callback| {
5875            let callback = SendSyncPtr::new(callback);
5876            let instance = handle.instance();
5877            Box::new(move |store: &mut dyn VMStore, event, handle| {
5878                let store = token.as_context_mut(store);
5879                // SAFETY: Per the contract of `prepare_call`, the callback
5880                // will remain valid at least as long is this task exists.
5881                unsafe { instance.call_callback(store, callback, event, handle) }
5882            }) as CallbackFn
5883        }),
5884        instance,
5885        async_function,
5886    )?;
5887
5888    if !store.0.may_enter(instance)? {
5889        bail!(Trap::CannotEnterComponent);
5890    }
5891
5892    Ok(PreparedCall {
5893        handle,
5894        thread,
5895        param_count,
5896        runtime_instance: instance,
5897        rx,
5898        _phantom: PhantomData,
5899    })
5900}
5901
5902pub(crate) struct QueuedCall<R> {
5903    store: StoreId,
5904    task: TableId<GuestTask>,
5905    rx: oneshot::Receiver<LiftedResult>,
5906    _marker: PhantomData<fn() -> R>,
5907}
5908
5909impl<R> QueuedCall<R> {
5910    /// Queue a call previously prepared using `prepare_call` to be run as part of
5911    /// the associated `ComponentInstance`'s event loop.
5912    ///
5913    /// The returned future will resolve to the result once it is available, but
5914    /// must only be polled via the instance's event loop. See
5915    /// `StoreContextMut::run_concurrent` for details.
5916    pub(crate) fn new<T: 'static>(
5917        mut store: StoreContextMut<T>,
5918        prepared: PreparedCall<R>,
5919    ) -> Result<QueuedCall<R>> {
5920        let PreparedCall {
5921            handle,
5922            thread,
5923            param_count,
5924            rx,
5925            ..
5926        } = prepared;
5927
5928        queue_call0(store.as_context_mut(), handle, thread, param_count)?;
5929
5930        Ok(QueuedCall {
5931            store: store.0.id(),
5932            task: thread.task,
5933            rx,
5934            _marker: PhantomData,
5935        })
5936    }
5937
5938    fn task(&self) -> GuestTaskId {
5939        GuestTaskId(self.task)
5940    }
5941}
5942
5943impl<R> Future for QueuedCall<R>
5944where
5945    R: 'static,
5946{
5947    type Output = Result<R>;
5948
5949    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
5950        check_ambient_store(self.store);
5951        Pin::new(&mut self.rx).poll(cx).map(|result| match result {
5952            Ok(r) => match r.downcast() {
5953                Ok(r) => Ok(*r),
5954                Err(_) => bail_bug!("wrong type of value produced"),
5955            },
5956            Err(oneshot::Canceled) => bail_bug!("channel erroneously dropped"),
5957        })
5958    }
5959}
5960
5961/// Queue a call previously prepared using `prepare_call` to be run as part of
5962/// the associated `ComponentInstance`'s event loop.
5963fn queue_call0<T: 'static>(
5964    store: StoreContextMut<T>,
5965    handle: Func,
5966    guest_thread: QualifiedThreadId,
5967    param_count: usize,
5968) -> Result<()> {
5969    let (_options, _, _ty, raw_options) = handle.abi_info(store.0);
5970    let is_concurrent = raw_options.async_;
5971    let callback = raw_options.callback;
5972    let instance = handle.instance();
5973    let callee = handle.lifted_core_func(store.0);
5974    let post_return = handle.post_return_core_func(store.0);
5975    let callback = callback.map(|i| {
5976        let instance = instance.id().get(store.0);
5977        SendSyncPtr::new(instance.runtime_callback(i))
5978    });
5979
5980    log::trace!("queueing call {guest_thread:?}");
5981
5982    // SAFETY: `callee`, `callback`, and `post_return` are valid pointers
5983    // (with signatures appropriate for this call) and will remain valid as
5984    // long as this instance is valid.
5985    unsafe {
5986        instance.queue_call(
5987            store,
5988            guest_thread,
5989            SendSyncPtr::new(callee),
5990            param_count,
5991            1,
5992            is_concurrent,
5993            callback,
5994            post_return.map(SendSyncPtr::new),
5995        )
5996    }
5997}