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