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 `GuestThread::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.thread)?.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 Box::new(move |_, _| bail_bug!("cannot lower params in sync call")), 1468 LiftResult { 1469 lift: Box::new(move |_, _| bail_bug!("cannot lift result in sync call")), 1470 ty: TypeTupleIndex::reserved_value(), 1471 memory: None, 1472 string_encoding: StringEncoding::Utf8, 1473 }, 1474 if let Some(thread) = thread.guest() { 1475 Caller::Guest { thread: *thread } 1476 } else { 1477 Caller::Host { 1478 tx: None, 1479 host_future_present: false, 1480 caller: thread, 1481 } 1482 }, 1483 None, 1484 callee, 1485 callee_async, 1486 )?; 1487 1488 let guest_task = state.push(task)?; 1489 let new_thread = GuestThread::new_implicit(state, guest_task)?; 1490 let guest_thread = state.push(new_thread)?; 1491 Instance::from_wasmtime(self, callee.instance).add_guest_thread_to_instance_table( 1492 guest_thread, 1493 self, 1494 callee.index, 1495 )?; 1496 1497 let state = self.concurrent_state_mut(); 1498 state.get_mut(guest_task)?.threads.insert(guest_thread); 1499 1500 self.set_thread(QualifiedThreadId { 1501 task: guest_task, 1502 thread: guest_thread, 1503 })?; 1504 1505 Ok(()) 1506 } 1507 1508 /// Pop a `GuestTask` previously pushed using `enter_sync_call`. 1509 pub(crate) fn exit_guest_sync_call(&mut self) -> Result<()> { 1510 if !self.concurrency_support() { 1511 return Ok(self.exit_call_not_concurrent()); 1512 } 1513 let thread = match self.set_thread(CurrentThread::None)?.guest() { 1514 Some(t) => *t, 1515 None => bail_bug!("expected task when exiting"), 1516 }; 1517 let instance = self.concurrent_state_mut().get_mut(thread.task)?.instance; 1518 log::trace!("exit sync call {instance:?}"); 1519 Instance::from_wasmtime(self, instance.instance).cleanup_thread( 1520 self, 1521 thread, 1522 instance.index, 1523 )?; 1524 1525 let state = self.concurrent_state_mut(); 1526 let task = state.get_mut(thread.task)?; 1527 let caller = match &task.caller { 1528 &Caller::Guest { thread } => thread.into(), 1529 &Caller::Host { caller, .. } => caller, 1530 }; 1531 self.set_thread(caller)?; 1532 1533 let state = self.concurrent_state_mut(); 1534 let task = state.get_mut(thread.task)?; 1535 if task.ready_to_delete() { 1536 state.delete(thread.task)?.dispose(state)?; 1537 } 1538 1539 Ok(()) 1540 } 1541 1542 /// Similar to `enter_guest_sync_call` except for when the guest makes a 1543 /// transition to the host. 1544 /// 1545 /// FIXME: this is called for all guest->host transitions and performs some 1546 /// relatively expensive table manipulations. This would ideally be 1547 /// optimized to avoid the full allocation of a `HostTask` in at least some 1548 /// situations. 1549 pub(crate) fn host_task_create(&mut self) -> Result<Option<TableId<HostTask>>> { 1550 if !self.concurrency_support() { 1551 self.enter_call_not_concurrent(); 1552 return Ok(None); 1553 } 1554 let state = self.concurrent_state_mut(); 1555 let caller = state.current_guest_thread()?; 1556 let task = state.push(HostTask::new(caller, HostTaskState::CalleeStarted))?; 1557 log::trace!("new host task {task:?}"); 1558 self.set_thread(task)?; 1559 Ok(Some(task)) 1560 } 1561 1562 /// Invoked before lowering the results of a host task to the guest. 1563 /// 1564 /// This is used to update the current thread annotations within the store 1565 /// to ensure that it reflects the guest task, not the host task, since 1566 /// lowering may execute guest code. 1567 pub fn host_task_reenter_caller(&mut self) -> Result<()> { 1568 if !self.concurrency_support() { 1569 return Ok(()); 1570 } 1571 let task = self.concurrent_state_mut().current_host_thread()?; 1572 let caller = self.concurrent_state_mut().get_mut(task)?.caller; 1573 self.set_thread(caller)?; 1574 Ok(()) 1575 } 1576 1577 /// Dual of `host_task_create` and signifies that the host has finished and 1578 /// will be cleaned up. 1579 /// 1580 /// Note that this isn't invoked when the host is invoked asynchronously and 1581 /// the host isn't complete yet. In that situation the host task persists 1582 /// and will be cleaned up separately in `subtask_drop` 1583 pub(crate) fn host_task_delete(&mut self, task: Option<TableId<HostTask>>) -> Result<()> { 1584 match task { 1585 Some(task) => { 1586 log::trace!("delete host task {task:?}"); 1587 self.concurrent_state_mut().delete(task)?; 1588 } 1589 None => { 1590 self.exit_call_not_concurrent(); 1591 } 1592 } 1593 Ok(()) 1594 } 1595 1596 /// Determine whether the specified instance may be entered from the host. 1597 /// 1598 /// We return `true` here only if all of the following hold: 1599 /// 1600 /// - The top-level instance is not already on the current task's call stack. 1601 /// - The instance is not in need of a post-return function call. 1602 /// - `self` has not been poisoned due to a trap. 1603 pub(crate) fn may_enter(&mut self, instance: RuntimeInstance) -> Result<bool> { 1604 if self.trapped() { 1605 return Ok(false); 1606 } 1607 if !self.concurrency_support() { 1608 return Ok(true); 1609 } 1610 let state = self.concurrent_state_mut(); 1611 let mut cur = state.current_thread; 1612 loop { 1613 match cur { 1614 CurrentThread::None => break Ok(true), 1615 CurrentThread::Guest(thread) => { 1616 let task = state.get_mut(thread.task)?; 1617 1618 // Note that we only compare top-level instance IDs here. 1619 // The idea is that the host is not allowed to recursively 1620 // enter a top-level instance even if the specific leaf 1621 // instance is not on the stack. This the behavior defined 1622 // in the spec, and it allows us to elide runtime checks in 1623 // guest-to-guest adapters. 1624 if task.instance.instance == instance.instance { 1625 break Ok(false); 1626 } 1627 cur = match task.caller { 1628 Caller::Host { caller, .. } => caller, 1629 Caller::Guest { thread } => thread.into(), 1630 }; 1631 } 1632 CurrentThread::Host(id) => { 1633 cur = state.get_mut(id)?.caller.into(); 1634 } 1635 } 1636 } 1637 } 1638 1639 /// Helper function to retrieve the `InstanceState` for the 1640 /// specified instance. 1641 fn instance_state(&mut self, instance: RuntimeInstance) -> &mut InstanceState { 1642 self.component_instance_mut(instance.instance) 1643 .instance_state(instance.index) 1644 } 1645 1646 fn set_thread(&mut self, thread: impl Into<CurrentThread>) -> Result<CurrentThread> { 1647 // Each time we switch threads, we conservatively set `task_may_block` 1648 // to `false` for the component instance we're switching away from (if 1649 // any), meaning it will be `false` for any new thread created for that 1650 // instance unless explicitly set otherwise. 1651 let state = self.concurrent_state_mut(); 1652 let old_thread = mem::replace(&mut state.current_thread, thread.into()); 1653 if let Some(old_thread) = old_thread.guest() { 1654 let instance = state.get_mut(old_thread.task)?.instance.instance; 1655 self.component_instance_mut(instance) 1656 .set_task_may_block(false) 1657 } 1658 1659 // If we're switching to a new thread, set its component instance's 1660 // `task_may_block` according to where it left off. 1661 if self.concurrent_state_mut().current_thread.guest().is_some() { 1662 self.set_task_may_block()?; 1663 } 1664 1665 Ok(old_thread) 1666 } 1667 1668 /// Set the global variable representing whether the current task may block 1669 /// prior to entering Wasm code. 1670 fn set_task_may_block(&mut self) -> Result<()> { 1671 let state = self.concurrent_state_mut(); 1672 let guest_thread = state.current_guest_thread()?; 1673 let instance = state.get_mut(guest_thread.task)?.instance.instance; 1674 let may_block = self.concurrent_state_mut().may_block(guest_thread.task)?; 1675 self.component_instance_mut(instance) 1676 .set_task_may_block(may_block); 1677 Ok(()) 1678 } 1679 1680 pub(crate) fn check_blocking(&mut self) -> Result<()> { 1681 if !self.concurrency_support() { 1682 return Ok(()); 1683 } 1684 let state = self.concurrent_state_mut(); 1685 let task = state.current_guest_thread()?.task; 1686 let instance = state.get_mut(task)?.instance.instance; 1687 let task_may_block = self.component_instance(instance).get_task_may_block(); 1688 1689 if task_may_block { 1690 Ok(()) 1691 } else { 1692 Err(Trap::CannotBlockSyncTask.into()) 1693 } 1694 } 1695 1696 /// Record that we're about to enter a (sub-)component instance which does 1697 /// not support more than one concurrent, stackful activation, meaning it 1698 /// cannot be entered again until the next call returns. 1699 fn enter_instance(&mut self, instance: RuntimeInstance) { 1700 log::trace!("enter {instance:?}"); 1701 self.instance_state(instance) 1702 .concurrent_state() 1703 .do_not_enter = true; 1704 } 1705 1706 /// Record that we've exited a (sub-)component instance previously entered 1707 /// with `Self::enter_instance` and then calls `Self::partition_pending`. 1708 /// See the documentation for the latter for details. 1709 fn exit_instance(&mut self, instance: RuntimeInstance) -> Result<()> { 1710 log::trace!("exit {instance:?}"); 1711 self.instance_state(instance) 1712 .concurrent_state() 1713 .do_not_enter = false; 1714 self.partition_pending(instance) 1715 } 1716 1717 /// Iterate over `InstanceState::pending`, moving any ready items into the 1718 /// "high priority" work item queue. 1719 /// 1720 /// See `GuestCall::is_ready` for details. 1721 fn partition_pending(&mut self, instance: RuntimeInstance) -> Result<()> { 1722 for (thread, kind) in 1723 mem::take(&mut self.instance_state(instance).concurrent_state().pending).into_iter() 1724 { 1725 let call = GuestCall { thread, kind }; 1726 if call.is_ready(self)? { 1727 self.concurrent_state_mut() 1728 .push_high_priority(WorkItem::GuestCall(instance.index, call)); 1729 } else { 1730 self.instance_state(instance) 1731 .concurrent_state() 1732 .pending 1733 .insert(call.thread, call.kind); 1734 } 1735 } 1736 1737 Ok(()) 1738 } 1739 1740 /// Implements the `backpressure.{inc,dec}` intrinsics. 1741 pub(crate) fn backpressure_modify( 1742 &mut self, 1743 caller_instance: RuntimeInstance, 1744 modify: impl FnOnce(u16) -> Option<u16>, 1745 ) -> Result<()> { 1746 let state = self.instance_state(caller_instance).concurrent_state(); 1747 let old = state.backpressure; 1748 let new = modify(old).ok_or_else(|| Trap::BackpressureOverflow)?; 1749 state.backpressure = new; 1750 1751 if old > 0 && new == 0 { 1752 // Backpressure was previously enabled and is now disabled; move any 1753 // newly-eligible guest calls to the "high priority" queue. 1754 self.partition_pending(caller_instance)?; 1755 } 1756 1757 Ok(()) 1758 } 1759 1760 /// Resume the specified fiber, giving it exclusive access to the specified 1761 /// store. 1762 async fn resume_fiber(&mut self, fiber: StoreFiber<'static>) -> Result<()> { 1763 let old_thread = self.concurrent_state_mut().current_thread; 1764 log::trace!("resume_fiber: save current thread {old_thread:?}"); 1765 1766 let fiber = fiber::resolve_or_release(self, fiber).await?; 1767 1768 self.set_thread(old_thread)?; 1769 1770 let state = self.concurrent_state_mut(); 1771 1772 if let Some(ot) = old_thread.guest() { 1773 state.get_mut(ot.thread)?.state = GuestThreadState::Running; 1774 } 1775 log::trace!("resume_fiber: restore current thread {old_thread:?}"); 1776 1777 if let Some(mut fiber) = fiber { 1778 log::trace!("resume_fiber: suspend reason {:?}", &state.suspend_reason); 1779 // See the `SuspendReason` documentation for what each case means. 1780 let reason = match state.suspend_reason.take() { 1781 Some(r) => r, 1782 None => bail_bug!("suspend reason missing when resuming fiber"), 1783 }; 1784 match reason { 1785 SuspendReason::NeedWork => { 1786 if state.worker.is_none() { 1787 state.worker = Some(fiber); 1788 } else { 1789 fiber.dispose(self); 1790 } 1791 } 1792 SuspendReason::Yielding { thread, .. } => { 1793 state.get_mut(thread.thread)?.state = GuestThreadState::Ready(fiber); 1794 let instance = state.get_mut(thread.task)?.instance.index; 1795 state.push_low_priority(WorkItem::ResumeThread(instance, thread)); 1796 } 1797 SuspendReason::ExplicitlySuspending { thread, .. } => { 1798 state.get_mut(thread.thread)?.state = GuestThreadState::Suspended(fiber); 1799 } 1800 SuspendReason::Waiting { set, thread, .. } => { 1801 let old = state 1802 .get_mut(set)? 1803 .waiting 1804 .insert(thread, WaitMode::Fiber(fiber)); 1805 assert!(old.is_none()); 1806 } 1807 }; 1808 } else { 1809 log::trace!("resume_fiber: fiber has exited"); 1810 } 1811 1812 Ok(()) 1813 } 1814 1815 /// Suspend the current fiber, storing the reason in 1816 /// `ConcurrentState::suspend_reason` to indicate the conditions under which 1817 /// it should be resumed. 1818 /// 1819 /// See the `SuspendReason` documentation for details. 1820 fn suspend(&mut self, reason: SuspendReason) -> Result<()> { 1821 log::trace!("suspend fiber: {reason:?}"); 1822 1823 // If we're yielding or waiting on behalf of a guest thread, we'll need to 1824 // pop the call context which manages resource borrows before suspending 1825 // and then push it again once we've resumed. 1826 let task = match &reason { 1827 SuspendReason::Yielding { thread, .. } 1828 | SuspendReason::Waiting { thread, .. } 1829 | SuspendReason::ExplicitlySuspending { thread, .. } => Some(thread.task), 1830 SuspendReason::NeedWork => None, 1831 }; 1832 1833 let old_guest_thread = if task.is_some() { 1834 self.concurrent_state_mut().current_thread 1835 } else { 1836 CurrentThread::None 1837 }; 1838 1839 // We should not have reached here unless either there's no current 1840 // task, or the current task is permitted to block. In addition, we 1841 // special-case `thread.switch-to` and waiting for a subtask to go from 1842 // `starting` to `started`, both of which we consider non-blocking 1843 // operations despite requiring a suspend. 1844 debug_assert!( 1845 matches!( 1846 reason, 1847 SuspendReason::ExplicitlySuspending { 1848 skip_may_block_check: true, 1849 .. 1850 } | SuspendReason::Waiting { 1851 skip_may_block_check: true, 1852 .. 1853 } | SuspendReason::Yielding { 1854 skip_may_block_check: true, 1855 .. 1856 } 1857 ) || old_guest_thread 1858 .guest() 1859 .map(|thread| self.concurrent_state_mut().may_block(thread.task)) 1860 .transpose()? 1861 .unwrap_or(true) 1862 ); 1863 1864 let suspend_reason = &mut self.concurrent_state_mut().suspend_reason; 1865 assert!(suspend_reason.is_none()); 1866 *suspend_reason = Some(reason); 1867 1868 self.with_blocking(|_, cx| cx.suspend(StoreFiberYield::ReleaseStore))?; 1869 1870 if task.is_some() { 1871 self.set_thread(old_guest_thread)?; 1872 } 1873 1874 Ok(()) 1875 } 1876 1877 fn wait_for_event(&mut self, waitable: Waitable) -> Result<()> { 1878 let state = self.concurrent_state_mut(); 1879 let caller = state.current_guest_thread()?; 1880 let old_set = waitable.common(state)?.set; 1881 let set = state.get_mut(caller.thread)?.sync_call_set; 1882 waitable.join(state, Some(set))?; 1883 self.suspend(SuspendReason::Waiting { 1884 set, 1885 thread: caller, 1886 skip_may_block_check: false, 1887 })?; 1888 let state = self.concurrent_state_mut(); 1889 waitable.join(state, old_set) 1890 } 1891 } 1892 1893 impl Instance { 1894 /// Get the next pending event for the specified task and (optional) 1895 /// waitable set, along with the waitable handle if applicable. 1896 fn get_event( 1897 self, 1898 store: &mut StoreOpaque, 1899 guest_task: TableId<GuestTask>, 1900 set: Option<TableId<WaitableSet>>, 1901 cancellable: bool, 1902 ) -> Result<Option<(Event, Option<(Waitable, u32)>)>> { 1903 let state = store.concurrent_state_mut(); 1904 1905 let event = &mut state.get_mut(guest_task)?.event; 1906 if let Some(ev) = event 1907 && (cancellable || !matches!(ev, Event::Cancelled)) 1908 { 1909 log::trace!("deliver event {ev:?} to {guest_task:?}"); 1910 let ev = *ev; 1911 *event = None; 1912 return Ok(Some((ev, None))); 1913 } 1914 1915 let set = match set { 1916 Some(set) => set, 1917 None => return Ok(None), 1918 }; 1919 let waitable = match state.get_mut(set)?.ready.pop_first() { 1920 Some(v) => v, 1921 None => return Ok(None), 1922 }; 1923 1924 let common = waitable.common(state)?; 1925 let handle = match common.handle { 1926 Some(h) => h, 1927 None => bail_bug!("handle not set when delivering event"), 1928 }; 1929 let event = match common.event.take() { 1930 Some(e) => e, 1931 None => bail_bug!("event not set when delivering event"), 1932 }; 1933 1934 log::trace!( 1935 "deliver event {event:?} to {guest_task:?} for {waitable:?} (handle {handle}); set {set:?}" 1936 ); 1937 1938 waitable.on_delivery(store, self, event)?; 1939 1940 Ok(Some((event, Some((waitable, handle))))) 1941 } 1942 1943 /// Handle the `CallbackCode` returned from an async-lifted export or its 1944 /// callback. 1945 /// 1946 /// If this returns `Ok(Some(call))`, then `call` should be run immediately 1947 /// using `handle_guest_call`. 1948 fn handle_callback_code( 1949 self, 1950 store: &mut StoreOpaque, 1951 guest_thread: QualifiedThreadId, 1952 runtime_instance: RuntimeComponentInstanceIndex, 1953 code: u32, 1954 ) -> Result<Option<GuestCall>> { 1955 let (code, set) = unpack_callback_code(code); 1956 1957 log::trace!("received callback code from {guest_thread:?}: {code} (set: {set})"); 1958 1959 let state = store.concurrent_state_mut(); 1960 1961 let get_set = |store: &mut StoreOpaque, handle| -> Result<_> { 1962 let set = store 1963 .instance_state(RuntimeInstance { 1964 instance: self.id().instance(), 1965 index: runtime_instance, 1966 }) 1967 .handle_table() 1968 .waitable_set_rep(handle)?; 1969 1970 Ok(TableId::<WaitableSet>::new(set)) 1971 }; 1972 1973 Ok(match code { 1974 callback_code::EXIT => { 1975 log::trace!("implicit thread {guest_thread:?} completed"); 1976 self.cleanup_thread(store, guest_thread, runtime_instance)?; 1977 let task = store.concurrent_state_mut().get_mut(guest_thread.task)?; 1978 if task.threads.is_empty() && !task.returned_or_cancelled() { 1979 bail!(Trap::NoAsyncResult); 1980 } 1981 if let Caller::Guest { .. } = task.caller { 1982 task.exited = true; 1983 task.callback = None; 1984 } 1985 if task.ready_to_delete() { 1986 Waitable::Guest(guest_thread.task).delete_from(store.concurrent_state_mut())?; 1987 } 1988 None 1989 } 1990 callback_code::YIELD => { 1991 let task = state.get_mut(guest_thread.task)?; 1992 // If an `Event::Cancelled` is pending, we'll deliver that; 1993 // otherwise, we'll deliver `Event::None`. Note that 1994 // `GuestTask::event` is only ever set to one of those two 1995 // `Event` variants. 1996 if let Some(event) = task.event { 1997 assert!(matches!(event, Event::None | Event::Cancelled)); 1998 } else { 1999 task.event = Some(Event::None); 2000 } 2001 let call = GuestCall { 2002 thread: guest_thread, 2003 kind: GuestCallKind::DeliverEvent { 2004 instance: self, 2005 set: None, 2006 }, 2007 }; 2008 if state.may_block(guest_thread.task)? { 2009 // Push this thread onto the "low priority" queue so it runs 2010 // after any other threads have had a chance to run. 2011 state.push_low_priority(WorkItem::GuestCall(runtime_instance, call)); 2012 None 2013 } else { 2014 // Yielding in a non-blocking context is defined as a no-op 2015 // according to the spec, so we must run this thread 2016 // immediately without allowing any others to run. 2017 Some(call) 2018 } 2019 } 2020 callback_code::WAIT => { 2021 // The task may only return `WAIT` if it was created for a call 2022 // to an async export). Otherwise, we'll trap. 2023 state.check_blocking_for(guest_thread.task)?; 2024 2025 let set = get_set(store, set)?; 2026 let state = store.concurrent_state_mut(); 2027 2028 if state.get_mut(guest_thread.task)?.event.is_some() 2029 || !state.get_mut(set)?.ready.is_empty() 2030 { 2031 // An event is immediately available; deliver it ASAP. 2032 state.push_high_priority(WorkItem::GuestCall( 2033 runtime_instance, 2034 GuestCall { 2035 thread: guest_thread, 2036 kind: GuestCallKind::DeliverEvent { 2037 instance: self, 2038 set: Some(set), 2039 }, 2040 }, 2041 )); 2042 } else { 2043 // No event is immediately available. 2044 // 2045 // We're waiting, so register to be woken up when an event 2046 // is published for this waitable set. 2047 // 2048 // Here we also set `GuestTask::wake_on_cancel` which allows 2049 // `subtask.cancel` to interrupt the wait. 2050 let old = state 2051 .get_mut(guest_thread.thread)? 2052 .wake_on_cancel 2053 .replace(set); 2054 if !old.is_none() { 2055 bail_bug!("thread unexpectedly had wake_on_cancel set"); 2056 } 2057 let old = state 2058 .get_mut(set)? 2059 .waiting 2060 .insert(guest_thread, WaitMode::Callback(self)); 2061 if !old.is_none() { 2062 bail_bug!("set's waiting set already had this thread registered"); 2063 } 2064 } 2065 None 2066 } 2067 _ => bail!(Trap::UnsupportedCallbackCode), 2068 }) 2069 } 2070 2071 fn cleanup_thread( 2072 self, 2073 store: &mut StoreOpaque, 2074 guest_thread: QualifiedThreadId, 2075 runtime_instance: RuntimeComponentInstanceIndex, 2076 ) -> Result<()> { 2077 let state = store.concurrent_state_mut(); 2078 let thread_data = state.get_mut(guest_thread.thread)?; 2079 let guest_id = match thread_data.instance_rep { 2080 Some(id) => id, 2081 None => bail_bug!("thread must have instance_rep set by now"), 2082 }; 2083 let sync_call_set = thread_data.sync_call_set; 2084 2085 // Clean up any pending subtasks in the sync_call_set 2086 for waitable in mem::take(&mut state.get_mut(sync_call_set)?.ready) { 2087 if let Some(Event::Subtask { 2088 status: Status::Returned | Status::ReturnCancelled, 2089 }) = waitable.common(state)?.event 2090 { 2091 waitable.delete_from(state)?; 2092 } 2093 } 2094 2095 store 2096 .instance_state(RuntimeInstance { 2097 instance: self.id().instance(), 2098 index: runtime_instance, 2099 }) 2100 .thread_handle_table() 2101 .guest_thread_remove(guest_id)?; 2102 2103 store.concurrent_state_mut().delete(guest_thread.thread)?; 2104 store.concurrent_state_mut().delete(sync_call_set)?; 2105 let task = store.concurrent_state_mut().get_mut(guest_thread.task)?; 2106 task.threads.remove(&guest_thread.thread); 2107 Ok(()) 2108 } 2109 2110 /// Add the specified guest call to the "high priority" work item queue, to 2111 /// be started as soon as backpressure and/or reentrance rules allow. 2112 /// 2113 /// SAFETY: The raw pointer arguments must be valid references to guest 2114 /// functions (with the appropriate signatures) when the closures queued by 2115 /// this function are called. 2116 unsafe fn queue_call<T: 'static>( 2117 self, 2118 mut store: StoreContextMut<T>, 2119 guest_thread: QualifiedThreadId, 2120 callee: SendSyncPtr<VMFuncRef>, 2121 param_count: usize, 2122 result_count: usize, 2123 async_: bool, 2124 callback: Option<SendSyncPtr<VMFuncRef>>, 2125 post_return: Option<SendSyncPtr<VMFuncRef>>, 2126 ) -> Result<()> { 2127 /// Return a closure which will call the specified function in the scope 2128 /// of the specified task. 2129 /// 2130 /// This will use `GuestTask::lower_params` to lower the parameters, but 2131 /// will not lift the result; instead, it returns a 2132 /// `[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]` from which the result, if 2133 /// any, may be lifted. Note that an async-lifted export will have 2134 /// returned its result using the `task.return` intrinsic (or not 2135 /// returned a result at all, in the case of `task.cancel`), in which 2136 /// case the "result" of this call will either be a callback code or 2137 /// nothing. 2138 /// 2139 /// SAFETY: `callee` must be a valid `*mut VMFuncRef` at the time when 2140 /// the returned closure is called. 2141 unsafe fn make_call<T: 'static>( 2142 store: StoreContextMut<T>, 2143 guest_thread: QualifiedThreadId, 2144 callee: SendSyncPtr<VMFuncRef>, 2145 param_count: usize, 2146 result_count: usize, 2147 ) -> impl FnOnce(&mut dyn VMStore) -> Result<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]> 2148 + Send 2149 + Sync 2150 + 'static 2151 + use<T> { 2152 let token = StoreToken::new(store); 2153 move |store: &mut dyn VMStore| { 2154 let mut storage = [MaybeUninit::uninit(); MAX_FLAT_PARAMS]; 2155 2156 store 2157 .concurrent_state_mut() 2158 .get_mut(guest_thread.thread)? 2159 .state = GuestThreadState::Running; 2160 let task = store.concurrent_state_mut().get_mut(guest_thread.task)?; 2161 let lower = match task.lower_params.take() { 2162 Some(l) => l, 2163 None => bail_bug!("lower_params missing"), 2164 }; 2165 2166 lower(store, &mut storage[..param_count])?; 2167 2168 let mut store = token.as_context_mut(store); 2169 2170 // SAFETY: Per the contract documented in `make_call's` 2171 // documentation, `callee` must be a valid pointer. 2172 unsafe { 2173 crate::Func::call_unchecked_raw( 2174 &mut store, 2175 callee.as_non_null(), 2176 NonNull::new( 2177 &mut storage[..param_count.max(result_count)] 2178 as *mut [MaybeUninit<ValRaw>] as _, 2179 ) 2180 .unwrap(), 2181 )?; 2182 } 2183 2184 Ok(storage) 2185 } 2186 } 2187 2188 // SAFETY: Per the contract described in this function documentation, 2189 // the `callee` pointer which `call` closes over must be valid when 2190 // called by the closure we queue below. 2191 let call = unsafe { 2192 make_call( 2193 store.as_context_mut(), 2194 guest_thread, 2195 callee, 2196 param_count, 2197 result_count, 2198 ) 2199 }; 2200 2201 let callee_instance = store 2202 .0 2203 .concurrent_state_mut() 2204 .get_mut(guest_thread.task)? 2205 .instance; 2206 2207 let fun = if callback.is_some() { 2208 assert!(async_); 2209 2210 Box::new(move |store: &mut dyn VMStore| { 2211 self.add_guest_thread_to_instance_table( 2212 guest_thread.thread, 2213 store, 2214 callee_instance.index, 2215 )?; 2216 let old_thread = store.set_thread(guest_thread)?; 2217 log::trace!( 2218 "stackless call: replaced {old_thread:?} with {guest_thread:?} as current thread" 2219 ); 2220 2221 store.enter_instance(callee_instance); 2222 2223 // SAFETY: See the documentation for `make_call` to review the 2224 // contract we must uphold for `call` here. 2225 // 2226 // Per the contract described in the `queue_call` 2227 // documentation, the `callee` pointer which `call` closes 2228 // over must be valid. 2229 let storage = call(store)?; 2230 2231 store.exit_instance(callee_instance)?; 2232 2233 store.set_thread(old_thread)?; 2234 let state = store.concurrent_state_mut(); 2235 if let Some(t) = old_thread.guest() { 2236 state.get_mut(t.thread)?.state = GuestThreadState::Running; 2237 } 2238 log::trace!("stackless call: restored {old_thread:?} as current thread"); 2239 2240 // SAFETY: `wasmparser` will have validated that the callback 2241 // function returns a `i32` result. 2242 let code = unsafe { storage[0].assume_init() }.get_i32() as u32; 2243 2244 self.handle_callback_code(store, guest_thread, callee_instance.index, code) 2245 }) 2246 as Box<dyn FnOnce(&mut dyn VMStore) -> Result<Option<GuestCall>> + Send + Sync> 2247 } else { 2248 let token = StoreToken::new(store.as_context_mut()); 2249 Box::new(move |store: &mut dyn VMStore| { 2250 self.add_guest_thread_to_instance_table( 2251 guest_thread.thread, 2252 store, 2253 callee_instance.index, 2254 )?; 2255 let old_thread = store.set_thread(guest_thread)?; 2256 log::trace!( 2257 "sync/async-stackful call: replaced {old_thread:?} with {guest_thread:?} as current thread", 2258 ); 2259 let flags = self.id().get(store).instance_flags(callee_instance.index); 2260 2261 // Unless this is a callback-less (i.e. stackful) 2262 // async-lifted export, we need to record that the instance 2263 // cannot be entered until the call returns. 2264 if !async_ { 2265 store.enter_instance(callee_instance); 2266 } 2267 2268 // SAFETY: See the documentation for `make_call` to review the 2269 // contract we must uphold for `call` here. 2270 // 2271 // Per the contract described in the `queue_call` 2272 // documentation, the `callee` pointer which `call` closes 2273 // over must be valid. 2274 let storage = call(store)?; 2275 2276 if async_ { 2277 let task = store.concurrent_state_mut().get_mut(guest_thread.task)?; 2278 if task.threads.len() == 1 && !task.returned_or_cancelled() { 2279 bail!(Trap::NoAsyncResult); 2280 } 2281 } else { 2282 // This is a sync-lifted export, so now is when we lift the 2283 // result, optionally call the post-return function, if any, 2284 // and finally notify any current or future waiters that the 2285 // subtask has returned. 2286 2287 let lift = { 2288 store.exit_instance(callee_instance)?; 2289 2290 let state = store.concurrent_state_mut(); 2291 if !state.get_mut(guest_thread.task)?.result.is_none() { 2292 bail_bug!("task has not yet produced a result"); 2293 } 2294 2295 match state.get_mut(guest_thread.task)?.lift_result.take() { 2296 Some(lift) => lift, 2297 None => bail_bug!("lift_result field is missing"), 2298 } 2299 }; 2300 2301 // SAFETY: `result_count` represents the number of core Wasm 2302 // results returned, per `wasmparser`. 2303 let result = (lift.lift)(store, unsafe { 2304 mem::transmute::<&[MaybeUninit<ValRaw>], &[ValRaw]>( 2305 &storage[..result_count], 2306 ) 2307 })?; 2308 2309 let post_return_arg = match result_count { 2310 0 => ValRaw::i32(0), 2311 // SAFETY: `result_count` represents the number of 2312 // core Wasm results returned, per `wasmparser`. 2313 1 => unsafe { storage[0].assume_init() }, 2314 _ => unreachable!(), 2315 }; 2316 2317 unsafe { 2318 call_post_return( 2319 token.as_context_mut(store), 2320 post_return.map(|v| v.as_non_null()), 2321 post_return_arg, 2322 flags, 2323 )?; 2324 } 2325 2326 self.task_complete(store, guest_thread.task, result, Status::Returned)?; 2327 } 2328 2329 // This is a callback-less call, so the implicit thread has now completed 2330 self.cleanup_thread(store, guest_thread, callee_instance.index)?; 2331 2332 store.set_thread(old_thread)?; 2333 2334 let state = store.concurrent_state_mut(); 2335 let task = state.get_mut(guest_thread.task)?; 2336 2337 match &task.caller { 2338 Caller::Host { .. } => { 2339 if task.ready_to_delete() { 2340 Waitable::Guest(guest_thread.task).delete_from(state)?; 2341 } 2342 } 2343 Caller::Guest { .. } => { 2344 task.exited = true; 2345 } 2346 } 2347 2348 Ok(None) 2349 }) 2350 }; 2351 2352 store 2353 .0 2354 .concurrent_state_mut() 2355 .push_high_priority(WorkItem::GuestCall( 2356 callee_instance.index, 2357 GuestCall { 2358 thread: guest_thread, 2359 kind: GuestCallKind::StartImplicit(fun), 2360 }, 2361 )); 2362 2363 Ok(()) 2364 } 2365 2366 /// Prepare (but do not start) a guest->guest call. 2367 /// 2368 /// This is called from fused adapter code generated in 2369 /// `wasmtime_environ::fact::trampoline::Compiler`. `start` and `return_` 2370 /// are synthesized Wasm functions which move the parameters from the caller 2371 /// to the callee and the result from the callee to the caller, 2372 /// respectively. The adapter will call `Self::start_call` immediately 2373 /// after calling this function. 2374 /// 2375 /// SAFETY: All the pointer arguments must be valid pointers to guest 2376 /// entities (and with the expected signatures for the function references 2377 /// -- see `wasmtime_environ::fact::trampoline::Compiler` for details). 2378 unsafe fn prepare_call<T: 'static>( 2379 self, 2380 mut store: StoreContextMut<T>, 2381 start: NonNull<VMFuncRef>, 2382 return_: NonNull<VMFuncRef>, 2383 caller_instance: RuntimeComponentInstanceIndex, 2384 callee_instance: RuntimeComponentInstanceIndex, 2385 task_return_type: TypeTupleIndex, 2386 callee_async: bool, 2387 memory: *mut VMMemoryDefinition, 2388 string_encoding: StringEncoding, 2389 caller_info: CallerInfo, 2390 ) -> Result<()> { 2391 if let (CallerInfo::Sync { .. }, true) = (&caller_info, callee_async) { 2392 // A task may only call an async-typed function via a sync lower if 2393 // it was created by a call to an async export. Otherwise, we'll 2394 // trap. 2395 store.0.check_blocking()?; 2396 } 2397 2398 enum ResultInfo { 2399 Heap { results: u32 }, 2400 Stack { result_count: u32 }, 2401 } 2402 2403 let result_info = match &caller_info { 2404 CallerInfo::Async { 2405 has_result: true, 2406 params, 2407 } => ResultInfo::Heap { 2408 results: match params.last() { 2409 Some(r) => r.get_u32(), 2410 None => bail_bug!("retptr missing"), 2411 }, 2412 }, 2413 CallerInfo::Async { 2414 has_result: false, .. 2415 } => ResultInfo::Stack { result_count: 0 }, 2416 CallerInfo::Sync { 2417 result_count, 2418 params, 2419 } if *result_count > u32::try_from(MAX_FLAT_RESULTS)? => ResultInfo::Heap { 2420 results: match params.last() { 2421 Some(r) => r.get_u32(), 2422 None => bail_bug!("arg ptr missing"), 2423 }, 2424 }, 2425 CallerInfo::Sync { result_count, .. } => ResultInfo::Stack { 2426 result_count: *result_count, 2427 }, 2428 }; 2429 2430 let sync_caller = matches!(caller_info, CallerInfo::Sync { .. }); 2431 2432 // Create a new guest task for the call, closing over the `start` and 2433 // `return_` functions to lift the parameters and lower the result, 2434 // respectively. 2435 let start = SendSyncPtr::new(start); 2436 let return_ = SendSyncPtr::new(return_); 2437 let token = StoreToken::new(store.as_context_mut()); 2438 let state = store.0.concurrent_state_mut(); 2439 let old_thread = state.current_guest_thread()?; 2440 2441 debug_assert_eq!( 2442 state.get_mut(old_thread.task)?.instance, 2443 RuntimeInstance { 2444 instance: self.id().instance(), 2445 index: caller_instance, 2446 } 2447 ); 2448 2449 let new_task = GuestTask::new( 2450 Box::new(move |store, dst| { 2451 let mut store = token.as_context_mut(store); 2452 assert!(dst.len() <= MAX_FLAT_PARAMS); 2453 // The `+ 1` here accounts for the return pointer, if any: 2454 let mut src = [MaybeUninit::uninit(); MAX_FLAT_PARAMS + 1]; 2455 let count = match caller_info { 2456 // Async callers, if they have a result, use the last 2457 // parameter as a return pointer so chop that off if 2458 // relevant here. 2459 CallerInfo::Async { params, has_result } => { 2460 let params = ¶ms[..params.len() - usize::from(has_result)]; 2461 for (param, src) in params.iter().zip(&mut src) { 2462 src.write(*param); 2463 } 2464 params.len() 2465 } 2466 2467 // Sync callers forward everything directly. 2468 CallerInfo::Sync { params, .. } => { 2469 for (param, src) in params.iter().zip(&mut src) { 2470 src.write(*param); 2471 } 2472 params.len() 2473 } 2474 }; 2475 // SAFETY: `start` is a valid `*mut VMFuncRef` from 2476 // `wasmtime-cranelift`-generated fused adapter code. Based on 2477 // how it was constructed (see 2478 // `wasmtime_environ::fact::trampoline::Compiler::compile_async_start_adapter` 2479 // for details) we know it takes count parameters and returns 2480 // `dst.len()` results. 2481 unsafe { 2482 crate::Func::call_unchecked_raw( 2483 &mut store, 2484 start.as_non_null(), 2485 NonNull::new( 2486 &mut src[..count.max(dst.len())] as *mut [MaybeUninit<ValRaw>] as _, 2487 ) 2488 .unwrap(), 2489 )?; 2490 } 2491 dst.copy_from_slice(&src[..dst.len()]); 2492 let state = store.0.concurrent_state_mut(); 2493 Waitable::Guest(state.current_guest_thread()?.task).set_event( 2494 state, 2495 Some(Event::Subtask { 2496 status: Status::Started, 2497 }), 2498 )?; 2499 Ok(()) 2500 }), 2501 LiftResult { 2502 lift: Box::new(move |store, src| { 2503 // SAFETY: See comment in closure passed as `lower_params` 2504 // parameter above. 2505 let mut store = token.as_context_mut(store); 2506 let mut my_src = src.to_owned(); // TODO: use stack to avoid allocation? 2507 if let ResultInfo::Heap { results } = &result_info { 2508 my_src.push(ValRaw::u32(*results)); 2509 } 2510 // SAFETY: `return_` is a valid `*mut VMFuncRef` from 2511 // `wasmtime-cranelift`-generated fused adapter code. Based 2512 // on how it was constructed (see 2513 // `wasmtime_environ::fact::trampoline::Compiler::compile_async_return_adapter` 2514 // for details) we know it takes `src.len()` parameters and 2515 // returns up to 1 result. 2516 unsafe { 2517 crate::Func::call_unchecked_raw( 2518 &mut store, 2519 return_.as_non_null(), 2520 my_src.as_mut_slice().into(), 2521 )?; 2522 } 2523 let state = store.0.concurrent_state_mut(); 2524 let thread = state.current_guest_thread()?; 2525 if sync_caller { 2526 state.get_mut(thread.task)?.sync_result = SyncResult::Produced( 2527 if let ResultInfo::Stack { result_count } = &result_info { 2528 match result_count { 2529 0 => None, 2530 1 => Some(my_src[0]), 2531 _ => unreachable!(), 2532 } 2533 } else { 2534 None 2535 }, 2536 ); 2537 } 2538 Ok(Box::new(DummyResult) as Box<dyn Any + Send + Sync>) 2539 }), 2540 ty: task_return_type, 2541 memory: NonNull::new(memory).map(SendSyncPtr::new), 2542 string_encoding, 2543 }, 2544 Caller::Guest { thread: old_thread }, 2545 None, 2546 RuntimeInstance { 2547 instance: self.id().instance(), 2548 index: callee_instance, 2549 }, 2550 callee_async, 2551 )?; 2552 2553 let guest_task = state.push(new_task)?; 2554 let new_thread = GuestThread::new_implicit(state, guest_task)?; 2555 let guest_thread = state.push(new_thread)?; 2556 state.get_mut(guest_task)?.threads.insert(guest_thread); 2557 2558 // Make the new thread the current one so that `Self::start_call` knows 2559 // which one to start. 2560 store.0.set_thread(QualifiedThreadId { 2561 task: guest_task, 2562 thread: guest_thread, 2563 })?; 2564 log::trace!( 2565 "pushed {guest_task:?}:{guest_thread:?} as current thread; old thread was {old_thread:?}" 2566 ); 2567 2568 Ok(()) 2569 } 2570 2571 /// Call the specified callback function for an async-lifted export. 2572 /// 2573 /// SAFETY: `function` must be a valid reference to a guest function of the 2574 /// correct signature for a callback. 2575 unsafe fn call_callback<T>( 2576 self, 2577 mut store: StoreContextMut<T>, 2578 function: SendSyncPtr<VMFuncRef>, 2579 event: Event, 2580 handle: u32, 2581 ) -> Result<u32> { 2582 let (ordinal, result) = event.parts(); 2583 let params = &mut [ 2584 ValRaw::u32(ordinal), 2585 ValRaw::u32(handle), 2586 ValRaw::u32(result), 2587 ]; 2588 // SAFETY: `func` is a valid `*mut VMFuncRef` from either 2589 // `wasmtime-cranelift`-generated fused adapter code or 2590 // `component::Options`. Per `wasmparser` callback signature 2591 // validation, we know it takes three parameters and returns one. 2592 unsafe { 2593 crate::Func::call_unchecked_raw( 2594 &mut store, 2595 function.as_non_null(), 2596 params.as_mut_slice().into(), 2597 )?; 2598 } 2599 Ok(params[0].get_u32()) 2600 } 2601 2602 /// Start a guest->guest call previously prepared using 2603 /// `Self::prepare_call`. 2604 /// 2605 /// This is called from fused adapter code generated in 2606 /// `wasmtime_environ::fact::trampoline::Compiler`. The adapter will call 2607 /// this function immediately after calling `Self::prepare_call`. 2608 /// 2609 /// SAFETY: The `*mut VMFuncRef` arguments must be valid pointers to guest 2610 /// functions with the appropriate signatures for the current guest task. 2611 /// If this is a call to an async-lowered import, the actual call may be 2612 /// deferred and run after this function returns, in which case the pointer 2613 /// arguments must also be valid when the call happens. 2614 unsafe fn start_call<T: 'static>( 2615 self, 2616 mut store: StoreContextMut<T>, 2617 callback: *mut VMFuncRef, 2618 post_return: *mut VMFuncRef, 2619 callee: NonNull<VMFuncRef>, 2620 param_count: u32, 2621 result_count: u32, 2622 flags: u32, 2623 storage: Option<&mut [MaybeUninit<ValRaw>]>, 2624 ) -> Result<u32> { 2625 let token = StoreToken::new(store.as_context_mut()); 2626 let async_caller = storage.is_none(); 2627 let state = store.0.concurrent_state_mut(); 2628 let guest_thread = state.current_guest_thread()?; 2629 let callee_async = state.get_mut(guest_thread.task)?.async_function; 2630 let callee = SendSyncPtr::new(callee); 2631 let param_count = usize::try_from(param_count)?; 2632 assert!(param_count <= MAX_FLAT_PARAMS); 2633 let result_count = usize::try_from(result_count)?; 2634 assert!(result_count <= MAX_FLAT_RESULTS); 2635 2636 let task = state.get_mut(guest_thread.task)?; 2637 if let Some(callback) = NonNull::new(callback) { 2638 // We're calling an async-lifted export with a callback, so store 2639 // the callback and related context as part of the task so we can 2640 // call it later when needed. 2641 let callback = SendSyncPtr::new(callback); 2642 task.callback = Some(Box::new(move |store, event, handle| { 2643 let store = token.as_context_mut(store); 2644 unsafe { self.call_callback::<T>(store, callback, event, handle) } 2645 })); 2646 } 2647 2648 let Caller::Guest { thread: caller } = &task.caller else { 2649 // As of this writing, `start_call` is only used for guest->guest 2650 // calls. 2651 bail_bug!("start_call unexpectedly invoked for host->guest call"); 2652 }; 2653 let caller = *caller; 2654 let caller_instance = state.get_mut(caller.task)?.instance; 2655 2656 // Queue the call as a "high priority" work item. 2657 unsafe { 2658 self.queue_call( 2659 store.as_context_mut(), 2660 guest_thread, 2661 callee, 2662 param_count, 2663 result_count, 2664 (flags & START_FLAG_ASYNC_CALLEE) != 0, 2665 NonNull::new(callback).map(SendSyncPtr::new), 2666 NonNull::new(post_return).map(SendSyncPtr::new), 2667 )?; 2668 } 2669 2670 let state = store.0.concurrent_state_mut(); 2671 2672 // Use the caller's `GuestThread::sync_call_set` to register interest in 2673 // the subtask... 2674 let guest_waitable = Waitable::Guest(guest_thread.task); 2675 let old_set = guest_waitable.common(state)?.set; 2676 let set = state.get_mut(caller.thread)?.sync_call_set; 2677 guest_waitable.join(state, Some(set))?; 2678 2679 // ... and suspend this fiber temporarily while we wait for it to start. 2680 // 2681 // Note that we _could_ call the callee directly using the current fiber 2682 // rather than suspend this one, but that would make reasoning about the 2683 // event loop more complicated and is probably only worth doing if 2684 // there's a measurable performance benefit. In addition, it would mean 2685 // blocking the caller if the callee calls a blocking sync-lowered 2686 // import, and as of this writing the spec says we must not do that. 2687 // 2688 // Alternatively, the fused adapter code could be modified to call the 2689 // callee directly without calling a host-provided intrinsic at all (in 2690 // which case it would need to do its own, inline backpressure checks, 2691 // etc.). Again, we'd want to see a measurable performance benefit 2692 // before committing to such an optimization. And again, we'd need to 2693 // update the spec to allow that. 2694 let (status, waitable) = loop { 2695 store.0.suspend(SuspendReason::Waiting { 2696 set, 2697 thread: caller, 2698 // Normally, `StoreOpaque::suspend` would assert it's being 2699 // called from a context where blocking is allowed. However, if 2700 // `async_caller` is `true`, we'll only "block" long enough for 2701 // the callee to start, i.e. we won't repeat this loop, so we 2702 // tell `suspend` it's okay even if we're not allowed to block. 2703 // Alternatively, if the callee is not an async function, then 2704 // we know it won't block anyway. 2705 skip_may_block_check: async_caller || !callee_async, 2706 })?; 2707 2708 let state = store.0.concurrent_state_mut(); 2709 2710 log::trace!("taking event for {:?}", guest_thread.task); 2711 let event = guest_waitable.take_event(state)?; 2712 let Some(Event::Subtask { status }) = event else { 2713 bail_bug!("subtasks should only get subtask events, got {event:?}") 2714 }; 2715 2716 log::trace!("status {status:?} for {:?}", guest_thread.task); 2717 2718 if status == Status::Returned { 2719 // It returned, so we can stop waiting. 2720 break (status, None); 2721 } else if async_caller { 2722 // It hasn't returned yet, but the caller is calling via an 2723 // async-lowered import, so we generate a handle for the task 2724 // waitable and return the status. 2725 let handle = store 2726 .0 2727 .instance_state(caller_instance) 2728 .handle_table() 2729 .subtask_insert_guest(guest_thread.task.rep())?; 2730 store 2731 .0 2732 .concurrent_state_mut() 2733 .get_mut(guest_thread.task)? 2734 .common 2735 .handle = Some(handle); 2736 break (status, Some(handle)); 2737 } else { 2738 // The callee hasn't returned yet, and the caller is calling via 2739 // a sync-lowered import, so we loop and keep waiting until the 2740 // callee returns. 2741 } 2742 }; 2743 2744 guest_waitable.join(store.0.concurrent_state_mut(), old_set)?; 2745 2746 // Reset the current thread to point to the caller as it resumes control. 2747 store.0.set_thread(caller)?; 2748 store.0.concurrent_state_mut().get_mut(caller.thread)?.state = GuestThreadState::Running; 2749 log::trace!("popped current thread {guest_thread:?}; new thread is {caller:?}"); 2750 2751 if let Some(storage) = storage { 2752 // The caller used a sync-lowered import to call an async-lifted 2753 // export, in which case the result, if any, has been stashed in 2754 // `GuestTask::sync_result`. 2755 let state = store.0.concurrent_state_mut(); 2756 let task = state.get_mut(guest_thread.task)?; 2757 if let Some(result) = task.sync_result.take()? { 2758 if let Some(result) = result { 2759 storage[0] = MaybeUninit::new(result); 2760 } 2761 2762 if task.exited && task.ready_to_delete() { 2763 Waitable::Guest(guest_thread.task).delete_from(state)?; 2764 } 2765 } 2766 } 2767 2768 Ok(status.pack(waitable)) 2769 } 2770 2771 /// Poll the specified future once on behalf of a guest->host call using an 2772 /// async-lowered import. 2773 /// 2774 /// If it returns `Ready`, return `Ok(None)`. Otherwise, if it returns 2775 /// `Pending`, add it to the set of futures to be polled as part of this 2776 /// instance's event loop until it completes, and then return 2777 /// `Ok(Some(handle))` where `handle` is the waitable handle to return. 2778 /// 2779 /// Whether the future returns `Ready` immediately or later, the `lower` 2780 /// function will be used to lower the result, if any, into the guest caller's 2781 /// stack and linear memory. The `lower` function is invoked with `None` if 2782 /// the future is cancelled. 2783 pub(crate) fn first_poll<T: 'static, R: Send + 'static>( 2784 self, 2785 mut store: StoreContextMut<'_, T>, 2786 future: impl Future<Output = Result<R>> + Send + 'static, 2787 lower: impl FnOnce(StoreContextMut<T>, Option<R>) -> Result<()> + Send + 'static, 2788 ) -> Result<Option<u32>> { 2789 let token = StoreToken::new(store.as_context_mut()); 2790 let state = store.0.concurrent_state_mut(); 2791 let task = state.current_host_thread()?; 2792 2793 // Create an abortable future which hooks calls to poll and manages call 2794 // context state for the future. 2795 let (join_handle, future) = JoinHandle::run(future); 2796 { 2797 let state = &mut state.get_mut(task)?.state; 2798 assert!(matches!(state, HostTaskState::CalleeStarted)); 2799 *state = HostTaskState::CalleeRunning(join_handle); 2800 } 2801 2802 let mut future = Box::pin(future); 2803 2804 // Finally, poll the future. We can use a dummy `Waker` here because 2805 // we'll add the future to `ConcurrentState::futures` and poll it 2806 // automatically from the event loop if it doesn't complete immediately 2807 // here. 2808 let poll = tls::set(store.0, || { 2809 future 2810 .as_mut() 2811 .poll(&mut Context::from_waker(&Waker::noop())) 2812 }); 2813 2814 match poll { 2815 // It finished immediately; lower the result and delete the task. 2816 Poll::Ready(result) => { 2817 let result = result.transpose()?; 2818 lower(store.as_context_mut(), result)?; 2819 return Ok(None); 2820 } 2821 2822 // Future isn't ready yet, so fall through. 2823 Poll::Pending => {} 2824 } 2825 2826 // It hasn't finished yet; add the future to 2827 // `ConcurrentState::futures` so it will be polled by the event 2828 // loop and allocate a waitable handle to return to the guest. 2829 2830 // Wrap the future in a closure responsible for lowering the result into 2831 // the guest's stack and memory, as well as notifying any waiters that 2832 // the task returned. 2833 let future = Box::pin(async move { 2834 let result = match future.await { 2835 Some(result) => Some(result?), 2836 None => None, 2837 }; 2838 let on_complete = move |store: &mut dyn VMStore| { 2839 // Restore the `current_thread` to be the host so `lower` knows 2840 // how to manipulate borrows and knows which scope of borrows 2841 // to check. 2842 let mut store = token.as_context_mut(store); 2843 let old = store.0.set_thread(task)?; 2844 2845 let status = if result.is_some() { 2846 Status::Returned 2847 } else { 2848 Status::ReturnCancelled 2849 }; 2850 2851 lower(store.as_context_mut(), result)?; 2852 let state = store.0.concurrent_state_mut(); 2853 state.get_mut(task)?.state = HostTaskState::CalleeDone; 2854 Waitable::Host(task).set_event(state, Some(Event::Subtask { status }))?; 2855 2856 store.0.set_thread(old)?; 2857 Ok(()) 2858 }; 2859 2860 // Here we schedule a task to run on a worker fiber to do the 2861 // lowering since it may involve a call to the guest's realloc 2862 // function. This is necessary because calling the guest while 2863 // there are host embedder frames on the stack is unsound. 2864 tls::get(move |store| { 2865 store 2866 .concurrent_state_mut() 2867 .push_high_priority(WorkItem::WorkerFunction(AlwaysMut::new(Box::new( 2868 on_complete, 2869 )))); 2870 Ok(()) 2871 }) 2872 }); 2873 2874 // Make this task visible to the guest and then record what it 2875 // was made visible as. 2876 let state = store.0.concurrent_state_mut(); 2877 state.push_future(future); 2878 let caller = state.get_mut(task)?.caller; 2879 let instance = state.get_mut(caller.task)?.instance; 2880 let handle = store 2881 .0 2882 .instance_state(instance) 2883 .handle_table() 2884 .subtask_insert_host(task.rep())?; 2885 store.0.concurrent_state_mut().get_mut(task)?.common.handle = Some(handle); 2886 log::trace!("assign {task:?} handle {handle} for {caller:?} instance {instance:?}"); 2887 2888 // Restore the currently running thread to this host task's 2889 // caller. Note that the host task isn't deallocated as it's 2890 // within the store and will get deallocated later. 2891 store.0.set_thread(caller)?; 2892 Ok(Some(handle)) 2893 } 2894 2895 /// Implements the `task.return` intrinsic, lifting the result for the 2896 /// current guest task. 2897 pub(crate) fn task_return( 2898 self, 2899 store: &mut dyn VMStore, 2900 ty: TypeTupleIndex, 2901 options: OptionsIndex, 2902 storage: &[ValRaw], 2903 ) -> Result<()> { 2904 let state = store.concurrent_state_mut(); 2905 let guest_thread = state.current_guest_thread()?; 2906 let lift = state 2907 .get_mut(guest_thread.task)? 2908 .lift_result 2909 .take() 2910 .ok_or_else(|| Trap::TaskCancelOrReturnTwice)?; 2911 if !state.get_mut(guest_thread.task)?.result.is_none() { 2912 bail_bug!("task result unexpectedly already set"); 2913 } 2914 2915 let CanonicalOptions { 2916 string_encoding, 2917 data_model, 2918 .. 2919 } = &self.id().get(store).component().env_component().options[options]; 2920 2921 let invalid = ty != lift.ty 2922 || string_encoding != &lift.string_encoding 2923 || match data_model { 2924 CanonicalOptionsDataModel::LinearMemory(opts) => match opts.memory { 2925 Some(memory) => { 2926 let expected = lift.memory.map(|v| v.as_ptr()).unwrap_or(ptr::null_mut()); 2927 let actual = self.id().get(store).runtime_memory(memory); 2928 expected != actual.as_ptr() 2929 } 2930 // Memory not specified, meaning it didn't need to be 2931 // specified per validation, so not invalid. 2932 None => false, 2933 }, 2934 // Always invalid as this isn't supported. 2935 CanonicalOptionsDataModel::Gc { .. } => true, 2936 }; 2937 2938 if invalid { 2939 bail!(Trap::TaskReturnInvalid); 2940 } 2941 2942 log::trace!("task.return for {guest_thread:?}"); 2943 2944 let result = (lift.lift)(store, storage)?; 2945 self.task_complete(store, guest_thread.task, result, Status::Returned) 2946 } 2947 2948 /// Implements the `task.cancel` intrinsic. 2949 pub(crate) fn task_cancel(self, store: &mut StoreOpaque) -> Result<()> { 2950 let state = store.concurrent_state_mut(); 2951 let guest_thread = state.current_guest_thread()?; 2952 let task = state.get_mut(guest_thread.task)?; 2953 if !task.cancel_sent { 2954 bail!(Trap::TaskCancelNotCancelled); 2955 } 2956 _ = task 2957 .lift_result 2958 .take() 2959 .ok_or_else(|| Trap::TaskCancelOrReturnTwice)?; 2960 2961 if !task.result.is_none() { 2962 bail_bug!("task result should not bet set yet"); 2963 } 2964 2965 log::trace!("task.cancel for {guest_thread:?}"); 2966 2967 self.task_complete( 2968 store, 2969 guest_thread.task, 2970 Box::new(DummyResult), 2971 Status::ReturnCancelled, 2972 ) 2973 } 2974 2975 /// Complete the specified guest task (i.e. indicate that it has either 2976 /// returned a (possibly empty) result or cancelled itself). 2977 /// 2978 /// This will return any resource borrows and notify any current or future 2979 /// waiters that the task has completed. 2980 fn task_complete( 2981 self, 2982 store: &mut StoreOpaque, 2983 guest_task: TableId<GuestTask>, 2984 result: Box<dyn Any + Send + Sync>, 2985 status: Status, 2986 ) -> Result<()> { 2987 store 2988 .component_resource_tables(Some(self)) 2989 .validate_scope_exit()?; 2990 2991 let state = store.concurrent_state_mut(); 2992 let task = state.get_mut(guest_task)?; 2993 2994 if let Caller::Host { tx, .. } = &mut task.caller { 2995 if let Some(tx) = tx.take() { 2996 _ = tx.send(result); 2997 } 2998 } else { 2999 task.result = Some(result); 3000 Waitable::Guest(guest_task).set_event(state, Some(Event::Subtask { status }))?; 3001 } 3002 3003 Ok(()) 3004 } 3005 3006 /// Implements the `waitable-set.new` intrinsic. 3007 pub(crate) fn waitable_set_new( 3008 self, 3009 store: &mut StoreOpaque, 3010 caller_instance: RuntimeComponentInstanceIndex, 3011 ) -> Result<u32> { 3012 let set = store.concurrent_state_mut().push(WaitableSet::default())?; 3013 let handle = store 3014 .instance_state(RuntimeInstance { 3015 instance: self.id().instance(), 3016 index: caller_instance, 3017 }) 3018 .handle_table() 3019 .waitable_set_insert(set.rep())?; 3020 log::trace!("new waitable set {set:?} (handle {handle})"); 3021 Ok(handle) 3022 } 3023 3024 /// Implements the `waitable-set.drop` intrinsic. 3025 pub(crate) fn waitable_set_drop( 3026 self, 3027 store: &mut StoreOpaque, 3028 caller_instance: RuntimeComponentInstanceIndex, 3029 set: u32, 3030 ) -> Result<()> { 3031 let rep = store 3032 .instance_state(RuntimeInstance { 3033 instance: self.id().instance(), 3034 index: caller_instance, 3035 }) 3036 .handle_table() 3037 .waitable_set_remove(set)?; 3038 3039 log::trace!("drop waitable set {rep} (handle {set})"); 3040 3041 let set = store 3042 .concurrent_state_mut() 3043 .delete(TableId::<WaitableSet>::new(rep))?; 3044 3045 if !set.waiting.is_empty() { 3046 bail!(Trap::WaitableSetDropHasWaiters); 3047 } 3048 3049 Ok(()) 3050 } 3051 3052 /// Implements the `waitable.join` intrinsic. 3053 pub(crate) fn waitable_join( 3054 self, 3055 store: &mut StoreOpaque, 3056 caller_instance: RuntimeComponentInstanceIndex, 3057 waitable_handle: u32, 3058 set_handle: u32, 3059 ) -> Result<()> { 3060 let mut instance = self.id().get_mut(store); 3061 let waitable = 3062 Waitable::from_instance(instance.as_mut(), caller_instance, waitable_handle)?; 3063 3064 let set = if set_handle == 0 { 3065 None 3066 } else { 3067 let set = instance.instance_states().0[caller_instance] 3068 .handle_table() 3069 .waitable_set_rep(set_handle)?; 3070 3071 Some(TableId::<WaitableSet>::new(set)) 3072 }; 3073 3074 log::trace!( 3075 "waitable {waitable:?} (handle {waitable_handle}) join set {set:?} (handle {set_handle})", 3076 ); 3077 3078 waitable.join(store.concurrent_state_mut(), set) 3079 } 3080 3081 /// Implements the `subtask.drop` intrinsic. 3082 pub(crate) fn subtask_drop( 3083 self, 3084 store: &mut StoreOpaque, 3085 caller_instance: RuntimeComponentInstanceIndex, 3086 task_id: u32, 3087 ) -> Result<()> { 3088 self.waitable_join(store, caller_instance, task_id, 0)?; 3089 3090 let (rep, is_host) = store 3091 .instance_state(RuntimeInstance { 3092 instance: self.id().instance(), 3093 index: caller_instance, 3094 }) 3095 .handle_table() 3096 .subtask_remove(task_id)?; 3097 3098 let concurrent_state = store.concurrent_state_mut(); 3099 let (waitable, expected_caller, delete) = if is_host { 3100 let id = TableId::<HostTask>::new(rep); 3101 let task = concurrent_state.get_mut(id)?; 3102 match &task.state { 3103 HostTaskState::CalleeRunning(_) => bail!(Trap::SubtaskDropNotResolved), 3104 HostTaskState::CalleeDone => {} 3105 HostTaskState::CalleeStarted | HostTaskState::CalleeFinished(_) => { 3106 bail_bug!("invalid state for callee in `subtask.drop`") 3107 } 3108 } 3109 (Waitable::Host(id), task.caller, true) 3110 } else { 3111 let id = TableId::<GuestTask>::new(rep); 3112 let task = concurrent_state.get_mut(id)?; 3113 if task.lift_result.is_some() { 3114 bail!(Trap::SubtaskDropNotResolved); 3115 } 3116 if let Caller::Guest { thread } = task.caller { 3117 ( 3118 Waitable::Guest(id), 3119 thread, 3120 concurrent_state.get_mut(id)?.exited, 3121 ) 3122 } else { 3123 bail_bug!("expected guest caller for `subtask.drop`") 3124 } 3125 }; 3126 3127 waitable.common(concurrent_state)?.handle = None; 3128 3129 // If this subtask has an event that means that the terminal status of 3130 // this subtask wasn't yet received so it can't be dropped yet. 3131 if waitable.take_event(concurrent_state)?.is_some() { 3132 bail!(Trap::SubtaskDropNotResolved); 3133 } 3134 3135 if delete { 3136 waitable.delete_from(concurrent_state)?; 3137 } 3138 3139 // Since waitables can neither be passed between instances nor forged, 3140 // this should never fail unless there's a bug in Wasmtime, but we check 3141 // here to be sure: 3142 debug_assert_eq!(expected_caller, concurrent_state.current_guest_thread()?); 3143 log::trace!("subtask_drop {waitable:?} (handle {task_id})"); 3144 Ok(()) 3145 } 3146 3147 /// Implements the `waitable-set.wait` intrinsic. 3148 pub(crate) fn waitable_set_wait( 3149 self, 3150 store: &mut StoreOpaque, 3151 options: OptionsIndex, 3152 set: u32, 3153 payload: u32, 3154 ) -> Result<u32> { 3155 if !self.options(store, options).async_ { 3156 // The caller may only call `waitable-set.wait` from an async task 3157 // (i.e. a task created via a call to an async export). 3158 // Otherwise, we'll trap. 3159 store.check_blocking()?; 3160 } 3161 3162 let &CanonicalOptions { 3163 cancellable, 3164 instance: caller_instance, 3165 .. 3166 } = &self.id().get(store).component().env_component().options[options]; 3167 let rep = store 3168 .instance_state(RuntimeInstance { 3169 instance: self.id().instance(), 3170 index: caller_instance, 3171 }) 3172 .handle_table() 3173 .waitable_set_rep(set)?; 3174 3175 self.waitable_check( 3176 store, 3177 cancellable, 3178 WaitableCheck::Wait, 3179 WaitableCheckParams { 3180 set: TableId::new(rep), 3181 options, 3182 payload, 3183 }, 3184 ) 3185 } 3186 3187 /// Implements the `waitable-set.poll` intrinsic. 3188 pub(crate) fn waitable_set_poll( 3189 self, 3190 store: &mut StoreOpaque, 3191 options: OptionsIndex, 3192 set: u32, 3193 payload: u32, 3194 ) -> Result<u32> { 3195 let &CanonicalOptions { 3196 cancellable, 3197 instance: caller_instance, 3198 .. 3199 } = &self.id().get(store).component().env_component().options[options]; 3200 let rep = store 3201 .instance_state(RuntimeInstance { 3202 instance: self.id().instance(), 3203 index: caller_instance, 3204 }) 3205 .handle_table() 3206 .waitable_set_rep(set)?; 3207 3208 self.waitable_check( 3209 store, 3210 cancellable, 3211 WaitableCheck::Poll, 3212 WaitableCheckParams { 3213 set: TableId::new(rep), 3214 options, 3215 payload, 3216 }, 3217 ) 3218 } 3219 3220 /// Implements the `thread.index` intrinsic. 3221 pub(crate) fn thread_index(&self, store: &mut dyn VMStore) -> Result<u32> { 3222 let thread_id = store.concurrent_state_mut().current_guest_thread()?.thread; 3223 match store 3224 .concurrent_state_mut() 3225 .get_mut(thread_id)? 3226 .instance_rep 3227 { 3228 Some(r) => Ok(r), 3229 None => bail_bug!("thread should have instance_rep by now"), 3230 } 3231 } 3232 3233 /// Implements the `thread.new-indirect` intrinsic. 3234 pub(crate) fn thread_new_indirect<T: 'static>( 3235 self, 3236 mut store: StoreContextMut<T>, 3237 runtime_instance: RuntimeComponentInstanceIndex, 3238 _func_ty_idx: TypeFuncIndex, // currently unused 3239 start_func_table_idx: RuntimeTableIndex, 3240 start_func_idx: u32, 3241 context: i32, 3242 ) -> Result<u32> { 3243 log::trace!("creating new thread"); 3244 3245 let start_func_ty = FuncType::new(store.engine(), [ValType::I32], []); 3246 let (instance, registry) = self.id().get_mut_and_registry(store.0); 3247 let callee = instance 3248 .index_runtime_func_table(registry, start_func_table_idx, start_func_idx as u64)? 3249 .ok_or_else(|| Trap::ThreadNewIndirectUninitialized)?; 3250 if callee.type_index(store.0) != start_func_ty.type_index() { 3251 bail!(Trap::ThreadNewIndirectInvalidType); 3252 } 3253 3254 let token = StoreToken::new(store.as_context_mut()); 3255 let start_func = Box::new( 3256 move |store: &mut dyn VMStore, guest_thread: QualifiedThreadId| -> Result<()> { 3257 let old_thread = store.set_thread(guest_thread)?; 3258 log::trace!( 3259 "thread start: replaced {old_thread:?} with {guest_thread:?} as current thread" 3260 ); 3261 3262 let mut store = token.as_context_mut(store); 3263 let mut params = [ValRaw::i32(context)]; 3264 // Use call_unchecked rather than call or call_async, as we don't want to run the function 3265 // on a separate fiber if we're running in an async store. 3266 unsafe { callee.call_unchecked(store.as_context_mut(), &mut params)? }; 3267 3268 self.cleanup_thread(store.0, guest_thread, runtime_instance)?; 3269 log::trace!("explicit thread {guest_thread:?} completed"); 3270 let state = store.0.concurrent_state_mut(); 3271 let task = state.get_mut(guest_thread.task)?; 3272 if task.threads.is_empty() && !task.returned_or_cancelled() { 3273 bail!(Trap::NoAsyncResult); 3274 } 3275 store.0.set_thread(old_thread)?; 3276 let state = store.0.concurrent_state_mut(); 3277 if let Some(t) = old_thread.guest() { 3278 state.get_mut(t.thread)?.state = GuestThreadState::Running; 3279 } 3280 if state.get_mut(guest_thread.task)?.ready_to_delete() { 3281 Waitable::Guest(guest_thread.task).delete_from(state)?; 3282 } 3283 log::trace!("thread start: restored {old_thread:?} as current thread"); 3284 3285 Ok(()) 3286 }, 3287 ); 3288 3289 let state = store.0.concurrent_state_mut(); 3290 let current_thread = state.current_guest_thread()?; 3291 let parent_task = current_thread.task; 3292 3293 let new_thread = GuestThread::new_explicit(state, parent_task, start_func)?; 3294 let thread_id = state.push(new_thread)?; 3295 state.get_mut(parent_task)?.threads.insert(thread_id); 3296 3297 log::trace!("new thread with id {thread_id:?} created"); 3298 3299 self.add_guest_thread_to_instance_table(thread_id, store.0, runtime_instance) 3300 } 3301 3302 pub(crate) fn resume_thread( 3303 self, 3304 store: &mut StoreOpaque, 3305 runtime_instance: RuntimeComponentInstanceIndex, 3306 thread_idx: u32, 3307 high_priority: bool, 3308 allow_ready: bool, 3309 ) -> Result<()> { 3310 let thread_id = 3311 GuestThread::from_instance(self.id().get_mut(store), runtime_instance, thread_idx)?; 3312 let state = store.concurrent_state_mut(); 3313 let guest_thread = QualifiedThreadId::qualify(state, thread_id)?; 3314 let thread = state.get_mut(guest_thread.thread)?; 3315 3316 match mem::replace(&mut thread.state, GuestThreadState::Running) { 3317 GuestThreadState::NotStartedExplicit(start_func) => { 3318 log::trace!("starting thread {guest_thread:?}"); 3319 let guest_call = WorkItem::GuestCall( 3320 runtime_instance, 3321 GuestCall { 3322 thread: guest_thread, 3323 kind: GuestCallKind::StartExplicit(Box::new(move |store| { 3324 start_func(store, guest_thread) 3325 })), 3326 }, 3327 ); 3328 store 3329 .concurrent_state_mut() 3330 .push_work_item(guest_call, high_priority); 3331 } 3332 GuestThreadState::Suspended(fiber) => { 3333 log::trace!("resuming thread {thread_id:?} that was suspended"); 3334 store 3335 .concurrent_state_mut() 3336 .push_work_item(WorkItem::ResumeFiber(fiber), high_priority); 3337 } 3338 GuestThreadState::Ready(fiber) if allow_ready => { 3339 log::trace!("resuming thread {thread_id:?} that was ready"); 3340 thread.state = GuestThreadState::Ready(fiber); 3341 store 3342 .concurrent_state_mut() 3343 .promote_thread_work_item(guest_thread); 3344 } 3345 other => { 3346 thread.state = other; 3347 bail!(Trap::CannotResumeThread); 3348 } 3349 } 3350 Ok(()) 3351 } 3352 3353 fn add_guest_thread_to_instance_table( 3354 self, 3355 thread_id: TableId<GuestThread>, 3356 store: &mut StoreOpaque, 3357 runtime_instance: RuntimeComponentInstanceIndex, 3358 ) -> Result<u32> { 3359 let guest_id = store 3360 .instance_state(RuntimeInstance { 3361 instance: self.id().instance(), 3362 index: runtime_instance, 3363 }) 3364 .thread_handle_table() 3365 .guest_thread_insert(thread_id.rep())?; 3366 store 3367 .concurrent_state_mut() 3368 .get_mut(thread_id)? 3369 .instance_rep = Some(guest_id); 3370 Ok(guest_id) 3371 } 3372 3373 /// Helper function for the `thread.yield`, `thread.yield-to-suspended`, `thread.suspend`, 3374 /// `thread.suspend-to`, and `thread.suspend-to-suspended` intrinsics. 3375 pub(crate) fn suspension_intrinsic( 3376 self, 3377 store: &mut StoreOpaque, 3378 caller: RuntimeComponentInstanceIndex, 3379 cancellable: bool, 3380 yielding: bool, 3381 to_thread: SuspensionTarget, 3382 ) -> Result<WaitResult> { 3383 let guest_thread = store.concurrent_state_mut().current_guest_thread()?; 3384 if to_thread.is_none() { 3385 let state = store.concurrent_state_mut(); 3386 if yielding { 3387 // This is a `thread.yield` call 3388 if !state.may_block(guest_thread.task)? { 3389 // In a non-blocking context, a `thread.yield` may trigger 3390 // other threads in the same component instance to run. 3391 if !state.promote_instance_local_thread_work_item(caller) { 3392 // No other threads are runnable, so just return 3393 return Ok(WaitResult::Completed); 3394 } 3395 } 3396 } else { 3397 // The caller may only call `thread.suspend` from an async task 3398 // (i.e. a task created via a call to an async export). 3399 // Otherwise, we'll trap. 3400 store.check_blocking()?; 3401 } 3402 } 3403 3404 // There could be a pending cancellation from a previous uncancellable wait 3405 if cancellable && store.concurrent_state_mut().take_pending_cancellation()? { 3406 return Ok(WaitResult::Cancelled); 3407 } 3408 3409 match to_thread { 3410 SuspensionTarget::SomeSuspended(thread) => { 3411 self.resume_thread(store, caller, thread, true, false)? 3412 } 3413 SuspensionTarget::Some(thread) => { 3414 self.resume_thread(store, caller, thread, true, true)? 3415 } 3416 SuspensionTarget::None => { /* nothing to do */ } 3417 } 3418 3419 let reason = if yielding { 3420 SuspendReason::Yielding { 3421 thread: guest_thread, 3422 // Tell `StoreOpaque::suspend` it's okay to suspend here since 3423 // we're handling a `thread.yield-to-suspended` call; otherwise it would 3424 // panic if we called it in a non-blocking context. 3425 skip_may_block_check: to_thread.is_some(), 3426 } 3427 } else { 3428 SuspendReason::ExplicitlySuspending { 3429 thread: guest_thread, 3430 // Tell `StoreOpaque::suspend` it's okay to suspend here since 3431 // we're handling a `thread.suspend-to(-suspended)` call; otherwise it would 3432 // panic if we called it in a non-blocking context. 3433 skip_may_block_check: to_thread.is_some(), 3434 } 3435 }; 3436 3437 store.suspend(reason)?; 3438 3439 if cancellable && store.concurrent_state_mut().take_pending_cancellation()? { 3440 Ok(WaitResult::Cancelled) 3441 } else { 3442 Ok(WaitResult::Completed) 3443 } 3444 } 3445 3446 /// Helper function for the `waitable-set.wait` and `waitable-set.poll` intrinsics. 3447 fn waitable_check( 3448 self, 3449 store: &mut StoreOpaque, 3450 cancellable: bool, 3451 check: WaitableCheck, 3452 params: WaitableCheckParams, 3453 ) -> Result<u32> { 3454 let guest_thread = store.concurrent_state_mut().current_guest_thread()?; 3455 3456 log::trace!("waitable check for {guest_thread:?}; set {:?}", params.set); 3457 3458 let state = store.concurrent_state_mut(); 3459 let task = state.get_mut(guest_thread.task)?; 3460 3461 // If we're waiting, and there are no events immediately available, 3462 // suspend the fiber until that changes. 3463 match &check { 3464 WaitableCheck::Wait => { 3465 let set = params.set; 3466 3467 if (task.event.is_none() 3468 || (matches!(task.event, Some(Event::Cancelled)) && !cancellable)) 3469 && state.get_mut(set)?.ready.is_empty() 3470 { 3471 if cancellable { 3472 let old = state 3473 .get_mut(guest_thread.thread)? 3474 .wake_on_cancel 3475 .replace(set); 3476 if !old.is_none() { 3477 bail_bug!("thread unexpectedly in a prior wake_on_cancel set"); 3478 } 3479 } 3480 3481 store.suspend(SuspendReason::Waiting { 3482 set, 3483 thread: guest_thread, 3484 skip_may_block_check: false, 3485 })?; 3486 } 3487 } 3488 WaitableCheck::Poll => {} 3489 } 3490 3491 log::trace!( 3492 "waitable check for {guest_thread:?}; set {:?}, part two", 3493 params.set 3494 ); 3495 3496 // Deliver any pending events to the guest and return. 3497 let event = self.get_event(store, guest_thread.task, Some(params.set), cancellable)?; 3498 3499 let (ordinal, handle, result) = match &check { 3500 WaitableCheck::Wait => { 3501 let (event, waitable) = match event { 3502 Some(p) => p, 3503 None => bail_bug!("event expected to be present"), 3504 }; 3505 let handle = waitable.map(|(_, v)| v).unwrap_or(0); 3506 let (ordinal, result) = event.parts(); 3507 (ordinal, handle, result) 3508 } 3509 WaitableCheck::Poll => { 3510 if let Some((event, waitable)) = event { 3511 let handle = waitable.map(|(_, v)| v).unwrap_or(0); 3512 let (ordinal, result) = event.parts(); 3513 (ordinal, handle, result) 3514 } else { 3515 log::trace!( 3516 "no events ready to deliver via waitable-set.poll to {:?}; set {:?}", 3517 guest_thread.task, 3518 params.set 3519 ); 3520 let (ordinal, result) = Event::None.parts(); 3521 (ordinal, 0, result) 3522 } 3523 } 3524 }; 3525 let memory = self.options_memory_mut(store, params.options); 3526 let ptr = func::validate_inbounds_dynamic( 3527 &CanonicalAbiInfo::POINTER_PAIR, 3528 memory, 3529 &ValRaw::u32(params.payload), 3530 )?; 3531 memory[ptr + 0..][..4].copy_from_slice(&handle.to_le_bytes()); 3532 memory[ptr + 4..][..4].copy_from_slice(&result.to_le_bytes()); 3533 Ok(ordinal) 3534 } 3535 3536 /// Implements the `subtask.cancel` intrinsic. 3537 pub(crate) fn subtask_cancel( 3538 self, 3539 store: &mut StoreOpaque, 3540 caller_instance: RuntimeComponentInstanceIndex, 3541 async_: bool, 3542 task_id: u32, 3543 ) -> Result<u32> { 3544 if !async_ { 3545 // The caller may only sync call `subtask.cancel` from an async task 3546 // (i.e. a task created via a call to an async export). Otherwise, 3547 // we'll trap. 3548 store.check_blocking()?; 3549 } 3550 3551 let (rep, is_host) = store 3552 .instance_state(RuntimeInstance { 3553 instance: self.id().instance(), 3554 index: caller_instance, 3555 }) 3556 .handle_table() 3557 .subtask_rep(task_id)?; 3558 let (waitable, expected_caller) = if is_host { 3559 let id = TableId::<HostTask>::new(rep); 3560 ( 3561 Waitable::Host(id), 3562 store.concurrent_state_mut().get_mut(id)?.caller, 3563 ) 3564 } else { 3565 let id = TableId::<GuestTask>::new(rep); 3566 if let Caller::Guest { thread } = store.concurrent_state_mut().get_mut(id)?.caller { 3567 (Waitable::Guest(id), thread) 3568 } else { 3569 bail_bug!("expected guest caller for `subtask.cancel`") 3570 } 3571 }; 3572 // Since waitables can neither be passed between instances nor forged, 3573 // this should never fail unless there's a bug in Wasmtime, but we check 3574 // here to be sure: 3575 let concurrent_state = store.concurrent_state_mut(); 3576 debug_assert_eq!(expected_caller, concurrent_state.current_guest_thread()?); 3577 3578 log::trace!("subtask_cancel {waitable:?} (handle {task_id})"); 3579 3580 let needs_block; 3581 if let Waitable::Host(host_task) = waitable { 3582 let state = &mut concurrent_state.get_mut(host_task)?.state; 3583 match mem::replace(state, HostTaskState::CalleeDone) { 3584 // If the callee is still running, signal an abort is requested. 3585 // Then fall through to determine what to do next. 3586 HostTaskState::CalleeRunning(handle) => handle.abort(), 3587 3588 // Cancellation was already requested, so fail as the task can't 3589 // be cancelled twice. 3590 HostTaskState::CalleeDone => { 3591 bail!(Trap::SubtaskCancelAfterTerminal); 3592 } 3593 3594 // These states should not be possible for a subtask that's 3595 // visible from the guest, so trap here. 3596 HostTaskState::CalleeStarted | HostTaskState::CalleeFinished(_) => { 3597 bail_bug!("invalid states for host callee") 3598 } 3599 } 3600 3601 // Cancelling host tasks always needs to block on them to await the 3602 // result of the completion set up in `first_poll`. This'll resolve 3603 // the race of `handle.abort()` above to see if it actually 3604 // cancelled something or if the future ended up finishing. 3605 needs_block = true; 3606 } else { 3607 let caller = concurrent_state.current_guest_thread()?; 3608 let guest_task = TableId::<GuestTask>::new(rep); 3609 let task = concurrent_state.get_mut(guest_task)?; 3610 if !task.already_lowered_parameters() { 3611 // The task is in a `starting` state, meaning it hasn't run at 3612 // all yet. Here we update its fields to indicate that it is 3613 // ready to delete immediately once `subtask.drop` is called. 3614 task.lower_params = None; 3615 task.lift_result = None; 3616 task.exited = true; 3617 3618 let instance = task.instance; 3619 3620 assert_eq!(1, task.threads.len()); 3621 let thread = mem::take(&mut task.threads).into_iter().next().unwrap(); 3622 let concurrent_state = store.concurrent_state_mut(); 3623 concurrent_state.delete(thread)?; 3624 assert!(concurrent_state.get_mut(guest_task)?.ready_to_delete()); 3625 3626 // Not yet started; cancel and remove from pending 3627 let pending = &mut store.instance_state(instance).concurrent_state().pending; 3628 let pending_count = pending.len(); 3629 pending.retain(|thread, _| thread.task != guest_task); 3630 // If there were no pending threads for this task, we're in an error state 3631 if pending.len() == pending_count { 3632 bail!(Trap::SubtaskCancelAfterTerminal); 3633 } 3634 return Ok(Status::StartCancelled as u32); 3635 } else if !task.returned_or_cancelled() { 3636 // Started, but not yet returned or cancelled; send the 3637 // `CANCELLED` event 3638 task.cancel_sent = true; 3639 // Note that this might overwrite an event that was set earlier 3640 // (e.g. `Event::None` if the task is yielding, or 3641 // `Event::Cancelled` if it was already cancelled), but that's 3642 // okay -- this should supersede the previous state. 3643 task.event = Some(Event::Cancelled); 3644 let runtime_instance = task.instance.index; 3645 for thread in task.threads.clone() { 3646 let thread = QualifiedThreadId { 3647 task: guest_task, 3648 thread, 3649 }; 3650 if let Some(set) = concurrent_state 3651 .get_mut(thread.thread)? 3652 .wake_on_cancel 3653 .take() 3654 { 3655 let item = match concurrent_state.get_mut(set)?.waiting.remove(&thread) { 3656 Some(WaitMode::Fiber(fiber)) => WorkItem::ResumeFiber(fiber), 3657 Some(WaitMode::Callback(instance)) => WorkItem::GuestCall( 3658 runtime_instance, 3659 GuestCall { 3660 thread, 3661 kind: GuestCallKind::DeliverEvent { 3662 instance, 3663 set: None, 3664 }, 3665 }, 3666 ), 3667 None => bail_bug!("thread not present in wake_on_cancel set"), 3668 }; 3669 concurrent_state.push_high_priority(item); 3670 3671 store.suspend(SuspendReason::Yielding { 3672 thread: caller, 3673 // `subtask.cancel` is not allowed to be called in a 3674 // sync context, so we cannot skip the may-block check. 3675 skip_may_block_check: false, 3676 })?; 3677 break; 3678 } 3679 } 3680 3681 // Guest tasks need to block if they have not yet returned or 3682 // cancelled, even as a result of the event delivery above. 3683 needs_block = !store 3684 .concurrent_state_mut() 3685 .get_mut(guest_task)? 3686 .returned_or_cancelled() 3687 } else { 3688 needs_block = false; 3689 } 3690 }; 3691 3692 // If we need to block waiting on the terminal status of this subtask 3693 // then return immediately in `async` mode, or otherwise wait for the 3694 // event to get signaled through the store. 3695 if needs_block { 3696 if async_ { 3697 return Ok(BLOCKED); 3698 } 3699 3700 // Wait for this waitable to get signaled with its terminal status 3701 // from the completion callback enqueued by `first_poll`. Once 3702 // that's done fall through to the sahred 3703 store.wait_for_event(waitable)?; 3704 3705 // .. fall through to determine what event's in store for us. 3706 } 3707 3708 let event = waitable.take_event(store.concurrent_state_mut())?; 3709 if let Some(Event::Subtask { 3710 status: status @ (Status::Returned | Status::ReturnCancelled), 3711 }) = event 3712 { 3713 Ok(status as u32) 3714 } else { 3715 bail!(Trap::SubtaskCancelAfterTerminal); 3716 } 3717 } 3718 3719 pub(crate) fn context_get(self, store: &mut StoreOpaque, slot: u32) -> Result<u32> { 3720 store.concurrent_state_mut().context_get(slot) 3721 } 3722 3723 pub(crate) fn context_set(self, store: &mut StoreOpaque, slot: u32, value: u32) -> Result<()> { 3724 store.concurrent_state_mut().context_set(slot, value) 3725 } 3726 } 3727 3728 /// Trait representing component model ABI async intrinsics and fused adapter 3729 /// helper functions. 3730 /// 3731 /// SAFETY (callers): Most of the methods in this trait accept raw pointers, 3732 /// which must be valid for at least the duration of the call (and possibly for 3733 /// as long as the relevant guest task exists, in the case of `*mut VMFuncRef` 3734 /// pointers used for async calls). 3735 pub trait VMComponentAsyncStore { 3736 /// A helper function for fused adapter modules involving calls where the 3737 /// one of the caller or callee is async. 3738 /// 3739 /// This helper is not used when the caller and callee both use the sync 3740 /// ABI, only when at least one is async is this used. 3741 unsafe fn prepare_call( 3742 &mut self, 3743 instance: Instance, 3744 memory: *mut VMMemoryDefinition, 3745 start: NonNull<VMFuncRef>, 3746 return_: NonNull<VMFuncRef>, 3747 caller_instance: RuntimeComponentInstanceIndex, 3748 callee_instance: RuntimeComponentInstanceIndex, 3749 task_return_type: TypeTupleIndex, 3750 callee_async: bool, 3751 string_encoding: StringEncoding, 3752 result_count: u32, 3753 storage: *mut ValRaw, 3754 storage_len: usize, 3755 ) -> Result<()>; 3756 3757 /// A helper function for fused adapter modules involving calls where the 3758 /// caller is sync-lowered but the callee is async-lifted. 3759 unsafe fn sync_start( 3760 &mut self, 3761 instance: Instance, 3762 callback: *mut VMFuncRef, 3763 callee: NonNull<VMFuncRef>, 3764 param_count: u32, 3765 storage: *mut MaybeUninit<ValRaw>, 3766 storage_len: usize, 3767 ) -> Result<()>; 3768 3769 /// A helper function for fused adapter modules involving calls where the 3770 /// caller is async-lowered. 3771 unsafe fn async_start( 3772 &mut self, 3773 instance: Instance, 3774 callback: *mut VMFuncRef, 3775 post_return: *mut VMFuncRef, 3776 callee: NonNull<VMFuncRef>, 3777 param_count: u32, 3778 result_count: u32, 3779 flags: u32, 3780 ) -> Result<u32>; 3781 3782 /// The `future.write` intrinsic. 3783 fn future_write( 3784 &mut self, 3785 instance: Instance, 3786 caller: RuntimeComponentInstanceIndex, 3787 ty: TypeFutureTableIndex, 3788 options: OptionsIndex, 3789 future: u32, 3790 address: u32, 3791 ) -> Result<u32>; 3792 3793 /// The `future.read` intrinsic. 3794 fn future_read( 3795 &mut self, 3796 instance: Instance, 3797 caller: RuntimeComponentInstanceIndex, 3798 ty: TypeFutureTableIndex, 3799 options: OptionsIndex, 3800 future: u32, 3801 address: u32, 3802 ) -> Result<u32>; 3803 3804 /// The `future.drop-writable` intrinsic. 3805 fn future_drop_writable( 3806 &mut self, 3807 instance: Instance, 3808 ty: TypeFutureTableIndex, 3809 writer: u32, 3810 ) -> Result<()>; 3811 3812 /// The `stream.write` intrinsic. 3813 fn stream_write( 3814 &mut self, 3815 instance: Instance, 3816 caller: RuntimeComponentInstanceIndex, 3817 ty: TypeStreamTableIndex, 3818 options: OptionsIndex, 3819 stream: u32, 3820 address: u32, 3821 count: u32, 3822 ) -> Result<u32>; 3823 3824 /// The `stream.read` intrinsic. 3825 fn stream_read( 3826 &mut self, 3827 instance: Instance, 3828 caller: RuntimeComponentInstanceIndex, 3829 ty: TypeStreamTableIndex, 3830 options: OptionsIndex, 3831 stream: u32, 3832 address: u32, 3833 count: u32, 3834 ) -> Result<u32>; 3835 3836 /// The "fast-path" implementation of the `stream.write` intrinsic for 3837 /// "flat" (i.e. memcpy-able) payloads. 3838 fn flat_stream_write( 3839 &mut self, 3840 instance: Instance, 3841 caller: RuntimeComponentInstanceIndex, 3842 ty: TypeStreamTableIndex, 3843 options: OptionsIndex, 3844 payload_size: u32, 3845 payload_align: u32, 3846 stream: u32, 3847 address: u32, 3848 count: u32, 3849 ) -> Result<u32>; 3850 3851 /// The "fast-path" implementation of the `stream.read` intrinsic for "flat" 3852 /// (i.e. memcpy-able) payloads. 3853 fn flat_stream_read( 3854 &mut self, 3855 instance: Instance, 3856 caller: RuntimeComponentInstanceIndex, 3857 ty: TypeStreamTableIndex, 3858 options: OptionsIndex, 3859 payload_size: u32, 3860 payload_align: u32, 3861 stream: u32, 3862 address: u32, 3863 count: u32, 3864 ) -> Result<u32>; 3865 3866 /// The `stream.drop-writable` intrinsic. 3867 fn stream_drop_writable( 3868 &mut self, 3869 instance: Instance, 3870 ty: TypeStreamTableIndex, 3871 writer: u32, 3872 ) -> Result<()>; 3873 3874 /// The `error-context.debug-message` intrinsic. 3875 fn error_context_debug_message( 3876 &mut self, 3877 instance: Instance, 3878 ty: TypeComponentLocalErrorContextTableIndex, 3879 options: OptionsIndex, 3880 err_ctx_handle: u32, 3881 debug_msg_address: u32, 3882 ) -> Result<()>; 3883 3884 /// The `thread.new-indirect` intrinsic 3885 fn thread_new_indirect( 3886 &mut self, 3887 instance: Instance, 3888 caller: RuntimeComponentInstanceIndex, 3889 func_ty_idx: TypeFuncIndex, 3890 start_func_table_idx: RuntimeTableIndex, 3891 start_func_idx: u32, 3892 context: i32, 3893 ) -> Result<u32>; 3894 } 3895 3896 /// SAFETY: See trait docs. 3897 impl<T: 'static> VMComponentAsyncStore for StoreInner<T> { 3898 unsafe fn prepare_call( 3899 &mut self, 3900 instance: Instance, 3901 memory: *mut VMMemoryDefinition, 3902 start: NonNull<VMFuncRef>, 3903 return_: NonNull<VMFuncRef>, 3904 caller_instance: RuntimeComponentInstanceIndex, 3905 callee_instance: RuntimeComponentInstanceIndex, 3906 task_return_type: TypeTupleIndex, 3907 callee_async: bool, 3908 string_encoding: StringEncoding, 3909 result_count_or_max_if_async: u32, 3910 storage: *mut ValRaw, 3911 storage_len: usize, 3912 ) -> Result<()> { 3913 // SAFETY: The `wasmtime_cranelift`-generated code that calls 3914 // this method will have ensured that `storage` is a valid 3915 // pointer containing at least `storage_len` items. 3916 let params = unsafe { std::slice::from_raw_parts(storage, storage_len) }.to_vec(); 3917 3918 unsafe { 3919 instance.prepare_call( 3920 StoreContextMut(self), 3921 start, 3922 return_, 3923 caller_instance, 3924 callee_instance, 3925 task_return_type, 3926 callee_async, 3927 memory, 3928 string_encoding, 3929 match result_count_or_max_if_async { 3930 PREPARE_ASYNC_NO_RESULT => CallerInfo::Async { 3931 params, 3932 has_result: false, 3933 }, 3934 PREPARE_ASYNC_WITH_RESULT => CallerInfo::Async { 3935 params, 3936 has_result: true, 3937 }, 3938 result_count => CallerInfo::Sync { 3939 params, 3940 result_count, 3941 }, 3942 }, 3943 ) 3944 } 3945 } 3946 3947 unsafe fn sync_start( 3948 &mut self, 3949 instance: Instance, 3950 callback: *mut VMFuncRef, 3951 callee: NonNull<VMFuncRef>, 3952 param_count: u32, 3953 storage: *mut MaybeUninit<ValRaw>, 3954 storage_len: usize, 3955 ) -> Result<()> { 3956 unsafe { 3957 instance 3958 .start_call( 3959 StoreContextMut(self), 3960 callback, 3961 ptr::null_mut(), 3962 callee, 3963 param_count, 3964 1, 3965 START_FLAG_ASYNC_CALLEE, 3966 // SAFETY: The `wasmtime_cranelift`-generated code that calls 3967 // this method will have ensured that `storage` is a valid 3968 // pointer containing at least `storage_len` items. 3969 Some(std::slice::from_raw_parts_mut(storage, storage_len)), 3970 ) 3971 .map(drop) 3972 } 3973 } 3974 3975 unsafe fn async_start( 3976 &mut self, 3977 instance: Instance, 3978 callback: *mut VMFuncRef, 3979 post_return: *mut VMFuncRef, 3980 callee: NonNull<VMFuncRef>, 3981 param_count: u32, 3982 result_count: u32, 3983 flags: u32, 3984 ) -> Result<u32> { 3985 unsafe { 3986 instance.start_call( 3987 StoreContextMut(self), 3988 callback, 3989 post_return, 3990 callee, 3991 param_count, 3992 result_count, 3993 flags, 3994 None, 3995 ) 3996 } 3997 } 3998 3999 fn future_write( 4000 &mut self, 4001 instance: Instance, 4002 caller: RuntimeComponentInstanceIndex, 4003 ty: TypeFutureTableIndex, 4004 options: OptionsIndex, 4005 future: u32, 4006 address: u32, 4007 ) -> Result<u32> { 4008 instance 4009 .guest_write( 4010 StoreContextMut(self), 4011 caller, 4012 TransmitIndex::Future(ty), 4013 options, 4014 None, 4015 future, 4016 address, 4017 1, 4018 ) 4019 .map(|result| result.encode()) 4020 } 4021 4022 fn future_read( 4023 &mut self, 4024 instance: Instance, 4025 caller: RuntimeComponentInstanceIndex, 4026 ty: TypeFutureTableIndex, 4027 options: OptionsIndex, 4028 future: u32, 4029 address: u32, 4030 ) -> Result<u32> { 4031 instance 4032 .guest_read( 4033 StoreContextMut(self), 4034 caller, 4035 TransmitIndex::Future(ty), 4036 options, 4037 None, 4038 future, 4039 address, 4040 1, 4041 ) 4042 .map(|result| result.encode()) 4043 } 4044 4045 fn stream_write( 4046 &mut self, 4047 instance: Instance, 4048 caller: RuntimeComponentInstanceIndex, 4049 ty: TypeStreamTableIndex, 4050 options: OptionsIndex, 4051 stream: u32, 4052 address: u32, 4053 count: u32, 4054 ) -> Result<u32> { 4055 instance 4056 .guest_write( 4057 StoreContextMut(self), 4058 caller, 4059 TransmitIndex::Stream(ty), 4060 options, 4061 None, 4062 stream, 4063 address, 4064 count, 4065 ) 4066 .map(|result| result.encode()) 4067 } 4068 4069 fn stream_read( 4070 &mut self, 4071 instance: Instance, 4072 caller: RuntimeComponentInstanceIndex, 4073 ty: TypeStreamTableIndex, 4074 options: OptionsIndex, 4075 stream: u32, 4076 address: u32, 4077 count: u32, 4078 ) -> Result<u32> { 4079 instance 4080 .guest_read( 4081 StoreContextMut(self), 4082 caller, 4083 TransmitIndex::Stream(ty), 4084 options, 4085 None, 4086 stream, 4087 address, 4088 count, 4089 ) 4090 .map(|result| result.encode()) 4091 } 4092 4093 fn future_drop_writable( 4094 &mut self, 4095 instance: Instance, 4096 ty: TypeFutureTableIndex, 4097 writer: u32, 4098 ) -> Result<()> { 4099 instance.guest_drop_writable(self, TransmitIndex::Future(ty), writer) 4100 } 4101 4102 fn flat_stream_write( 4103 &mut self, 4104 instance: Instance, 4105 caller: RuntimeComponentInstanceIndex, 4106 ty: TypeStreamTableIndex, 4107 options: OptionsIndex, 4108 payload_size: u32, 4109 payload_align: u32, 4110 stream: u32, 4111 address: u32, 4112 count: u32, 4113 ) -> Result<u32> { 4114 instance 4115 .guest_write( 4116 StoreContextMut(self), 4117 caller, 4118 TransmitIndex::Stream(ty), 4119 options, 4120 Some(FlatAbi { 4121 size: payload_size, 4122 align: payload_align, 4123 }), 4124 stream, 4125 address, 4126 count, 4127 ) 4128 .map(|result| result.encode()) 4129 } 4130 4131 fn flat_stream_read( 4132 &mut self, 4133 instance: Instance, 4134 caller: RuntimeComponentInstanceIndex, 4135 ty: TypeStreamTableIndex, 4136 options: OptionsIndex, 4137 payload_size: u32, 4138 payload_align: u32, 4139 stream: u32, 4140 address: u32, 4141 count: u32, 4142 ) -> Result<u32> { 4143 instance 4144 .guest_read( 4145 StoreContextMut(self), 4146 caller, 4147 TransmitIndex::Stream(ty), 4148 options, 4149 Some(FlatAbi { 4150 size: payload_size, 4151 align: payload_align, 4152 }), 4153 stream, 4154 address, 4155 count, 4156 ) 4157 .map(|result| result.encode()) 4158 } 4159 4160 fn stream_drop_writable( 4161 &mut self, 4162 instance: Instance, 4163 ty: TypeStreamTableIndex, 4164 writer: u32, 4165 ) -> Result<()> { 4166 instance.guest_drop_writable(self, TransmitIndex::Stream(ty), writer) 4167 } 4168 4169 fn error_context_debug_message( 4170 &mut self, 4171 instance: Instance, 4172 ty: TypeComponentLocalErrorContextTableIndex, 4173 options: OptionsIndex, 4174 err_ctx_handle: u32, 4175 debug_msg_address: u32, 4176 ) -> Result<()> { 4177 instance.error_context_debug_message( 4178 StoreContextMut(self), 4179 ty, 4180 options, 4181 err_ctx_handle, 4182 debug_msg_address, 4183 ) 4184 } 4185 4186 fn thread_new_indirect( 4187 &mut self, 4188 instance: Instance, 4189 caller: RuntimeComponentInstanceIndex, 4190 func_ty_idx: TypeFuncIndex, 4191 start_func_table_idx: RuntimeTableIndex, 4192 start_func_idx: u32, 4193 context: i32, 4194 ) -> Result<u32> { 4195 instance.thread_new_indirect( 4196 StoreContextMut(self), 4197 caller, 4198 func_ty_idx, 4199 start_func_table_idx, 4200 start_func_idx, 4201 context, 4202 ) 4203 } 4204 } 4205 4206 type HostTaskFuture = Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>; 4207 4208 /// Represents the state of a pending host task. 4209 /// 4210 /// This is used to represent tasks when the guest calls into the host. 4211 pub(crate) struct HostTask { 4212 common: WaitableCommon, 4213 4214 /// Guest thread which called the host. 4215 caller: QualifiedThreadId, 4216 4217 /// State of borrows/etc the host needs to track. Used when the guest passes 4218 /// borrows to the host, for example. 4219 call_context: CallContext, 4220 4221 state: HostTaskState, 4222 } 4223 4224 enum HostTaskState { 4225 /// A host task has been created and it's considered "started". 4226 /// 4227 /// The host task has yet to enter `first_poll` or `poll_and_block` which 4228 /// is where this will get updated further. 4229 CalleeStarted, 4230 4231 /// State used for tasks in `first_poll` meaning that the guest did an async 4232 /// lower of a host async function which is blocked. The specified handle is 4233 /// linked to the future in the main `FuturesUnordered` of a store which is 4234 /// used to cancel it if the guest requests cancellation. 4235 CalleeRunning(JoinHandle), 4236 4237 /// Terminal state used for tasks in `poll_and_block` to store the result of 4238 /// their computation. Note that this state is not used for tasks in 4239 /// `first_poll`. 4240 CalleeFinished(LiftedResult), 4241 4242 /// Terminal state for host tasks meaning that the task was cancelled or the 4243 /// result was taken. 4244 CalleeDone, 4245 } 4246 4247 impl HostTask { 4248 fn new(caller: QualifiedThreadId, state: HostTaskState) -> Self { 4249 Self { 4250 common: WaitableCommon::default(), 4251 call_context: CallContext::default(), 4252 caller, 4253 state, 4254 } 4255 } 4256 } 4257 4258 impl TableDebug for HostTask { 4259 fn type_name() -> &'static str { 4260 "HostTask" 4261 } 4262 } 4263 4264 type CallbackFn = Box<dyn Fn(&mut dyn VMStore, Event, u32) -> Result<u32> + Send + Sync + 'static>; 4265 4266 /// Represents the caller of a given guest task. 4267 enum Caller { 4268 /// The host called the guest task. 4269 Host { 4270 /// If present, may be used to deliver the result. 4271 tx: Option<oneshot::Sender<LiftedResult>>, 4272 /// If true, there's a host future that must be dropped before the task 4273 /// can be deleted. 4274 host_future_present: bool, 4275 /// Represents the caller of the host function which called back into a 4276 /// guest. Note that this thread could belong to an entirely unrelated 4277 /// top-level component instance than the one the host called into. 4278 caller: CurrentThread, 4279 }, 4280 /// Another guest thread called the guest task 4281 Guest { 4282 /// The id of the caller 4283 thread: QualifiedThreadId, 4284 }, 4285 } 4286 4287 /// Represents a closure and related canonical ABI parameters required to 4288 /// validate a `task.return` call at runtime and lift the result. 4289 struct LiftResult { 4290 lift: RawLift, 4291 ty: TypeTupleIndex, 4292 memory: Option<SendSyncPtr<VMMemoryDefinition>>, 4293 string_encoding: StringEncoding, 4294 } 4295 4296 /// The table ID for a guest thread, qualified by the task to which it belongs. 4297 /// 4298 /// This exists to minimize table lookups and the necessity to pass stores around mutably 4299 /// for the common case of identifying the task to which a thread belongs. 4300 #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)] 4301 struct QualifiedThreadId { 4302 task: TableId<GuestTask>, 4303 thread: TableId<GuestThread>, 4304 } 4305 4306 impl QualifiedThreadId { 4307 fn qualify( 4308 state: &mut ConcurrentState, 4309 thread: TableId<GuestThread>, 4310 ) -> Result<QualifiedThreadId> { 4311 Ok(QualifiedThreadId { 4312 task: state.get_mut(thread)?.parent_task, 4313 thread, 4314 }) 4315 } 4316 } 4317 4318 impl fmt::Debug for QualifiedThreadId { 4319 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 4320 f.debug_tuple("QualifiedThreadId") 4321 .field(&self.task.rep()) 4322 .field(&self.thread.rep()) 4323 .finish() 4324 } 4325 } 4326 4327 enum GuestThreadState { 4328 NotStartedImplicit, 4329 NotStartedExplicit( 4330 Box<dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync>, 4331 ), 4332 Running, 4333 Suspended(StoreFiber<'static>), 4334 Ready(StoreFiber<'static>), 4335 Completed, 4336 } 4337 pub struct GuestThread { 4338 /// Context-local state used to implement the `context.{get,set}` 4339 /// intrinsics. 4340 context: [u32; 2], 4341 /// The owning guest task. 4342 parent_task: TableId<GuestTask>, 4343 /// If present, indicates that the thread is currently waiting on the 4344 /// specified set but may be cancelled and woken immediately. 4345 wake_on_cancel: Option<TableId<WaitableSet>>, 4346 /// The execution state of this guest thread 4347 state: GuestThreadState, 4348 /// The index of this thread in the component instance's handle table. 4349 /// This must always be `Some` after initialization. 4350 instance_rep: Option<u32>, 4351 /// Scratch waitable set used to watch subtasks during synchronous calls. 4352 sync_call_set: TableId<WaitableSet>, 4353 } 4354 4355 impl GuestThread { 4356 /// Retrieve the `GuestThread` corresponding to the specified guest-visible 4357 /// handle. 4358 fn from_instance( 4359 state: Pin<&mut ComponentInstance>, 4360 caller_instance: RuntimeComponentInstanceIndex, 4361 guest_thread: u32, 4362 ) -> Result<TableId<Self>> { 4363 let rep = state.instance_states().0[caller_instance] 4364 .thread_handle_table() 4365 .guest_thread_rep(guest_thread)?; 4366 Ok(TableId::new(rep)) 4367 } 4368 4369 fn new_implicit(state: &mut ConcurrentState, parent_task: TableId<GuestTask>) -> Result<Self> { 4370 let sync_call_set = state.push(WaitableSet::default())?; 4371 Ok(Self { 4372 context: [0; 2], 4373 parent_task, 4374 wake_on_cancel: None, 4375 state: GuestThreadState::NotStartedImplicit, 4376 instance_rep: None, 4377 sync_call_set, 4378 }) 4379 } 4380 4381 fn new_explicit( 4382 state: &mut ConcurrentState, 4383 parent_task: TableId<GuestTask>, 4384 start_func: Box< 4385 dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync, 4386 >, 4387 ) -> Result<Self> { 4388 let sync_call_set = state.push(WaitableSet::default())?; 4389 Ok(Self { 4390 context: [0; 2], 4391 parent_task, 4392 wake_on_cancel: None, 4393 state: GuestThreadState::NotStartedExplicit(start_func), 4394 instance_rep: None, 4395 sync_call_set, 4396 }) 4397 } 4398 } 4399 4400 impl TableDebug for GuestThread { 4401 fn type_name() -> &'static str { 4402 "GuestThread" 4403 } 4404 } 4405 4406 enum SyncResult { 4407 NotProduced, 4408 Produced(Option<ValRaw>), 4409 Taken, 4410 } 4411 4412 impl SyncResult { 4413 fn take(&mut self) -> Result<Option<Option<ValRaw>>> { 4414 Ok(match mem::replace(self, SyncResult::Taken) { 4415 SyncResult::NotProduced => None, 4416 SyncResult::Produced(val) => Some(val), 4417 SyncResult::Taken => { 4418 bail_bug!("attempted to take a synchronous result that was already taken") 4419 } 4420 }) 4421 } 4422 } 4423 4424 #[derive(Debug)] 4425 enum HostFutureState { 4426 NotApplicable, 4427 Live, 4428 Dropped, 4429 } 4430 4431 /// Represents a pending guest task. 4432 pub(crate) struct GuestTask { 4433 /// See `WaitableCommon` 4434 common: WaitableCommon, 4435 /// Closure to lower the parameters passed to this task. 4436 lower_params: Option<RawLower>, 4437 /// See `LiftResult` 4438 lift_result: Option<LiftResult>, 4439 /// A place to stash the type-erased lifted result if it can't be delivered 4440 /// immediately. 4441 result: Option<LiftedResult>, 4442 /// Closure to call the callback function for an async-lifted export, if 4443 /// provided. 4444 callback: Option<CallbackFn>, 4445 /// See `Caller` 4446 caller: Caller, 4447 /// Borrow state for this task. 4448 /// 4449 /// Keeps track of `borrow<T>` received to this task to ensure that 4450 /// everything is dropped by the time it exits. 4451 call_context: CallContext, 4452 /// A place to stash the lowered result for a sync-to-async call until it 4453 /// can be returned to the caller. 4454 sync_result: SyncResult, 4455 /// Whether or not the task has been cancelled (i.e. whether the task is 4456 /// permitted to call `task.cancel`). 4457 cancel_sent: bool, 4458 /// Whether or not we've sent a `Status::Starting` event to any current or 4459 /// future waiters for this waitable. 4460 starting_sent: bool, 4461 /// The runtime instance to which the exported function for this guest task 4462 /// belongs. 4463 /// 4464 /// Note that the task may do a sync->sync call via a fused adapter which 4465 /// results in that task executing code in a different instance, and it may 4466 /// call host functions and intrinsics from that other instance. 4467 instance: RuntimeInstance, 4468 /// If present, a pending `Event::None` or `Event::Cancelled` to be 4469 /// delivered to this task. 4470 event: Option<Event>, 4471 /// Whether or not the task has exited. 4472 exited: bool, 4473 /// Threads belonging to this task 4474 threads: HashSet<TableId<GuestThread>>, 4475 /// The state of the host future that represents an async task, which must 4476 /// be dropped before we can delete the task. 4477 host_future_state: HostFutureState, 4478 /// Indicates whether this task was created for a call to an async-lifted 4479 /// export. 4480 async_function: bool, 4481 } 4482 4483 impl GuestTask { 4484 fn already_lowered_parameters(&self) -> bool { 4485 // We reset `lower_params` after we lower the parameters 4486 self.lower_params.is_none() 4487 } 4488 4489 fn returned_or_cancelled(&self) -> bool { 4490 // We reset `lift_result` after we return or exit 4491 self.lift_result.is_none() 4492 } 4493 4494 fn ready_to_delete(&self) -> bool { 4495 let threads_completed = self.threads.is_empty(); 4496 let has_sync_result = matches!(self.sync_result, SyncResult::Produced(_)); 4497 let pending_completion_event = matches!( 4498 self.common.event, 4499 Some(Event::Subtask { 4500 status: Status::Returned | Status::ReturnCancelled 4501 }) 4502 ); 4503 let ready = threads_completed 4504 && !has_sync_result 4505 && !pending_completion_event 4506 && !matches!(self.host_future_state, HostFutureState::Live); 4507 log::trace!( 4508 "ready to delete? {ready} (threads_completed: {}, has_sync_result: {}, pending_completion_event: {}, host_future_state: {:?})", 4509 threads_completed, 4510 has_sync_result, 4511 pending_completion_event, 4512 self.host_future_state 4513 ); 4514 ready 4515 } 4516 4517 fn new( 4518 lower_params: RawLower, 4519 lift_result: LiftResult, 4520 caller: Caller, 4521 callback: Option<CallbackFn>, 4522 instance: RuntimeInstance, 4523 async_function: bool, 4524 ) -> Result<Self> { 4525 let host_future_state = match &caller { 4526 Caller::Guest { .. } => HostFutureState::NotApplicable, 4527 Caller::Host { 4528 host_future_present, 4529 .. 4530 } => { 4531 if *host_future_present { 4532 HostFutureState::Live 4533 } else { 4534 HostFutureState::NotApplicable 4535 } 4536 } 4537 }; 4538 Ok(Self { 4539 common: WaitableCommon::default(), 4540 lower_params: Some(lower_params), 4541 lift_result: Some(lift_result), 4542 result: None, 4543 callback, 4544 caller, 4545 call_context: CallContext::default(), 4546 sync_result: SyncResult::NotProduced, 4547 cancel_sent: false, 4548 starting_sent: false, 4549 instance, 4550 event: None, 4551 exited: false, 4552 threads: HashSet::new(), 4553 host_future_state, 4554 async_function, 4555 }) 4556 } 4557 4558 /// Dispose of this guest task. 4559 fn dispose(self, _state: &mut ConcurrentState) -> Result<()> { 4560 assert!(self.threads.is_empty()); 4561 Ok(()) 4562 } 4563 } 4564 4565 impl TableDebug for GuestTask { 4566 fn type_name() -> &'static str { 4567 "GuestTask" 4568 } 4569 } 4570 4571 /// Represents state common to all kinds of waitables. 4572 #[derive(Default)] 4573 struct WaitableCommon { 4574 /// The currently pending event for this waitable, if any. 4575 event: Option<Event>, 4576 /// The set to which this waitable belongs, if any. 4577 set: Option<TableId<WaitableSet>>, 4578 /// The handle with which the guest refers to this waitable, if any. 4579 handle: Option<u32>, 4580 } 4581 4582 /// Represents a Component Model Async `waitable`. 4583 #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)] 4584 enum Waitable { 4585 /// A host task 4586 Host(TableId<HostTask>), 4587 /// A guest task 4588 Guest(TableId<GuestTask>), 4589 /// The read or write end of a stream or future 4590 Transmit(TableId<TransmitHandle>), 4591 } 4592 4593 impl Waitable { 4594 /// Retrieve the `Waitable` corresponding to the specified guest-visible 4595 /// handle. 4596 fn from_instance( 4597 state: Pin<&mut ComponentInstance>, 4598 caller_instance: RuntimeComponentInstanceIndex, 4599 waitable: u32, 4600 ) -> Result<Self> { 4601 use crate::runtime::vm::component::Waitable; 4602 4603 let (waitable, kind) = state.instance_states().0[caller_instance] 4604 .handle_table() 4605 .waitable_rep(waitable)?; 4606 4607 Ok(match kind { 4608 Waitable::Subtask { is_host: true } => Self::Host(TableId::new(waitable)), 4609 Waitable::Subtask { is_host: false } => Self::Guest(TableId::new(waitable)), 4610 Waitable::Stream | Waitable::Future => Self::Transmit(TableId::new(waitable)), 4611 }) 4612 } 4613 4614 /// Retrieve the host-visible identifier for this `Waitable`. 4615 fn rep(&self) -> u32 { 4616 match self { 4617 Self::Host(id) => id.rep(), 4618 Self::Guest(id) => id.rep(), 4619 Self::Transmit(id) => id.rep(), 4620 } 4621 } 4622 4623 /// Move this `Waitable` to the specified set (when `set` is `Some(_)`) or 4624 /// remove it from any set it may currently belong to (when `set` is 4625 /// `None`). 4626 fn join(&self, state: &mut ConcurrentState, set: Option<TableId<WaitableSet>>) -> Result<()> { 4627 log::trace!("waitable {self:?} join set {set:?}",); 4628 4629 let old = mem::replace(&mut self.common(state)?.set, set); 4630 4631 if let Some(old) = old { 4632 match *self { 4633 Waitable::Host(id) => state.remove_child(id, old), 4634 Waitable::Guest(id) => state.remove_child(id, old), 4635 Waitable::Transmit(id) => state.remove_child(id, old), 4636 }?; 4637 4638 state.get_mut(old)?.ready.remove(self); 4639 } 4640 4641 if let Some(set) = set { 4642 match *self { 4643 Waitable::Host(id) => state.add_child(id, set), 4644 Waitable::Guest(id) => state.add_child(id, set), 4645 Waitable::Transmit(id) => state.add_child(id, set), 4646 }?; 4647 4648 if self.common(state)?.event.is_some() { 4649 self.mark_ready(state)?; 4650 } 4651 } 4652 4653 Ok(()) 4654 } 4655 4656 /// Retrieve mutable access to the `WaitableCommon` for this `Waitable`. 4657 fn common<'a>(&self, state: &'a mut ConcurrentState) -> Result<&'a mut WaitableCommon> { 4658 Ok(match self { 4659 Self::Host(id) => &mut state.get_mut(*id)?.common, 4660 Self::Guest(id) => &mut state.get_mut(*id)?.common, 4661 Self::Transmit(id) => &mut state.get_mut(*id)?.common, 4662 }) 4663 } 4664 4665 /// Set or clear the pending event for this waitable and either deliver it 4666 /// to the first waiter, if any, or mark it as ready to be delivered to the 4667 /// next waiter that arrives. 4668 fn set_event(&self, state: &mut ConcurrentState, event: Option<Event>) -> Result<()> { 4669 log::trace!("set event for {self:?}: {event:?}"); 4670 self.common(state)?.event = event; 4671 self.mark_ready(state) 4672 } 4673 4674 /// Take the pending event from this waitable, leaving `None` in its place. 4675 fn take_event(&self, state: &mut ConcurrentState) -> Result<Option<Event>> { 4676 let common = self.common(state)?; 4677 let event = common.event.take(); 4678 if let Some(set) = self.common(state)?.set { 4679 state.get_mut(set)?.ready.remove(self); 4680 } 4681 4682 Ok(event) 4683 } 4684 4685 /// Deliver the current event for this waitable to the first waiter, if any, 4686 /// or else mark it as ready to be delivered to the next waiter that 4687 /// arrives. 4688 fn mark_ready(&self, state: &mut ConcurrentState) -> Result<()> { 4689 if let Some(set) = self.common(state)?.set { 4690 state.get_mut(set)?.ready.insert(*self); 4691 if let Some((thread, mode)) = state.get_mut(set)?.waiting.pop_first() { 4692 let wake_on_cancel = state.get_mut(thread.thread)?.wake_on_cancel.take(); 4693 assert!(wake_on_cancel.is_none() || wake_on_cancel == Some(set)); 4694 4695 let item = match mode { 4696 WaitMode::Fiber(fiber) => WorkItem::ResumeFiber(fiber), 4697 WaitMode::Callback(instance) => WorkItem::GuestCall( 4698 state.get_mut(thread.task)?.instance.index, 4699 GuestCall { 4700 thread, 4701 kind: GuestCallKind::DeliverEvent { 4702 instance, 4703 set: Some(set), 4704 }, 4705 }, 4706 ), 4707 }; 4708 state.push_high_priority(item); 4709 } 4710 } 4711 Ok(()) 4712 } 4713 4714 /// Remove this waitable from the instance's rep table. 4715 fn delete_from(&self, state: &mut ConcurrentState) -> Result<()> { 4716 match self { 4717 Self::Host(task) => { 4718 log::trace!("delete host task {task:?}"); 4719 state.delete(*task)?; 4720 } 4721 Self::Guest(task) => { 4722 log::trace!("delete guest task {task:?}"); 4723 state.delete(*task)?.dispose(state)?; 4724 } 4725 Self::Transmit(task) => { 4726 state.delete(*task)?; 4727 } 4728 } 4729 4730 Ok(()) 4731 } 4732 } 4733 4734 impl fmt::Debug for Waitable { 4735 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 4736 match self { 4737 Self::Host(id) => write!(f, "{id:?}"), 4738 Self::Guest(id) => write!(f, "{id:?}"), 4739 Self::Transmit(id) => write!(f, "{id:?}"), 4740 } 4741 } 4742 } 4743 4744 /// Represents a Component Model Async `waitable-set`. 4745 #[derive(Default)] 4746 struct WaitableSet { 4747 /// Which waitables in this set have pending events, if any. 4748 ready: BTreeSet<Waitable>, 4749 /// Which guest threads are currently waiting on this set, if any. 4750 waiting: BTreeMap<QualifiedThreadId, WaitMode>, 4751 } 4752 4753 impl TableDebug for WaitableSet { 4754 fn type_name() -> &'static str { 4755 "WaitableSet" 4756 } 4757 } 4758 4759 /// Type-erased closure to lower the parameters for a guest task. 4760 type RawLower = 4761 Box<dyn FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync>; 4762 4763 /// Type-erased closure to lift the result for a guest task. 4764 type RawLift = Box< 4765 dyn FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync, 4766 >; 4767 4768 /// Type erased result of a guest task which may be downcast to the expected 4769 /// type by a host caller (or simply ignored in the case of a guest caller; see 4770 /// `DummyResult`). 4771 type LiftedResult = Box<dyn Any + Send + Sync>; 4772 4773 /// Used to return a result from a `LiftFn` when the actual result has already 4774 /// been lowered to a guest task's stack and linear memory. 4775 struct DummyResult; 4776 4777 /// Represents the Component Model Async state of a (sub-)component instance. 4778 #[derive(Default)] 4779 pub struct ConcurrentInstanceState { 4780 /// Whether backpressure is set for this instance (enabled if >0) 4781 backpressure: u16, 4782 /// Whether this instance can be entered 4783 do_not_enter: bool, 4784 /// Pending calls for this instance which require `Self::backpressure` to be 4785 /// `true` and/or `Self::do_not_enter` to be false before they can proceed. 4786 pending: BTreeMap<QualifiedThreadId, GuestCallKind>, 4787 } 4788 4789 impl ConcurrentInstanceState { 4790 pub fn pending_is_empty(&self) -> bool { 4791 self.pending.is_empty() 4792 } 4793 } 4794 4795 #[derive(Debug, Copy, Clone)] 4796 enum CurrentThread { 4797 Guest(QualifiedThreadId), 4798 Host(TableId<HostTask>), 4799 None, 4800 } 4801 4802 impl CurrentThread { 4803 fn guest(&self) -> Option<&QualifiedThreadId> { 4804 match self { 4805 Self::Guest(id) => Some(id), 4806 _ => None, 4807 } 4808 } 4809 4810 fn host(&self) -> Option<TableId<HostTask>> { 4811 match self { 4812 Self::Host(id) => Some(*id), 4813 _ => None, 4814 } 4815 } 4816 4817 fn is_none(&self) -> bool { 4818 matches!(self, Self::None) 4819 } 4820 } 4821 4822 impl From<QualifiedThreadId> for CurrentThread { 4823 fn from(id: QualifiedThreadId) -> Self { 4824 Self::Guest(id) 4825 } 4826 } 4827 4828 impl From<TableId<HostTask>> for CurrentThread { 4829 fn from(id: TableId<HostTask>) -> Self { 4830 Self::Host(id) 4831 } 4832 } 4833 4834 /// Represents the Component Model Async state of a store. 4835 pub struct ConcurrentState { 4836 /// The currently running thread, if any. 4837 current_thread: CurrentThread, 4838 4839 /// The set of pending host and background tasks, if any. 4840 /// 4841 /// See `ComponentInstance::poll_until` for where we temporarily take this 4842 /// out, poll it, then put it back to avoid any mutable aliasing hazards. 4843 futures: AlwaysMut<Option<FuturesUnordered<HostTaskFuture>>>, 4844 /// The table of waitables, waitable sets, etc. 4845 table: AlwaysMut<ResourceTable>, 4846 /// The "high priority" work queue for this store's event loop. 4847 high_priority: Vec<WorkItem>, 4848 /// The "low priority" work queue for this store's event loop. 4849 low_priority: VecDeque<WorkItem>, 4850 /// A place to stash the reason a fiber is suspending so that the code which 4851 /// resumed it will know under what conditions the fiber should be resumed 4852 /// again. 4853 suspend_reason: Option<SuspendReason>, 4854 /// A cached fiber which is waiting for work to do. 4855 /// 4856 /// This helps us avoid creating a new fiber for each `GuestCall` work item. 4857 worker: Option<StoreFiber<'static>>, 4858 /// A place to stash the work item for which we're resuming a worker fiber. 4859 worker_item: Option<WorkerItem>, 4860 4861 /// Reference counts for all component error contexts 4862 /// 4863 /// NOTE: it is possible the global ref count to be *greater* than the sum of 4864 /// (sub)component ref counts as tracked by `error_context_tables`, for 4865 /// example when the host holds one or more references to error contexts. 4866 /// 4867 /// The key of this primary map is often referred to as the "rep" (i.e. host-side 4868 /// component-wide representation) of the index into concurrent state for a given 4869 /// stored `ErrorContext`. 4870 /// 4871 /// Stated another way, `TypeComponentGlobalErrorContextTableIndex` is essentially the same 4872 /// as a `TableId<ErrorContextState>`. 4873 global_error_context_ref_counts: 4874 BTreeMap<TypeComponentGlobalErrorContextTableIndex, GlobalErrorContextRefCount>, 4875 } 4876 4877 impl Default for ConcurrentState { 4878 fn default() -> Self { 4879 Self { 4880 current_thread: CurrentThread::None, 4881 table: AlwaysMut::new(ResourceTable::new()), 4882 futures: AlwaysMut::new(Some(FuturesUnordered::new())), 4883 high_priority: Vec::new(), 4884 low_priority: VecDeque::new(), 4885 suspend_reason: None, 4886 worker: None, 4887 worker_item: None, 4888 global_error_context_ref_counts: BTreeMap::new(), 4889 } 4890 } 4891 } 4892 4893 impl ConcurrentState { 4894 /// Take ownership of any fibers and futures owned by this object. 4895 /// 4896 /// This should be used when disposing of the `Store` containing this object 4897 /// in order to gracefully resolve any and all fibers using 4898 /// `StoreFiber::dispose`. This is necessary to avoid possible 4899 /// use-after-free bugs due to fibers which may still have access to the 4900 /// `Store`. 4901 /// 4902 /// Additionally, the futures collected with this function should be dropped 4903 /// within a `tls::set` call, which will ensure than any futures closing 4904 /// over an `&Accessor` will have access to the store when dropped, allowing 4905 /// e.g. `WithAccessor[AndValue]` instances to be disposed of without 4906 /// panicking. 4907 /// 4908 /// Note that this will leave the object in an inconsistent and unusable 4909 /// state, so it should only be used just prior to dropping it. 4910 pub(crate) fn take_fibers_and_futures( 4911 &mut self, 4912 fibers: &mut Vec<StoreFiber<'static>>, 4913 futures: &mut Vec<FuturesUnordered<HostTaskFuture>>, 4914 ) { 4915 for entry in self.table.get_mut().iter_mut() { 4916 if let Some(set) = entry.downcast_mut::<WaitableSet>() { 4917 for mode in mem::take(&mut set.waiting).into_values() { 4918 if let WaitMode::Fiber(fiber) = mode { 4919 fibers.push(fiber); 4920 } 4921 } 4922 } else if let Some(thread) = entry.downcast_mut::<GuestThread>() { 4923 if let GuestThreadState::Suspended(fiber) | GuestThreadState::Ready(fiber) = 4924 mem::replace(&mut thread.state, GuestThreadState::Completed) 4925 { 4926 fibers.push(fiber); 4927 } 4928 } 4929 } 4930 4931 if let Some(fiber) = self.worker.take() { 4932 fibers.push(fiber); 4933 } 4934 4935 let mut handle_item = |item| match item { 4936 WorkItem::ResumeFiber(fiber) => { 4937 fibers.push(fiber); 4938 } 4939 WorkItem::PushFuture(future) => { 4940 self.futures 4941 .get_mut() 4942 .as_mut() 4943 .unwrap() 4944 .push(future.into_inner()); 4945 } 4946 WorkItem::ResumeThread(..) | WorkItem::GuestCall(..) | WorkItem::WorkerFunction(..) => { 4947 } 4948 }; 4949 4950 for item in mem::take(&mut self.high_priority) { 4951 handle_item(item); 4952 } 4953 for item in mem::take(&mut self.low_priority) { 4954 handle_item(item); 4955 } 4956 4957 if let Some(them) = self.futures.get_mut().take() { 4958 futures.push(them); 4959 } 4960 } 4961 4962 /// Collect the next set of work items to run. This will be either all 4963 /// high-priority items, or a single low-priority item if there are no 4964 /// high-priority items. 4965 fn collect_work_items_to_run(&mut self) -> Vec<WorkItem> { 4966 let mut ready = mem::take(&mut self.high_priority); 4967 if ready.is_empty() { 4968 if let Some(item) = self.low_priority.pop_back() { 4969 ready.push(item); 4970 } 4971 } 4972 ready 4973 } 4974 4975 fn push<V: Send + Sync + 'static>( 4976 &mut self, 4977 value: V, 4978 ) -> Result<TableId<V>, ResourceTableError> { 4979 self.table.get_mut().push(value).map(TableId::from) 4980 } 4981 4982 fn get_mut<V: 'static>(&mut self, id: TableId<V>) -> Result<&mut V, ResourceTableError> { 4983 self.table.get_mut().get_mut(&Resource::from(id)) 4984 } 4985 4986 pub fn add_child<T: 'static, U: 'static>( 4987 &mut self, 4988 child: TableId<T>, 4989 parent: TableId<U>, 4990 ) -> Result<(), ResourceTableError> { 4991 self.table 4992 .get_mut() 4993 .add_child(Resource::from(child), Resource::from(parent)) 4994 } 4995 4996 pub fn remove_child<T: 'static, U: 'static>( 4997 &mut self, 4998 child: TableId<T>, 4999 parent: TableId<U>, 5000 ) -> Result<(), ResourceTableError> { 5001 self.table 5002 .get_mut() 5003 .remove_child(Resource::from(child), Resource::from(parent)) 5004 } 5005 5006 fn delete<V: 'static>(&mut self, id: TableId<V>) -> Result<V, ResourceTableError> { 5007 self.table.get_mut().delete(Resource::from(id)) 5008 } 5009 5010 fn push_future(&mut self, future: HostTaskFuture) { 5011 // Note that we can't directly push to `ConcurrentState::futures` here 5012 // since this may be called from a future that's being polled inside 5013 // `Self::poll_until`, which temporarily removes the `FuturesUnordered` 5014 // so it has exclusive access while polling it. Therefore, we push a 5015 // work item to the "high priority" queue, which will actually push to 5016 // `ConcurrentState::futures` later. 5017 self.push_high_priority(WorkItem::PushFuture(AlwaysMut::new(future))); 5018 } 5019 5020 fn push_high_priority(&mut self, item: WorkItem) { 5021 log::trace!("push high priority: {item:?}"); 5022 self.high_priority.push(item); 5023 } 5024 5025 fn push_low_priority(&mut self, item: WorkItem) { 5026 log::trace!("push low priority: {item:?}"); 5027 self.low_priority.push_front(item); 5028 } 5029 5030 fn push_work_item(&mut self, item: WorkItem, high_priority: bool) { 5031 if high_priority { 5032 self.push_high_priority(item); 5033 } else { 5034 self.push_low_priority(item); 5035 } 5036 } 5037 5038 fn promote_instance_local_thread_work_item( 5039 &mut self, 5040 current_instance: RuntimeComponentInstanceIndex, 5041 ) -> bool { 5042 self.promote_work_items_matching(|item: &WorkItem| match item { 5043 WorkItem::ResumeThread(instance, _) | WorkItem::GuestCall(instance, _) => { 5044 *instance == current_instance 5045 } 5046 _ => false, 5047 }) 5048 } 5049 5050 fn promote_thread_work_item(&mut self, thread: QualifiedThreadId) -> bool { 5051 self.promote_work_items_matching(|item: &WorkItem| match item { 5052 WorkItem::ResumeThread(_, t) | WorkItem::GuestCall(_, GuestCall { thread: t, .. }) => { 5053 *t == thread 5054 } 5055 _ => false, 5056 }) 5057 } 5058 5059 fn promote_work_items_matching<F>(&mut self, mut predicate: F) -> bool 5060 where 5061 F: FnMut(&WorkItem) -> bool, 5062 { 5063 // If there's a high-priority work item to resume the current guest thread, 5064 // we don't need to promote anything, but we return true to indicate that 5065 // work is pending for the current instance. 5066 if self.high_priority.iter().any(&mut predicate) { 5067 true 5068 } 5069 // Otherwise, look for a low-priority work item that matches the current 5070 // instance and promote it to high-priority. 5071 else if let Some(idx) = self.low_priority.iter().position(&mut predicate) { 5072 let item = self.low_priority.remove(idx).unwrap(); 5073 self.push_high_priority(item); 5074 true 5075 } else { 5076 false 5077 } 5078 } 5079 5080 /// Implements the `context.get` intrinsic. 5081 pub(crate) fn context_get(&mut self, slot: u32) -> Result<u32> { 5082 let thread = self.current_guest_thread()?; 5083 let val = self.get_mut(thread.thread)?.context[usize::try_from(slot)?]; 5084 log::trace!("context_get {thread:?} slot {slot} val {val:#x}"); 5085 Ok(val) 5086 } 5087 5088 /// Implements the `context.set` intrinsic. 5089 pub(crate) fn context_set(&mut self, slot: u32, val: u32) -> Result<()> { 5090 let thread = self.current_guest_thread()?; 5091 log::trace!("context_set {thread:?} slot {slot} val {val:#x}"); 5092 self.get_mut(thread.thread)?.context[usize::try_from(slot)?] = val; 5093 Ok(()) 5094 } 5095 5096 /// Returns whether there's a pending cancellation on the current guest thread, 5097 /// consuming the event if so. 5098 fn take_pending_cancellation(&mut self) -> Result<bool> { 5099 let thread = self.current_guest_thread()?; 5100 if let Some(event) = self.get_mut(thread.task)?.event.take() { 5101 assert!(matches!(event, Event::Cancelled)); 5102 Ok(true) 5103 } else { 5104 Ok(false) 5105 } 5106 } 5107 5108 fn check_blocking_for(&mut self, task: TableId<GuestTask>) -> Result<()> { 5109 if self.may_block(task)? { 5110 Ok(()) 5111 } else { 5112 Err(Trap::CannotBlockSyncTask.into()) 5113 } 5114 } 5115 5116 fn may_block(&mut self, task: TableId<GuestTask>) -> Result<bool> { 5117 let task = self.get_mut(task)?; 5118 Ok(task.async_function || task.returned_or_cancelled()) 5119 } 5120 5121 /// Used by `ResourceTables` to acquire the current `CallContext` for the 5122 /// specified task. 5123 /// 5124 /// The `task` is bit-packed as returned by `current_call_context_scope_id` 5125 /// below. 5126 pub fn call_context(&mut self, task: u32) -> &mut CallContext { 5127 let (task, is_host) = (task >> 1, task & 1 == 1); 5128 if is_host { 5129 let task: TableId<HostTask> = TableId::new(task); 5130 &mut self.get_mut(task).unwrap().call_context 5131 } else { 5132 let task: TableId<GuestTask> = TableId::new(task); 5133 &mut self.get_mut(task).unwrap().call_context 5134 } 5135 } 5136 5137 /// Used by `ResourceTables` to record the scope of a borrow to get undone 5138 /// in the future. 5139 pub fn current_call_context_scope_id(&self) -> u32 { 5140 let (bits, is_host) = match self.current_thread { 5141 CurrentThread::Guest(id) => (id.task.rep(), false), 5142 CurrentThread::Host(id) => (id.rep(), true), 5143 CurrentThread::None => unreachable!(), 5144 }; 5145 assert_eq!((bits << 1) >> 1, bits); 5146 (bits << 1) | u32::from(is_host) 5147 } 5148 5149 fn current_guest_thread(&self) -> Result<QualifiedThreadId> { 5150 match self.current_thread.guest() { 5151 Some(id) => Ok(*id), 5152 None => bail_bug!("current thread is not a guest thread"), 5153 } 5154 } 5155 5156 fn current_host_thread(&self) -> Result<TableId<HostTask>> { 5157 match self.current_thread.host() { 5158 Some(id) => Ok(id), 5159 None => bail_bug!("current thread is not a host thread"), 5160 } 5161 } 5162 5163 fn futures_mut(&mut self) -> Result<&mut FuturesUnordered<HostTaskFuture>> { 5164 match self.futures.get_mut().as_mut() { 5165 Some(f) => Ok(f), 5166 None => bail_bug!("futures field of concurrent state is currently taken"), 5167 } 5168 } 5169 } 5170 5171 /// Provide a type hint to compiler about the shape of a parameter lower 5172 /// closure. 5173 fn for_any_lower< 5174 F: FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync, 5175 >( 5176 fun: F, 5177 ) -> F { 5178 fun 5179 } 5180 5181 /// Provide a type hint to compiler about the shape of a result lift closure. 5182 fn for_any_lift< 5183 F: FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync, 5184 >( 5185 fun: F, 5186 ) -> F { 5187 fun 5188 } 5189 5190 /// Wrap the specified future in a `poll_fn` which asserts that the future is 5191 /// only polled from the event loop of the specified `Store`. 5192 /// 5193 /// See `StoreContextMut::run_concurrent` for details. 5194 fn checked<F: Future + Send + 'static>( 5195 id: StoreId, 5196 fut: F, 5197 ) -> impl Future<Output = F::Output> + Send + 'static { 5198 async move { 5199 let mut fut = pin!(fut); 5200 future::poll_fn(move |cx| { 5201 let message = "\ 5202 `Future`s which depend on asynchronous component tasks, streams, or \ 5203 futures to complete may only be polled from the event loop of the \ 5204 store to which they belong. Please use \ 5205 `StoreContextMut::{run_concurrent,spawn}` to poll or await them.\ 5206 "; 5207 tls::try_get(|store| { 5208 let matched = match store { 5209 tls::TryGet::Some(store) => store.id() == id, 5210 tls::TryGet::Taken | tls::TryGet::None => false, 5211 }; 5212 5213 if !matched { 5214 panic!("{message}") 5215 } 5216 }); 5217 fut.as_mut().poll(cx) 5218 }) 5219 .await 5220 } 5221 } 5222 5223 /// Assert that `StoreContextMut::run_concurrent` has not been called from 5224 /// within an store's event loop. 5225 fn check_recursive_run() { 5226 tls::try_get(|store| { 5227 if !matches!(store, tls::TryGet::None) { 5228 panic!("Recursive `StoreContextMut::run_concurrent` calls not supported") 5229 } 5230 }); 5231 } 5232 5233 fn unpack_callback_code(code: u32) -> (u32, u32) { 5234 (code & 0xF, code >> 4) 5235 } 5236 5237 /// Helper struct for packaging parameters to be passed to 5238 /// `ComponentInstance::waitable_check` for calls to `waitable-set.wait` or 5239 /// `waitable-set.poll`. 5240 struct WaitableCheckParams { 5241 set: TableId<WaitableSet>, 5242 options: OptionsIndex, 5243 payload: u32, 5244 } 5245 5246 /// Indicates whether `ComponentInstance::waitable_check` is being called for 5247 /// `waitable-set.wait` or `waitable-set.poll`. 5248 enum WaitableCheck { 5249 Wait, 5250 Poll, 5251 } 5252 5253 /// Represents a guest task called from the host, prepared using `prepare_call`. 5254 pub(crate) struct PreparedCall<R> { 5255 /// The guest export to be called 5256 handle: Func, 5257 /// The guest thread created by `prepare_call` 5258 thread: QualifiedThreadId, 5259 /// The number of lowered core Wasm parameters to pass to the call. 5260 param_count: usize, 5261 /// The `oneshot::Receiver` to which the result of the call will be 5262 /// delivered when it is available. 5263 rx: oneshot::Receiver<LiftedResult>, 5264 _phantom: PhantomData<R>, 5265 } 5266 5267 impl<R> PreparedCall<R> { 5268 /// Get a copy of the `TaskId` for this `PreparedCall`. 5269 pub(crate) fn task_id(&self) -> TaskId { 5270 TaskId { 5271 task: self.thread.task, 5272 } 5273 } 5274 } 5275 5276 /// Represents a task created by `prepare_call`. 5277 pub(crate) struct TaskId { 5278 task: TableId<GuestTask>, 5279 } 5280 5281 impl TaskId { 5282 /// The host future for an async task was dropped. If the parameters have not been lowered yet, 5283 /// it is no longer valid to do so, as the lowering closure would see a dangling pointer. In this case, 5284 /// we delete the task eagerly. Otherwise, there may be running threads, or ones that are suspended 5285 /// and can be resumed by other tasks for this component, so we mark the future as dropped 5286 /// and delete the task when all threads are done. 5287 pub(crate) fn host_future_dropped<T>(&self, store: StoreContextMut<T>) -> Result<()> { 5288 let task = store.0.concurrent_state_mut().get_mut(self.task)?; 5289 if !task.already_lowered_parameters() { 5290 Waitable::Guest(self.task).delete_from(store.0.concurrent_state_mut())? 5291 } else { 5292 task.host_future_state = HostFutureState::Dropped; 5293 if task.ready_to_delete() { 5294 Waitable::Guest(self.task).delete_from(store.0.concurrent_state_mut())? 5295 } 5296 } 5297 Ok(()) 5298 } 5299 } 5300 5301 /// Prepare a call to the specified exported Wasm function, providing functions 5302 /// for lowering the parameters and lifting the result. 5303 /// 5304 /// To enqueue the returned `PreparedCall` in the `ComponentInstance`'s event 5305 /// loop, use `queue_call`. 5306 pub(crate) fn prepare_call<T, R>( 5307 mut store: StoreContextMut<T>, 5308 handle: Func, 5309 param_count: usize, 5310 host_future_present: bool, 5311 lower_params: impl FnOnce(Func, StoreContextMut<T>, &mut [MaybeUninit<ValRaw>]) -> Result<()> 5312 + Send 5313 + Sync 5314 + 'static, 5315 lift_result: impl FnOnce(Func, &mut StoreOpaque, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> 5316 + Send 5317 + Sync 5318 + 'static, 5319 ) -> Result<PreparedCall<R>> { 5320 let (options, _flags, ty, raw_options) = handle.abi_info(store.0); 5321 5322 let instance = handle.instance().id().get(store.0); 5323 let options = &instance.component().env_component().options[options]; 5324 let ty = &instance.component().types()[ty]; 5325 let async_function = ty.async_; 5326 let task_return_type = ty.results; 5327 let component_instance = raw_options.instance; 5328 let callback = options.callback.map(|i| instance.runtime_callback(i)); 5329 let memory = options 5330 .memory() 5331 .map(|i| instance.runtime_memory(i)) 5332 .map(SendSyncPtr::new); 5333 let string_encoding = options.string_encoding; 5334 let token = StoreToken::new(store.as_context_mut()); 5335 let state = store.0.concurrent_state_mut(); 5336 5337 let (tx, rx) = oneshot::channel(); 5338 5339 let instance = RuntimeInstance { 5340 instance: handle.instance().id().instance(), 5341 index: component_instance, 5342 }; 5343 let caller = state.current_thread; 5344 let task = GuestTask::new( 5345 Box::new(for_any_lower(move |store, params| { 5346 lower_params(handle, token.as_context_mut(store), params) 5347 })), 5348 LiftResult { 5349 lift: Box::new(for_any_lift(move |store, result| { 5350 lift_result(handle, store, result) 5351 })), 5352 ty: task_return_type, 5353 memory, 5354 string_encoding, 5355 }, 5356 Caller::Host { 5357 tx: Some(tx), 5358 host_future_present, 5359 caller, 5360 }, 5361 callback.map(|callback| { 5362 let callback = SendSyncPtr::new(callback); 5363 let instance = handle.instance(); 5364 Box::new(move |store: &mut dyn VMStore, event, handle| { 5365 let store = token.as_context_mut(store); 5366 // SAFETY: Per the contract of `prepare_call`, the callback 5367 // will remain valid at least as long is this task exists. 5368 unsafe { instance.call_callback(store, callback, event, handle) } 5369 }) as CallbackFn 5370 }), 5371 instance, 5372 async_function, 5373 )?; 5374 5375 let task = state.push(task)?; 5376 let new_thread = GuestThread::new_implicit(state, task)?; 5377 let thread = state.push(new_thread)?; 5378 state.get_mut(task)?.threads.insert(thread); 5379 5380 if !store.0.may_enter(instance)? { 5381 bail!(Trap::CannotEnterComponent); 5382 } 5383 5384 Ok(PreparedCall { 5385 handle, 5386 thread: QualifiedThreadId { task, thread }, 5387 param_count, 5388 rx, 5389 _phantom: PhantomData, 5390 }) 5391 } 5392 5393 /// Queue a call previously prepared using `prepare_call` to be run as part of 5394 /// the associated `ComponentInstance`'s event loop. 5395 /// 5396 /// The returned future will resolve to the result once it is available, but 5397 /// must only be polled via the instance's event loop. See 5398 /// `StoreContextMut::run_concurrent` for details. 5399 pub(crate) fn queue_call<T: 'static, R: Send + 'static>( 5400 mut store: StoreContextMut<T>, 5401 prepared: PreparedCall<R>, 5402 ) -> Result<impl Future<Output = Result<R>> + Send + 'static + use<T, R>> { 5403 let PreparedCall { 5404 handle, 5405 thread, 5406 param_count, 5407 rx, 5408 .. 5409 } = prepared; 5410 5411 queue_call0(store.as_context_mut(), handle, thread, param_count)?; 5412 5413 Ok(checked( 5414 store.0.id(), 5415 rx.map(move |result| match result { 5416 Ok(r) => match r.downcast() { 5417 Ok(r) => Ok(*r), 5418 Err(_) => bail_bug!("wrong type of value produced"), 5419 }, 5420 Err(e) => Err(e.into()), 5421 }), 5422 )) 5423 } 5424 5425 /// Queue a call previously prepared using `prepare_call` to be run as part of 5426 /// the associated `ComponentInstance`'s event loop. 5427 fn queue_call0<T: 'static>( 5428 store: StoreContextMut<T>, 5429 handle: Func, 5430 guest_thread: QualifiedThreadId, 5431 param_count: usize, 5432 ) -> Result<()> { 5433 let (_options, _, _ty, raw_options) = handle.abi_info(store.0); 5434 let is_concurrent = raw_options.async_; 5435 let callback = raw_options.callback; 5436 let instance = handle.instance(); 5437 let callee = handle.lifted_core_func(store.0); 5438 let post_return = handle.post_return_core_func(store.0); 5439 let callback = callback.map(|i| { 5440 let instance = instance.id().get(store.0); 5441 SendSyncPtr::new(instance.runtime_callback(i)) 5442 }); 5443 5444 log::trace!("queueing call {guest_thread:?}"); 5445 5446 // SAFETY: `callee`, `callback`, and `post_return` are valid pointers 5447 // (with signatures appropriate for this call) and will remain valid as 5448 // long as this instance is valid. 5449 unsafe { 5450 instance.queue_call( 5451 store, 5452 guest_thread, 5453 SendSyncPtr::new(callee), 5454 param_count, 5455 1, 5456 is_concurrent, 5457 callback, 5458 post_return.map(SendSyncPtr::new), 5459 ) 5460 } 5461 } 5462