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/Async.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 //! `ComponentInstance` 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. `Instance::run_concurrent`. The `ComponentInstance::poll_until` 14 //! function contains the loop itself, while the 15 //! `ComponentInstance::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 //! - `Instance::run_concurrent`: Run the event loop for the specified instance, 25 //! allowing any and all tasks belonging to that instance to make progress. 26 //! 27 //! - `Instance::spawn`: Run a background task as part of the event loop for the 28 //! specified instance. 29 //! 30 //! - `Instance::{future,stream}`: Create a new Component Model `future` or 31 //! `stream`; the read end may be passed to the guest. 32 //! 33 //! - `{Future,Stream}Reader::read` and `{Future,Stream}Writer::write`: read 34 //! from or write to a future or stream, respectively. 35 //! 36 //! ## Host Task API (e.g. implementing concurrent host functions and background tasks) 37 //! 38 //! - `LinkerInstance::func_wrap_concurrent`: Register a concurrent host 39 //! function with the linker. That function will take an `Accessor` as its 40 //! first parameter, which provides access to the store and instance between 41 //! (but not across) await points. 42 //! 43 //! - `Accessor::with`: Access the store, its associated data, and the current 44 //! instance. 45 //! 46 //! - `Accessor::spawn`: Run a background task as part of the event loop for the 47 //! specified instance. This is equivalent to `Instance::spawn` but more 48 //! convenient to use in host functions. 49 50 use crate::component::func::{self, Func, Options}; 51 use crate::component::{Component, ComponentInstanceId, HasData, HasSelf, Instance}; 52 use crate::fiber::{self, StoreFiber, StoreFiberYield}; 53 use crate::store::{StoreInner, StoreOpaque, StoreToken}; 54 use crate::vm::component::{ 55 CallContext, ComponentInstance, InstanceFlags, ResourceTables, TransmitLocalState, 56 }; 57 use crate::vm::{SendSyncPtr, VMFuncRef, VMMemoryDefinition, VMStore}; 58 use crate::{AsContext, AsContextMut, StoreContext, StoreContextMut, ValRaw}; 59 use anyhow::{Context as _, Result, anyhow, bail}; 60 use error_contexts::GlobalErrorContextRefCount; 61 use futures::channel::oneshot; 62 use futures::future::{self, Either, FutureExt}; 63 use futures::stream::{FuturesUnordered, StreamExt}; 64 use futures_and_streams::{FlatAbi, ReturnCode, TransmitHandle, TransmitIndex}; 65 use std::any::Any; 66 use std::borrow::ToOwned; 67 use std::boxed::Box; 68 use std::cell::UnsafeCell; 69 use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; 70 use std::fmt; 71 use std::future::Future; 72 use std::marker::PhantomData; 73 use std::mem::{self, ManuallyDrop, MaybeUninit}; 74 use std::ops::DerefMut; 75 use std::pin::{Pin, pin}; 76 use std::ptr::{self, NonNull}; 77 use std::slice; 78 use std::sync::Mutex; 79 use std::task::{Context, Poll, Waker}; 80 use std::vec::Vec; 81 use table::{Table, TableDebug, TableError, TableId}; 82 use wasmtime_environ::component::{ 83 CanonicalOptions, CanonicalOptionsDataModel, ExportIndex, MAX_FLAT_PARAMS, MAX_FLAT_RESULTS, 84 OptionsIndex, PREPARE_ASYNC_NO_RESULT, PREPARE_ASYNC_WITH_RESULT, 85 RuntimeComponentInstanceIndex, StringEncoding, TypeComponentGlobalErrorContextTableIndex, 86 TypeComponentLocalErrorContextTableIndex, TypeFutureTableIndex, TypeStreamTableIndex, 87 TypeTupleIndex, 88 }; 89 90 pub use abort::JoinHandle; 91 pub use futures_and_streams::{ 92 ErrorContext, FutureReader, FutureWriter, GuardedFutureReader, GuardedFutureWriter, 93 GuardedStreamReader, GuardedStreamWriter, ReadBuffer, StreamReader, StreamWriter, VecBuffer, 94 WriteBuffer, 95 }; 96 pub(crate) use futures_and_streams::{ 97 ResourcePair, lower_error_context_to_index, lower_future_to_index, lower_stream_to_index, 98 }; 99 100 mod abort; 101 mod error_contexts; 102 mod futures_and_streams; 103 mod table; 104 pub(crate) mod tls; 105 106 /// Constant defined in the Component Model spec to indicate that the async 107 /// intrinsic (e.g. `future.write`) has not yet completed. 108 const BLOCKED: u32 = 0xffff_ffff; 109 110 /// Corresponds to `CallState` in the upstream spec. 111 #[derive(Clone, Copy, Eq, PartialEq, Debug)] 112 pub enum Status { 113 Starting = 0, 114 Started = 1, 115 Returned = 2, 116 StartCancelled = 3, 117 ReturnCancelled = 4, 118 } 119 120 impl Status { 121 /// Packs this status and the optional `waitable` provided into a 32-bit 122 /// result that the canonical ABI requires. 123 /// 124 /// The low 4 bits are reserved for the status while the upper 28 bits are 125 /// the waitable, if present. 126 pub fn pack(self, waitable: Option<u32>) -> u32 { 127 assert!(matches!(self, Status::Returned) == waitable.is_none()); 128 let waitable = waitable.unwrap_or(0); 129 assert!(waitable < (1 << 28)); 130 (waitable << 4) | (self as u32) 131 } 132 } 133 134 /// Corresponds to `EventCode` in the Component Model spec, plus related payload 135 /// data. 136 #[derive(Clone, Copy, Debug)] 137 enum Event { 138 None, 139 Cancelled, 140 Subtask { 141 status: Status, 142 }, 143 StreamRead { 144 code: ReturnCode, 145 pending: Option<(TypeStreamTableIndex, u32)>, 146 }, 147 StreamWrite { 148 code: ReturnCode, 149 pending: Option<(TypeStreamTableIndex, u32)>, 150 }, 151 FutureRead { 152 code: ReturnCode, 153 pending: Option<(TypeFutureTableIndex, u32)>, 154 }, 155 FutureWrite { 156 code: ReturnCode, 157 pending: Option<(TypeFutureTableIndex, u32)>, 158 }, 159 } 160 161 impl Event { 162 /// Lower this event to core Wasm integers for delivery to the guest. 163 /// 164 /// Note that the waitable handle, if any, is assumed to be lowered 165 /// separately. 166 fn parts(self) -> (u32, u32) { 167 const EVENT_NONE: u32 = 0; 168 const EVENT_SUBTASK: u32 = 1; 169 const EVENT_STREAM_READ: u32 = 2; 170 const EVENT_STREAM_WRITE: u32 = 3; 171 const EVENT_FUTURE_READ: u32 = 4; 172 const EVENT_FUTURE_WRITE: u32 = 5; 173 const EVENT_CANCELLED: u32 = 6; 174 match self { 175 Event::None => (EVENT_NONE, 0), 176 Event::Cancelled => (EVENT_CANCELLED, 0), 177 Event::Subtask { status } => (EVENT_SUBTASK, status as u32), 178 Event::StreamRead { code, .. } => (EVENT_STREAM_READ, code.encode()), 179 Event::StreamWrite { code, .. } => (EVENT_STREAM_WRITE, code.encode()), 180 Event::FutureRead { code, .. } => (EVENT_FUTURE_READ, code.encode()), 181 Event::FutureWrite { code, .. } => (EVENT_FUTURE_WRITE, code.encode()), 182 } 183 } 184 } 185 186 /// Corresponds to `CallbackCode` in the spec. 187 mod callback_code { 188 pub const EXIT: u32 = 0; 189 pub const YIELD: u32 = 1; 190 pub const WAIT: u32 = 2; 191 pub const POLL: u32 = 3; 192 } 193 194 /// A flag indicating that the callee is an async-lowered export. 195 /// 196 /// This may be passed to the `async-start` intrinsic from a fused adapter. 197 const START_FLAG_ASYNC_CALLEE: u32 = wasmtime_environ::component::START_FLAG_ASYNC_CALLEE as u32; 198 199 /// Provides access to either store data (via the `get` method) or the store 200 /// itself (via [`AsContext`]/[`AsContextMut`]), as well as the component 201 /// instance to which the current host task belongs. 202 /// 203 /// See [`Accessor::with`] for details. 204 pub struct Access<'a, T: 'static, D: HasData + ?Sized = HasSelf<T>> { 205 accessor: &'a Accessor<T, D>, 206 store: StoreContextMut<'a, T>, 207 } 208 209 impl<'a, T, D> Access<'a, T, D> 210 where 211 D: HasData + ?Sized, 212 T: 'static, 213 { 214 /// Get mutable access to the store data. 215 pub fn data_mut(&mut self) -> &mut T { 216 self.store.data_mut() 217 } 218 219 /// Get mutable access to the store data. 220 pub fn get(&mut self) -> D::Data<'_> { 221 let get_data = self.accessor.get_data; 222 get_data(self.data_mut()) 223 } 224 225 /// Spawn a background task. 226 /// 227 /// See [`Accessor::spawn`] for details. 228 pub fn spawn(&mut self, task: impl AccessorTask<T, D, Result<()>>) -> JoinHandle 229 where 230 T: 'static, 231 { 232 self.accessor.instance.unwrap().spawn_with_accessor( 233 self.store.as_context_mut(), 234 self.accessor.clone_for_spawn(), 235 task, 236 ) 237 } 238 239 /// Retrieve the component instance of the caller. 240 pub fn instance(&self) -> Instance { 241 self.accessor.instance() 242 } 243 } 244 245 impl<'a, T, D> AsContext for Access<'a, T, D> 246 where 247 D: HasData + ?Sized, 248 T: 'static, 249 { 250 type Data = T; 251 252 fn as_context(&self) -> StoreContext<'_, T> { 253 self.store.as_context() 254 } 255 } 256 257 impl<'a, T, D> AsContextMut for Access<'a, T, D> 258 where 259 D: HasData + ?Sized, 260 T: 'static, 261 { 262 fn as_context_mut(&mut self) -> StoreContextMut<'_, T> { 263 self.store.as_context_mut() 264 } 265 } 266 267 /// Provides scoped mutable access to store data in the context of a concurrent 268 /// host task future. 269 /// 270 /// This allows multiple host task futures to execute concurrently and access 271 /// the store between (but not across) `await` points. 272 /// 273 /// # Rationale 274 /// 275 /// This structure is sort of like `&mut T` plus a projection from `&mut T` to 276 /// `D::Data<'_>`. The problem this is solving, however, is that it does not 277 /// literally store these values. The basic problem is that when a concurrent 278 /// host future is being polled it has access to `&mut T` (and the whole 279 /// `Store`) but when it's not being polled it does not have access to these 280 /// values. This reflects how the store is only ever polling one future at a 281 /// time so the store is effectively being passed between futures. 282 /// 283 /// Rust's `Future` trait, however, has no means of passing a `Store` 284 /// temporarily between futures. The [`Context`](std::task::Context) type does 285 /// not have the ability to attach arbitrary information to it at this time. 286 /// This type, [`Accessor`], is used to bridge this expressivity gap. 287 /// 288 /// The [`Accessor`] type here represents the ability to acquire, temporarily in 289 /// a synchronous manner, the current store. The [`Accessor::with`] function 290 /// yields an [`Access`] which can be used to access [`StoreContextMut`], `&mut 291 /// T`, or `D::Data<'_>`. Note though that [`Accessor::with`] intentionally does 292 /// not take an `async` closure as its argument, instead it's a synchronous 293 /// closure which must complete during on run of `Future::poll`. This reflects 294 /// how the store is temporarily made available while a host future is being 295 /// polled. 296 /// 297 /// # Implementation 298 /// 299 /// This type does not actually store `&mut T` nor `StoreContextMut<T>`, and 300 /// this type additionally doesn't even have a lifetime parameter. This is 301 /// instead a representation of proof of the ability to acquire these while a 302 /// future is being polled. Wasmtime will, when it polls a host future, 303 /// configure ambient state such that the `Accessor` that a future closes over 304 /// will work and be able to access the store. 305 /// 306 /// This has a number of implications for users such as: 307 /// 308 /// * It's intentional that `Accessor` cannot be cloned, it needs to stay within 309 /// the lifetime of a single future. 310 /// * A futures is expected to, however, close over an `Accessor` and keep it 311 /// alive probably for the duration of the entire future. 312 /// * Different host futures will be given different `Accessor`s, and that's 313 /// intentional. 314 /// * The `Accessor` type is `Send` and `Sync` irrespective of `T` which 315 /// alleviates some otherwise required bounds to be written down. 316 /// 317 /// # Using `Accessor` in `Drop` 318 /// 319 /// The methods on `Accessor` are only expected to work in the context of 320 /// `Future::poll` and are not guaranteed to work in `Drop`. This is because a 321 /// host future can be dropped at any time throughout the system and Wasmtime 322 /// store context is not necessarily available at that time. It's recommended to 323 /// not use `Accessor` methods in anything connected to a `Drop` implementation 324 /// as they will panic and have unintended results. If you run into this though 325 /// feel free to file an issue on the Wasmtime repository. 326 pub struct Accessor<T: 'static, D = HasSelf<T>> 327 where 328 D: HasData + ?Sized, 329 { 330 token: StoreToken<T>, 331 get_data: fn(&mut T) -> D::Data<'_>, 332 instance: Option<Instance>, 333 } 334 335 /// A helper trait to take any type of accessor-with-data in functions. 336 /// 337 /// This trait is similar to [`AsContextMut`] except that it's used when 338 /// working with an [`Accessor`] instead of a [`StoreContextMut`]. The 339 /// [`Accessor`] is the main type used in concurrent settings and is passed to 340 /// functions such as [`Func::call_concurrent`] or [`FutureWriter::write`]. 341 /// 342 /// This trait is implemented for [`Accessor`] and `&T` where `T` implements 343 /// this trait. This effectively means that regardless of the `D` in 344 /// `Accessor<T, D>` it can still be passed to a function which just needs a 345 /// store accessor. 346 /// 347 /// Acquiring an [`Accessor`] can be done through [`Instance::run_concurrent`] 348 /// for example or in a host function through 349 /// [`Linker::func_wrap_concurrent`](crate::component::Linker::func_wrap_concurrent). 350 pub trait AsAccessor { 351 /// The `T` in `Store<T>` that this accessor refers to. 352 type Data: 'static; 353 354 /// The `D` in `Accessor<T, D>`, or the projection out of 355 /// `Self::Data`. 356 type AccessorData: HasData + ?Sized; 357 358 /// Returns the accessor that this is referring to. 359 fn as_accessor(&self) -> &Accessor<Self::Data, Self::AccessorData>; 360 } 361 362 impl<T: AsAccessor + ?Sized> AsAccessor for &T { 363 type Data = T::Data; 364 type AccessorData = T::AccessorData; 365 366 fn as_accessor(&self) -> &Accessor<Self::Data, Self::AccessorData> { 367 T::as_accessor(self) 368 } 369 } 370 371 impl<T, D: HasData + ?Sized> AsAccessor for Accessor<T, D> { 372 type Data = T; 373 type AccessorData = D; 374 375 fn as_accessor(&self) -> &Accessor<T, D> { 376 self 377 } 378 } 379 380 // Note that it is intentional at this time that `Accessor` does not actually 381 // store `&mut T` or anything similar. This distinctly enables the `Accessor` 382 // structure to be both `Send` and `Sync` regardless of what `T` is (or `D` for 383 // that matter). This is used to ergonomically simplify bindings where the 384 // majority of the time `Accessor` is closed over in a future which then needs 385 // to be `Send` and `Sync`. To avoid needing to write `T: Send` everywhere (as 386 // you already have to write `T: 'static`...) it helps to avoid this. 387 // 388 // Note as well that `Accessor` doesn't actually store its data at all. Instead 389 // it's more of a "proof" of what can be accessed from TLS. API design around 390 // `Accessor` and functions like `Linker::func_wrap_concurrent` are 391 // intentionally made to ensure that `Accessor` is ideally only used in the 392 // context that TLS variables are actually set. For example host functions are 393 // given `&Accessor`, not `Accessor`, and this prevents them from persisting 394 // the value outside of a future. Within the future the TLS variables are all 395 // guaranteed to be set while the future is being polled. 396 // 397 // Finally though this is not an ironclad guarantee, but nor does it need to be. 398 // The TLS APIs are designed to panic or otherwise model usage where they're 399 // called recursively or similar. It's hoped that code cannot be constructed to 400 // actually hit this at runtime but this is not a safety requirement at this 401 // time. 402 const _: () = { 403 const fn assert<T: Send + Sync>() {} 404 assert::<Accessor<UnsafeCell<u32>>>(); 405 }; 406 407 impl<T> Accessor<T> { 408 /// Creates a new `Accessor` backed by the specified functions. 409 /// 410 /// - `get`: used to retrieve the store 411 /// 412 /// - `get_data`: used to "project" from the store's associated data to 413 /// another type (e.g. a field of that data or a wrapper around it). 414 /// 415 /// - `spawn`: used to queue spawned background tasks to be run later 416 /// 417 /// - `instance`: used to access the `Instance` to which this `Accessor` 418 /// (and the future which closes over it) belongs 419 pub(crate) fn new(token: StoreToken<T>, instance: Option<Instance>) -> Self { 420 Self { 421 token, 422 get_data: |x| x, 423 instance, 424 } 425 } 426 } 427 428 impl<T, D> Accessor<T, D> 429 where 430 D: HasData + ?Sized, 431 { 432 /// Run the specified closure, passing it mutable access to the store. 433 /// 434 /// This function is one of the main building blocks of the [`Accessor`] 435 /// type. This yields synchronous, blocking, access to store via an 436 /// [`Access`]. The [`Access`] implements [`AsContextMut`] in addition to 437 /// providing the ability to access `D` via [`Access::get`]. Note that the 438 /// `fun` here is given only temporary access to the store and `T`/`D` 439 /// meaning that the return value `R` here is not allowed to capture borrows 440 /// into the two. If access is needed to data within `T` or `D` outside of 441 /// this closure then it must be `clone`d out, for example. 442 /// 443 /// # Panics 444 /// 445 /// This function will panic if it is call recursively with any other 446 /// accessor already in scope. For example if `with` is called within `fun`, 447 /// then this function will panic. It is up to the embedder to ensure that 448 /// this does not happen. 449 pub fn with<R>(&self, fun: impl FnOnce(Access<'_, T, D>) -> R) -> R { 450 tls::get(|vmstore| { 451 fun(Access { 452 store: self.token.as_context_mut(vmstore), 453 accessor: self, 454 }) 455 }) 456 } 457 458 /// Changes this accessor to access `D2` instead of the current type 459 /// parameter `D`. 460 /// 461 /// This changes the underlying data access from `T` to `D2::Data<'_>`. 462 /// 463 /// Note that this is not a public or recommended API because it's easy to 464 /// cause panics with this by having two `Accessor` values live at the same 465 /// time. The returned `Accessor` does not refer to this `Accessor` meaning 466 /// that both can be used. You could, for example, call `Accessor::with` 467 /// simultaneously on both. That would cause a panic though. 468 /// 469 /// In short while there's nothing unsafe about this it's a footgun. It's 470 /// here for bindings generation where the provided accessor is transformed 471 /// into a new accessor and then this returned accessor is passed to 472 /// implementations. 473 /// 474 /// Note that one possible fix for this would be a lifetime parameter on 475 /// `Accessor` itself so the returned value could borrow from the original 476 /// value (or this could be `self`-by-value instead of `&mut self`) but in 477 /// attempting that it was found to be a bit too onerous in terms of 478 /// plumbing things around without a whole lot of benefit. 479 /// 480 /// In short, this works, but must be treated with care. The current main 481 /// user, bindings generation, treats this with care. 482 #[doc(hidden)] 483 pub fn with_data<D2: HasData>(&self, get_data: fn(&mut T) -> D2::Data<'_>) -> Accessor<T, D2> { 484 Accessor { 485 token: self.token, 486 get_data, 487 instance: self.instance, 488 } 489 } 490 491 /// Spawn a background task which will receive an `&Accessor<T, D>` and 492 /// run concurrently with any other tasks in progress for the current 493 /// instance. 494 /// 495 /// This is particularly useful for host functions which return a `stream` 496 /// or `future` such that the code to write to the write end of that 497 /// `stream` or `future` must run after the function returns. 498 /// 499 /// The returned [`JoinHandle`] may be used to cancel the task. 500 /// 501 /// # Panics 502 /// 503 /// Panics if called within a closure provided to the [`Accessor::with`] 504 /// function. This can only be called outside an active invocation of 505 /// [`Accessor::with`]. 506 pub fn spawn(&self, task: impl AccessorTask<T, D, Result<()>>) -> JoinHandle 507 where 508 T: 'static, 509 { 510 let instance = self.instance.unwrap(); 511 let accessor = self.clone_for_spawn(); 512 self.with(|mut access| { 513 instance.spawn_with_accessor(access.as_context_mut(), accessor, task) 514 }) 515 } 516 517 /// Retrieve the component instance of the caller. 518 pub fn instance(&self) -> Instance { 519 self.instance.unwrap() 520 } 521 522 fn clone_for_spawn(&self) -> Self { 523 Self { 524 token: self.token, 525 get_data: self.get_data, 526 instance: self.instance, 527 } 528 } 529 } 530 531 /// Represents a task which may be provided to `Accessor::spawn`, 532 /// `Accessor::forward`, or `Instance::spawn`. 533 // TODO: Replace this with `std::ops::AsyncFnOnce` when that becomes a viable 534 // option. 535 // 536 // `AsyncFnOnce` is still nightly-only in latest stable Rust version as of this 537 // writing (1.84.1), and even with 1.85.0-beta it's not possible to specify 538 // e.g. `Send` and `Sync` bounds on the `Future` type returned by an 539 // `AsyncFnOnce`. Also, using `F: Future<Output = Result<()>> + Send + Sync, 540 // FN: FnOnce(&Accessor<T>) -> F + Send + Sync + 'static` fails with a type 541 // mismatch error when we try to pass it an async closure (e.g. `async move |_| 542 // { ... }`). So this seems to be the best we can do for the time being. 543 pub trait AccessorTask<T, D, R>: Send + 'static 544 where 545 D: HasData + ?Sized, 546 { 547 /// Run the task. 548 fn run(self, accessor: &Accessor<T, D>) -> impl Future<Output = R> + Send; 549 } 550 551 /// Represents parameter and result metadata for the caller side of a 552 /// guest->guest call orchestrated by a fused adapter. 553 enum CallerInfo { 554 /// Metadata for a call to an async-lowered import 555 Async { 556 params: Vec<ValRaw>, 557 has_result: bool, 558 }, 559 /// Metadata for a call to an sync-lowered import 560 Sync { 561 params: Vec<ValRaw>, 562 result_count: u32, 563 }, 564 } 565 566 /// Indicates how a guest task is waiting on a waitable set. 567 enum WaitMode { 568 /// The guest task is waiting using `task.wait` 569 Fiber(StoreFiber<'static>), 570 /// The guest task is waiting via a callback declared as part of an 571 /// async-lifted export. 572 Callback, 573 } 574 575 /// Represents the reason a fiber is suspending itself. 576 #[derive(Debug)] 577 enum SuspendReason { 578 /// The fiber is waiting for an event to be delivered to the specified 579 /// waitable set or task. 580 Waiting { 581 set: TableId<WaitableSet>, 582 task: TableId<GuestTask>, 583 }, 584 /// The fiber has finished handling its most recent work item and is waiting 585 /// for another (or to be dropped if it is no longer needed). 586 NeedWork, 587 /// The fiber is yielding and should be resumed once other tasks have had a 588 /// chance to run. 589 Yielding { task: TableId<GuestTask> }, 590 } 591 592 /// Represents a pending call into guest code for a given guest task. 593 enum GuestCallKind { 594 /// Indicates there's an event to deliver to the task, possibly related to a 595 /// waitable set the task has been waiting on or polling. 596 DeliverEvent { 597 /// The waitable set the event belongs to, if any. 598 /// 599 /// If this is `None` the event will be waiting in the 600 /// `GuestTask::event` field for the task. 601 set: Option<TableId<WaitableSet>>, 602 }, 603 /// Indicates that a new guest task call is pending and may be executed 604 /// using the specified closure. 605 Start(Box<dyn FnOnce(&mut dyn VMStore, Instance) -> Result<()> + Send + Sync>), 606 } 607 608 impl fmt::Debug for GuestCallKind { 609 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 610 match self { 611 Self::DeliverEvent { set } => f.debug_struct("DeliverEvent").field("set", set).finish(), 612 Self::Start(_) => f.debug_tuple("Start").finish(), 613 } 614 } 615 } 616 617 /// Represents a pending call into guest code for a given guest task. 618 #[derive(Debug)] 619 struct GuestCall { 620 task: TableId<GuestTask>, 621 kind: GuestCallKind, 622 } 623 624 impl GuestCall { 625 /// Returns whether or not the call is ready to run. 626 /// 627 /// A call will not be ready to run if either: 628 /// 629 /// - the (sub-)component instance to be called has already been entered and 630 /// cannot be reentered until an in-progress call completes 631 /// 632 /// - the call is for a not-yet started task and the (sub-)component 633 /// instance to be called has backpressure enabled 634 fn is_ready(&self, state: &mut ConcurrentState) -> Result<bool> { 635 let task_instance = state.get(self.task)?.instance; 636 let state = state.instance_state(task_instance); 637 let ready = match &self.kind { 638 GuestCallKind::DeliverEvent { .. } => !state.do_not_enter, 639 GuestCallKind::Start(_) => !(state.do_not_enter || state.backpressure), 640 }; 641 log::trace!( 642 "call {self:?} ready? {ready} (do_not_enter: {}; backpressure: {})", 643 state.do_not_enter, 644 state.backpressure 645 ); 646 Ok(ready) 647 } 648 } 649 650 /// Job to be run on a worker fiber. 651 enum WorkerItem { 652 GuestCall(GuestCall), 653 Function(Mutex<Box<dyn FnOnce(&mut dyn VMStore, Instance) -> Result<()> + Send>>), 654 } 655 656 /// Represents state related to an in-progress poll operation (e.g. `task.poll` 657 /// or `CallbackCode.POLL`). 658 #[derive(Debug)] 659 struct PollParams { 660 /// Identifies the polling task. 661 task: TableId<GuestTask>, 662 /// The waitable set being polled. 663 set: TableId<WaitableSet>, 664 } 665 666 /// Represents a pending work item to be handled by the event loop for a given 667 /// component instance. 668 enum WorkItem { 669 /// A host task to be pushed to `ConcurrentState::futures`. 670 PushFuture(Mutex<HostTaskFuture>), 671 /// A fiber to resume. 672 ResumeFiber(StoreFiber<'static>), 673 /// A pending call into guest code for a given guest task. 674 GuestCall(GuestCall), 675 /// A pending `task.poll` or `CallbackCode.POLL` operation. 676 Poll(PollParams), 677 /// A job to run on a worker fiber. 678 WorkerFunction(Mutex<Box<dyn FnOnce(&mut dyn VMStore, Instance) -> Result<()> + Send>>), 679 } 680 681 impl fmt::Debug for WorkItem { 682 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 683 match self { 684 Self::PushFuture(_) => f.debug_tuple("PushFuture").finish(), 685 Self::ResumeFiber(_) => f.debug_tuple("ResumeFiber").finish(), 686 Self::GuestCall(call) => f.debug_tuple("GuestCall").field(call).finish(), 687 Self::Poll(params) => f.debug_tuple("Poll").field(params).finish(), 688 Self::WorkerFunction(_) => f.debug_tuple("WorkerFunction").finish(), 689 } 690 } 691 } 692 693 impl ComponentInstance { 694 /// Handle the `CallbackCode` returned from an async-lifted export or its 695 /// callback. 696 /// 697 /// If `initial_call` is `true`, then the code was received from the 698 /// async-lifted export; otherwise, it was received from its callback. 699 fn handle_callback_code( 700 mut self: Pin<&mut Self>, 701 guest_task: TableId<GuestTask>, 702 runtime_instance: RuntimeComponentInstanceIndex, 703 code: u32, 704 initial_call: bool, 705 ) -> Result<()> { 706 let (code, set) = unpack_callback_code(code); 707 708 log::trace!("received callback code from {guest_task:?}: {code} (set: {set})"); 709 710 let state = self.as_mut().concurrent_state_mut(); 711 let task = state.get_mut(guest_task)?; 712 713 if task.lift_result.is_some() { 714 if code == callback_code::EXIT { 715 return Err(anyhow!(crate::Trap::NoAsyncResult)); 716 } 717 if initial_call { 718 // Notify any current or future waiters that this subtask has 719 // started. 720 Waitable::Guest(guest_task).set_event( 721 state, 722 Some(Event::Subtask { 723 status: Status::Started, 724 }), 725 )?; 726 } 727 } 728 729 let get_set = |instance: Pin<&mut Self>, handle| { 730 if handle == 0 { 731 bail!("invalid waitable-set handle"); 732 } 733 734 let set = instance.guest_tables().0[runtime_instance].waitable_set_rep(handle)?; 735 736 Ok(TableId::<WaitableSet>::new(set)) 737 }; 738 739 match code { 740 callback_code::EXIT => { 741 let task = state.get_mut(guest_task)?; 742 match &task.caller { 743 Caller::Host { 744 remove_task_automatically, 745 .. 746 } => { 747 if *remove_task_automatically { 748 log::trace!("handle_callback_code will delete task {guest_task:?}"); 749 Waitable::Guest(guest_task).delete_from(state)?; 750 } 751 } 752 Caller::Guest { .. } => { 753 task.exited = true; 754 task.callback = None; 755 } 756 } 757 } 758 callback_code::YIELD => { 759 // Push this task onto the "low priority" queue so it runs after 760 // any other tasks have had a chance to run. 761 let task = state.get_mut(guest_task)?; 762 assert!(task.event.is_none()); 763 task.event = Some(Event::None); 764 state.push_low_priority(WorkItem::GuestCall(GuestCall { 765 task: guest_task, 766 kind: GuestCallKind::DeliverEvent { set: None }, 767 })); 768 } 769 callback_code::WAIT | callback_code::POLL => { 770 let set = get_set(self.as_mut(), set)?; 771 let state = self.concurrent_state_mut(); 772 773 if state.get_mut(guest_task)?.event.is_some() 774 || !state.get_mut(set)?.ready.is_empty() 775 { 776 // An event is immediately available; deliver it ASAP. 777 state.push_high_priority(WorkItem::GuestCall(GuestCall { 778 task: guest_task, 779 kind: GuestCallKind::DeliverEvent { set: Some(set) }, 780 })); 781 } else { 782 // No event is immediately available. 783 match code { 784 callback_code::POLL => { 785 // We're polling, so just yield and check whether an 786 // event has arrived after that. 787 state.push_low_priority(WorkItem::Poll(PollParams { 788 task: guest_task, 789 set, 790 })); 791 } 792 callback_code::WAIT => { 793 // We're waiting, so register to be woken up when an 794 // event is published for this waitable set. 795 // 796 // Here we also set `GuestTask::wake_on_cancel` 797 // which allows `subtask.cancel` to interrupt the 798 // wait. 799 let old = state.get_mut(guest_task)?.wake_on_cancel.replace(set); 800 assert!(old.is_none()); 801 let old = state 802 .get_mut(set)? 803 .waiting 804 .insert(guest_task, WaitMode::Callback); 805 assert!(old.is_none()); 806 } 807 _ => unreachable!(), 808 } 809 } 810 } 811 _ => bail!("unsupported callback code: {code}"), 812 } 813 814 Ok(()) 815 } 816 817 /// Get the next pending event for the specified task and (optional) 818 /// waitable set, along with the waitable handle if applicable. 819 fn get_event( 820 mut self: Pin<&mut Self>, 821 guest_task: TableId<GuestTask>, 822 set: Option<TableId<WaitableSet>>, 823 ) -> Result<Option<(Event, Option<(Waitable, u32)>)>> { 824 let state = self.as_mut().concurrent_state_mut(); 825 826 Ok( 827 if let Some(event) = state.get_mut(guest_task)?.event.take() { 828 log::trace!("deliver event {event:?} to {guest_task:?}"); 829 830 Some((event, None)) 831 } else if let Some((set, waitable)) = set 832 .and_then(|set| { 833 state 834 .get_mut(set) 835 .map(|v| v.ready.pop_first().map(|v| (set, v))) 836 .transpose() 837 }) 838 .transpose()? 839 { 840 let common = waitable.common(state)?; 841 let handle = common.handle.unwrap(); 842 let event = common.event.take().unwrap(); 843 844 log::trace!( 845 "deliver event {event:?} to {guest_task:?} for {waitable:?} (handle {handle}); set {set:?}" 846 ); 847 848 waitable.on_delivery(self, event); 849 850 Some((event, Some((waitable, handle)))) 851 } else { 852 None 853 }, 854 ) 855 } 856 857 /// Implements the `waitable-set.new` intrinsic. 858 pub(crate) fn waitable_set_new( 859 mut self: Pin<&mut Self>, 860 caller_instance: RuntimeComponentInstanceIndex, 861 ) -> Result<u32> { 862 let set = self 863 .as_mut() 864 .concurrent_state_mut() 865 .push(WaitableSet::default())?; 866 let handle = self.guest_tables().0[caller_instance].waitable_set_insert(set.rep())?; 867 log::trace!("new waitable set {set:?} (handle {handle})"); 868 Ok(handle) 869 } 870 871 /// Implements the `waitable-set.drop` intrinsic. 872 pub(crate) fn waitable_set_drop( 873 mut self: Pin<&mut Self>, 874 caller_instance: RuntimeComponentInstanceIndex, 875 set: u32, 876 ) -> Result<()> { 877 let rep = self.as_mut().guest_tables().0[caller_instance].waitable_set_remove(set)?; 878 879 log::trace!("drop waitable set {rep} (handle {set})"); 880 881 let set = self 882 .concurrent_state_mut() 883 .delete(TableId::<WaitableSet>::new(rep))?; 884 885 if !set.waiting.is_empty() { 886 bail!("cannot drop waitable set with waiters"); 887 } 888 889 Ok(()) 890 } 891 892 /// Implements the `waitable.join` intrinsic. 893 pub(crate) fn waitable_join( 894 mut self: Pin<&mut Self>, 895 caller_instance: RuntimeComponentInstanceIndex, 896 waitable_handle: u32, 897 set_handle: u32, 898 ) -> Result<()> { 899 let waitable = Waitable::from_instance(self.as_mut(), caller_instance, waitable_handle)?; 900 901 let set = if set_handle == 0 { 902 None 903 } else { 904 let set = 905 self.as_mut().guest_tables().0[caller_instance].waitable_set_rep(set_handle)?; 906 907 Some(TableId::<WaitableSet>::new(set)) 908 }; 909 910 log::trace!( 911 "waitable {waitable:?} (handle {waitable_handle}) join set {set:?} (handle {set_handle})", 912 ); 913 914 waitable.join(self.concurrent_state_mut(), set) 915 } 916 917 /// Implements the `subtask.drop` intrinsic. 918 pub(crate) fn subtask_drop( 919 mut self: Pin<&mut Self>, 920 caller_instance: RuntimeComponentInstanceIndex, 921 task_id: u32, 922 ) -> Result<()> { 923 self.as_mut().waitable_join(caller_instance, task_id, 0)?; 924 925 let (rep, is_host) = 926 self.as_mut().guest_tables().0[caller_instance].subtask_remove(task_id)?; 927 928 let concurrent_state = self.concurrent_state_mut(); 929 let (waitable, expected_caller_instance, delete) = if is_host { 930 let id = TableId::<HostTask>::new(rep); 931 let task = concurrent_state.get(id)?; 932 if task.join_handle.is_some() { 933 bail!("cannot drop a subtask which has not yet resolved"); 934 } 935 (Waitable::Host(id), task.caller_instance, true) 936 } else { 937 let id = TableId::<GuestTask>::new(rep); 938 let task = concurrent_state.get(id)?; 939 if task.lift_result.is_some() { 940 bail!("cannot drop a subtask which has not yet resolved"); 941 } 942 if let Caller::Guest { instance, .. } = &task.caller { 943 (Waitable::Guest(id), *instance, task.exited) 944 } else { 945 unreachable!() 946 } 947 }; 948 949 waitable.common(concurrent_state)?.handle = None; 950 951 if waitable.take_event(concurrent_state)?.is_some() { 952 bail!("cannot drop a subtask with an undelivered event"); 953 } 954 955 if delete { 956 waitable.delete_from(concurrent_state)?; 957 } 958 959 // Since waitables can neither be passed between instances nor forged, 960 // this should never fail unless there's a bug in Wasmtime, but we check 961 // here to be sure: 962 assert_eq!(expected_caller_instance, caller_instance); 963 log::trace!("subtask_drop {waitable:?} (handle {task_id})"); 964 Ok(()) 965 } 966 } 967 968 impl Instance { 969 /// Enable or disable concurrent state debugging mode for e.g. integration 970 /// tests. 971 /// 972 /// This will avoid re-using deleted handles, making it easier to catch 973 /// e.g. "use-after-delete" and "double-delete" errors. It can also make 974 /// reading trace output easier since it ensures handles are never 975 /// repurposed. 976 #[doc(hidden)] 977 pub fn enable_concurrent_state_debug(&self, mut store: impl AsContextMut, enable: bool) { 978 self.id() 979 .get_mut(store.as_context_mut().0) 980 .concurrent_state_mut() 981 .table 982 .enable_debug(enable); 983 // TODO: do the same for the tables holding guest-facing handles 984 } 985 986 /// Assert that all the relevant tables and queues in the concurrent state 987 /// for this instance are empty. 988 /// 989 /// This is for sanity checking in integration tests 990 /// (e.g. `component-async-tests`) that the relevant state has been cleared 991 /// after each test concludes. This should help us catch leaks, e.g. guest 992 /// tasks which haven't been deleted despite having completed and having 993 /// been dropped by their supertasks. 994 #[doc(hidden)] 995 pub fn assert_concurrent_state_empty(&self, mut store: impl AsContextMut) { 996 let mut instance = self.id().get_mut(store.as_context_mut().0); 997 assert!( 998 instance 999 .as_mut() 1000 .guest_tables() 1001 .0 1002 .iter() 1003 .all(|(_, table)| table.is_empty()) 1004 ); 1005 let state = instance.concurrent_state_mut(); 1006 assert!(state.table.is_empty(), "non-empty table: {:?}", state.table); 1007 assert!(state.high_priority.is_empty()); 1008 assert!(state.low_priority.is_empty()); 1009 assert!(state.guest_task.is_none()); 1010 assert!( 1011 state 1012 .futures 1013 .get_mut() 1014 .unwrap() 1015 .as_ref() 1016 .unwrap() 1017 .is_empty() 1018 ); 1019 assert!( 1020 state 1021 .instance_states 1022 .iter() 1023 .all(|(_, state)| state.pending.is_empty()) 1024 ); 1025 assert!(state.global_error_context_ref_counts.is_empty()); 1026 } 1027 1028 /// Run the specified closure `fun` to completion as part of this instance's 1029 /// event loop. 1030 /// 1031 /// Like [`Self::run`], this will run `fun` as part of this instance's event 1032 /// loop until it yields a result _or_ there are no more tasks to run. 1033 /// Unlike [`Self::run`], `fun` is provided an [`Accessor`], which provides 1034 /// controlled access to the `Store` and its data. 1035 /// 1036 /// This function can be used to invoke [`Func::call_concurrent`] for 1037 /// example within the async closure provided here. 1038 /// 1039 /// # Example 1040 /// 1041 /// ``` 1042 /// # use { 1043 /// # anyhow::{Result}, 1044 /// # wasmtime::{ 1045 /// # component::{ Component, Linker, Resource, ResourceTable}, 1046 /// # Config, Engine, Store 1047 /// # }, 1048 /// # }; 1049 /// # 1050 /// # struct MyResource(u32); 1051 /// # struct Ctx { table: ResourceTable } 1052 /// # 1053 /// # async fn foo() -> Result<()> { 1054 /// # let mut config = Config::new(); 1055 /// # let engine = Engine::new(&config)?; 1056 /// # let mut store = Store::new(&engine, Ctx { table: ResourceTable::new() }); 1057 /// # let mut linker = Linker::new(&engine); 1058 /// # let component = Component::new(&engine, "")?; 1059 /// # let instance = linker.instantiate_async(&mut store, &component).await?; 1060 /// # let foo = instance.get_typed_func::<(Resource<MyResource>,), (Resource<MyResource>,)>(&mut store, "foo")?; 1061 /// # let bar = instance.get_typed_func::<(u32,), ()>(&mut store, "bar")?; 1062 /// instance.run_concurrent(&mut store, async |accessor| -> wasmtime::Result<_> { 1063 /// let resource = accessor.with(|mut access| access.get().table.push(MyResource(42)))?; 1064 /// let (another_resource,) = foo.call_concurrent(accessor, (resource,)).await?; 1065 /// let value = accessor.with(|mut access| access.get().table.delete(another_resource))?; 1066 /// bar.call_concurrent(accessor, (value.0,)).await?; 1067 /// Ok(()) 1068 /// }).await??; 1069 /// # Ok(()) 1070 /// # } 1071 /// ``` 1072 pub async fn run_concurrent<T, R>( 1073 self, 1074 mut store: impl AsContextMut<Data = T>, 1075 fun: impl AsyncFnOnce(&Accessor<T>) -> R, 1076 ) -> Result<R> 1077 where 1078 T: 'static, 1079 { 1080 check_recursive_run(); 1081 let mut store = store.as_context_mut(); 1082 let token = StoreToken::new(store.as_context_mut()); 1083 1084 struct Dropper<'a, T: 'static, V> { 1085 store: StoreContextMut<'a, T>, 1086 value: ManuallyDrop<V>, 1087 } 1088 1089 impl<'a, T, V> Drop for Dropper<'a, T, V> { 1090 fn drop(&mut self) { 1091 tls::set(self.store.0.traitobj_mut(), || { 1092 // SAFETY: Here we drop the value without moving it for the 1093 // first and only time -- per the contract for `Drop::drop`, 1094 // this code won't run again, and the `value` field will no 1095 // longer be accessible. 1096 unsafe { ManuallyDrop::drop(&mut self.value) } 1097 }); 1098 } 1099 } 1100 1101 let accessor = &Accessor::new(token, Some(self)); 1102 let dropper = &mut Dropper { 1103 store, 1104 value: ManuallyDrop::new(fun(accessor)), 1105 }; 1106 // SAFETY: We never move `dropper` nor its `value` field. 1107 let future = unsafe { Pin::new_unchecked(dropper.value.deref_mut()) }; 1108 1109 self.poll_until(dropper.store.as_context_mut(), future) 1110 .await 1111 } 1112 1113 /// Spawn a background task to run as part of this instance's event loop. 1114 /// 1115 /// The task will receive an `&Accessor<U>` and run concurrently with 1116 /// any other tasks in progress for the instance. 1117 /// 1118 /// Note that the task will only make progress if and when the event loop 1119 /// for this instance is run. 1120 /// 1121 /// The returned [`SpawnHandle`] may be used to cancel the task. 1122 pub fn spawn<U: 'static>( 1123 self, 1124 mut store: impl AsContextMut<Data = U>, 1125 task: impl AccessorTask<U, HasSelf<U>, Result<()>>, 1126 ) -> JoinHandle { 1127 let mut store = store.as_context_mut(); 1128 let accessor = Accessor::new(StoreToken::new(store.as_context_mut()), Some(self)); 1129 self.spawn_with_accessor(store, accessor, task) 1130 } 1131 1132 /// Internal implementation of `spawn` functions where a `store` is 1133 /// available along with an `Accessor`. 1134 fn spawn_with_accessor<T, D>( 1135 self, 1136 mut store: StoreContextMut<T>, 1137 accessor: Accessor<T, D>, 1138 task: impl AccessorTask<T, D, Result<()>>, 1139 ) -> JoinHandle 1140 where 1141 T: 'static, 1142 D: HasData + ?Sized, 1143 { 1144 let store = store.as_context_mut(); 1145 1146 // Create an "abortable future" here where internally the future will 1147 // hook calls to poll and possibly spawn more background tasks on each 1148 // iteration. 1149 let (handle, future) = 1150 JoinHandle::run(async move { HostTaskOutput::Result(task.run(&accessor).await) }); 1151 self.concurrent_state_mut(store.0) 1152 .push_future(Box::pin(async move { 1153 future.await.unwrap_or(HostTaskOutput::Result(Ok(()))) 1154 })); 1155 1156 handle 1157 } 1158 1159 /// Run this instance's event loop. 1160 /// 1161 /// The returned future will resolve when either the specified future 1162 /// completes (in which case we return its result) or no further progress 1163 /// can be made (in which case we trap with `Trap::AsyncDeadlock`). 1164 async fn poll_until<T, R>( 1165 self, 1166 store: StoreContextMut<'_, T>, 1167 mut future: Pin<&mut impl Future<Output = R>>, 1168 ) -> Result<R> { 1169 loop { 1170 // Take `ConcurrentState::futures` out of the instance so we can 1171 // poll it while also safely giving any of the futures inside access 1172 // to `self`. 1173 let mut futures = self 1174 .concurrent_state_mut(store.0) 1175 .futures 1176 .get_mut() 1177 .unwrap() 1178 .take() 1179 .unwrap(); 1180 let mut next = pin!(futures.next()); 1181 1182 let result = future::poll_fn(|cx| { 1183 // First, poll the future we were passed as an argument and 1184 // return immediately if it's ready. 1185 if let Poll::Ready(value) = self.set_tls(store.0, || future.as_mut().poll(cx)) { 1186 return Poll::Ready(Ok(Either::Left(value))); 1187 } 1188 1189 // Next, poll `ConcurrentState::futures` (which includes any 1190 // pending host tasks and/or background tasks), returning 1191 // immediately if one of them fails. 1192 let next = match self.set_tls(store.0, || next.as_mut().poll(cx)) { 1193 Poll::Ready(Some(output)) => { 1194 match output { 1195 HostTaskOutput::Result(Err(e)) => return Poll::Ready(Err(e)), 1196 HostTaskOutput::Result(Ok(())) => {} 1197 HostTaskOutput::Function(fun) => { 1198 // Defer calling this function to a worker fiber 1199 // in case it involves calling a guest realloc 1200 // function as part of a lowering operation. 1201 // 1202 // TODO: This isn't necessary for _all_ 1203 // `HostOutput::Function`s, so we could optimize 1204 // by adding another variant to `HostOutput` to 1205 // distinguish which ones need it and which 1206 // don't. 1207 self.concurrent_state_mut(store.0) 1208 .push_high_priority(WorkItem::WorkerFunction(Mutex::new(fun))) 1209 } 1210 } 1211 Poll::Ready(true) 1212 } 1213 Poll::Ready(None) => Poll::Ready(false), 1214 Poll::Pending => Poll::Pending, 1215 }; 1216 1217 let mut instance = self.id().get_mut(store.0); 1218 1219 // Next, check the "high priority" work queue and return 1220 // immediately if it has at least one item. 1221 let state = instance.as_mut().concurrent_state_mut(); 1222 let ready = mem::take(&mut state.high_priority); 1223 let ready = if ready.is_empty() { 1224 // Next, check the "low priority" work queue and return 1225 // immediately if it has at least one item. 1226 let ready = mem::take(&mut state.low_priority); 1227 if ready.is_empty() { 1228 return match next { 1229 Poll::Ready(true) => { 1230 // In this case, one of the futures in 1231 // `ConcurrentState::futures` completed 1232 // successfully, so we return now and continue 1233 // the outer loop in case there is another one 1234 // ready to complete. 1235 Poll::Ready(Ok(Either::Right(Vec::new()))) 1236 } 1237 Poll::Ready(false) => { 1238 // Poll the future we were passed one last time 1239 // in case one of `ConcurrentState::futures` had 1240 // the side effect of unblocking it. 1241 if let Poll::Ready(value) = 1242 self.set_tls(store.0, || future.as_mut().poll(cx)) 1243 { 1244 Poll::Ready(Ok(Either::Left(value))) 1245 } else { 1246 // In this case, there are no more pending 1247 // futures in `ConcurrentState::futures`, 1248 // there are no remaining work items, _and_ 1249 // the future we were passed as an argument 1250 // still hasn't completed, meaning we're 1251 // stuck, so we return an error. The 1252 // underlying assumption is that `future` 1253 // depends on this component instance making 1254 // such progress, and thus there's no point 1255 // in continuing to poll it given we've run 1256 // out of work to do. 1257 // 1258 // Note that we'd also reach this point if 1259 // the host embedder passed e.g. a 1260 // `std::future::Pending` to 1261 // `Instance::run_concurrent`, in which case 1262 // we'd return a "deadlock" error even when 1263 // any and all tasks have completed 1264 // normally. However, that's not how 1265 // `Instance::run_concurrent` is intended 1266 // (and documented) to be used, so it seems 1267 // reasonable to lump that case in with 1268 // "real" deadlocks. 1269 // 1270 // TODO: Once we've added host APIs for 1271 // cancelling in-progress tasks, we can 1272 // return some other, non-error value here, 1273 // treating it as "normal" and giving the 1274 // host embedder a chance to intervene by 1275 // cancelling one or more tasks and/or 1276 // starting new tasks capable of waking the 1277 // existing ones. 1278 Poll::Ready(Err(anyhow!(crate::Trap::AsyncDeadlock))) 1279 } 1280 } 1281 // There is at least one pending future in 1282 // `ConcurrentState::futures` and we have nothing 1283 // else to do but wait for now, so we return 1284 // `Pending`. 1285 Poll::Pending => Poll::Pending, 1286 }; 1287 } else { 1288 ready 1289 } 1290 } else { 1291 ready 1292 }; 1293 1294 Poll::Ready(Ok(Either::Right(ready))) 1295 }) 1296 .await; 1297 1298 // Put the `ConcurrentState::futures` back into the instance before 1299 // we return or handle any work items since one or more of those 1300 // items might append more futures. 1301 *self 1302 .concurrent_state_mut(store.0) 1303 .futures 1304 .get_mut() 1305 .unwrap() = Some(futures); 1306 1307 match result? { 1308 // The future we were passed as an argument completed, so we 1309 // return the result. 1310 Either::Left(value) => break Ok(value), 1311 // The future we were passed has not yet completed, so handle 1312 // any work items and then loop again. 1313 Either::Right(ready) => { 1314 for item in ready { 1315 self.handle_work_item(store.0.traitobj_mut(), item).await?; 1316 } 1317 } 1318 } 1319 } 1320 } 1321 1322 /// Handle the specified work item, possibly resuming a fiber if applicable. 1323 async fn handle_work_item(self, store: &mut StoreOpaque, item: WorkItem) -> Result<()> { 1324 log::trace!("handle work item {item:?}"); 1325 match item { 1326 WorkItem::PushFuture(future) => { 1327 self.concurrent_state_mut(store) 1328 .futures 1329 .get_mut() 1330 .unwrap() 1331 .as_mut() 1332 .unwrap() 1333 .push(future.into_inner().unwrap()); 1334 } 1335 WorkItem::ResumeFiber(fiber) => { 1336 self.resume_fiber(store, fiber).await?; 1337 } 1338 WorkItem::GuestCall(call) => { 1339 let state = self.concurrent_state_mut(store); 1340 if call.is_ready(state)? { 1341 self.run_on_worker(store, WorkerItem::GuestCall(call)) 1342 .await?; 1343 } else { 1344 let task = state.get_mut(call.task)?; 1345 if !task.starting_sent { 1346 task.starting_sent = true; 1347 if let GuestCallKind::Start(_) = &call.kind { 1348 Waitable::Guest(call.task).set_event( 1349 state, 1350 Some(Event::Subtask { 1351 status: Status::Starting, 1352 }), 1353 )?; 1354 } 1355 } 1356 1357 let runtime_instance = state.get(call.task)?.instance; 1358 state 1359 .instance_state(runtime_instance) 1360 .pending 1361 .insert(call.task, call.kind); 1362 } 1363 } 1364 WorkItem::Poll(params) => { 1365 let state = self.concurrent_state_mut(store); 1366 if state.get_mut(params.task)?.event.is_some() 1367 || !state.get_mut(params.set)?.ready.is_empty() 1368 { 1369 // There's at least one event immediately available; deliver 1370 // it to the guest ASAP. 1371 state.push_high_priority(WorkItem::GuestCall(GuestCall { 1372 task: params.task, 1373 kind: GuestCallKind::DeliverEvent { 1374 set: Some(params.set), 1375 }, 1376 })); 1377 } else { 1378 // There are no events immediately available; deliver 1379 // `Event::None` to the guest. 1380 state.get_mut(params.task)?.event = Some(Event::None); 1381 state.push_high_priority(WorkItem::GuestCall(GuestCall { 1382 task: params.task, 1383 kind: GuestCallKind::DeliverEvent { 1384 set: Some(params.set), 1385 }, 1386 })); 1387 } 1388 } 1389 WorkItem::WorkerFunction(fun) => { 1390 self.run_on_worker(store, WorkerItem::Function(fun)).await?; 1391 } 1392 } 1393 1394 Ok(()) 1395 } 1396 1397 /// Resume the specified fiber, giving it exclusive access to the specified 1398 /// store. 1399 async fn resume_fiber(self, store: &mut StoreOpaque, fiber: StoreFiber<'static>) -> Result<()> { 1400 let old_task = self.concurrent_state_mut(store).guest_task; 1401 log::trace!("resume_fiber: save current task {old_task:?}"); 1402 1403 let fiber = fiber::resolve_or_release(store, fiber).await?; 1404 1405 let state = self.concurrent_state_mut(store); 1406 1407 state.guest_task = old_task; 1408 log::trace!("resume_fiber: restore current task {old_task:?}"); 1409 1410 if let Some(mut fiber) = fiber { 1411 // See the `SuspendReason` documentation for what each case means. 1412 match state.suspend_reason.take().unwrap() { 1413 SuspendReason::NeedWork => { 1414 if state.worker.is_none() { 1415 state.worker = Some(fiber); 1416 } else { 1417 fiber.dispose(store); 1418 } 1419 } 1420 SuspendReason::Yielding { .. } => { 1421 state.push_low_priority(WorkItem::ResumeFiber(fiber)); 1422 } 1423 SuspendReason::Waiting { set, task } => { 1424 let old = state 1425 .get_mut(set)? 1426 .waiting 1427 .insert(task, WaitMode::Fiber(fiber)); 1428 assert!(old.is_none()); 1429 } 1430 } 1431 } 1432 1433 Ok(()) 1434 } 1435 1436 /// Execute the specified guest call on a worker fiber. 1437 async fn run_on_worker(self, store: &mut StoreOpaque, item: WorkerItem) -> Result<()> { 1438 let worker = if let Some(fiber) = self.concurrent_state_mut(store).worker.take() { 1439 fiber 1440 } else { 1441 fiber::make_fiber(store.traitobj_mut(), move |store| { 1442 loop { 1443 match self.concurrent_state_mut(store).worker_item.take().unwrap() { 1444 WorkerItem::GuestCall(call) => self.handle_guest_call(store, call)?, 1445 WorkerItem::Function(fun) => fun.into_inner().unwrap()(store, self)?, 1446 } 1447 1448 self.suspend(store, SuspendReason::NeedWork)?; 1449 } 1450 })? 1451 }; 1452 1453 let worker_item = &mut self.concurrent_state_mut(store).worker_item; 1454 assert!(worker_item.is_none()); 1455 *worker_item = Some(item); 1456 1457 self.resume_fiber(store, worker).await 1458 } 1459 1460 /// Execute the specified guest call. 1461 fn handle_guest_call(self, store: &mut dyn VMStore, call: GuestCall) -> Result<()> { 1462 match call.kind { 1463 GuestCallKind::DeliverEvent { set } => { 1464 let (event, waitable) = 1465 self.id().get_mut(store).get_event(call.task, set)?.unwrap(); 1466 let state = self.concurrent_state_mut(store); 1467 let task = state.get_mut(call.task)?; 1468 let runtime_instance = task.instance; 1469 let handle = waitable.map(|(_, v)| v).unwrap_or(0); 1470 1471 log::trace!( 1472 "use callback to deliver event {event:?} to {:?} for {waitable:?}", 1473 call.task, 1474 ); 1475 1476 let old_task = state.guest_task.replace(call.task); 1477 log::trace!( 1478 "GuestCallKind::DeliverEvent: replaced {old_task:?} with {:?} as current task", 1479 call.task 1480 ); 1481 1482 self.maybe_push_call_context(store.store_opaque_mut(), call.task)?; 1483 1484 let state = self.concurrent_state_mut(store); 1485 state.enter_instance(runtime_instance); 1486 1487 let callback = state.get_mut(call.task)?.callback.take().unwrap(); 1488 1489 let code = callback(store, self, runtime_instance, event, handle)?; 1490 1491 let state = self.concurrent_state_mut(store); 1492 1493 state.get_mut(call.task)?.callback = Some(callback); 1494 1495 state.exit_instance(runtime_instance)?; 1496 1497 self.maybe_pop_call_context(store.store_opaque_mut(), call.task)?; 1498 1499 self.id().get_mut(store).handle_callback_code( 1500 call.task, 1501 runtime_instance, 1502 code, 1503 false, 1504 )?; 1505 1506 self.concurrent_state_mut(store).guest_task = old_task; 1507 log::trace!("GuestCallKind::DeliverEvent: restored {old_task:?} as current task"); 1508 } 1509 GuestCallKind::Start(fun) => { 1510 fun(store, self)?; 1511 } 1512 } 1513 1514 Ok(()) 1515 } 1516 1517 /// Suspend the current fiber, storing the reason in 1518 /// `ConcurrentState::suspend_reason` to indicate the conditions under which 1519 /// it should be resumed. 1520 /// 1521 /// See the `SuspendReason` documentation for details. 1522 fn suspend(self, store: &mut dyn VMStore, reason: SuspendReason) -> Result<()> { 1523 log::trace!("suspend fiber: {reason:?}"); 1524 1525 // If we're yielding or waiting on behalf of a guest task, we'll need to 1526 // pop the call context which manages resource borrows before suspending 1527 // and then push it again once we've resumed. 1528 let task = match &reason { 1529 SuspendReason::Yielding { task } | SuspendReason::Waiting { task, .. } => Some(*task), 1530 SuspendReason::NeedWork => None, 1531 }; 1532 1533 let old_guest_task = if let Some(task) = task { 1534 self.maybe_pop_call_context(store.store_opaque_mut(), task)?; 1535 self.concurrent_state_mut(store).guest_task 1536 } else { 1537 None 1538 }; 1539 1540 let suspend_reason = &mut self.concurrent_state_mut(store).suspend_reason; 1541 assert!(suspend_reason.is_none()); 1542 *suspend_reason = Some(reason); 1543 1544 store.with_blocking(|_, cx| cx.suspend(StoreFiberYield::ReleaseStore))?; 1545 1546 if let Some(task) = task { 1547 self.concurrent_state_mut(store).guest_task = old_guest_task; 1548 self.maybe_push_call_context(store.store_opaque_mut(), task)?; 1549 } 1550 1551 Ok(()) 1552 } 1553 1554 /// Push the call context for managing resource borrows for the specified 1555 /// guest task if it has not yet either returned a result or cancelled 1556 /// itself. 1557 fn maybe_push_call_context( 1558 self, 1559 store: &mut StoreOpaque, 1560 guest_task: TableId<GuestTask>, 1561 ) -> Result<()> { 1562 let task = self.concurrent_state_mut(store).get_mut(guest_task)?; 1563 if task.lift_result.is_some() { 1564 log::trace!("push call context for {guest_task:?}"); 1565 let call_context = task.call_context.take().unwrap(); 1566 store.component_resource_state().0.push(call_context); 1567 } 1568 Ok(()) 1569 } 1570 1571 /// Pop the call context for managing resource borrows for the specified 1572 /// guest task if it has not yet either returned a result or cancelled 1573 /// itself. 1574 fn maybe_pop_call_context( 1575 self, 1576 store: &mut StoreOpaque, 1577 guest_task: TableId<GuestTask>, 1578 ) -> Result<()> { 1579 if self 1580 .concurrent_state_mut(store) 1581 .get(guest_task)? 1582 .lift_result 1583 .is_some() 1584 { 1585 log::trace!("pop call context for {guest_task:?}"); 1586 let call_context = Some(store.component_resource_state().0.pop().unwrap()); 1587 self.concurrent_state_mut(store) 1588 .get_mut(guest_task)? 1589 .call_context = call_context; 1590 } 1591 Ok(()) 1592 } 1593 1594 /// Add the specified guest call to the "high priority" work item queue, to 1595 /// be started as soon as backpressure and/or reentrance rules allow. 1596 /// 1597 /// SAFETY: The raw pointer arguments must be valid references to guest 1598 /// functions (with the appropriate signatures) when the closures queued by 1599 /// this function are called. 1600 unsafe fn queue_call<T: 'static>( 1601 self, 1602 mut store: StoreContextMut<T>, 1603 guest_task: TableId<GuestTask>, 1604 callee: SendSyncPtr<VMFuncRef>, 1605 param_count: usize, 1606 result_count: usize, 1607 flags: Option<InstanceFlags>, 1608 async_: bool, 1609 callback: Option<SendSyncPtr<VMFuncRef>>, 1610 post_return: Option<SendSyncPtr<VMFuncRef>>, 1611 ) -> Result<()> { 1612 /// Return a closure which will call the specified function in the scope 1613 /// of the specified task. 1614 /// 1615 /// This will use `GuestTask::lower_params` to lower the parameters, but 1616 /// will not lift the result; instead, it returns a 1617 /// `[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]` from which the result, if 1618 /// any, may be lifted. Note that an async-lifted export will have 1619 /// returned its result using the `task.return` intrinsic (or not 1620 /// returned a result at all, in the case of `task.cancel`), in which 1621 /// case the "result" of this call will either be a callback code or 1622 /// nothing. 1623 /// 1624 /// SAFETY: `callee` must be a valid `*mut VMFuncRef` at the time when 1625 /// the returned closure is called. 1626 unsafe fn make_call<T: 'static>( 1627 store: StoreContextMut<T>, 1628 guest_task: TableId<GuestTask>, 1629 callee: SendSyncPtr<VMFuncRef>, 1630 param_count: usize, 1631 result_count: usize, 1632 flags: Option<InstanceFlags>, 1633 ) -> impl FnOnce( 1634 &mut dyn VMStore, 1635 Instance, 1636 ) -> Result<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]> 1637 + Send 1638 + Sync 1639 + 'static 1640 + use<T> { 1641 let token = StoreToken::new(store); 1642 move |store: &mut dyn VMStore, instance: Instance| { 1643 let mut storage = [MaybeUninit::uninit(); MAX_FLAT_PARAMS]; 1644 let task = instance.concurrent_state_mut(store).get_mut(guest_task)?; 1645 let may_enter_after_call = task.call_post_return_automatically(); 1646 let lower = task.lower_params.take().unwrap(); 1647 1648 lower(store, instance, &mut storage[..param_count])?; 1649 1650 let mut store = token.as_context_mut(store); 1651 1652 // SAFETY: Per the contract documented in `make_call's` 1653 // documentation, `callee` must be a valid pointer. 1654 unsafe { 1655 if let Some(mut flags) = flags { 1656 flags.set_may_enter(false); 1657 } 1658 crate::Func::call_unchecked_raw( 1659 &mut store, 1660 callee.as_non_null(), 1661 NonNull::new( 1662 &mut storage[..param_count.max(result_count)] 1663 as *mut [MaybeUninit<ValRaw>] as _, 1664 ) 1665 .unwrap(), 1666 )?; 1667 if let Some(mut flags) = flags { 1668 flags.set_may_enter(may_enter_after_call); 1669 } 1670 } 1671 1672 Ok(storage) 1673 } 1674 } 1675 1676 // SAFETY: Per the contract described in this function documentation, 1677 // the `callee` pointer which `call` closes over must be valid when 1678 // called by the closure we queue below. 1679 let call = unsafe { 1680 make_call( 1681 store.as_context_mut(), 1682 guest_task, 1683 callee, 1684 param_count, 1685 result_count, 1686 flags, 1687 ) 1688 }; 1689 1690 let callee_instance = self.concurrent_state_mut(store.0).get(guest_task)?.instance; 1691 let fun = if callback.is_some() { 1692 assert!(async_); 1693 1694 Box::new(move |store: &mut dyn VMStore, instance: Instance| { 1695 let old_task = instance 1696 .concurrent_state_mut(store) 1697 .guest_task 1698 .replace(guest_task); 1699 log::trace!( 1700 "stackless call: replaced {old_task:?} with {guest_task:?} as current task" 1701 ); 1702 1703 instance.maybe_push_call_context(store.store_opaque_mut(), guest_task)?; 1704 1705 instance 1706 .concurrent_state_mut(store) 1707 .enter_instance(callee_instance); 1708 1709 // SAFETY: See the documentation for `make_call` to review the 1710 // contract we must uphold for `call` here. 1711 // 1712 // Per the contract described in the `queue_call` 1713 // documentation, the `callee` pointer which `call` closes 1714 // over must be valid. 1715 let storage = call(store, instance)?; 1716 1717 instance 1718 .concurrent_state_mut(store) 1719 .exit_instance(callee_instance)?; 1720 1721 instance.maybe_pop_call_context(store.store_opaque_mut(), guest_task)?; 1722 1723 let state = instance.concurrent_state_mut(store); 1724 state.guest_task = old_task; 1725 log::trace!("stackless call: restored {old_task:?} as current task"); 1726 1727 // SAFETY: `wasmparser` will have validated that the callback 1728 // function returns a `i32` result. 1729 let code = unsafe { storage[0].assume_init() }.get_i32() as u32; 1730 1731 instance.id().get_mut(store).handle_callback_code( 1732 guest_task, 1733 callee_instance, 1734 code, 1735 true, 1736 )?; 1737 1738 Ok(()) 1739 }) 1740 as Box<dyn FnOnce(&mut dyn VMStore, Instance) -> Result<()> + Send + Sync> 1741 } else { 1742 let token = StoreToken::new(store.as_context_mut()); 1743 Box::new(move |store: &mut dyn VMStore, instance: Instance| { 1744 let old_task = instance 1745 .concurrent_state_mut(store) 1746 .guest_task 1747 .replace(guest_task); 1748 log::trace!( 1749 "stackful call: replaced {old_task:?} with {guest_task:?} as current task", 1750 ); 1751 1752 let mut flags = instance.id().get(store).instance_flags(callee_instance); 1753 1754 instance.maybe_push_call_context(store.store_opaque_mut(), guest_task)?; 1755 1756 // Unless this is a callback-less (i.e. stackful) 1757 // async-lifted export, we need to record that the instance 1758 // cannot be entered until the call returns. 1759 if !async_ { 1760 instance 1761 .concurrent_state_mut(store) 1762 .enter_instance(callee_instance); 1763 } 1764 1765 // SAFETY: See the documentation for `make_call` to review the 1766 // contract we must uphold for `call` here. 1767 // 1768 // Per the contract described in the `queue_call` 1769 // documentation, the `callee` pointer which `call` closes 1770 // over must be valid. 1771 let storage = call(store, instance)?; 1772 1773 if async_ { 1774 // This is a callback-less (i.e. stackful) async-lifted 1775 // export, so there is no post-return function, and 1776 // either `task.return` or `task.cancel` should have 1777 // been called. 1778 if instance 1779 .concurrent_state_mut(store) 1780 .get(guest_task)? 1781 .lift_result 1782 .is_some() 1783 { 1784 return Err(anyhow!(crate::Trap::NoAsyncResult)); 1785 } 1786 } else { 1787 // This is a sync-lifted export, so now is when we lift the 1788 // result, optionally call the post-return function, if any, 1789 // and finally notify any current or future waiters that the 1790 // subtask has returned. 1791 1792 let lift = { 1793 let state = instance.concurrent_state_mut(store); 1794 state.exit_instance(callee_instance)?; 1795 1796 assert!(state.get(guest_task)?.result.is_none()); 1797 1798 state.get_mut(guest_task)?.lift_result.take().unwrap() 1799 }; 1800 1801 // SAFETY: `result_count` represents the number of core Wasm 1802 // results returned, per `wasmparser`. 1803 let result = (lift.lift)(store, instance, unsafe { 1804 mem::transmute::<&[MaybeUninit<ValRaw>], &[ValRaw]>( 1805 &storage[..result_count], 1806 ) 1807 })?; 1808 1809 let post_return_arg = match result_count { 1810 0 => ValRaw::i32(0), 1811 // SAFETY: `result_count` represents the number of 1812 // core Wasm results returned, per `wasmparser`. 1813 1 => unsafe { storage[0].assume_init() }, 1814 _ => unreachable!(), 1815 }; 1816 1817 if instance 1818 .concurrent_state_mut(store) 1819 .get(guest_task)? 1820 .call_post_return_automatically() 1821 { 1822 unsafe { flags.set_needs_post_return(false) } 1823 1824 if let Some(func) = post_return { 1825 let mut store = token.as_context_mut(store); 1826 1827 // SAFETY: `func` is a valid `*mut VMFuncRef` from 1828 // either `wasmtime-cranelift`-generated fused adapter 1829 // code or `component::Options`. Per `wasmparser` 1830 // post-return signature validation, we know it takes a 1831 // single parameter. 1832 unsafe { 1833 crate::Func::call_unchecked_raw( 1834 &mut store, 1835 func.as_non_null(), 1836 slice::from_ref(&post_return_arg).into(), 1837 )?; 1838 } 1839 } 1840 1841 unsafe { flags.set_may_enter(true) } 1842 } 1843 1844 instance.task_complete( 1845 store, 1846 guest_task, 1847 result, 1848 Status::Returned, 1849 post_return_arg, 1850 )?; 1851 } 1852 1853 instance.maybe_pop_call_context(store.store_opaque_mut(), guest_task)?; 1854 1855 let task = instance.concurrent_state_mut(store).get_mut(guest_task)?; 1856 1857 match &task.caller { 1858 Caller::Host { 1859 remove_task_automatically, 1860 .. 1861 } => { 1862 if *remove_task_automatically { 1863 Waitable::Guest(guest_task) 1864 .delete_from(instance.concurrent_state_mut(store))?; 1865 } 1866 } 1867 Caller::Guest { .. } => { 1868 task.exited = true; 1869 } 1870 } 1871 1872 Ok(()) 1873 }) 1874 }; 1875 1876 self.concurrent_state_mut(store.0) 1877 .push_high_priority(WorkItem::GuestCall(GuestCall { 1878 task: guest_task, 1879 kind: GuestCallKind::Start(fun), 1880 })); 1881 1882 Ok(()) 1883 } 1884 1885 /// Prepare (but do not start) a guest->guest call. 1886 /// 1887 /// This is called from fused adapter code generated in 1888 /// `wasmtime_environ::fact::trampoline::Compiler`. `start` and `return_` 1889 /// are synthesized Wasm functions which move the parameters from the caller 1890 /// to the callee and the result from the callee to the caller, 1891 /// respectively. The adapter will call `Self::start_call` immediately 1892 /// after calling this function. 1893 /// 1894 /// SAFETY: All the pointer arguments must be valid pointers to guest 1895 /// entities (and with the expected signatures for the function references 1896 /// -- see `wasmtime_environ::fact::trampoline::Compiler` for details). 1897 unsafe fn prepare_call<T: 'static>( 1898 self, 1899 mut store: StoreContextMut<T>, 1900 start: *mut VMFuncRef, 1901 return_: *mut VMFuncRef, 1902 caller_instance: RuntimeComponentInstanceIndex, 1903 callee_instance: RuntimeComponentInstanceIndex, 1904 task_return_type: TypeTupleIndex, 1905 memory: *mut VMMemoryDefinition, 1906 string_encoding: u8, 1907 caller_info: CallerInfo, 1908 ) -> Result<()> { 1909 enum ResultInfo { 1910 Heap { results: u32 }, 1911 Stack { result_count: u32 }, 1912 } 1913 1914 let result_info = match &caller_info { 1915 CallerInfo::Async { 1916 has_result: true, 1917 params, 1918 } => ResultInfo::Heap { 1919 results: params.last().unwrap().get_u32(), 1920 }, 1921 CallerInfo::Async { 1922 has_result: false, .. 1923 } => ResultInfo::Stack { result_count: 0 }, 1924 CallerInfo::Sync { 1925 result_count, 1926 params, 1927 } if *result_count > u32::try_from(MAX_FLAT_RESULTS).unwrap() => ResultInfo::Heap { 1928 results: params.last().unwrap().get_u32(), 1929 }, 1930 CallerInfo::Sync { result_count, .. } => ResultInfo::Stack { 1931 result_count: *result_count, 1932 }, 1933 }; 1934 1935 let sync_caller = matches!(caller_info, CallerInfo::Sync { .. }); 1936 1937 // Create a new guest task for the call, closing over the `start` and 1938 // `return_` functions to lift the parameters and lower the result, 1939 // respectively. 1940 let start = SendSyncPtr::new(NonNull::new(start).unwrap()); 1941 let return_ = SendSyncPtr::new(NonNull::new(return_).unwrap()); 1942 let token = StoreToken::new(store.as_context_mut()); 1943 let state = self.concurrent_state_mut(store.0); 1944 let old_task = state.guest_task.take(); 1945 let new_task = GuestTask::new( 1946 state, 1947 Box::new(move |store, instance, dst| { 1948 let mut store = token.as_context_mut(store); 1949 assert!(dst.len() <= MAX_FLAT_PARAMS); 1950 let mut src = [MaybeUninit::uninit(); MAX_FLAT_PARAMS]; 1951 let count = match caller_info { 1952 // Async callers, if they have a result, use the last 1953 // parameter as a return pointer so chop that off if 1954 // relevant here. 1955 CallerInfo::Async { params, has_result } => { 1956 let params = ¶ms[..params.len() - usize::from(has_result)]; 1957 for (param, src) in params.iter().zip(&mut src) { 1958 src.write(*param); 1959 } 1960 params.len() 1961 } 1962 1963 // Sync callers forward everything directly. 1964 CallerInfo::Sync { params, .. } => { 1965 for (param, src) in params.iter().zip(&mut src) { 1966 src.write(*param); 1967 } 1968 params.len() 1969 } 1970 }; 1971 // SAFETY: `start` is a valid `*mut VMFuncRef` from 1972 // `wasmtime-cranelift`-generated fused adapter code. Based on 1973 // how it was constructed (see 1974 // `wasmtime_environ::fact::trampoline::Compiler::compile_async_start_adapter` 1975 // for details) we know it takes count parameters and returns 1976 // `dst.len()` results. 1977 unsafe { 1978 crate::Func::call_unchecked_raw( 1979 &mut store, 1980 start.as_non_null(), 1981 NonNull::new( 1982 &mut src[..count.max(dst.len())] as *mut [MaybeUninit<ValRaw>] as _, 1983 ) 1984 .unwrap(), 1985 )?; 1986 } 1987 dst.copy_from_slice(&src[..dst.len()]); 1988 let state = instance.concurrent_state_mut(store.0); 1989 let task = state.guest_task.unwrap(); 1990 Waitable::Guest(task).set_event( 1991 state, 1992 Some(Event::Subtask { 1993 status: Status::Started, 1994 }), 1995 )?; 1996 Ok(()) 1997 }), 1998 LiftResult { 1999 lift: Box::new(move |store, instance, src| { 2000 // SAFETY: See comment in closure passed as `lower_params` 2001 // parameter above. 2002 let mut store = token.as_context_mut(store); 2003 let mut my_src = src.to_owned(); // TODO: use stack to avoid allocation? 2004 if let ResultInfo::Heap { results } = &result_info { 2005 my_src.push(ValRaw::u32(*results)); 2006 } 2007 // SAFETY: `return_` is a valid `*mut VMFuncRef` from 2008 // `wasmtime-cranelift`-generated fused adapter code. Based 2009 // on how it was constructed (see 2010 // `wasmtime_environ::fact::trampoline::Compiler::compile_async_return_adapter` 2011 // for details) we know it takes `src.len()` parameters and 2012 // returns up to 1 result. 2013 unsafe { 2014 crate::Func::call_unchecked_raw( 2015 &mut store, 2016 return_.as_non_null(), 2017 my_src.as_mut_slice().into(), 2018 )?; 2019 } 2020 let state = instance.concurrent_state_mut(store.0); 2021 let task = state.guest_task.unwrap(); 2022 if sync_caller { 2023 state.get_mut(task)?.sync_result = 2024 Some(if let ResultInfo::Stack { result_count } = &result_info { 2025 match result_count { 2026 0 => None, 2027 1 => Some(my_src[0]), 2028 _ => unreachable!(), 2029 } 2030 } else { 2031 None 2032 }); 2033 } 2034 Ok(Box::new(DummyResult) as Box<dyn Any + Send + Sync>) 2035 }), 2036 ty: task_return_type, 2037 memory: NonNull::new(memory).map(SendSyncPtr::new), 2038 string_encoding: StringEncoding::from_u8(string_encoding).unwrap(), 2039 }, 2040 Caller::Guest { 2041 task: old_task.unwrap(), 2042 instance: caller_instance, 2043 }, 2044 None, 2045 callee_instance, 2046 )?; 2047 2048 let guest_task = state.push(new_task)?; 2049 2050 if let Some(old_task) = old_task { 2051 if !state.may_enter(guest_task) { 2052 bail!(crate::Trap::CannotEnterComponent); 2053 } 2054 2055 state.get_mut(old_task)?.subtasks.insert(guest_task); 2056 }; 2057 2058 // Make the new task the current one so that `Self::start_call` knows 2059 // which one to start. 2060 state.guest_task = Some(guest_task); 2061 log::trace!("pushed {guest_task:?} as current task; old task was {old_task:?}"); 2062 2063 Ok(()) 2064 } 2065 2066 /// Call the specified callback function for an async-lifted export. 2067 /// 2068 /// SAFETY: `function` must be a valid reference to a guest function of the 2069 /// correct signature for a callback. 2070 unsafe fn call_callback<T>( 2071 self, 2072 mut store: StoreContextMut<T>, 2073 callee_instance: RuntimeComponentInstanceIndex, 2074 function: SendSyncPtr<VMFuncRef>, 2075 event: Event, 2076 handle: u32, 2077 may_enter_after_call: bool, 2078 ) -> Result<u32> { 2079 let mut flags = self.id().get(store.0).instance_flags(callee_instance); 2080 2081 let (ordinal, result) = event.parts(); 2082 let params = &mut [ 2083 ValRaw::u32(ordinal), 2084 ValRaw::u32(handle), 2085 ValRaw::u32(result), 2086 ]; 2087 // SAFETY: `func` is a valid `*mut VMFuncRef` from either 2088 // `wasmtime-cranelift`-generated fused adapter code or 2089 // `component::Options`. Per `wasmparser` callback signature 2090 // validation, we know it takes three parameters and returns one. 2091 unsafe { 2092 flags.set_may_enter(false); 2093 crate::Func::call_unchecked_raw( 2094 &mut store, 2095 function.as_non_null(), 2096 params.as_mut_slice().into(), 2097 )?; 2098 flags.set_may_enter(may_enter_after_call); 2099 } 2100 Ok(params[0].get_u32()) 2101 } 2102 2103 /// Start a guest->guest call previously prepared using 2104 /// `Self::prepare_call`. 2105 /// 2106 /// This is called from fused adapter code generated in 2107 /// `wasmtime_environ::fact::trampoline::Compiler`. The adapter will call 2108 /// this function immediately after calling `Self::prepare_call`. 2109 /// 2110 /// SAFETY: The `*mut VMFuncRef` arguments must be valid pointers to guest 2111 /// functions with the appropriate signatures for the current guest task. 2112 /// If this is a call to an async-lowered import, the actual call may be 2113 /// deferred and run after this function returns, in which case the pointer 2114 /// arguments must also be valid when the call happens. 2115 unsafe fn start_call<T: 'static>( 2116 self, 2117 mut store: StoreContextMut<T>, 2118 callback: *mut VMFuncRef, 2119 post_return: *mut VMFuncRef, 2120 callee: *mut VMFuncRef, 2121 param_count: u32, 2122 result_count: u32, 2123 flags: u32, 2124 storage: Option<&mut [MaybeUninit<ValRaw>]>, 2125 ) -> Result<u32> { 2126 let token = StoreToken::new(store.as_context_mut()); 2127 let async_caller = storage.is_none(); 2128 let state = self.concurrent_state_mut(store.0); 2129 let guest_task = state.guest_task.unwrap(); 2130 let may_enter_after_call = state.get(guest_task)?.call_post_return_automatically(); 2131 let callee = SendSyncPtr::new(NonNull::new(callee).unwrap()); 2132 let param_count = usize::try_from(param_count).unwrap(); 2133 assert!(param_count <= MAX_FLAT_PARAMS); 2134 let result_count = usize::try_from(result_count).unwrap(); 2135 assert!(result_count <= MAX_FLAT_RESULTS); 2136 2137 let task = state.get_mut(guest_task)?; 2138 if !callback.is_null() { 2139 // We're calling an async-lifted export with a callback, so store 2140 // the callback and related context as part of the task so we can 2141 // call it later when needed. 2142 let callback = SendSyncPtr::new(NonNull::new(callback).unwrap()); 2143 task.callback = Some(Box::new( 2144 move |store, instance, runtime_instance, event, handle| { 2145 let store = token.as_context_mut(store); 2146 unsafe { 2147 instance.call_callback::<T>( 2148 store, 2149 runtime_instance, 2150 callback, 2151 event, 2152 handle, 2153 may_enter_after_call, 2154 ) 2155 } 2156 }, 2157 )); 2158 } 2159 2160 let Caller::Guest { 2161 task: caller, 2162 instance: runtime_instance, 2163 } = &task.caller 2164 else { 2165 // As of this writing, `start_call` is only used for guest->guest 2166 // calls. 2167 unreachable!() 2168 }; 2169 let caller = *caller; 2170 let caller_instance = *runtime_instance; 2171 2172 let callee_instance = task.instance; 2173 2174 let instance_flags = if callback.is_null() { 2175 None 2176 } else { 2177 Some(self.id().get(store.0).instance_flags(callee_instance)) 2178 }; 2179 2180 // Queue the call as a "high priority" work item. 2181 unsafe { 2182 self.queue_call( 2183 store.as_context_mut(), 2184 guest_task, 2185 callee, 2186 param_count, 2187 result_count, 2188 instance_flags, 2189 (flags & START_FLAG_ASYNC_CALLEE) != 0, 2190 NonNull::new(callback).map(SendSyncPtr::new), 2191 NonNull::new(post_return).map(SendSyncPtr::new), 2192 )?; 2193 } 2194 2195 let state = self.concurrent_state_mut(store.0); 2196 2197 // Use the caller's `GuestTask::sync_call_set` to register interest in 2198 // the subtask... 2199 let guest_waitable = Waitable::Guest(guest_task); 2200 let old_set = guest_waitable.common(state)?.set; 2201 let set = state.get_mut(caller)?.sync_call_set; 2202 guest_waitable.join(state, Some(set))?; 2203 2204 // ... and suspend this fiber temporarily while we wait for it to start. 2205 // 2206 // Note that we _could_ call the callee directly using the current fiber 2207 // rather than suspend this one, but that would make reasoning about the 2208 // event loop more complicated and is probably only worth doing if 2209 // there's a measurable performance benefit. In addition, it would mean 2210 // blocking the caller if the callee calls a blocking sync-lowered 2211 // import, and as of this writing the spec says we must not do that. 2212 // 2213 // Alternatively, the fused adapter code could be modified to call the 2214 // callee directly without calling a host-provided intrinsic at all (in 2215 // which case it would need to do its own, inline backpressure checks, 2216 // etc.). Again, we'd want to see a measurable performance benefit 2217 // before committing to such an optimization. And again, we'd need to 2218 // update the spec to allow that. 2219 let (status, waitable) = loop { 2220 self.suspend( 2221 store.0.traitobj_mut(), 2222 SuspendReason::Waiting { set, task: caller }, 2223 )?; 2224 2225 let state = self.concurrent_state_mut(store.0); 2226 2227 let event = guest_waitable.take_event(state)?; 2228 let Some(Event::Subtask { status }) = event else { 2229 unreachable!(); 2230 }; 2231 2232 log::trace!("status {status:?} for {guest_task:?}"); 2233 2234 if status == Status::Returned { 2235 // It returned, so we can stop waiting. 2236 break (status, None); 2237 } else if async_caller { 2238 // It hasn't returned yet, but the caller is calling via an 2239 // async-lowered import, so we generate a handle for the task 2240 // waitable and return the status. 2241 let handle = self.id().get_mut(store.0).guest_tables().0[caller_instance] 2242 .subtask_insert_guest(guest_task.rep())?; 2243 self.concurrent_state_mut(store.0) 2244 .get_mut(guest_task)? 2245 .common 2246 .handle = Some(handle); 2247 break (status, Some(handle)); 2248 } else { 2249 // The callee hasn't returned yet, and the caller is calling via 2250 // a sync-lowered import, so we loop and keep waiting until the 2251 // callee returns. 2252 } 2253 }; 2254 2255 let state = self.concurrent_state_mut(store.0); 2256 2257 guest_waitable.join(state, old_set)?; 2258 2259 if let Some(storage) = storage { 2260 // The caller used a sync-lowered import to call an async-lifted 2261 // export, in which case the result, if any, has been stashed in 2262 // `GuestTask::sync_result`. 2263 if let Some(result) = state.get_mut(guest_task)?.sync_result.take() { 2264 if let Some(result) = result { 2265 storage[0] = MaybeUninit::new(result); 2266 } 2267 2268 Waitable::Guest(guest_task).delete_from(state)?; 2269 } else { 2270 // This means the callee failed to call either `task.return` or 2271 // `task.cancel` before exiting. 2272 return Err(anyhow!(crate::Trap::NoAsyncResult)); 2273 } 2274 } 2275 2276 // Reset the current task to point to the caller as it resumes control. 2277 state.guest_task = Some(caller); 2278 log::trace!("popped current task {guest_task:?}; new task is {caller:?}"); 2279 2280 Ok(status.pack(waitable)) 2281 } 2282 2283 /// Wrap the specified host function in a future which will call it, passing 2284 /// it an `&Accessor<T>`. 2285 /// 2286 /// See the `Accessor` documentation for details. 2287 pub(crate) fn wrap_call<T, F, R>( 2288 self, 2289 store: StoreContextMut<T>, 2290 closure: F, 2291 ) -> impl Future<Output = Result<R>> + 'static 2292 where 2293 T: 'static, 2294 F: FnOnce(&Accessor<T>) -> Pin<Box<dyn Future<Output = Result<R>> + Send + '_>> 2295 + Send 2296 + Sync 2297 + 'static, 2298 R: Send + Sync + 'static, 2299 { 2300 let token = StoreToken::new(store); 2301 async move { 2302 let mut accessor = Accessor::new(token, Some(self)); 2303 closure(&mut accessor).await 2304 } 2305 } 2306 2307 /// Poll the specified future once on behalf of a guest->host call using an 2308 /// async-lowered import. 2309 /// 2310 /// If it returns `Ready`, return `Ok(None)`. Otherwise, if it returns 2311 /// `Pending`, add it to the set of futures to be polled as part of this 2312 /// instance's event loop until it completes, and then return 2313 /// `Ok(Some(handle))` where `handle` is the waitable handle to return. 2314 /// 2315 /// Whether the future returns `Ready` immediately or later, the `lower` 2316 /// function will be used to lower the result, if any, into the guest caller's 2317 /// stack and linear memory unless the task has been cancelled. 2318 pub(crate) fn first_poll<T: 'static, R: Send + 'static>( 2319 self, 2320 mut store: StoreContextMut<T>, 2321 future: impl Future<Output = Result<R>> + Send + 'static, 2322 caller_instance: RuntimeComponentInstanceIndex, 2323 lower: impl FnOnce(StoreContextMut<T>, Instance, R) -> Result<()> + Send + 'static, 2324 ) -> Result<Option<u32>> { 2325 let token = StoreToken::new(store.as_context_mut()); 2326 let state = self.concurrent_state_mut(store.0); 2327 let caller = state.guest_task.unwrap(); 2328 2329 // Create an abortable future which hooks calls to poll and manages call 2330 // context state for the future. 2331 let (join_handle, future) = JoinHandle::run(async move { 2332 let mut future = pin!(future); 2333 let mut call_context = None; 2334 future::poll_fn(move |cx| { 2335 // Push the call context for managing any resource borrows 2336 // for the task. 2337 tls::get(|store| { 2338 if let Some(call_context) = call_context.take() { 2339 token 2340 .as_context_mut(store) 2341 .0 2342 .component_resource_state() 2343 .0 2344 .push(call_context); 2345 } 2346 }); 2347 2348 let result = future.as_mut().poll(cx); 2349 2350 if result.is_pending() { 2351 // Pop the call context for managing any resource 2352 // borrows for the task. 2353 tls::get(|store| { 2354 call_context = Some( 2355 token 2356 .as_context_mut(store) 2357 .0 2358 .component_resource_state() 2359 .0 2360 .pop() 2361 .unwrap(), 2362 ); 2363 }); 2364 } 2365 result 2366 }) 2367 .await 2368 }); 2369 2370 // We create a new host task even though it might complete immediately 2371 // (in which case we won't need to pass a waitable back to the guest). 2372 // If it does complete immediately, we'll remove it before we return. 2373 let task = state.push(HostTask::new(caller_instance, Some(join_handle)))?; 2374 2375 log::trace!("new host task child of {caller:?}: {task:?}"); 2376 let token = StoreToken::new(store.as_context_mut()); 2377 2378 // Map the output of the future to a `HostTaskOutput` responsible for 2379 // lowering the result into the guest's stack and memory, as well as 2380 // notifying any waiters that the task returned. 2381 let mut future = Box::pin(async move { 2382 let result = match future.await { 2383 Some(result) => result, 2384 // Task was cancelled; nothing left to do. 2385 None => return HostTaskOutput::Result(Ok(())), 2386 }; 2387 HostTaskOutput::Function(Box::new(move |store, instance| { 2388 let mut store = token.as_context_mut(store); 2389 lower(store.as_context_mut(), instance, result?)?; 2390 let state = instance.concurrent_state_mut(store.0); 2391 state.get_mut(task)?.join_handle.take(); 2392 Waitable::Host(task).set_event( 2393 state, 2394 Some(Event::Subtask { 2395 status: Status::Returned, 2396 }), 2397 )?; 2398 2399 Ok(()) 2400 })) 2401 }); 2402 2403 // Finally, poll the future. We can use a dummy `Waker` here because 2404 // we'll add the future to `ConcurrentState::futures` and poll it 2405 // automatically from the event loop if it doesn't complete immediately 2406 // here. 2407 let poll = self.set_tls(store.0, || { 2408 future 2409 .as_mut() 2410 .poll(&mut Context::from_waker(&Waker::noop())) 2411 }); 2412 2413 Ok(match poll { 2414 Poll::Ready(output) => { 2415 // It finished immediately; lower the result and delete the 2416 // task. 2417 output.consume(store.0.traitobj_mut(), self)?; 2418 log::trace!("delete host task {task:?} (already ready)"); 2419 self.concurrent_state_mut(store.0).delete(task)?; 2420 None 2421 } 2422 Poll::Pending => { 2423 // It hasn't finished yet; add the future to 2424 // `ConcurrentState::futures` so it will be polled by the event 2425 // loop and allocate a waitable handle to return to the guest. 2426 self.concurrent_state_mut(store.0).push_future(future); 2427 let handle = self.id().get_mut(store.0).guest_tables().0[caller_instance] 2428 .subtask_insert_host(task.rep())?; 2429 self.concurrent_state_mut(store.0) 2430 .get_mut(task)? 2431 .common 2432 .handle = Some(handle); 2433 log::trace!( 2434 "assign {task:?} handle {handle} for {caller:?} instance {caller_instance:?}" 2435 ); 2436 Some(handle) 2437 } 2438 }) 2439 } 2440 2441 /// Poll the specified future until it completes on behalf of a guest->host 2442 /// call using a sync-lowered import. 2443 /// 2444 /// This is similar to `Self::first_poll` except it's for sync-lowered 2445 /// imports, meaning we don't need to handle cancellation and we can block 2446 /// the caller until the task completes, at which point the caller can 2447 /// handle lowering the result to the guest's stack and linear memory. 2448 pub(crate) fn poll_and_block<R: Send + Sync + 'static>( 2449 self, 2450 store: &mut dyn VMStore, 2451 future: impl Future<Output = Result<R>> + Send + 'static, 2452 caller_instance: RuntimeComponentInstanceIndex, 2453 ) -> Result<R> { 2454 let state = self.concurrent_state_mut(store); 2455 2456 // If there is no current guest task set, that means the host function 2457 // was registered using e.g. `LinkerInstance::func_wrap`, in which case 2458 // it should complete immediately. 2459 let Some(caller) = state.guest_task else { 2460 return match pin!(future).poll(&mut Context::from_waker(&Waker::noop())) { 2461 Poll::Ready(result) => result, 2462 Poll::Pending => { 2463 unreachable!() 2464 } 2465 }; 2466 }; 2467 2468 // Save any existing result stashed in `GuestTask::result` so we can 2469 // replace it with the new result. 2470 let old_result = state 2471 .get_mut(caller) 2472 .with_context(|| format!("bad handle: {caller:?}"))? 2473 .result 2474 .take(); 2475 2476 // Add a temporary host task into the table so we can track its 2477 // progress. Note that we'll never allocate a waitable handle for the 2478 // guest since we're being called synchronously. 2479 let task = state.push(HostTask::new(caller_instance, None))?; 2480 2481 log::trace!("new host task child of {caller:?}: {task:?}"); 2482 2483 // Map the output of the future to a `HostTaskOutput` which will take 2484 // care of stashing the result in `GuestTask::result` and resuming this 2485 // fiber when the host task completes. 2486 let mut future = Box::pin(future.map(move |result| { 2487 HostTaskOutput::Function(Box::new(move |store, instance| { 2488 let state = instance.concurrent_state_mut(store); 2489 state.get_mut(caller)?.result = Some(Box::new(result?) as _); 2490 2491 Waitable::Host(task).set_event( 2492 state, 2493 Some(Event::Subtask { 2494 status: Status::Returned, 2495 }), 2496 )?; 2497 2498 Ok(()) 2499 })) 2500 })) as HostTaskFuture; 2501 2502 // Finally, poll the future. We can use a dummy `Waker` here because 2503 // we'll add the future to `ConcurrentState::futures` and poll it 2504 // automatically from the event loop if it doesn't complete immediately 2505 // here. 2506 let poll = self.set_tls(store, || { 2507 future 2508 .as_mut() 2509 .poll(&mut Context::from_waker(&Waker::noop())) 2510 }); 2511 2512 match poll { 2513 Poll::Ready(output) => { 2514 // It completed immediately; run the `HostTaskOutput` function 2515 // to stash the result and delete the task. 2516 output.consume(store, self)?; 2517 log::trace!("delete host task {task:?} (already ready)"); 2518 self.concurrent_state_mut(store).delete(task)?; 2519 } 2520 Poll::Pending => { 2521 // It did not complete immediately; add it to 2522 // `ConcurrentState::futures` so it will be polled via the event 2523 // loop, then use `GuestTask::sync_call_set` to wait for the 2524 // task to complete, suspending the current fiber until it does 2525 // so. 2526 let state = self.concurrent_state_mut(store); 2527 state.push_future(future); 2528 2529 let set = state.get_mut(caller)?.sync_call_set; 2530 Waitable::Host(task).join(state, Some(set))?; 2531 2532 self.suspend(store, SuspendReason::Waiting { set, task: caller })?; 2533 } 2534 } 2535 2536 // Retrieve and return the result. 2537 Ok(*mem::replace( 2538 &mut self.concurrent_state_mut(store).get_mut(caller)?.result, 2539 old_result, 2540 ) 2541 .unwrap() 2542 .downcast() 2543 .unwrap()) 2544 } 2545 2546 /// Implements the `task.return` intrinsic, lifting the result for the 2547 /// current guest task. 2548 pub(crate) fn task_return( 2549 self, 2550 store: &mut dyn VMStore, 2551 ty: TypeTupleIndex, 2552 options: OptionsIndex, 2553 storage: &[ValRaw], 2554 ) -> Result<()> { 2555 let state = self.concurrent_state_mut(store); 2556 let CanonicalOptions { 2557 string_encoding, 2558 data_model, 2559 .. 2560 } = *state.options(options); 2561 let guest_task = state.guest_task.unwrap(); 2562 let lift = state 2563 .get_mut(guest_task)? 2564 .lift_result 2565 .take() 2566 .ok_or_else(|| { 2567 anyhow!("`task.return` or `task.cancel` called more than once for current task") 2568 })?; 2569 assert!(state.get(guest_task)?.result.is_none()); 2570 2571 let invalid = ty != lift.ty 2572 || string_encoding != lift.string_encoding 2573 || match data_model { 2574 CanonicalOptionsDataModel::LinearMemory(opts) => match opts.memory { 2575 Some(memory) => { 2576 let expected = lift.memory.map(|v| v.as_ptr()).unwrap_or(ptr::null_mut()); 2577 let actual = self.id().get(store).runtime_memory(memory); 2578 expected != actual 2579 } 2580 // Memory not specified, meaning it didn't need to be 2581 // specified per validation, so not invalid. 2582 None => false, 2583 }, 2584 // Always invalid as this isn't supported. 2585 CanonicalOptionsDataModel::Gc { .. } => true, 2586 }; 2587 2588 if invalid { 2589 bail!("invalid `task.return` signature and/or options for current task"); 2590 } 2591 2592 log::trace!("task.return for {guest_task:?}"); 2593 2594 let result = (lift.lift)(store, self, storage)?; 2595 2596 self.task_complete(store, guest_task, result, Status::Returned, ValRaw::i32(0)) 2597 } 2598 2599 /// Implements the `task.cancel` intrinsic. 2600 pub(crate) fn task_cancel( 2601 self, 2602 store: &mut dyn VMStore, 2603 _caller_instance: RuntimeComponentInstanceIndex, 2604 ) -> Result<()> { 2605 let state = self.concurrent_state_mut(store); 2606 let guest_task = state.guest_task.unwrap(); 2607 let task = state.get_mut(guest_task)?; 2608 if !task.cancel_sent { 2609 bail!("`task.cancel` called by task which has not been cancelled") 2610 } 2611 _ = task.lift_result.take().ok_or_else(|| { 2612 anyhow!("`task.return` or `task.cancel` called more than once for current task") 2613 })?; 2614 2615 assert!(task.result.is_none()); 2616 2617 log::trace!("task.cancel for {guest_task:?}"); 2618 2619 self.task_complete( 2620 store, 2621 guest_task, 2622 Box::new(DummyResult), 2623 Status::ReturnCancelled, 2624 ValRaw::i32(0), 2625 ) 2626 } 2627 2628 /// Complete the specified guest task (i.e. indicate that it has either 2629 /// returned a (possibly empty) result or cancelled itself). 2630 /// 2631 /// This will return any resource borrows and notify any current or future 2632 /// waiters that the task has completed. 2633 fn task_complete( 2634 self, 2635 store: &mut dyn VMStore, 2636 guest_task: TableId<GuestTask>, 2637 result: Box<dyn Any + Send + Sync>, 2638 status: Status, 2639 post_return_arg: ValRaw, 2640 ) -> Result<()> { 2641 if self 2642 .concurrent_state_mut(store) 2643 .get(guest_task)? 2644 .call_post_return_automatically() 2645 { 2646 let (calls, host_table, _, instance) = store 2647 .store_opaque_mut() 2648 .component_resource_state_with_instance(self); 2649 ResourceTables { 2650 calls, 2651 host_table: Some(host_table), 2652 guest: Some(instance.guest_tables()), 2653 } 2654 .exit_call()?; 2655 } else { 2656 // As of this writing, the only scenario where `call_post_return_automatically` 2657 // would be false for a `GuestTask` is for host-to-guest calls using 2658 // `[Typed]Func::call_async`, in which case the `function_index` 2659 // should be a non-`None` value. 2660 let function_index = self 2661 .concurrent_state_mut(store) 2662 .get(guest_task)? 2663 .function_index 2664 .unwrap(); 2665 2666 self.id() 2667 .get_mut(store) 2668 .post_return_arg_set(function_index, post_return_arg); 2669 } 2670 2671 let state = self.concurrent_state_mut(store); 2672 let task = state.get_mut(guest_task)?; 2673 2674 if let Caller::Host { tx, .. } = &mut task.caller { 2675 if let Some(tx) = tx.take() { 2676 _ = tx.send(result); 2677 } 2678 } else { 2679 task.result = Some(result); 2680 Waitable::Guest(guest_task).set_event(state, Some(Event::Subtask { status }))?; 2681 } 2682 2683 Ok(()) 2684 } 2685 2686 /// Implements the `waitable-set.wait` intrinsic. 2687 pub(crate) fn waitable_set_wait( 2688 self, 2689 store: &mut dyn VMStore, 2690 options: OptionsIndex, 2691 set: u32, 2692 payload: u32, 2693 ) -> Result<u32> { 2694 let opts = self.concurrent_state_mut(store).options(options); 2695 let async_ = opts.async_; 2696 let caller_instance = opts.instance; 2697 let rep = 2698 self.id().get_mut(store).guest_tables().0[caller_instance].waitable_set_rep(set)?; 2699 2700 self.waitable_check( 2701 store, 2702 async_, 2703 WaitableCheck::Wait(WaitableCheckParams { 2704 set: TableId::new(rep), 2705 options, 2706 payload, 2707 }), 2708 ) 2709 } 2710 2711 /// Implements the `waitable-set.poll` intrinsic. 2712 pub(crate) fn waitable_set_poll( 2713 self, 2714 store: &mut dyn VMStore, 2715 options: OptionsIndex, 2716 set: u32, 2717 payload: u32, 2718 ) -> Result<u32> { 2719 let opts = self.concurrent_state_mut(store).options(options); 2720 let async_ = opts.async_; 2721 let caller_instance = opts.instance; 2722 let rep = 2723 self.id().get_mut(store).guest_tables().0[caller_instance].waitable_set_rep(set)?; 2724 2725 self.waitable_check( 2726 store, 2727 async_, 2728 WaitableCheck::Poll(WaitableCheckParams { 2729 set: TableId::new(rep), 2730 options, 2731 payload, 2732 }), 2733 ) 2734 } 2735 2736 /// Implements the `yield` intrinsic. 2737 pub(crate) fn yield_(self, store: &mut dyn VMStore, async_: bool) -> Result<bool> { 2738 self.waitable_check(store, async_, WaitableCheck::Yield) 2739 .map(|_code| { 2740 // TODO: plumb cancellation to here: 2741 // https://github.com/bytecodealliance/wasmtime/issues/11191 2742 false 2743 }) 2744 } 2745 2746 /// Helper function for the `waitable-set.wait`, `waitable-set.poll`, and 2747 /// `yield` intrinsics. 2748 fn waitable_check( 2749 self, 2750 store: &mut dyn VMStore, 2751 async_: bool, 2752 check: WaitableCheck, 2753 ) -> Result<u32> { 2754 if async_ { 2755 bail!( 2756 "todo: async `waitable-set.wait`, `waitable-set.poll`, and `yield` not yet implemented" 2757 ); 2758 } 2759 2760 let guest_task = self.concurrent_state_mut(store).guest_task.unwrap(); 2761 2762 let (wait, set) = match &check { 2763 WaitableCheck::Wait(params) => (true, Some(params.set)), 2764 WaitableCheck::Poll(params) => (false, Some(params.set)), 2765 WaitableCheck::Yield => (false, None), 2766 }; 2767 2768 // First, suspend this fiber, allowing any other tasks to run. 2769 self.suspend(store, SuspendReason::Yielding { task: guest_task })?; 2770 2771 log::trace!("waitable check for {guest_task:?}; set {set:?}"); 2772 2773 let state = self.concurrent_state_mut(store); 2774 let task = state.get(guest_task)?; 2775 2776 if wait && task.callback.is_some() { 2777 bail!("cannot call `task.wait` from async-lifted export with callback"); 2778 } 2779 2780 // If we're waiting, and there are no events immediately available, 2781 // suspend the fiber until that changes. 2782 if wait { 2783 let set = set.unwrap(); 2784 2785 if task.event.is_none() && state.get(set)?.ready.is_empty() { 2786 let old = state.get_mut(guest_task)?.wake_on_cancel.replace(set); 2787 assert!(old.is_none()); 2788 2789 self.suspend( 2790 store, 2791 SuspendReason::Waiting { 2792 set, 2793 task: guest_task, 2794 }, 2795 )?; 2796 } 2797 } 2798 2799 log::trace!("waitable check for {guest_task:?}; set {set:?}, part two"); 2800 2801 let result = match check { 2802 // Deliver any pending events to the guest and return. 2803 WaitableCheck::Wait(params) | WaitableCheck::Poll(params) => { 2804 let event = self 2805 .id() 2806 .get_mut(store) 2807 .get_event(guest_task, Some(params.set))?; 2808 2809 let (ordinal, handle, result) = if wait { 2810 let (event, waitable) = event.unwrap(); 2811 let handle = waitable.map(|(_, v)| v).unwrap_or(0); 2812 let (ordinal, result) = event.parts(); 2813 (ordinal, handle, result) 2814 } else { 2815 if let Some((event, waitable)) = event { 2816 let handle = waitable.map(|(_, v)| v).unwrap_or(0); 2817 let (ordinal, result) = event.parts(); 2818 (ordinal, handle, result) 2819 } else { 2820 log::trace!( 2821 "no events ready to deliver via waitable-set.poll to {guest_task:?}; set {:?}", 2822 params.set 2823 ); 2824 let (ordinal, result) = Event::None.parts(); 2825 (ordinal, 0, result) 2826 } 2827 }; 2828 let store = store.store_opaque_mut(); 2829 let options = Options::new_index(store, self, params.options); 2830 let ptr = func::validate_inbounds::<(u32, u32)>( 2831 options.memory_mut(store), 2832 &ValRaw::u32(params.payload), 2833 )?; 2834 options.memory_mut(store)[ptr + 0..][..4].copy_from_slice(&handle.to_le_bytes()); 2835 options.memory_mut(store)[ptr + 4..][..4].copy_from_slice(&result.to_le_bytes()); 2836 Ok(ordinal) 2837 } 2838 // TODO: Check `GuestTask::event` in case it contains 2839 // `Event::Cancelled`, in which case we'll need to return that to 2840 // the guest: 2841 // https://github.com/bytecodealliance/wasmtime/issues/11191 2842 WaitableCheck::Yield => Ok(0), 2843 }; 2844 2845 result 2846 } 2847 2848 /// Implements the `subtask.cancel` intrinsic. 2849 pub(crate) fn subtask_cancel( 2850 self, 2851 store: &mut dyn VMStore, 2852 caller_instance: RuntimeComponentInstanceIndex, 2853 async_: bool, 2854 task_id: u32, 2855 ) -> Result<u32> { 2856 let (rep, is_host) = 2857 self.id().get_mut(store).guest_tables().0[caller_instance].subtask_rep(task_id)?; 2858 let (waitable, expected_caller_instance) = if is_host { 2859 let id = TableId::<HostTask>::new(rep); 2860 ( 2861 Waitable::Host(id), 2862 self.concurrent_state_mut(store).get(id)?.caller_instance, 2863 ) 2864 } else { 2865 let id = TableId::<GuestTask>::new(rep); 2866 if let Caller::Guest { instance, .. } = 2867 &self.concurrent_state_mut(store).get(id)?.caller 2868 { 2869 (Waitable::Guest(id), *instance) 2870 } else { 2871 unreachable!() 2872 } 2873 }; 2874 // Since waitables can neither be passed between instances nor forged, 2875 // this should never fail unless there's a bug in Wasmtime, but we check 2876 // here to be sure: 2877 assert_eq!(expected_caller_instance, caller_instance); 2878 2879 log::trace!("subtask_cancel {waitable:?} (handle {task_id})"); 2880 2881 let concurrent_state = self.concurrent_state_mut(store); 2882 if let Waitable::Host(host_task) = waitable { 2883 if let Some(handle) = concurrent_state.get_mut(host_task)?.join_handle.take() { 2884 handle.abort(); 2885 return Ok(Status::ReturnCancelled as u32); 2886 } 2887 } else { 2888 let caller = concurrent_state.guest_task.unwrap(); 2889 let guest_task = TableId::<GuestTask>::new(rep); 2890 let task = concurrent_state.get_mut(guest_task)?; 2891 if task.lower_params.is_some() { 2892 task.lower_params = None; 2893 task.lift_result = None; 2894 2895 // Not yet started; cancel and remove from pending 2896 let callee_instance = task.instance; 2897 2898 let kind = concurrent_state 2899 .instance_state(callee_instance) 2900 .pending 2901 .remove(&guest_task); 2902 2903 if kind.is_none() { 2904 bail!("`subtask.cancel` called after terminal status delivered"); 2905 } 2906 2907 return Ok(Status::StartCancelled as u32); 2908 } else if task.lift_result.is_some() { 2909 // Started, but not yet returned or cancelled; send the 2910 // `CANCELLED` event 2911 task.cancel_sent = true; 2912 // Note that this might overwrite an event that was set earlier 2913 // (e.g. `Event::None` if the task is yielding, or 2914 // `Event::Cancelled` if it was already cancelled), but that's 2915 // okay -- this should supersede the previous state. 2916 task.event = Some(Event::Cancelled); 2917 if let Some(set) = task.wake_on_cancel.take() { 2918 let item = match concurrent_state 2919 .get_mut(set)? 2920 .waiting 2921 .remove(&guest_task) 2922 .unwrap() 2923 { 2924 WaitMode::Fiber(fiber) => WorkItem::ResumeFiber(fiber), 2925 WaitMode::Callback => WorkItem::GuestCall(GuestCall { 2926 task: guest_task, 2927 kind: GuestCallKind::DeliverEvent { set: None }, 2928 }), 2929 }; 2930 concurrent_state.push_high_priority(item); 2931 2932 self.suspend(store, SuspendReason::Yielding { task: caller })?; 2933 } 2934 2935 let concurrent_state = self.concurrent_state_mut(store); 2936 let task = concurrent_state.get_mut(guest_task)?; 2937 if task.lift_result.is_some() { 2938 // Still not yet returned or cancelled; if `async_`, return 2939 // `BLOCKED`; otherwise wait 2940 if async_ { 2941 return Ok(BLOCKED); 2942 } else { 2943 let waitable = Waitable::Guest(guest_task); 2944 let old_set = waitable.common(concurrent_state)?.set; 2945 let set = concurrent_state.get_mut(caller)?.sync_call_set; 2946 waitable.join(concurrent_state, Some(set))?; 2947 2948 self.suspend(store, SuspendReason::Waiting { set, task: caller })?; 2949 2950 waitable.join(self.concurrent_state_mut(store), old_set)?; 2951 } 2952 } 2953 } 2954 } 2955 2956 let event = waitable.take_event(self.concurrent_state_mut(store))?; 2957 if let Some(Event::Subtask { 2958 status: status @ (Status::Returned | Status::ReturnCancelled), 2959 }) = event 2960 { 2961 Ok(status as u32) 2962 } else { 2963 bail!("`subtask.cancel` called after terminal status delivered"); 2964 } 2965 } 2966 2967 /// Configures TLS state so `store` will be available via `tls::get` within 2968 /// the closure `f` provided. 2969 /// 2970 /// This is used to ensure that `Future::poll`, which doesn't take a `store` 2971 /// parameter, is able to get access to the `store` during future poll 2972 /// methods. 2973 fn set_tls<R>(self, store: &mut dyn VMStore, f: impl FnOnce() -> R) -> R { 2974 struct Reset<'a>(&'a mut dyn VMStore, Option<ComponentInstanceId>); 2975 2976 impl Drop for Reset<'_> { 2977 fn drop(&mut self) { 2978 self.0.concurrent_async_state_mut().current_instance = self.1; 2979 } 2980 } 2981 let prev = mem::replace( 2982 &mut store.concurrent_async_state_mut().current_instance, 2983 Some(self.id().instance()), 2984 ); 2985 let reset = Reset(store, prev); 2986 2987 tls::set(reset.0, f) 2988 } 2989 2990 /// Convenience function to reduce boilerplate. 2991 pub(crate) fn concurrent_state_mut<'a>( 2992 &self, 2993 store: &'a mut StoreOpaque, 2994 ) -> &'a mut ConcurrentState { 2995 self.id().get_mut(store).concurrent_state_mut() 2996 } 2997 } 2998 2999 /// Trait representing component model ABI async intrinsics and fused adapter 3000 /// helper functions. 3001 /// 3002 /// SAFETY (callers): Most of the methods in this trait accept raw pointers, 3003 /// which must be valid for at least the duration of the call (and possibly for 3004 /// as long as the relevant guest task exists, in the case of `*mut VMFuncRef` 3005 /// pointers used for async calls). 3006 pub trait VMComponentAsyncStore { 3007 /// A helper function for fused adapter modules involving calls where the 3008 /// one of the caller or callee is async. 3009 /// 3010 /// This helper is not used when the caller and callee both use the sync 3011 /// ABI, only when at least one is async is this used. 3012 unsafe fn prepare_call( 3013 &mut self, 3014 instance: Instance, 3015 memory: *mut VMMemoryDefinition, 3016 start: *mut VMFuncRef, 3017 return_: *mut VMFuncRef, 3018 caller_instance: RuntimeComponentInstanceIndex, 3019 callee_instance: RuntimeComponentInstanceIndex, 3020 task_return_type: TypeTupleIndex, 3021 string_encoding: u8, 3022 result_count: u32, 3023 storage: *mut ValRaw, 3024 storage_len: usize, 3025 ) -> Result<()>; 3026 3027 /// A helper function for fused adapter modules involving calls where the 3028 /// caller is sync-lowered but the callee is async-lifted. 3029 unsafe fn sync_start( 3030 &mut self, 3031 instance: Instance, 3032 callback: *mut VMFuncRef, 3033 callee: *mut VMFuncRef, 3034 param_count: u32, 3035 storage: *mut MaybeUninit<ValRaw>, 3036 storage_len: usize, 3037 ) -> Result<()>; 3038 3039 /// A helper function for fused adapter modules involving calls where the 3040 /// caller is async-lowered. 3041 unsafe fn async_start( 3042 &mut self, 3043 instance: Instance, 3044 callback: *mut VMFuncRef, 3045 post_return: *mut VMFuncRef, 3046 callee: *mut VMFuncRef, 3047 param_count: u32, 3048 result_count: u32, 3049 flags: u32, 3050 ) -> Result<u32>; 3051 3052 /// The `future.write` intrinsic. 3053 fn future_write( 3054 &mut self, 3055 instance: Instance, 3056 ty: TypeFutureTableIndex, 3057 options: OptionsIndex, 3058 future: u32, 3059 address: u32, 3060 ) -> Result<u32>; 3061 3062 /// The `future.read` intrinsic. 3063 fn future_read( 3064 &mut self, 3065 instance: Instance, 3066 ty: TypeFutureTableIndex, 3067 options: OptionsIndex, 3068 future: u32, 3069 address: u32, 3070 ) -> Result<u32>; 3071 3072 /// The `future.drop-writable` intrinsic. 3073 fn future_drop_writable( 3074 &mut self, 3075 instance: Instance, 3076 ty: TypeFutureTableIndex, 3077 writer: u32, 3078 ) -> Result<()>; 3079 3080 /// The `stream.write` intrinsic. 3081 fn stream_write( 3082 &mut self, 3083 instance: Instance, 3084 ty: TypeStreamTableIndex, 3085 options: OptionsIndex, 3086 stream: u32, 3087 address: u32, 3088 count: u32, 3089 ) -> Result<u32>; 3090 3091 /// The `stream.read` intrinsic. 3092 fn stream_read( 3093 &mut self, 3094 instance: Instance, 3095 ty: TypeStreamTableIndex, 3096 options: OptionsIndex, 3097 stream: u32, 3098 address: u32, 3099 count: u32, 3100 ) -> Result<u32>; 3101 3102 /// The "fast-path" implementation of the `stream.write` intrinsic for 3103 /// "flat" (i.e. memcpy-able) payloads. 3104 fn flat_stream_write( 3105 &mut self, 3106 instance: Instance, 3107 ty: TypeStreamTableIndex, 3108 options: OptionsIndex, 3109 payload_size: u32, 3110 payload_align: u32, 3111 stream: u32, 3112 address: u32, 3113 count: u32, 3114 ) -> Result<u32>; 3115 3116 /// The "fast-path" implementation of the `stream.read` intrinsic for "flat" 3117 /// (i.e. memcpy-able) payloads. 3118 fn flat_stream_read( 3119 &mut self, 3120 instance: Instance, 3121 ty: TypeStreamTableIndex, 3122 options: OptionsIndex, 3123 payload_size: u32, 3124 payload_align: u32, 3125 stream: u32, 3126 address: u32, 3127 count: u32, 3128 ) -> Result<u32>; 3129 3130 /// The `stream.drop-writable` intrinsic. 3131 fn stream_drop_writable( 3132 &mut self, 3133 instance: Instance, 3134 ty: TypeStreamTableIndex, 3135 writer: u32, 3136 ) -> Result<()>; 3137 3138 /// The `error-context.debug-message` intrinsic. 3139 fn error_context_debug_message( 3140 &mut self, 3141 instance: Instance, 3142 ty: TypeComponentLocalErrorContextTableIndex, 3143 options: OptionsIndex, 3144 err_ctx_handle: u32, 3145 debug_msg_address: u32, 3146 ) -> Result<()>; 3147 } 3148 3149 /// SAFETY: See trait docs. 3150 impl<T: 'static> VMComponentAsyncStore for StoreInner<T> { 3151 unsafe fn prepare_call( 3152 &mut self, 3153 instance: Instance, 3154 memory: *mut VMMemoryDefinition, 3155 start: *mut VMFuncRef, 3156 return_: *mut VMFuncRef, 3157 caller_instance: RuntimeComponentInstanceIndex, 3158 callee_instance: RuntimeComponentInstanceIndex, 3159 task_return_type: TypeTupleIndex, 3160 string_encoding: u8, 3161 result_count_or_max_if_async: u32, 3162 storage: *mut ValRaw, 3163 storage_len: usize, 3164 ) -> Result<()> { 3165 // SAFETY: The `wasmtime_cranelift`-generated code that calls 3166 // this method will have ensured that `storage` is a valid 3167 // pointer containing at least `storage_len` items. 3168 let params = unsafe { std::slice::from_raw_parts(storage, storage_len) }.to_vec(); 3169 3170 unsafe { 3171 instance.prepare_call( 3172 StoreContextMut(self), 3173 start, 3174 return_, 3175 caller_instance, 3176 callee_instance, 3177 task_return_type, 3178 memory, 3179 string_encoding, 3180 match result_count_or_max_if_async { 3181 PREPARE_ASYNC_NO_RESULT => CallerInfo::Async { 3182 params, 3183 has_result: false, 3184 }, 3185 PREPARE_ASYNC_WITH_RESULT => CallerInfo::Async { 3186 params, 3187 has_result: true, 3188 }, 3189 result_count => CallerInfo::Sync { 3190 params, 3191 result_count, 3192 }, 3193 }, 3194 ) 3195 } 3196 } 3197 3198 unsafe fn sync_start( 3199 &mut self, 3200 instance: Instance, 3201 callback: *mut VMFuncRef, 3202 callee: *mut VMFuncRef, 3203 param_count: u32, 3204 storage: *mut MaybeUninit<ValRaw>, 3205 storage_len: usize, 3206 ) -> Result<()> { 3207 unsafe { 3208 instance 3209 .start_call( 3210 StoreContextMut(self), 3211 callback, 3212 ptr::null_mut(), 3213 callee, 3214 param_count, 3215 1, 3216 START_FLAG_ASYNC_CALLEE, 3217 // SAFETY: The `wasmtime_cranelift`-generated code that calls 3218 // this method will have ensured that `storage` is a valid 3219 // pointer containing at least `storage_len` items. 3220 Some(std::slice::from_raw_parts_mut(storage, storage_len)), 3221 ) 3222 .map(drop) 3223 } 3224 } 3225 3226 unsafe fn async_start( 3227 &mut self, 3228 instance: Instance, 3229 callback: *mut VMFuncRef, 3230 post_return: *mut VMFuncRef, 3231 callee: *mut VMFuncRef, 3232 param_count: u32, 3233 result_count: u32, 3234 flags: u32, 3235 ) -> Result<u32> { 3236 unsafe { 3237 instance.start_call( 3238 StoreContextMut(self), 3239 callback, 3240 post_return, 3241 callee, 3242 param_count, 3243 result_count, 3244 flags, 3245 None, 3246 ) 3247 } 3248 } 3249 3250 fn future_write( 3251 &mut self, 3252 instance: Instance, 3253 ty: TypeFutureTableIndex, 3254 options: OptionsIndex, 3255 future: u32, 3256 address: u32, 3257 ) -> Result<u32> { 3258 instance 3259 .guest_write( 3260 StoreContextMut(self), 3261 TransmitIndex::Future(ty), 3262 options, 3263 None, 3264 future, 3265 address, 3266 1, 3267 ) 3268 .map(|result| result.encode()) 3269 } 3270 3271 fn future_read( 3272 &mut self, 3273 instance: Instance, 3274 ty: TypeFutureTableIndex, 3275 options: OptionsIndex, 3276 future: u32, 3277 address: u32, 3278 ) -> Result<u32> { 3279 instance 3280 .guest_read( 3281 StoreContextMut(self), 3282 TransmitIndex::Future(ty), 3283 options, 3284 None, 3285 future, 3286 address, 3287 1, 3288 ) 3289 .map(|result| result.encode()) 3290 } 3291 3292 fn stream_write( 3293 &mut self, 3294 instance: Instance, 3295 ty: TypeStreamTableIndex, 3296 options: OptionsIndex, 3297 stream: u32, 3298 address: u32, 3299 count: u32, 3300 ) -> Result<u32> { 3301 instance 3302 .guest_write( 3303 StoreContextMut(self), 3304 TransmitIndex::Stream(ty), 3305 options, 3306 None, 3307 stream, 3308 address, 3309 count, 3310 ) 3311 .map(|result| result.encode()) 3312 } 3313 3314 fn stream_read( 3315 &mut self, 3316 instance: Instance, 3317 ty: TypeStreamTableIndex, 3318 options: OptionsIndex, 3319 stream: u32, 3320 address: u32, 3321 count: u32, 3322 ) -> Result<u32> { 3323 instance 3324 .guest_read( 3325 StoreContextMut(self), 3326 TransmitIndex::Stream(ty), 3327 options, 3328 None, 3329 stream, 3330 address, 3331 count, 3332 ) 3333 .map(|result| result.encode()) 3334 } 3335 3336 fn future_drop_writable( 3337 &mut self, 3338 instance: Instance, 3339 ty: TypeFutureTableIndex, 3340 writer: u32, 3341 ) -> Result<()> { 3342 instance.guest_drop_writable(StoreContextMut(self), TransmitIndex::Future(ty), writer) 3343 } 3344 3345 fn flat_stream_write( 3346 &mut self, 3347 instance: Instance, 3348 ty: TypeStreamTableIndex, 3349 options: OptionsIndex, 3350 payload_size: u32, 3351 payload_align: u32, 3352 stream: u32, 3353 address: u32, 3354 count: u32, 3355 ) -> Result<u32> { 3356 instance 3357 .guest_write( 3358 StoreContextMut(self), 3359 TransmitIndex::Stream(ty), 3360 options, 3361 Some(FlatAbi { 3362 size: payload_size, 3363 align: payload_align, 3364 }), 3365 stream, 3366 address, 3367 count, 3368 ) 3369 .map(|result| result.encode()) 3370 } 3371 3372 fn flat_stream_read( 3373 &mut self, 3374 instance: Instance, 3375 ty: TypeStreamTableIndex, 3376 options: OptionsIndex, 3377 payload_size: u32, 3378 payload_align: u32, 3379 stream: u32, 3380 address: u32, 3381 count: u32, 3382 ) -> Result<u32> { 3383 instance 3384 .guest_read( 3385 StoreContextMut(self), 3386 TransmitIndex::Stream(ty), 3387 options, 3388 Some(FlatAbi { 3389 size: payload_size, 3390 align: payload_align, 3391 }), 3392 stream, 3393 address, 3394 count, 3395 ) 3396 .map(|result| result.encode()) 3397 } 3398 3399 fn stream_drop_writable( 3400 &mut self, 3401 instance: Instance, 3402 ty: TypeStreamTableIndex, 3403 writer: u32, 3404 ) -> Result<()> { 3405 instance.guest_drop_writable(StoreContextMut(self), TransmitIndex::Stream(ty), writer) 3406 } 3407 3408 fn error_context_debug_message( 3409 &mut self, 3410 instance: Instance, 3411 ty: TypeComponentLocalErrorContextTableIndex, 3412 options: OptionsIndex, 3413 err_ctx_handle: u32, 3414 debug_msg_address: u32, 3415 ) -> Result<()> { 3416 instance.error_context_debug_message( 3417 StoreContextMut(self), 3418 ty, 3419 options, 3420 err_ctx_handle, 3421 debug_msg_address, 3422 ) 3423 } 3424 } 3425 3426 /// Represents the output of a host task or background task. 3427 pub(crate) enum HostTaskOutput { 3428 /// A plain result 3429 Result(Result<()>), 3430 /// A function to be run after the future completes (e.g. post-processing 3431 /// which requires access to the store and instance). 3432 Function(Box<dyn FnOnce(&mut dyn VMStore, Instance) -> Result<()> + Send>), 3433 } 3434 3435 impl HostTaskOutput { 3436 /// Retrieve the result of the host or background task, running the 3437 /// post-processing function if present. 3438 fn consume(self, store: &mut dyn VMStore, instance: Instance) -> Result<()> { 3439 match self { 3440 Self::Function(fun) => fun(store, instance), 3441 Self::Result(result) => result, 3442 } 3443 } 3444 } 3445 3446 type HostTaskFuture = Pin<Box<dyn Future<Output = HostTaskOutput> + Send + 'static>>; 3447 3448 /// Represents the state of a pending host task. 3449 struct HostTask { 3450 common: WaitableCommon, 3451 caller_instance: RuntimeComponentInstanceIndex, 3452 join_handle: Option<JoinHandle>, 3453 } 3454 3455 impl HostTask { 3456 fn new( 3457 caller_instance: RuntimeComponentInstanceIndex, 3458 join_handle: Option<JoinHandle>, 3459 ) -> Self { 3460 Self { 3461 common: WaitableCommon::default(), 3462 caller_instance, 3463 join_handle, 3464 } 3465 } 3466 } 3467 3468 impl TableDebug for HostTask { 3469 fn type_name() -> &'static str { 3470 "HostTask" 3471 } 3472 } 3473 3474 type CallbackFn = Box< 3475 dyn Fn(&mut dyn VMStore, Instance, RuntimeComponentInstanceIndex, Event, u32) -> Result<u32> 3476 + Send 3477 + Sync 3478 + 'static, 3479 >; 3480 3481 /// Represents the caller of a given guest task. 3482 enum Caller { 3483 /// The host called the guest task. 3484 Host { 3485 /// If present, may be used to deliver the result. 3486 tx: Option<oneshot::Sender<LiftedResult>>, 3487 /// If true, remove the task from the concurrent state that owns it 3488 /// automatically after it completes. 3489 remove_task_automatically: bool, 3490 /// If true, call `post-return` function (if any) automatically. 3491 call_post_return_automatically: bool, 3492 }, 3493 /// Another guest task called the guest task 3494 Guest { 3495 /// The id of the caller 3496 task: TableId<GuestTask>, 3497 /// The instance to use to enforce reentrance rules. 3498 /// 3499 /// Note that this might not be the same as the instance the caller task 3500 /// started executing in given that one or more synchronous guest->guest 3501 /// calls may have occurred involving multiple instances. 3502 instance: RuntimeComponentInstanceIndex, 3503 }, 3504 } 3505 3506 /// Represents a closure and related canonical ABI parameters required to 3507 /// validate a `task.return` call at runtime and lift the result. 3508 struct LiftResult { 3509 lift: RawLift, 3510 ty: TypeTupleIndex, 3511 memory: Option<SendSyncPtr<VMMemoryDefinition>>, 3512 string_encoding: StringEncoding, 3513 } 3514 3515 /// Represents a pending guest task. 3516 struct GuestTask { 3517 /// See `WaitableCommon` 3518 common: WaitableCommon, 3519 /// Closure to lower the parameters passed to this task. 3520 lower_params: Option<RawLower>, 3521 /// See `LiftResult` 3522 lift_result: Option<LiftResult>, 3523 /// A place to stash the type-erased lifted result if it can't be delivered 3524 /// immediately. 3525 result: Option<LiftedResult>, 3526 /// Closure to call the callback function for an async-lifted export, if 3527 /// provided. 3528 callback: Option<CallbackFn>, 3529 /// See `Caller` 3530 caller: Caller, 3531 /// A place to stash the call context for managing resource borrows while 3532 /// switching between guest tasks. 3533 call_context: Option<CallContext>, 3534 /// A place to stash the lowered result for a sync-to-async call until it 3535 /// can be returned to the caller. 3536 sync_result: Option<Option<ValRaw>>, 3537 /// Whether or not the task has been cancelled (i.e. whether the task is 3538 /// permitted to call `task.cancel`). 3539 cancel_sent: bool, 3540 /// Whether or not we've sent a `Status::Starting` event to any current or 3541 /// future waiters for this waitable. 3542 starting_sent: bool, 3543 /// Context-local state used to implement the `context.{get,set}` 3544 /// intrinsics. 3545 context: [u32; 2], 3546 /// Pending guest subtasks created by this task (directly or indirectly). 3547 /// 3548 /// This is used to re-parent subtasks which are still running when their 3549 /// parent task is disposed. 3550 subtasks: HashSet<TableId<GuestTask>>, 3551 /// Scratch waitable set used to watch subtasks during synchronous calls. 3552 sync_call_set: TableId<WaitableSet>, 3553 /// The instance to which the exported function for this guest task belongs. 3554 /// 3555 /// Note that the task may do a sync->sync call via a fused adapter which 3556 /// results in that task executing code in a different instance, and it may 3557 /// call host functions and intrinsics from that other instance. 3558 instance: RuntimeComponentInstanceIndex, 3559 /// If present, a pending `Event::None` or `Event::Cancelled` to be 3560 /// delivered to this task. 3561 event: Option<Event>, 3562 /// If present, indicates that the task is currently waiting on the 3563 /// specified set but may be cancelled and woken immediately. 3564 wake_on_cancel: Option<TableId<WaitableSet>>, 3565 /// The `ExportIndex` of the guest function being called, if known. 3566 function_index: Option<ExportIndex>, 3567 /// Whether or not the task has exited. 3568 exited: bool, 3569 } 3570 3571 impl GuestTask { 3572 fn new( 3573 state: &mut ConcurrentState, 3574 lower_params: RawLower, 3575 lift_result: LiftResult, 3576 caller: Caller, 3577 callback: Option<CallbackFn>, 3578 component_instance: RuntimeComponentInstanceIndex, 3579 ) -> Result<Self> { 3580 let sync_call_set = state.push(WaitableSet::default())?; 3581 3582 Ok(Self { 3583 common: WaitableCommon::default(), 3584 lower_params: Some(lower_params), 3585 lift_result: Some(lift_result), 3586 result: None, 3587 callback, 3588 caller, 3589 call_context: Some(CallContext::default()), 3590 sync_result: None, 3591 cancel_sent: false, 3592 starting_sent: false, 3593 context: [0u32; 2], 3594 subtasks: HashSet::new(), 3595 sync_call_set, 3596 instance: component_instance, 3597 event: None, 3598 wake_on_cancel: None, 3599 function_index: None, 3600 exited: false, 3601 }) 3602 } 3603 3604 /// Dispose of this guest task, reparenting any pending subtasks to the 3605 /// caller. 3606 fn dispose(self, state: &mut ConcurrentState, me: TableId<GuestTask>) -> Result<()> { 3607 // If there are not-yet-delivered completion events for subtasks in 3608 // `self.sync_call_set`, recursively dispose of those subtasks as well. 3609 for waitable in mem::take(&mut state.get_mut(self.sync_call_set)?.ready) { 3610 if let Some(Event::Subtask { 3611 status: Status::Returned | Status::ReturnCancelled, 3612 }) = waitable.common(state)?.event 3613 { 3614 waitable.delete_from(state)?; 3615 } 3616 } 3617 3618 state.delete(self.sync_call_set)?; 3619 3620 // Reparent any pending subtasks to the caller. 3621 if let Caller::Guest { 3622 task, 3623 instance: runtime_instance, 3624 } = &self.caller 3625 { 3626 let task_mut = state.get_mut(*task)?; 3627 let present = task_mut.subtasks.remove(&me); 3628 assert!(present); 3629 3630 for subtask in &self.subtasks { 3631 task_mut.subtasks.insert(*subtask); 3632 } 3633 3634 for subtask in &self.subtasks { 3635 state.get_mut(*subtask)?.caller = Caller::Guest { 3636 task: *task, 3637 instance: *runtime_instance, 3638 }; 3639 } 3640 } else { 3641 for subtask in &self.subtasks { 3642 state.get_mut(*subtask)?.caller = Caller::Host { 3643 tx: None, 3644 remove_task_automatically: true, 3645 call_post_return_automatically: true, 3646 }; 3647 } 3648 } 3649 3650 Ok(()) 3651 } 3652 3653 fn call_post_return_automatically(&self) -> bool { 3654 matches!( 3655 self.caller, 3656 Caller::Guest { .. } 3657 | Caller::Host { 3658 call_post_return_automatically: true, 3659 .. 3660 } 3661 ) 3662 } 3663 } 3664 3665 impl TableDebug for GuestTask { 3666 fn type_name() -> &'static str { 3667 "GuestTask" 3668 } 3669 } 3670 3671 /// Represents state common to all kinds of waitables. 3672 #[derive(Default)] 3673 struct WaitableCommon { 3674 /// The currently pending event for this waitable, if any. 3675 event: Option<Event>, 3676 /// The set to which this waitable belongs, if any. 3677 set: Option<TableId<WaitableSet>>, 3678 /// The handle with which the guest refers to this waitable, if any. 3679 handle: Option<u32>, 3680 } 3681 3682 /// Represents a Component Model Async `waitable`. 3683 #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)] 3684 enum Waitable { 3685 /// A host task 3686 Host(TableId<HostTask>), 3687 /// A guest task 3688 Guest(TableId<GuestTask>), 3689 /// The read or write end of a stream or future 3690 Transmit(TableId<TransmitHandle>), 3691 } 3692 3693 impl Waitable { 3694 /// Retrieve the `Waitable` corresponding to the specified guest-visible 3695 /// handle. 3696 fn from_instance( 3697 state: Pin<&mut ComponentInstance>, 3698 caller_instance: RuntimeComponentInstanceIndex, 3699 waitable: u32, 3700 ) -> Result<Self> { 3701 use crate::runtime::vm::component::Waitable; 3702 3703 let (waitable, kind) = state.guest_tables().0[caller_instance].waitable_rep(waitable)?; 3704 3705 Ok(match kind { 3706 Waitable::Subtask { is_host: true } => Self::Host(TableId::new(waitable)), 3707 Waitable::Subtask { is_host: false } => Self::Guest(TableId::new(waitable)), 3708 Waitable::Stream | Waitable::Future => Self::Transmit(TableId::new(waitable)), 3709 }) 3710 } 3711 3712 /// Retrieve the host-visible identifier for this `Waitable`. 3713 fn rep(&self) -> u32 { 3714 match self { 3715 Self::Host(id) => id.rep(), 3716 Self::Guest(id) => id.rep(), 3717 Self::Transmit(id) => id.rep(), 3718 } 3719 } 3720 3721 /// Move this `Waitable` to the specified set (when `set` is `Some(_)`) or 3722 /// remove it from any set it may currently belong to (when `set` is 3723 /// `None`). 3724 fn join(&self, state: &mut ConcurrentState, set: Option<TableId<WaitableSet>>) -> Result<()> { 3725 log::trace!("waitable {self:?} join set {set:?}",); 3726 3727 let old = mem::replace(&mut self.common(state)?.set, set); 3728 3729 if let Some(old) = old { 3730 match *self { 3731 Waitable::Host(id) => state.remove_child(id, old), 3732 Waitable::Guest(id) => state.remove_child(id, old), 3733 Waitable::Transmit(id) => state.remove_child(id, old), 3734 }?; 3735 3736 state.get_mut(old)?.ready.remove(self); 3737 } 3738 3739 if let Some(set) = set { 3740 match *self { 3741 Waitable::Host(id) => state.add_child(id, set), 3742 Waitable::Guest(id) => state.add_child(id, set), 3743 Waitable::Transmit(id) => state.add_child(id, set), 3744 }?; 3745 3746 if self.common(state)?.event.is_some() { 3747 self.mark_ready(state)?; 3748 } 3749 } 3750 3751 Ok(()) 3752 } 3753 3754 /// Retrieve mutable access to the `WaitableCommon` for this `Waitable`. 3755 fn common<'a>(&self, state: &'a mut ConcurrentState) -> Result<&'a mut WaitableCommon> { 3756 Ok(match self { 3757 Self::Host(id) => &mut state.get_mut(*id)?.common, 3758 Self::Guest(id) => &mut state.get_mut(*id)?.common, 3759 Self::Transmit(id) => &mut state.get_mut(*id)?.common, 3760 }) 3761 } 3762 3763 /// Set or clear the pending event for this waitable and either deliver it 3764 /// to the first waiter, if any, or mark it as ready to be delivered to the 3765 /// next waiter that arrives. 3766 fn set_event(&self, state: &mut ConcurrentState, event: Option<Event>) -> Result<()> { 3767 log::trace!("set event for {self:?}: {event:?}"); 3768 self.common(state)?.event = event; 3769 self.mark_ready(state) 3770 } 3771 3772 /// Take the pending event from this waitable, leaving `None` in its place. 3773 fn take_event(&self, state: &mut ConcurrentState) -> Result<Option<Event>> { 3774 let common = self.common(state)?; 3775 let event = common.event.take(); 3776 if let Some(set) = self.common(state)?.set { 3777 state.get_mut(set)?.ready.remove(self); 3778 } 3779 Ok(event) 3780 } 3781 3782 /// Deliver the current event for this waitable to the first waiter, if any, 3783 /// or else mark it as ready to be delivered to the next waiter that 3784 /// arrives. 3785 fn mark_ready(&self, state: &mut ConcurrentState) -> Result<()> { 3786 if let Some(set) = self.common(state)?.set { 3787 state.get_mut(set)?.ready.insert(*self); 3788 if let Some((task, mode)) = state.get_mut(set)?.waiting.pop_first() { 3789 let wake_on_cancel = state.get_mut(task)?.wake_on_cancel.take(); 3790 assert!(wake_on_cancel.is_none() || wake_on_cancel == Some(set)); 3791 3792 let item = match mode { 3793 WaitMode::Fiber(fiber) => WorkItem::ResumeFiber(fiber), 3794 WaitMode::Callback => WorkItem::GuestCall(GuestCall { 3795 task, 3796 kind: GuestCallKind::DeliverEvent { set: Some(set) }, 3797 }), 3798 }; 3799 state.push_high_priority(item); 3800 } 3801 } 3802 Ok(()) 3803 } 3804 3805 /// Handle the imminent delivery of the specified event, e.g. by updating 3806 /// the state of the stream or future. 3807 fn on_delivery(&self, instance: Pin<&mut ComponentInstance>, event: Event) { 3808 match event { 3809 Event::FutureRead { 3810 pending: Some((ty, handle)), 3811 .. 3812 } 3813 | Event::FutureWrite { 3814 pending: Some((ty, handle)), 3815 .. 3816 } => { 3817 let runtime_instance = instance.component().types()[ty].instance; 3818 let (rep, state) = instance.guest_tables().0[runtime_instance] 3819 .future_rep(ty, handle) 3820 .unwrap(); 3821 assert_eq!(rep, self.rep()); 3822 assert_eq!(*state, TransmitLocalState::Busy); 3823 *state = match event { 3824 Event::FutureRead { .. } => TransmitLocalState::Read { done: false }, 3825 Event::FutureWrite { .. } => TransmitLocalState::Write { done: false }, 3826 _ => unreachable!(), 3827 }; 3828 } 3829 Event::StreamRead { 3830 pending: Some((ty, handle)), 3831 code, 3832 } 3833 | Event::StreamWrite { 3834 pending: Some((ty, handle)), 3835 code, 3836 } => { 3837 let runtime_instance = instance.component().types()[ty].instance; 3838 let (rep, state) = instance.guest_tables().0[runtime_instance] 3839 .stream_rep(ty, handle) 3840 .unwrap(); 3841 assert_eq!(rep, self.rep()); 3842 assert_eq!(*state, TransmitLocalState::Busy); 3843 let done = matches!(code, ReturnCode::Dropped(_)); 3844 *state = match event { 3845 Event::StreamRead { .. } => TransmitLocalState::Read { done }, 3846 Event::StreamWrite { .. } => TransmitLocalState::Write { done }, 3847 _ => unreachable!(), 3848 }; 3849 } 3850 _ => {} 3851 } 3852 } 3853 3854 /// Remove this waitable from the instance's rep table. 3855 fn delete_from(&self, state: &mut ConcurrentState) -> Result<()> { 3856 match self { 3857 Self::Host(task) => { 3858 log::trace!("delete host task {task:?}"); 3859 state.delete(*task)?; 3860 } 3861 Self::Guest(task) => { 3862 log::trace!("delete guest task {task:?}"); 3863 state.delete(*task)?.dispose(state, *task)?; 3864 } 3865 Self::Transmit(task) => { 3866 state.delete(*task)?; 3867 } 3868 } 3869 3870 Ok(()) 3871 } 3872 } 3873 3874 impl fmt::Debug for Waitable { 3875 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 3876 match self { 3877 Self::Host(id) => write!(f, "{id:?}"), 3878 Self::Guest(id) => write!(f, "{id:?}"), 3879 Self::Transmit(id) => write!(f, "{id:?}"), 3880 } 3881 } 3882 } 3883 3884 /// Represents a Component Model Async `waitable-set`. 3885 #[derive(Default)] 3886 struct WaitableSet { 3887 /// Which waitables in this set have pending events, if any. 3888 ready: BTreeSet<Waitable>, 3889 /// Which guest tasks are currently waiting on this set, if any. 3890 waiting: BTreeMap<TableId<GuestTask>, WaitMode>, 3891 } 3892 3893 impl TableDebug for WaitableSet { 3894 fn type_name() -> &'static str { 3895 "WaitableSet" 3896 } 3897 } 3898 3899 /// Type-erased closure to lower the parameters for a guest task. 3900 type RawLower = Box< 3901 dyn FnOnce(&mut dyn VMStore, Instance, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync, 3902 >; 3903 3904 /// Type-erased closure to lift the result for a guest task. 3905 type RawLift = Box< 3906 dyn FnOnce(&mut dyn VMStore, Instance, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> 3907 + Send 3908 + Sync, 3909 >; 3910 3911 /// Type erased result of a guest task which may be downcast to the expected 3912 /// type by a host caller (or simply ignored in the case of a guest caller; see 3913 /// `DummyResult`). 3914 type LiftedResult = Box<dyn Any + Send + Sync>; 3915 3916 /// Used to return a result from a `LiftFn` when the actual result has already 3917 /// been lowered to a guest task's stack and linear memory. 3918 struct DummyResult; 3919 3920 /// Represents the state of a currently executing fiber which has been resumed 3921 /// via `self::poll_fn`. 3922 pub(crate) struct AsyncState { 3923 /// The current instance being polled, if any, which is used to perform 3924 /// checks to ensure that futures are always polled within the correct 3925 /// instance. 3926 current_instance: Option<ComponentInstanceId>, 3927 } 3928 3929 impl Default for AsyncState { 3930 fn default() -> Self { 3931 Self { 3932 current_instance: None, 3933 } 3934 } 3935 } 3936 3937 /// Represents the Component Model Async state of a (sub-)component instance. 3938 #[derive(Default)] 3939 struct InstanceState { 3940 /// Whether backpressure is set for this instance 3941 backpressure: bool, 3942 /// Whether this instance can be entered 3943 do_not_enter: bool, 3944 /// Pending calls for this instance which require `Self::backpressure` to be 3945 /// `true` and/or `Self::do_not_enter` to be false before they can proceed. 3946 pending: BTreeMap<TableId<GuestTask>, GuestCallKind>, 3947 } 3948 3949 /// Represents the Component Model Async state of a top-level component instance 3950 /// (i.e. a `super::ComponentInstance`). 3951 pub struct ConcurrentState { 3952 /// The currently running guest task, if any. 3953 guest_task: Option<TableId<GuestTask>>, 3954 /// The set of pending host and background tasks, if any. 3955 /// 3956 /// We must wrap this in a `Mutex` to ensure that `ComponentInstance` and 3957 /// `Store` satisfy a `Sync` bound, but it can't actually be accessed from 3958 /// more than one thread at a time. 3959 /// 3960 /// See `ComponentInstance::poll_until` for where we temporarily take this 3961 /// out, poll it, then put it back to avoid any mutable aliasing hazards. 3962 futures: Mutex<Option<FuturesUnordered<HostTaskFuture>>>, 3963 /// The table of waitables, waitable sets, etc. 3964 table: Table, 3965 /// Per (sub-)component instance states. 3966 /// 3967 /// See `InstanceState` for details and note that this map is lazily 3968 /// populated as needed. 3969 // TODO: this can and should be a `PrimaryMap` 3970 instance_states: HashMap<RuntimeComponentInstanceIndex, InstanceState>, 3971 /// The "high priority" work queue for this instance's event loop. 3972 high_priority: Vec<WorkItem>, 3973 /// The "high priority" work queue for this instance's event loop. 3974 low_priority: Vec<WorkItem>, 3975 /// A place to stash the reason a fiber is suspending so that the code which 3976 /// resumed it will know under what conditions the fiber should be resumed 3977 /// again. 3978 suspend_reason: Option<SuspendReason>, 3979 /// A cached fiber which is waiting for work to do. 3980 /// 3981 /// This helps us avoid creating a new fiber for each `GuestCall` work item. 3982 worker: Option<StoreFiber<'static>>, 3983 /// A place to stash the work item for which we're resuming a worker fiber. 3984 worker_item: Option<WorkerItem>, 3985 3986 /// Reference counts for all component error contexts 3987 /// 3988 /// NOTE: it is possible the global ref count to be *greater* than the sum of 3989 /// (sub)component ref counts as tracked by `error_context_tables`, for 3990 /// example when the host holds one or more references to error contexts. 3991 /// 3992 /// The key of this primary map is often referred to as the "rep" (i.e. host-side 3993 /// component-wide representation) of the index into concurrent state for a given 3994 /// stored `ErrorContext`. 3995 /// 3996 /// Stated another way, `TypeComponentGlobalErrorContextTableIndex` is essentially the same 3997 /// as a `TableId<ErrorContextState>`. 3998 global_error_context_ref_counts: 3999 BTreeMap<TypeComponentGlobalErrorContextTableIndex, GlobalErrorContextRefCount>, 4000 4001 /// Mirror of type information in `ComponentInstance`, placed here for 4002 /// convenience at the cost of an extra `Arc` clone. 4003 component: Component, 4004 } 4005 4006 impl ConcurrentState { 4007 pub(crate) fn new(component: &Component) -> Self { 4008 Self { 4009 guest_task: None, 4010 table: Table::new(), 4011 futures: Mutex::new(Some(FuturesUnordered::new())), 4012 instance_states: HashMap::new(), 4013 high_priority: Vec::new(), 4014 low_priority: Vec::new(), 4015 suspend_reason: None, 4016 worker: None, 4017 worker_item: None, 4018 global_error_context_ref_counts: BTreeMap::new(), 4019 component: component.clone(), 4020 } 4021 } 4022 4023 /// Take ownership of any fibers and futures owned by this object. 4024 /// 4025 /// This should be used when disposing of the `Store` containing this object 4026 /// in order to gracefully resolve any and all fibers using 4027 /// `StoreFiber::dispose`. This is necessary to avoid possible 4028 /// use-after-free bugs due to fibers which may still have access to the 4029 /// `Store`. 4030 /// 4031 /// Additionally, the futures collected with this function should be dropped 4032 /// within a `tls::set` call, which will ensure than any futures closing 4033 /// over an `&Accessor` will have access to the store when dropped, allowing 4034 /// e.g. `WithAccessor[AndValue]` instances to be disposed of without 4035 /// panicking. 4036 /// 4037 /// Note that this will leave the object in an inconsistent and unusable 4038 /// state, so it should only be used just prior to dropping it. 4039 pub(crate) fn take_fibers_and_futures( 4040 &mut self, 4041 fibers: &mut Vec<StoreFiber<'static>>, 4042 futures: &mut Vec<FuturesUnordered<HostTaskFuture>>, 4043 ) { 4044 for entry in self.table.iter_mut() { 4045 if let Some(set) = entry.downcast_mut::<WaitableSet>() { 4046 for mode in mem::take(&mut set.waiting).into_values() { 4047 if let WaitMode::Fiber(fiber) = mode { 4048 fibers.push(fiber); 4049 } 4050 } 4051 } 4052 } 4053 4054 if let Some(fiber) = self.worker.take() { 4055 fibers.push(fiber); 4056 } 4057 4058 let mut take_items = |list| { 4059 for item in mem::take(list) { 4060 match item { 4061 WorkItem::ResumeFiber(fiber) => { 4062 fibers.push(fiber); 4063 } 4064 WorkItem::PushFuture(future) => { 4065 self.futures 4066 .get_mut() 4067 .unwrap() 4068 .as_mut() 4069 .unwrap() 4070 .push(future.into_inner().unwrap()); 4071 } 4072 _ => {} 4073 } 4074 } 4075 }; 4076 4077 take_items(&mut self.high_priority); 4078 take_items(&mut self.low_priority); 4079 4080 if let Some(them) = self.futures.get_mut().unwrap().take() { 4081 futures.push(them); 4082 } 4083 } 4084 4085 fn instance_state(&mut self, instance: RuntimeComponentInstanceIndex) -> &mut InstanceState { 4086 self.instance_states.entry(instance).or_default() 4087 } 4088 4089 fn push<V: Send + Sync + 'static>(&mut self, value: V) -> Result<TableId<V>, TableError> { 4090 self.table.push(value) 4091 } 4092 4093 fn get<V: 'static>(&self, id: TableId<V>) -> Result<&V, TableError> { 4094 self.table.get(id) 4095 } 4096 4097 fn get_mut<V: 'static>(&mut self, id: TableId<V>) -> Result<&mut V, TableError> { 4098 self.table.get_mut(id) 4099 } 4100 4101 pub fn add_child<T, U>( 4102 &mut self, 4103 child: TableId<T>, 4104 parent: TableId<U>, 4105 ) -> Result<(), TableError> { 4106 self.table.add_child(child, parent) 4107 } 4108 4109 pub fn remove_child<T, U>( 4110 &mut self, 4111 child: TableId<T>, 4112 parent: TableId<U>, 4113 ) -> Result<(), TableError> { 4114 self.table.remove_child(child, parent) 4115 } 4116 4117 fn delete<V: 'static>(&mut self, id: TableId<V>) -> Result<V, TableError> { 4118 self.table.delete(id) 4119 } 4120 4121 fn push_future(&mut self, future: HostTaskFuture) { 4122 // Note that we can't directly push to `ConcurrentState::futures` here 4123 // since this may be called from a future that's being polled inside 4124 // `Self::poll_until`, which temporarily removes the `FuturesUnordered` 4125 // so it has exclusive access while polling it. Therefore, we push a 4126 // work item to the "high priority" queue, which will actually push to 4127 // `ConcurrentState::futures` later. 4128 self.push_high_priority(WorkItem::PushFuture(Mutex::new(future))); 4129 } 4130 4131 fn push_high_priority(&mut self, item: WorkItem) { 4132 log::trace!("push high priority: {item:?}"); 4133 self.high_priority.push(item); 4134 } 4135 4136 fn push_low_priority(&mut self, item: WorkItem) { 4137 log::trace!("push low priority: {item:?}"); 4138 self.low_priority.push(item); 4139 } 4140 4141 /// Determine whether the instance associated with the specified guest task 4142 /// may be entered (i.e. is not already on the async call stack). 4143 /// 4144 /// This is an additional check on top of the "may_enter" instance flag; 4145 /// it's needed because async-lifted exports with callback functions must 4146 /// not call their own instances directly or indirectly, and due to the 4147 /// "stackless" nature of callback-enabled guest tasks this may happen even 4148 /// if there are no activation records on the stack (i.e. the "may_enter" 4149 /// field is `true`) for that instance. 4150 fn may_enter(&mut self, mut guest_task: TableId<GuestTask>) -> bool { 4151 let guest_instance = self.get(guest_task).unwrap().instance; 4152 4153 // Walk the task tree back to the root, looking for potential 4154 // reentrance. 4155 // 4156 // TODO: This could be optimized by maintaining a per-`GuestTask` bitset 4157 // such that each bit represents and instance which has been entered by 4158 // that task or an ancestor of that task, in which case this would be a 4159 // constant time check. 4160 loop { 4161 match &self.get_mut(guest_task).unwrap().caller { 4162 Caller::Host { .. } => break true, 4163 Caller::Guest { task, instance } => { 4164 if *instance == guest_instance { 4165 break false; 4166 } else { 4167 guest_task = *task; 4168 } 4169 } 4170 } 4171 } 4172 } 4173 4174 /// Record that we're about to enter a (sub-)component instance which does 4175 /// not support more than one concurrent, stackful activation, meaning it 4176 /// cannot be entered again until the next call returns. 4177 fn enter_instance(&mut self, instance: RuntimeComponentInstanceIndex) { 4178 self.instance_state(instance).do_not_enter = true; 4179 } 4180 4181 /// Record that we've exited a (sub-)component instance previously entered 4182 /// with `Self::enter_instance` and then calls `Self::partition_pending`. 4183 /// See the documentation for the latter for details. 4184 fn exit_instance(&mut self, instance: RuntimeComponentInstanceIndex) -> Result<()> { 4185 self.instance_state(instance).do_not_enter = false; 4186 self.partition_pending(instance) 4187 } 4188 4189 /// Iterate over `InstanceState::pending`, moving any ready items into the 4190 /// "high priority" work item queue. 4191 /// 4192 /// See `GuestCall::is_ready` for details. 4193 fn partition_pending(&mut self, instance: RuntimeComponentInstanceIndex) -> Result<()> { 4194 for (task, kind) in mem::take(&mut self.instance_state(instance).pending).into_iter() { 4195 let call = GuestCall { task, kind }; 4196 if call.is_ready(self)? { 4197 self.push_high_priority(WorkItem::GuestCall(call)); 4198 } else { 4199 self.instance_state(instance) 4200 .pending 4201 .insert(call.task, call.kind); 4202 } 4203 } 4204 4205 Ok(()) 4206 } 4207 4208 /// Implements the `backpressure.set` intrinsic. 4209 pub(crate) fn backpressure_set( 4210 &mut self, 4211 caller_instance: RuntimeComponentInstanceIndex, 4212 enabled: u32, 4213 ) -> Result<()> { 4214 let state = self.instance_state(caller_instance); 4215 let old = state.backpressure; 4216 let new = enabled != 0; 4217 state.backpressure = new; 4218 4219 if old && !new { 4220 // Backpressure was previously enabled and is now disabled; move any 4221 // newly-eligible guest calls to the "high priority" queue. 4222 self.partition_pending(caller_instance)?; 4223 } 4224 4225 Ok(()) 4226 } 4227 4228 /// Implements the `context.get` intrinsic. 4229 pub(crate) fn context_get(&mut self, slot: u32) -> Result<u32> { 4230 let task = self.guest_task.unwrap(); 4231 let val = self.get(task)?.context[usize::try_from(slot).unwrap()]; 4232 log::trace!("context_get {task:?} slot {slot} val {val:#x}"); 4233 Ok(val) 4234 } 4235 4236 /// Implements the `context.set` intrinsic. 4237 pub(crate) fn context_set(&mut self, slot: u32, val: u32) -> Result<()> { 4238 let task = self.guest_task.unwrap(); 4239 log::trace!("context_set {task:?} slot {slot} val {val:#x}"); 4240 self.get_mut(task)?.context[usize::try_from(slot).unwrap()] = val; 4241 Ok(()) 4242 } 4243 4244 fn options(&self, options: OptionsIndex) -> &CanonicalOptions { 4245 &self.component.env_component().options[options] 4246 } 4247 } 4248 4249 /// Provide a type hint to compiler about the shape of a parameter lower 4250 /// closure. 4251 fn for_any_lower< 4252 F: FnOnce(&mut dyn VMStore, Instance, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync, 4253 >( 4254 fun: F, 4255 ) -> F { 4256 fun 4257 } 4258 4259 /// Provide a type hint to compiler about the shape of a result lift closure. 4260 fn for_any_lift< 4261 F: FnOnce(&mut dyn VMStore, Instance, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> 4262 + Send 4263 + Sync, 4264 >( 4265 fun: F, 4266 ) -> F { 4267 fun 4268 } 4269 4270 /// Wrap the specified future in a `poll_fn` which asserts that the future is 4271 /// only polled from the event loop of the specified `Instance`. 4272 /// 4273 /// See `Instance::run_concurrent` for details. 4274 fn checked<F: Future + Send + 'static>( 4275 instance: Instance, 4276 fut: F, 4277 ) -> impl Future<Output = F::Output> + Send + 'static { 4278 async move { 4279 let mut fut = pin!(fut); 4280 future::poll_fn(move |cx| { 4281 let message = "\ 4282 `Future`s which depend on asynchronous component tasks, streams, or \ 4283 futures to complete may only be polled from the event loop of the \ 4284 instance from which they originated. Please use \ 4285 `Instance::{run_concurrent,spawn}` to poll or await them.\ 4286 "; 4287 tls::try_get(|store| { 4288 let matched = match store { 4289 tls::TryGet::Some(store) => { 4290 let a = store.concurrent_async_state_mut().current_instance; 4291 a == Some(instance.id().instance()) 4292 } 4293 tls::TryGet::Taken | tls::TryGet::None => false, 4294 }; 4295 4296 if !matched { 4297 panic!("{message}") 4298 } 4299 }); 4300 fut.as_mut().poll(cx) 4301 }) 4302 .await 4303 } 4304 } 4305 4306 /// Assert that `Instance::run_concurrent` has not been called from within an 4307 /// instance's event loop. 4308 fn check_recursive_run() { 4309 tls::try_get(|store| { 4310 if !matches!(store, tls::TryGet::None) { 4311 panic!("Recursive `Instance::run_concurrent` calls not supported") 4312 } 4313 }); 4314 } 4315 4316 fn unpack_callback_code(code: u32) -> (u32, u32) { 4317 (code & 0xF, code >> 4) 4318 } 4319 4320 /// Helper struct for packaging parameters to be passed to 4321 /// `ComponentInstance::waitable_check` for calls to `waitable-set.wait` or 4322 /// `waitable-set.poll`. 4323 struct WaitableCheckParams { 4324 set: TableId<WaitableSet>, 4325 options: OptionsIndex, 4326 payload: u32, 4327 } 4328 4329 /// Helper enum for passing parameters to `ComponentInstance::waitable_check`. 4330 enum WaitableCheck { 4331 Wait(WaitableCheckParams), 4332 Poll(WaitableCheckParams), 4333 Yield, 4334 } 4335 4336 /// Represents a guest task called from the host, prepared using `prepare_call`. 4337 pub(crate) struct PreparedCall<R> { 4338 /// The guest export to be called 4339 handle: Func, 4340 /// The guest task created by `prepare_call` 4341 task: TableId<GuestTask>, 4342 /// The number of lowered core Wasm parameters to pass to the call. 4343 param_count: usize, 4344 /// The `oneshot::Receiver` to which the result of the call will be 4345 /// delivered when it is available. 4346 rx: oneshot::Receiver<LiftedResult>, 4347 _phantom: PhantomData<R>, 4348 } 4349 4350 impl<R> PreparedCall<R> { 4351 /// Get a copy of the `TaskId` for this `PreparedCall`. 4352 pub(crate) fn task_id(&self) -> TaskId { 4353 TaskId { 4354 handle: self.handle, 4355 task: self.task, 4356 } 4357 } 4358 } 4359 4360 /// Represents a task created by `prepare_call`. 4361 pub(crate) struct TaskId { 4362 handle: Func, 4363 task: TableId<GuestTask>, 4364 } 4365 4366 impl TaskId { 4367 /// Remove the specified task from the concurrent state to which it belongs. 4368 /// 4369 /// This must be used with care to avoid use-after-delete or double-delete 4370 /// bugs. Specifically, it should only be called on tasks created with the 4371 /// `remove_task_automatically` parameter to `prepare_call` set to `false`, 4372 /// which tells the runtime that the caller is responsible for removing the 4373 /// task from the state; otherwise, it will be removed automatically. Also, 4374 /// it should only be called once for a given task, and only after either 4375 /// the task has completed or the instance has trapped. 4376 pub(crate) fn remove<T>(&self, store: StoreContextMut<T>) -> Result<()> { 4377 Waitable::Guest(self.task).delete_from(self.handle.instance().concurrent_state_mut(store.0)) 4378 } 4379 } 4380 4381 /// Prepare a call to the specified exported Wasm function, providing functions 4382 /// for lowering the parameters and lifting the result. 4383 /// 4384 /// To enqueue the returned `PreparedCall` in the `ComponentInstance`'s event 4385 /// loop, use `queue_call`. 4386 pub(crate) fn prepare_call<T, R>( 4387 mut store: StoreContextMut<T>, 4388 handle: Func, 4389 param_count: usize, 4390 remove_task_automatically: bool, 4391 call_post_return_automatically: bool, 4392 lower_params: impl FnOnce(Func, StoreContextMut<T>, &mut [MaybeUninit<ValRaw>]) -> Result<()> 4393 + Send 4394 + Sync 4395 + 'static, 4396 lift_result: impl FnOnce(Func, &mut StoreOpaque, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> 4397 + Send 4398 + Sync 4399 + 'static, 4400 ) -> Result<PreparedCall<R>> { 4401 let (options, _flags, ty, raw_options) = handle.abi_info(store.0); 4402 4403 let instance = handle.instance().id().get(store.0); 4404 let task_return_type = instance.component().types()[ty].results; 4405 let component_instance = raw_options.instance; 4406 let callback = options.callback(); 4407 let memory = options.memory_raw().map(SendSyncPtr::new); 4408 let string_encoding = options.string_encoding(); 4409 let token = StoreToken::new(store.as_context_mut()); 4410 let state = handle.instance().concurrent_state_mut(store.0); 4411 4412 assert!(state.guest_task.is_none()); 4413 4414 let (tx, rx) = oneshot::channel(); 4415 4416 let mut task = GuestTask::new( 4417 state, 4418 Box::new(for_any_lower(move |store, instance, params| { 4419 debug_assert!(instance.id() == handle.instance().id()); 4420 lower_params(handle, token.as_context_mut(store), params) 4421 })), 4422 LiftResult { 4423 lift: Box::new(for_any_lift(move |store, instance, result| { 4424 debug_assert!(instance.id() == handle.instance().id()); 4425 lift_result(handle, store, result) 4426 })), 4427 ty: task_return_type, 4428 memory, 4429 string_encoding, 4430 }, 4431 Caller::Host { 4432 tx: Some(tx), 4433 remove_task_automatically, 4434 call_post_return_automatically, 4435 }, 4436 callback.map(|callback| { 4437 let callback = SendSyncPtr::new(callback); 4438 Box::new( 4439 move |store: &mut dyn VMStore, 4440 instance: Instance, 4441 runtime_instance, 4442 event, 4443 handle| { 4444 let store = token.as_context_mut(store); 4445 // SAFETY: Per the contract of `prepare_call`, the callback 4446 // will remain valid at least as long is this task exists. 4447 unsafe { 4448 instance.call_callback( 4449 store, 4450 runtime_instance, 4451 callback, 4452 event, 4453 handle, 4454 call_post_return_automatically, 4455 ) 4456 } 4457 }, 4458 ) as CallbackFn 4459 }), 4460 component_instance, 4461 )?; 4462 task.function_index = Some(handle.index()); 4463 4464 let task = state.push(task)?; 4465 4466 Ok(PreparedCall { 4467 handle, 4468 task, 4469 param_count, 4470 rx, 4471 _phantom: PhantomData, 4472 }) 4473 } 4474 4475 /// Queue a call previously prepared using `prepare_call` to be run as part of 4476 /// the associated `ComponentInstance`'s event loop. 4477 /// 4478 /// The returned future will resolve to the result once it is available, but 4479 /// must only be polled via the instance's event loop. See 4480 /// `Instance::run_concurrent` for details. 4481 pub(crate) fn queue_call<T: 'static, R: Send + 'static>( 4482 mut store: StoreContextMut<T>, 4483 prepared: PreparedCall<R>, 4484 ) -> Result<impl Future<Output = Result<R>> + Send + 'static + use<T, R>> { 4485 let PreparedCall { 4486 handle, 4487 task, 4488 param_count, 4489 rx, 4490 .. 4491 } = prepared; 4492 4493 queue_call0(store.as_context_mut(), handle, task, param_count)?; 4494 4495 Ok(checked( 4496 handle.instance(), 4497 rx.map(|result| { 4498 result 4499 .map(|v| *v.downcast().unwrap()) 4500 .map_err(anyhow::Error::from) 4501 }), 4502 )) 4503 } 4504 4505 /// Queue a call previously prepared using `prepare_call` to be run as part of 4506 /// the associated `ComponentInstance`'s event loop. 4507 fn queue_call0<T: 'static>( 4508 store: StoreContextMut<T>, 4509 handle: Func, 4510 guest_task: TableId<GuestTask>, 4511 param_count: usize, 4512 ) -> Result<()> { 4513 let (options, flags, _ty, raw_options) = handle.abi_info(store.0); 4514 let is_concurrent = raw_options.async_; 4515 let instance = handle.instance(); 4516 let callee = handle.lifted_core_func(store.0); 4517 let callback = options.callback(); 4518 let post_return = handle.post_return_core_func(store.0); 4519 4520 log::trace!("queueing call {guest_task:?}"); 4521 4522 let instance_flags = if callback.is_none() { 4523 None 4524 } else { 4525 Some(flags) 4526 }; 4527 4528 // SAFETY: `callee`, `callback`, and `post_return` are valid pointers 4529 // (with signatures appropriate for this call) and will remain valid as 4530 // long as this instance is valid. 4531 unsafe { 4532 instance.queue_call( 4533 store, 4534 guest_task, 4535 SendSyncPtr::new(callee), 4536 param_count, 4537 1, 4538 instance_flags, 4539 is_concurrent, 4540 callback.map(SendSyncPtr::new), 4541 post_return.map(SendSyncPtr::new), 4542 ) 4543 } 4544 } 4545