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