Skip to main content

wasmtime_environ/
vmtypes.rs

1//! Centralized definitions of the various `VM*` types whose layout is shared
2//! between the runtime (which uses the actual structures) and the compiler
3//! (which uses the types' offsets and has per-type alias regions).
4//!
5//! To keep these in sync, the shape of each type is defined exactly once here,
6//! via the higher-order [`for_each_vm_type!`] macro, and each consumer
7//! generates its view of the type from that single source of truth.
8
9/// Invoke the given macro `$mac` once, passing it the definitions of each of the
10/// `VM*` types whose layout is shared between the runtime, compilation offsets,
11/// and Cranelift alias regions.
12///
13/// This is a higher-order macro: callers define a `macro_rules!` macro that
14/// matches the grammar defined below and pass its name as an argument to this
15/// macro's invocation, e.g. `for_each_vm_type!(define_vm_types)`.
16///
17/// # Grammar
18///
19/// Each type is either a `struct` or a `#[repr(C, _)]` `enum`, preceded by:
20///
21/// * Doc-comment attributes (`#[doc = "..."]`).
22///
23/// * An optional `#[cfg(...)]` attribute, gating the type on the Cargo features
24///   whose code actually uses it.
25///
26///   Only the runtime's `struct` definition (and its layout test) is gated by
27///   it. A type's offsets and alias regions are always generated because the
28///   `wasmtime-environ` and `wasmtime-internal-cranelift` crates do not have
29///   Cargo features for all the various Wasm features.
30///
31/// * An optional `#[derive(...)]` attribute.
32///
33/// * A `#[repr(...)]` attribute.
34///
35/// * A `#[snake_name = <ident>]` attribute giving the type's name in
36///   `snake_case`, used to generate accessor method names.
37///
38/// Each field may be preceded by doc-comment attributes and, optionally, these
39/// marker attributes, in this order:
40///
41/// * `#[aggregate]`: this field is a composite (a nested struct or array)
42///   rather than a single scalar. Compiled Wasm code accesses such a field's
43///   interior piecewise, so there is no one Cranelift type for the field as a
44///   whole and no alias-region accessor is generated for it. The field's offset
45///   is still generated, since that is what interior accesses are computed
46///   relative to.
47///
48/// * `#[indexed]`: this field is a fixed-size array of a scalar type, whose
49///   elements compiled Wasm code accesses individually by a compile-time
50///   constant index. Like `#[aggregate]`, the field has no single Cranelift
51///   type; unlike `#[aggregate]`, its elements all do, so an alias-region
52///   accessor taking that index is generated for it and each element gets its
53///   own alias region.
54///
55/// * `#[readonly]` and/or `#[can_move]`: describe how Cranelift may treat loads
56///   and stores of that field.
57///
58/// ## Enums
59///
60/// A type may also be an `enum`, which must be `#[repr(C, $tag)]` for an
61/// integer `$tag`:
62///
63/// ```ignore
64/// #[derive(Debug)]
65/// #[repr(C, u32)]
66/// #[snake_name = vm_example]
67/// pub enum VMExample {
68///     #[snake_name = variant_a]
69///     VariantA {
70///         field: u32,
71///     } = 0,
72///
73///     #[snake_name = variant_b]
74///     VariantB {
75///         other: u64,
76///     } = 1,
77/// }
78/// ```
79///
80/// Rust lays such an enum out as a `#[repr(C)]` struct of a `$tag` tag followed
81/// by a union of the variants, which is what lets the same offset machinery
82/// describe it. The `C` is what guarantees that, so it is required.
83///
84/// Beyond a struct's rules, each variant needs an explicit discriminant (the
85/// tag values compiled code compares against), braces even when empty, and its
86/// own `#[snake_name]` for its generated accessors. Later attributes reach only
87/// the runtime definition; `#[cfg]` is not among them, since a type's layout
88/// must not vary with Cargo features. Variant fields take a struct field's
89/// marker attributes but no visibility.
90///
91/// An enum gets two alias regions rather than a struct's one per field: one for
92/// the tag, one shared by all variants' fields, because they overlap.
93#[macro_export]
94macro_rules! for_each_vm_type {
95    ($mac:ident) => {
96        $mac! {
97            /// The fields compiled code needs to access to utilize a WebAssembly linear
98            /// memory defined within the instance, namely the start address and the
99            /// size in bytes.
100            #[derive(Debug)]
101            #[repr(C)]
102            #[snake_name = vm_memory_definition]
103            pub struct VMMemoryDefinition {
104                /// The start address.
105                pub base: VmPtr<u8>,
106
107                /// The current logical size of this linear memory in bytes.
108                ///
109                /// This is atomic because shared memories must be able to grow their length
110                /// atomically. For relaxed access, see
111                /// [`VMMemoryDefinition::current_length()`].
112                pub current_length: AtomicUsize,
113            }
114
115            /// The fields compiled code needs to access to utilize a WebAssembly table
116            /// defined within the instance.
117            #[derive(Debug, Copy, Clone)]
118            #[repr(C)]
119            #[snake_name = vm_table_definition]
120            pub struct VMTableDefinition {
121                /// Pointer to the table data.
122                pub base: VmPtr<u8>,
123
124                /// The current number of elements in the table.
125                pub current_elements: usize,
126            }
127
128            /// A WebAssembly tag defined within the instance.
129            #[derive(Debug)]
130            #[repr(C)]
131            #[snake_name = vm_tag_definition]
132            pub struct VMTagDefinition {
133                /// Function signature's type id.
134                pub type_index: VMSharedTypeIndex,
135            }
136
137            /// The VM caller-checked "funcref" record, for caller-side signature checking.
138            ///
139            /// It consists of function pointer(s), a type id to be checked by the
140            /// caller, and the vmctx closure associated with this function.
141            #[derive(Debug, Clone)]
142            #[repr(C)]
143            #[snake_name = vm_func_ref]
144            pub struct VMFuncRef {
145                /// Function pointer for this funcref if being called via the "array"
146                /// calling convention that `Func::new` et al use.
147                pub array_call: VmPtr<VMArrayCallFunction>,
148
149                /// Function pointer for this funcref if being called via the calling
150                /// convention we use when compiling Wasm.
151                ///
152                /// Most functions come with a function pointer that we can use when they
153                /// are called from Wasm. The notable exception is when we `Func::wrap` a
154                /// host function, and we don't have a Wasm compiler on hand to compile a
155                /// Wasm-to-native trampoline for the function. In this case, we leave
156                /// `wasm_call` empty until the function is passed as an import to Wasm (or
157                /// otherwise exposed to Wasm via tables/globals). At this point, we look up
158                /// a Wasm-to-native trampoline for the function in the Wasm's compiled
159                /// module and use that fill in `VMFunctionImport::wasm_call`. **However**
160                /// there is no guarantee that the Wasm module has a trampoline for this
161                /// function's signature. The Wasm module only has trampolines for its
162                /// types, and if this function isn't of one of those types, then the Wasm
163                /// module will not have a trampoline for it. This is actually okay, because
164                /// it means that the Wasm cannot actually call this function. But it does
165                /// mean that this field needs to be an `Option` even though it is non-null
166                /// the vast vast vast majority of the time.
167                ///
168                /// Once a `VMFuncRef` is exposed to compiled code this field
169                /// never changes again, so accesses of it are `readonly`. It is
170                /// not `can_move`, however: the load may be the one that traps
171                /// on a null funcref, and moving it would move that trap.
172                #[readonly]
173                pub wasm_call: Option<VmPtr<VMWasmCallFunction>>,
174
175                /// Function signature's type id.
176                ///
177                /// See the note about `readonly` and not `can_move` on
178                /// `wasm_call`.
179                #[readonly]
180                pub type_index: VMSharedTypeIndex,
181
182                /// The VM state associated with this function.
183                ///
184                /// The actual definition of what this pointer points to depends on the
185                /// function being referenced: for core Wasm functions, this is a `*mut
186                /// VMContext`, for host functions it is a `*mut VMHostFuncContext`, and for
187                /// component functions it is a `*mut VMComponentContext`.
188                ///
189                /// See the note about `readonly` and not `can_move` on
190                /// `wasm_call`.
191                #[readonly]
192                pub vmctx: VmPtr<VMOpaqueContext>,
193            }
194
195            /// An imported function.
196            ///
197            /// Basically the same as `VMFuncRef`, except that `wasm_call` is not optional.
198            #[derive(Debug, Clone)]
199            #[repr(C)]
200            #[snake_name = vm_function_import]
201            pub struct VMFunctionImport {
202                /// Same as `VMFuncRef::array_call`.
203                #[readonly]
204                #[can_move]
205                pub array_call: VmPtr<VMArrayCallFunction>,
206
207                /// Same as `VMFuncRef::wasm_call`, except always non-null. Must be filled
208                /// in by the time Wasm is importing this function!
209                #[readonly]
210                #[can_move]
211                pub wasm_call: VmPtr<VMWasmCallFunction>,
212
213                /// Function signature's _actual_ type id.
214                ///
215                /// This is the type that the function was defined with, not the type that
216                /// it was imported as. These two can be different in the face of subtyping
217                /// and we need the former for to correctly implement dynamic downcasts.
218                #[readonly]
219                #[can_move]
220                pub type_index: VMSharedTypeIndex,
221
222                /// Same as `VMFuncRef::vmctx`.
223                #[readonly]
224                #[can_move]
225                pub vmctx: VmPtr<VMOpaqueContext>,
226            }
227
228            /// The fields compiled code needs to access to utilize a WebAssembly table
229            /// imported from another instance.
230            #[derive(Debug, Copy, Clone)]
231            #[repr(C)]
232            #[snake_name = vm_table_import]
233            pub struct VMTableImport {
234                /// A pointer to the imported table description.
235                #[readonly]
236                #[can_move]
237                pub from: VmPtr<VMTableDefinition>,
238
239                /// A pointer to the `VMContext` that owns the table description.
240                #[readonly]
241                #[can_move]
242                pub vmctx: VmPtr<VMContext>,
243
244                /// The table index, within `vmctx`, this definition resides at.
245                #[readonly]
246                #[can_move]
247                pub index: DefinedTableIndex,
248            }
249
250            /// The fields compiled code needs to access to utilize a WebAssembly linear
251            /// memory imported from another instance.
252            #[derive(Debug, Copy, Clone)]
253            #[repr(C)]
254            #[snake_name = vm_memory_import]
255            pub struct VMMemoryImport {
256                /// A pointer to the imported memory description.
257                #[readonly]
258                #[can_move]
259                pub from: VmPtr<VMMemoryDefinition>,
260
261                /// A pointer to the `VMContext` that owns the memory description.
262                #[readonly]
263                #[can_move]
264                pub vmctx: VmPtr<VMContext>,
265
266                /// The index of the memory in the containing `vmctx`.
267                #[readonly]
268                #[can_move]
269                pub index: DefinedMemoryIndex,
270            }
271
272            /// The fields compiled code needs to access to utilize a WebAssembly global
273            /// variable imported from another instance.
274            ///
275            /// Note that unlike with functions, tables, and memories, `VMGlobalImport`
276            /// doesn't include a `vmctx` pointer. Globals are never resized, and don't
277            /// require a `vmctx` pointer to access.
278            #[derive(Debug, Copy, Clone)]
279            #[repr(C)]
280            #[snake_name = vm_global_import]
281            pub struct VMGlobalImport {
282                /// A pointer to the imported global variable description.
283                #[readonly]
284                #[can_move]
285                pub from: VmPtr<VMGlobalDefinition>,
286
287                /// A pointer to the context that owns the global.
288                ///
289                /// Exactly what's stored here is dictated by `kind` below. This is `None`
290                /// for `VMGlobalKind::Host`, it's a `VMContext` for
291                /// `VMGlobalKind::Instance`, and it's `VMComponentContext` for
292                /// `VMGlobalKind::ComponentFlags`.
293                #[readonly]
294                #[can_move]
295                pub vmctx: Option<VmPtr<VMOpaqueContext>>,
296
297                /// The kind of global, and extra location information in addition to
298                /// `vmctx` above.
299                #[readonly]
300                #[can_move]
301                pub kind: VMGlobalKind,
302            }
303
304            /// The fields compiled code needs to access to utilize a WebAssembly
305            /// tag imported from another instance.
306            #[derive(Debug, Copy, Clone)]
307            #[repr(C)]
308            #[snake_name = vm_tag_import]
309            pub struct VMTagImport {
310                /// A pointer to the imported tag description.
311                #[readonly]
312                #[can_move]
313                pub from: VmPtr<VMTagDefinition>,
314
315                /// The instance that owns this tag.
316                #[readonly]
317                #[can_move]
318                pub vmctx: VmPtr<VMContext>,
319
320                /// The index of the tag in the containing `vmctx`.
321                #[readonly]
322                #[can_move]
323                pub index: DefinedTagIndex,
324            }
325
326            /// Structure that holds all mutable context that is shared across all instances
327            /// in a store, for example data related to fuel or epochs.
328            ///
329            /// `VMStoreContext`s are one-to-one with `wasmtime::Store`s, the same way that
330            /// `VMContext`s are one-to-one with `wasmtime::Instance`s. And the same way
331            /// that multiple `wasmtime::Instance`s may be associated with the same
332            /// `wasmtime::Store`, multiple `VMContext`s hold a pointer to the same
333            /// `VMStoreContext` when they are associated with the same `wasmtime::Store`.
334            #[derive(Debug)]
335            // NB: `align(8)` is forced rather than inferred because the i386
336            // System V ABI aligns 64-bit integers to 4 bytes, and `VMOffsets`
337            // can't tell that target apart from the ones that align them to 8,
338            // since it only knows the target's pointer width.
339            #[repr(C, align(8))]
340            #[snake_name = vm_store_context]
341            pub struct VMStoreContext {
342                // NB: 64-bit integer fields are located first with pointer-sized fields
343                // trailing afterwards. That makes the offsets in this structure easier to
344                // calculate on 32-bit platforms as we don't have to worry about the
345                // alignment of 64-bit integers.
346                //
347                /// Indicator of how much fuel has been consumed and is remaining to
348                /// WebAssembly.
349                ///
350                /// This field is typically negative and increments towards positive. Upon
351                /// turning positive a wasm trap will be generated. This field is only
352                /// modified if wasm is configured to consume fuel.
353                pub fuel_consumed: UnsafeCell<i64>,
354
355                /// Deadline epoch for interruption: if epoch-based interruption
356                /// is enabled and the global (per engine) epoch counter is
357                /// observed to reach or exceed this value, the guest code will
358                /// yield if running asynchronously.
359                pub epoch_deadline: UnsafeCell<u64>,
360
361                /// Current stack limit of the wasm module.
362                ///
363                /// For more information see `crates/cranelift/src/lib.rs`.
364                pub stack_limit: UnsafeCell<usize>,
365
366                /// The `VMMemoryDefinition` for this store's GC heap.
367                #[aggregate]
368                pub gc_heap: UnsafeCell<VMMemoryDefinition>,
369
370                /// The value of the frame pointer register in the trampoline used
371                /// to call from Wasm to the host.
372                ///
373                /// Maintained by our Wasm-to-host trampoline, and cleared just
374                /// before calling into Wasm in `catch_traps`.
375                ///
376                /// This member is `0` when Wasm is actively running and has not called out
377                /// to the host.
378                ///
379                /// Used to find the start of a contiguous sequence of Wasm frames
380                /// when walking the stack. Note that we record the FP of the
381                /// *trampoline*'s frame, not the last Wasm frame, because we need
382                /// to know the SP (bottom of frame) of the last Wasm frame as
383                /// well in case we need to resume to an exception handler in that
384                /// frame. The FP of the last Wasm frame can be recovered by
385                /// loading the saved FP value at this FP address.
386                pub last_wasm_exit_trampoline_fp: UnsafeCell<usize>,
387
388                /// The last Wasm program counter before we called from Wasm to the host.
389                ///
390                /// Maintained by our Wasm-to-host trampoline, and cleared just before
391                /// calling into Wasm in `catch_traps`.
392                ///
393                /// This member is `0` when Wasm is actively running and has not called out
394                /// to the host.
395                ///
396                /// Used when walking a contiguous sequence of Wasm frames.
397                pub last_wasm_exit_pc: UnsafeCell<usize>,
398
399                /// The last host stack pointer before we called into Wasm from the host.
400                ///
401                /// Maintained by our host-to-Wasm trampoline. This member is `0` when Wasm
402                /// is not running, and it's set to nonzero once a host-to-wasm trampoline
403                /// is executed.
404                ///
405                /// When a host function is wrapped into a `wasmtime::Func`, and is then
406                /// called from the host, then this member is not changed meaning that the
407                /// previous activation in pointed to by `last_wasm_exit_trampoline_fp` is
408                /// still the last wasm set of frames on the stack.
409                ///
410                /// This field is saved/restored during fiber suspension/resumption
411                /// resumption as part of `CallThreadState::swap`.
412                ///
413                /// This field is used to find the end of a contiguous sequence of Wasm
414                /// frames when walking the stack. Additionally it's used when a trap is
415                /// raised as part of the set of parameters used to resume in the entry
416                /// trampoline's "catch" block.
417                pub last_wasm_entry_sp: UnsafeCell<usize>,
418
419                /// Same as `last_wasm_entry_sp`, but for the `fp` of the trampoline.
420                pub last_wasm_entry_fp: UnsafeCell<usize>,
421
422                /// The last trap handler from a host-to-wasm entry trampoline on the stack.
423                ///
424                /// This field is configured when the host calls into wasm by the trampoline
425                /// itself. It stores the `pc` of an exception handler suitable to handle
426                /// all traps (or uncaught exceptions).
427                pub last_wasm_entry_trap_handler: UnsafeCell<usize>,
428
429                /// Stack information used by stack switching instructions. See documentation
430                /// on `VMStackChain` for details.
431                #[aggregate]
432                pub stack_chain: UnsafeCell<VMStackChain>,
433
434                /// A pointer to the embedder's `T` inside a `Store<T>`, for use with the
435                /// `store-data-address` unsafe intrinsic.
436                ///
437                /// This pointer is fixed for the lifetime of the store, so loads
438                /// of it are `readonly` and `can_move`.
439                #[readonly]
440                #[can_move]
441                pub store_data: VmPtr<()>,
442
443                /// The range, in addresses, of the guard page that is currently in use.
444                ///
445                /// This field is used when signal handlers are run to determine whether a
446                /// faulting address lies within the guard page of an async stack for
447                /// example. If this happens then the signal handler aborts with a stack
448                /// overflow message similar to what would happen had the stack overflow
449                /// happened on the main thread. This field is, by default a null..null
450                /// range indicating that no async guard is in use (aka no fiber). In such a
451                /// situation while this field is read it'll never classify a fault as an
452                /// guard page fault.
453                #[aggregate]
454                pub async_guard_range: Range<*mut u8>,
455
456                /// The `context.{get,set}` values for the current thread in the component
457                /// model. This is only used for `component-model-async` and slot[1] is only
458                /// used for `component-model-threading`. Despite the conditional use nature
459                /// this is unconditionally present as it avoids the need to make logic in
460                /// `VMOffsets` conditional.
461                ///
462                /// This is saved/restored when threads are swapped in the component model.
463                ///
464                /// NB: `UnsafeCell` because JIT code writes to the slots.
465                #[indexed]
466                pub component_context: UnsafeCell<[u32; NUM_COMPONENT_CONTEXT_SLOTS]>,
467
468                /// JIT-visible current thread for the component model's sync-to-sync
469                /// adapter fast path.
470                ///
471                /// Like `component_context`, this is unconditionally present to keep
472                /// `VMOffsets` logic unconditional even though it is only used when
473                /// `component-model-async` is enabled.
474                ///
475                /// NB: `UnsafeCell` because JIT code writes to this field.
476                pub current_thread: UnsafeCell<VMLazyThread>,
477
478                /// Resource lends made under unforced `VMDeferredThread`s and not
479                /// yet reflected in any handle's `lend_count`.
480                ///
481                /// Holds `LAZY_LENDERS_CAPACITY` entries.
482                #[readonly]
483                #[can_move]
484                pub lazy_lenders: VmPtr<VMResourceIndex>,
485
486                /// Number of occupied slots at the front of `lazy_lenders`.
487                ///
488                /// NB: `UnsafeCell` because JIT code writes to this field.
489                pub lazy_lenders_len: UnsafeCell<usize>,
490
491                /// Nonzero while the store records its execution.
492                ///
493                /// Trampolines compiled for record/replay engines check it
494                /// before calling the `rr_enter` and `rr_leave` builtins. Like
495                /// `component_context` it is present even without the `rr`
496                /// feature to keep `VMOffsets` unconditional.
497                pub recording: u32,
498            }
499
500            /// JIT-visible representation of the store's current thread for the component
501            /// model, encoded as a single pointer-sized integer so that generated JIT code
502            /// can load, store, and compare it with a handful of instructions.
503            ///
504            /// This is the inline fast-path counterpart to the host-side `CurrentThread`: a
505            /// fused sync-to-sync adapter records a lazy deferred thread here (a pointer to
506            /// a `VMDeferredThread` on its own stack frame) instead of eagerly allocating a
507            /// `GuestTask`/`GuestThread` in the host. Host code promotes the deferred
508            /// thread into a real one only when it actually needs it; see
509            /// `StoreOpaque::force_current_thread`.
510            ///
511            /// This type is a bitpacked equivalent of the following logical `enum`:
512            ///
513            /// ```ignore
514            /// enum VMLazyThread {
515            ///     /// No thread.
516            ///     None,
517            ///
518            ///     /// The lazy thread was promoted and materialized; get it from
519            ///     /// `ConcurrentState::current_thread`.
520            ///     Forced,
521            ///
522            ///     /// The lazy thread has not been materialized, here is a pointer to the
523            ///     /// stack-allocated data needed to do force that promotion.
524            ///     Deferred(*mut VMDeferredThread),
525            /// }
526            /// ```
527            ///
528            /// Bitpacking details:
529            ///
530            /// * `None`: `0`
531            ///
532            /// * `Forced`: A non-zero value with its low-bit set.
533            ///
534            /// * `Deferred`: A non-zero value with its low-bit clear.
535            #[derive(Debug, Copy, Clone, PartialEq, Eq)]
536            #[repr(transparent)]
537            #[snake_name = vm_lazy_thread]
538            pub struct VMLazyThread {
539                /// The bitpacked thread representation described above.
540                ///
541                /// Private: use the `VMLazyThread::{none,forced,deferred}` constructors
542                /// and the `is_*`/`as_deferred` accessors instead of touching this
543                /// directly.
544                thread: Option<VmPtr<VMDeferredThread>>,
545            }
546
547            /// JIT-visible encoding of a component-model resource handle, as stored in
548            /// the `VMStoreContext::lazy_lenders` buffer.
549            ///
550            /// This is the raw version of `TypedResourceIndex` that is exposed to Wasm
551            /// code; use `VMResourceIndex::{new,get}` to convert.
552            #[derive(Debug, Copy, Clone, PartialEq, Eq)]
553            #[repr(C)]
554            #[snake_name = vm_resource_index]
555            pub struct VMResourceIndex {
556                /// The raw `TypeResourceTableIndex`, or `u32::MAX` for a host resource.
557                pub(crate) ty: u32,
558
559                /// The handle's index within its table.
560                pub(crate) index: u32,
561            }
562
563            /// A resource's type and "rep", as stored in a `VMHandleTableSlot`.
564            #[cfg(feature = "component-model")]
565            #[derive(Debug, Copy, Clone, PartialEq, Eq)]
566            #[repr(C)]
567            #[snake_name = vm_typed_resource]
568            pub struct VMTypedResource {
569                /// The raw `TypeResourceTableIndex`, or `u32::MAX` for a host resource.
570                pub(crate) ty: u32,
571
572                /// An integer whose meaning is up to whoever defined the
573                /// resource.
574                pub(crate) rep: u32,
575            }
576
577            /// A call's resource-borrow scope, as stored in a
578            /// `VMHandleTableSlot::ResourceBorrow`.
579            ///
580            /// Compiled code never reads this; it needs a defined layout only because
581            /// it shares a slot with `lend_count`, which compiled code does read.
582            #[cfg(feature = "component-model")]
583            #[derive(Debug, Copy, Clone, PartialEq, Eq)]
584            #[repr(C)]
585            #[snake_name = vm_scope]
586            pub struct VMScope {
587                /// The kind of scope. See the `id`/`host_id` constructors.
588                pub(crate) kind: u32,
589
590                /// The scope's identifier, whose meaning depends on `kind`.
591                pub(crate) id: u32,
592            }
593
594            /// One instance's view of a stream or future handle, as stored in a
595            /// `VMHandleTableSlot::{Stream,Future}`.
596            ///
597            /// As with `VMScope`, compiled code never reads this; it needs a defined
598            /// layout only because it sits inside a slot.
599            #[cfg(feature = "component-model")]
600            #[derive(Debug, Copy, Clone, PartialEq, Eq)]
601            #[repr(C)]
602            #[snake_name = vm_transmit_local_state]
603            pub struct VMTransmitLocalState {
604                /// The kind of transmit state. See the `VMTransmitLocalState`
605                /// constructors for details.
606                pub(crate) kind: u32,
607
608                /// Meaningful only for the `Write` and `Read` kinds.
609                pub(crate) done: u32,
610            }
611
612            /// One slot of a component instance's `HandleTable`.
613            ///
614            /// An instance keeps every kind of handle in one heterogeneous table, so a
615            /// slot is a tagged union over all of them, with free slots threaded into a
616            /// free list through `Free::next`.
617            ///
618            /// The layout is guaranteed because compiled adapter code reads and writes
619            /// slots directly; see `transfer_borrow_to_owner`.
620            #[cfg(feature = "component-model")]
621            #[derive(Debug)]
622            #[repr(C, u32)]
623            #[snake_name = vm_handle_table_slot]
624            pub enum VMHandleTableSlot {
625                /// An unallocated slot, holding the index of the next free slot.
626                #[snake_name = free]
627                Free {
628                    /// The next free slot's index, forming a free list.
629                    next: u32,
630                } = 0,
631
632                /// An owned resource handle.
633                #[snake_name = resource_own]
634                ResourceOwn {
635                    /// The resource's type and representation.
636                    #[aggregate]
637                    resource: VMTypedResource,
638
639                    /// How many times this handle has been lent out as a `borrow`.
640                    ///
641                    /// A handle with a nonzero lend count cannot be removed.
642                    ///
643                    /// NB: must be at the same offset as `Self::ResourceBorrow::lend_count`.
644                    lend_count: u32,
645                } = 1,
646
647                /// A borrowed resource handle, connected to the call scope it was
648                /// created within.
649                ///
650                /// Dropping the borrow decrements that scope's borrow count.
651                #[snake_name = resource_borrow]
652                ResourceBorrow {
653                    /// The resource's type and representation.
654                    #[aggregate]
655                    resource: VMTypedResource,
656
657                    /// How many times this borrow has been lent out to other calls.
658                    ///
659                    /// NB: must be at the same offset as `Self::ResourceOwn::lend_count`.
660                    lend_count: u32,
661
662                    /// The scope this borrow was created within.
663                    #[aggregate]
664                    scope: VMScope,
665                } = 2,
666
667                /// A host task handle.
668                #[snake_name = host_task]
669                HostTask {
670                    /// The task's representation.
671                    rep: u32,
672                } = 3,
673
674                /// A guest task handle.
675                #[snake_name = guest_task]
676                GuestTask {
677                    /// The task's representation.
678                    rep: u32,
679                } = 4,
680
681                /// A guest thread handle.
682                #[snake_name = guest_thread]
683                #[cfg_attr(
684                    not(feature = "component-model-async"),
685                    allow(
686                        dead_code,
687                        reason = "slot layout should not vary with cargo features"
688                    )
689                )]
690                GuestThread {
691                    /// The thread's representation.
692                    rep: u32,
693                } = 5,
694
695                /// A stream handle.
696                #[snake_name = stream]
697                Stream {
698                    /// The stream's `TypeStreamTableIndex`.
699                    ty: u32,
700
701                    /// The stream's representation.
702                    rep: u32,
703
704                    /// This instance's view of the stream's state.
705                    #[aggregate]
706                    state: VMTransmitLocalState,
707                } = 6,
708
709                /// A future handle.
710                #[snake_name = future]
711                Future {
712                    /// The future's `TypeFutureTableIndex`.
713                    ty: u32,
714
715                    /// The future's representation.
716                    rep: u32,
717
718                    /// This instance's view of the future's state.
719                    #[aggregate]
720                    state: VMTransmitLocalState,
721                } = 7,
722
723                /// A waitable-set handle.
724                #[snake_name = waitable_set]
725                WaitableSet {
726                    /// The waitable set's representation.
727                    rep: u32,
728                } = 8,
729
730                /// An error-context handle.
731                #[snake_name = error_context]
732                ErrorContext {
733                    /// The error context's representation.
734                    rep: u32,
735                } = 9,
736            }
737
738            /// One `HandleTable`'s slots, as compiled code sees them.
739            ///
740            /// The length lets a fused adapter's inline to-owner lend bounds check a
741            /// guest-supplied handle. Must be rewritten whenever the buffer grows.
742            #[cfg(feature = "component-model")]
743            #[derive(Debug, Copy, Clone)]
744            #[repr(C)]
745            #[snake_name = vm_handle_table]
746            pub struct VMHandleTable {
747                /// Pointer to the slots.
748                pub base: VmPtr<VMHandleTableSlot>,
749
750                /// The number of slots in `base`.
751                pub current_slots: usize,
752            }
753
754            /// A deferred component-model thread.
755            ///
756            /// This is an on-stack record pushed by a fused sync-to-sync adapter's fast
757            /// path to defer the work that the `enter_sync_call` libcall would otherwise do
758            /// eagerly.
759            ///
760            /// The adapter allocates one of these in its own stack frame, links the
761            /// previous current-thread value to it via `parent`, and finally points
762            /// `VMStoreContext::current_thread` at it. When host code actually needs the
763            /// real thread, it walks the `parent` chain to materialize thread state (see
764            /// `StoreOpaque::force_current_thread`).
765            #[derive(Debug)]
766            #[repr(C)]
767            #[snake_name = vm_deferred_thread]
768            pub struct VMDeferredThread {
769                /// The previous value of `VMStoreContext::current_thread`.
770                pub parent: VMLazyThread,
771
772                /// Whether the callee is async-lifted (a deferred `enter_sync_call` arg).
773                pub callee_async: u32,
774
775                /// The callee component instance (a deferred `enter_sync_call` argument).
776                pub callee_instance: u32,
777
778                /// The caller thread's `context.{get,set}` slots, saved on entry and
779                /// restored on the fast-path exit (or recovered while forcing).
780                #[indexed]
781                pub saved_context: [u32; NUM_COMPONENT_CONTEXT_SLOTS],
782
783                /// `VMStoreContext::lazy_lenders_len` as of this frame's push, so
784                /// that the lends this frame recorded are everything at or after it.
785                ///
786                /// Frames nest with the call stack, so that is always a contiguous
787                /// suffix by the time this frame exits, and exiting an unforced frame
788                /// discards it by resetting `lazy_lenders_len` back to this.
789                pub lazy_lenders_start: usize,
790            }
791
792            /// This type is used to save (and subsequently restore) a subset of
793            /// the data in `VMStoreContext`.
794            ///
795            /// See documentation of `VMStackChain` for the exact uses.
796            #[derive(Debug, Default, Clone)]
797            #[repr(C)]
798            #[snake_name = vm_stack_limits]
799            pub struct VMStackLimits {
800                /// Saved version of the `stack_limit` field of `VMStoreContext`.
801                pub stack_limit: usize,
802                /// Saved version of the `last_wasm_entry_fp` field of
803                /// `VMStoreContext`.
804                pub last_wasm_entry_fp: usize,
805                /// Saved version of the `last_wasm_entry_sp` field of
806                /// `VMStoreContext`.
807                pub last_wasm_entry_sp: usize,
808                /// Saved version of the `last_wasm_entry_trap_handler` field of
809                /// `VMStoreContext`.
810                pub last_wasm_entry_trap_handler: usize,
811            }
812
813            /// A reference to a buffer ("array") allocated on a continuation's
814            /// stack.
815            ///
816            /// The elements are of whatever type the buffer's user expects;
817            /// `data` is an untyped pointer, and the runtime casts it at each
818            /// use site.
819            #[derive(Debug, Clone)]
820            #[repr(C)]
821            #[snake_name = vm_host_array]
822            pub struct VMHostArray {
823                /// Number of currently occupied slots.
824                pub length: u32,
825
826                /// Number of slots in the data buffer. Note that this is *not*
827                /// the size of the buffer in bytes!
828                pub capacity: u32,
829
830                /// The buffer itself, which lives on the continuation's stack
831                /// rather than in this object.
832                pub data: Option<VmPtr<u8>>,
833            }
834
835            /// Payload values exchanged with a continuation and the metadata
836            /// needed to trace GC references among them.
837            #[derive(Debug, Clone)]
838            #[repr(C)]
839            #[snake_name = vm_payloads]
840            pub struct VMPayloads {
841                /// The payload values themselves.
842                #[aggregate]
843                pub buffer: VMHostArray,
844
845                /// One marker byte per buffer slot, indicating whether that
846                /// slot contains a GC reference, or `None` when no slots do.
847                pub gc_ref_data: Option<VmPtr<u8>>,
848            }
849
850            /// AddressSanitizer bookkeeping associated with a stack.
851            #[derive(Debug, Clone, Default)]
852            #[repr(C)]
853            #[snake_name = vm_asan_stack_support]
854            pub struct VMAsanStackSupport {
855                /// Bottom of the usable stack range reported to ASan,
856                /// or `None` until ASan discovers an initial stack's
857                /// bounds. Technically only needed by the runtime,
858                /// but we are using `VmPtr` here to avoid introducing
859                /// macro rules for `*mut u8` just for the sake of ASan
860                /// builds.
861                pub stack_bottom: Option<VmPtr<u8>>,
862
863                /// Size of the usable stack range reported to ASan.
864                pub stack_size: usize,
865
866                /// The stack whose bounds ASan will report when the next
867                /// stack-switch handshake is completed on this stack.
868                /// `None` when no handshake is pending.
869                pub pending_source_csi: Option<VmPtr<VMCommonStackInformation>>,
870            }
871
872            /// The information saved for every stack, whether it is a
873            /// continuation's or the initial stack's.
874            #[derive(Debug, Clone)]
875            #[repr(C)]
876            #[snake_name = vm_common_stack_information]
877            pub struct VMCommonStackInformation {
878                /// The subset of `VMStoreContext` saved for this stack.
879                #[aggregate]
880                pub limits: VMStackLimits,
881
882                /// Where this stack is in its life cycle; a `VMStackState`
883                /// discriminant.
884                pub state: VMStackState,
885
886                /// The tags this stack handles, set while it is a `Parent`.
887                #[aggregate]
888                pub handlers: VMHostArray,
889
890                /// The index within `handlers` of the first `switch` handler.
891                pub first_switch_handler_index: u32,
892
893                /// AddressSanitizer bookkeeping for this stack.
894                #[aggregate]
895                pub asan: VMAsanStackSupport,
896            }
897
898            /// A continuation.
899            #[repr(C)]
900            #[snake_name = vm_cont_ref]
901            pub struct VMContRef {
902                /// The information saved for this continuation's stack.
903                #[aggregate]
904                pub common_stack_information: VMCommonStackInformation,
905
906                /// This continuation's parent: another continuation, the
907                /// initial stack, or absent.
908                #[aggregate]
909                pub parent_chain: VMStackChain,
910
911                /// Revision counter.
912                pub revision: usize,
913
914                /// The end of this continuation's parent chain while it is
915                /// `Suspended` or `Fresh`, and `None` while it is running.
916                pub last_ancestor: Option<VmPtr<VMContRef>>,
917
918                /// The stack this continuation runs on.
919                #[aggregate]
920                pub stack: VMContinuationStack,
921
922                /// The arguments to, and return values of, the function passed
923                /// to `cont.new`.
924                #[aggregate]
925                pub args: VMPayloads,
926
927                /// The payloads passed to and from this continuation once it
928                /// has been suspended.
929                #[aggregate]
930                pub values: VMPayloads,
931
932                /// Tells the compiler that this structure has potential
933                /// self-references, through `last_ancestor`.
934                ///
935                /// This is a zero-sized type in final position, so it affects
936                /// neither this type's size nor its alignment.
937                #[aggregate]
938                pub _marker: PhantomPinned,
939            }
940
941            /// A slight variation of `VMContObj` which allows the
942            /// `contref` to be instantiated to null,
943            /// i.e. `Option::None`. This representation is used by
944            /// the GC infrastructure to construct a canonical
945            /// null-esque continuation object.
946            #[cfg(all(feature = "gc", feature = "stack-switching"))]
947            #[repr(C)]
948            #[snake_name = vm_raw_cont_obj]
949            pub struct VMRawContObj {
950                pub contref: Option<VmPtr<u8>>,
951                pub revision: usize,
952            }
953
954            /// The deferred-reference-counting collector's JIT-accessible heap
955            /// data.
956            ///
957            /// This is a separate allocation, reached through the
958            /// `VMContext::gc_heap_data` pointer. Its fields are not GC heap
959            /// locations, so they get this type's own alias regions rather than
960            /// the GC heap's.
961            ///
962            /// `wasmtime::runtime::vm::gc::enabled::drc` owns one of these,
963            /// wrapped in a cell because compiled Wasm writes to it, and
964            /// accesses it only through that wrapper's methods.
965            #[cfg(feature = "gc-drc")]
966            #[derive(Default)]
967            #[repr(C)]
968            #[snake_name = vm_drc_heap_data]
969            pub struct VMDrcHeapData {
970                /// The head of the over-approximated-stack-roots list.
971                pub over_approximated_stack_roots: Option<VMGcRef>,
972
973                /// The current size of the over-approximated-stack-roots list.
974                pub current_over_approximated_stack_roots_len: u32,
975
976                /// The size of the over-approximated-stack-roots list
977                /// immediately after the last GC.
978                pub over_approximated_stack_roots_len_after_last_gc: u32,
979            }
980
981            /// The copying collector's JIT-accessible bump-allocation state.
982            ///
983            /// Like [`VMDrcHeapData`], this is a separate allocation reached
984            /// through `VMContext::gc_heap_data`, and is owned, wrapped in a
985            /// cell, by `wasmtime::runtime::vm::gc::enabled::copying`.
986            #[cfg(feature = "gc-copying")]
987            #[derive(Default)]
988            #[repr(C)]
989            #[snake_name = vm_copying_heap_data]
990            pub struct VMCopyingHeapData {
991                /// Current bump pointer (an index into the GC heap).
992                pub bump_ptr: u32,
993
994                /// End of the active semi-space.
995                pub active_space_end: u32,
996            }
997
998            /// The null collector's JIT-accessible bump-allocation state.
999            ///
1000            /// Unlike the two above, this is not a separate allocation: it is
1001            /// the first field of `NullHeap` (in
1002            /// `wasmtime::runtime::vm::gc::enabled::null`), again wrapped in a
1003            /// cell, and compiled Wasm reaches it through a pointer to that
1004            /// field.
1005            #[cfg(feature = "gc-null")]
1006            #[repr(C)]
1007            #[snake_name = vm_null_heap_data]
1008            pub struct VMNullHeapData {
1009                /// The bump-allocation finger, an index into the GC heap.
1010                pub next: NonZeroU32,
1011            }
1012
1013            /// The common header for all objects allocated in a GC heap.
1014            ///
1015            /// This header is shared across all collectors, although particular
1016            /// collectors may always add their own trailing fields to this
1017            /// header for all of their own GC objects.
1018            ///
1019            /// This is a bit-packed structure that logically has the following
1020            /// fields:
1021            ///
1022            /// ```ignore
1023            /// struct VMGcHeader {
1024            ///     // Highest 5 bits.
1025            ///     kind: VMGcKind,
1026            ///
1027            ///     // 27 bits available for the `GcRuntime` to make use of
1028            ///     // however it sees fit.
1029            ///     reserved: u27,
1030            ///
1031            ///     // The `VMSharedTypeIndex` for this GC object, if it isn't an
1032            ///     // `externref` (or an `externref` re-wrapped as an
1033            ///     // `anyref`). `None` is represented with
1034            ///     // `VMSharedTypeIndex::reserved_value()`.
1035            ///     ty: Option<VMSharedTypeIndex>,
1036            /// }
1037            /// ```
1038            ///
1039            /// NB: the `kind` and `reserved` fields share one word, and
1040            /// therefore one alias region: splitting them would let Cranelift
1041            /// forward a stale kind across a reserved-bits store.
1042            #[derive(Debug, Clone, Copy)]
1043            #[repr(C, align(8))]
1044            #[snake_name = vm_gc_header]
1045            pub struct VMGcHeader {
1046                /// The object's `VMGcKind` and 27 bits of space reserved for
1047                /// however the GC sees fit to use it.
1048                pub(crate) kind: u32,
1049
1050                /// The object's type index.
1051                pub(crate) ty: VMSharedTypeIndex,
1052            }
1053
1054            /// The common header for all objects in the DRC collector.
1055            ///
1056            /// This adds a ref count and over-approximated-stack-roots list
1057            /// link on top of the collector-agnostic [`VMGcHeader`].
1058            #[cfg(feature = "gc-drc")]
1059            #[repr(C)]
1060            #[snake_name = vm_drc_header]
1061            pub(crate) struct VMDrcHeader {
1062                /// The collector-agnostic header.
1063                #[aggregate]
1064                pub(crate) header: VMGcHeader,
1065
1066                /// This object's reference count.
1067                pub(crate) ref_count: u64,
1068
1069                /// The next object in the over-approximated-stack-roots list,
1070                /// if this object is in that list.
1071                pub(crate) next_over_approximated_stack_root: Option<VMGcRef>,
1072
1073                /// The size of this object in the GC heap.
1074                ///
1075                /// Written by the runtime at allocation time; compiled Wasm
1076                /// never accesses it.
1077                pub(crate) object_size: u32,
1078            }
1079
1080            /// The common header for all objects in the copying collector.
1081            #[cfg(feature = "gc-copying")]
1082            #[repr(C)]
1083            #[snake_name = vm_copying_header]
1084            pub(crate) struct VMCopyingHeader {
1085                /// The collector-agnostic header.
1086                #[aggregate]
1087                pub(crate) header: VMGcHeader,
1088
1089                /// The size of this object in the GC heap.
1090                pub(crate) object_size: u32,
1091            }
1092        }
1093    };
1094}