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