wasmtime_environ/vmctxtypes.rs
1//! Centralized definitions of the layouts of Wasmtime's two "vmctx" types:
2//! `VMContext`, the runtime context for a core Wasm instance, and
3//! `VMComponentContext`, the runtime context for a component.
4//!
5//! Unlike the `VM*` types defined by `for_each_vm_type!`, neither of these has
6//! a corresponding `#[repr(C)]` Rust `struct`: their sizes depend on the module
7//! or component being instantiated, so they are dynamically laid out and
8//! accessed exclusively through the computed offsets in `VMOffsets` and
9//! `VMComponentOffsets`. That layout is defined exactly once here, via the
10//! higher-order `for_each_vmctx_type!` macro, and each consumer generates its
11//! view of it from that single source of truth.
12
13/// Invoke the given macro `$mac` once, passing it the layout of each of
14/// Wasmtime's "vmctx" types.
15///
16/// This is a higher-order macro: callers define a `macro_rules!` macro that
17/// matches the grammar described below and pass its name as an argument to this
18/// macro's invocation, e.g. `for_each_vmctx_type!(define_vmctx_offsets)`.
19///
20/// # Grammar
21///
22/// The layout below is written in exactly the same grammar that it is handed to
23/// `$mac` in: this macro has a single rule, and that rule does nothing but
24/// forward those tokens along. Writing the layout in the grammar that consumers
25/// match makes it more verbose than a bespoke input syntax would be, but in
26/// exchange there is no normalization pass in between, so what a consumer matches
27/// is exactly what a reader of the layout sees.
28///
29/// `$mac` receives one brace-delimited group per vmctx type:
30///
31/// ```ignore
32/// {
33/// VMContext vmctx
34/// static { ...entries... }
35/// dynamic { ...entries... }
36/// }
37/// ```
38///
39/// where `vmctx` is the name used for accessor methods of that type, `static`
40/// holds the fixed-width prefix whose offsets depend only on the target pointer
41/// size, and `dynamic` holds the rest, whose offsets additionally depend on the
42/// module or component being compiled.
43///
44/// Each entry within a section is a keyword naming the entry's shape followed by
45/// a single delimited group, so that a consumer can iterate over a section with
46/// `$( ...$kind:ident $entry:tt... )*` and dispatch on one whole entry at a time
47/// instead of munching the section token by token. An entry is one of:
48///
49/// * `align { ptr }` or `align { N }`: round the running offset up to the target
50/// pointer size, or to `N` bytes. Alignment is *always* explicit: it is never
51/// derived from a field's type, because the layout being described here does
52/// not necessarily align every field to its natural alignment, and inserting
53/// padding that the layout does not actually have would silently corrupt every
54/// subsequent offset.
55///
56/// * `field { <attrs> <name>: <ty> }`: a single field.
57///
58/// * `array { <attrs> <name>[<count>; <IndexType>]: <ty> }` (`dynamic` only): an
59/// array of `self.<count>` elements, indexed by `<IndexType>`.
60///
61/// * `optional { <attrs> <name>[if <flag>]: <ty> }` (`dynamic` only): a field that
62/// is present when `self.<flag>` is true and absent (zero-sized) otherwise.
63///
64/// A field's type is always the last thing in its entry. Consumers capture it
65/// as a trailing `$($fty:tt)*` and re-dispatch on its tokens only where they
66/// actually need to classify it into a size or a Cranelift type; a `:ty`
67/// capture would be opaque forever, and so could never be classified at
68/// all.
69///
70/// `<attrs>` is a possibly-empty sequence of marker attributes, which consumers
71/// match with `$(# $fattr:tt)*`. They do not affect the layout, but they do affect
72/// the accesses generated for the field:
73///
74/// * `#[aggregate]`: this field is a composite (a nested struct, or an array of
75/// them) rather than a single scalar. Compiled code accesses such a field's
76/// interior piecewise, so there is no one Cranelift type for the field as a
77/// whole and no alias-region accessor is generated for it. Its offset is still
78/// generated, since that is what interior accesses are computed relative to.
79///
80/// * `#[readonly]` and/or `#[can_move]`: describe how Cranelift may treat loads
81/// and stores of this field.
82///
83/// * `#[access_as = Type]`: this field is *declared* with one type (because that
84/// is what determines its size and stride) but *accessed* as another. For
85/// example, the component context's `may_leave` flags are each stored in a
86/// whole `VMGlobalDefinition` but only ever accessed as a `u32`.
87///
88/// * `#[ptr_size_offset]` (`dynamic` only): this field's offset is a function
89/// of the target pointer size alone, even though it lives in the `dynamic`
90/// section, because it and everything before it have sizes that do not depend
91/// on the vmctx's shape. These fields get generated accessors that do not
92/// need to be parameterized over `VMOffsets`, only `GetPtrSize`.
93///
94/// * `#[pointee(<attrs> <Region> as <name> $([<IndexType>])? : <ty>)]`: this
95/// field is a pointer to memory that lives *outside* the vmctx and so is not
96/// part of its layout at all, but that compiled code reaches only by loading
97/// this field first. `<Region>` names the alias region that memory belongs
98/// to, `<name>` is the accessor generated for it, and `<ty>` is the type it is
99/// accessed as. With an `[<IndexType>]`, the pointee is an array of `<ty>`
100/// indexed by `<IndexType>` and each element gets its own alias region;
101/// without one, it is a single `<ty>`. The pointee's `<attrs>` are its own:
102/// how compiled code may treat a load of the pointee is independent of how it
103/// may treat a load of the pointer.
104///
105/// Doc comments are deliberately *not* accepted on fields; use `//` comments for
106/// prose about the layout. Accessor documentation is synthesized from the field
107/// names instead, so that there is only one place a field can be described.
108///
109/// A consumer that only cares about one of the two types can filter with a
110/// literal-name arm followed by a catch-all, e.g.
111///
112/// ```ignore
113/// (@one VMContext $snake:ident dynamic { $($dyn:tt)* }) => { ...generate... };
114/// (@one $other:ident $snake:ident dynamic { $($dyn:tt)* }) => {};
115/// ```
116#[macro_export]
117macro_rules! for_each_vmctx_type {
118 ($mac:ident) => {
119 $mac! {
120 {
121 VMContext vmctx
122
123 // Fixed-width data comes first so that the calculation of these
124 // fields' offsets is a compile-time constant when using
125 // `HostPtr`.
126 static {
127 field { #[readonly] #[can_move] magic: u32 }
128
129 // NB: this is where the four bytes of padding after `magic`
130 // live on targets with eight-byte pointers.
131 align { ptr }
132
133 field { #[readonly] #[can_move] store_context: VmPtr<VMStoreContext> }
134
135 // NB: `VMBuiltinFunctionsArray` is a `repr(C)` struct of
136 // `unsafe extern "C" fn` fields rather than a true array,
137 // so its elements are pointer-width and pointer-aligned.
138 field {
139 #[readonly]
140 #[can_move]
141 #[pointee(
142 #[readonly]
143 #[can_move]
144 BuiltinFunctionsArray as builtin_functions_array[BuiltinFunctionIndex]:
145 unsafe extern "C" fn
146 )]
147 builtin_functions: VmPtr<VMBuiltinFunctionsArray>
148 }
149
150 field {
151 #[pointee(EpochCounter as epoch_counter: AtomicU64)]
152 epoch_ptr: VmPtr<AtomicU64>
153 }
154
155 // A pointer that different collectors use however they see
156 // fit.
157 field { #[readonly] #[can_move] gc_heap_data: VmPtr<u8> }
158
159 field {
160 #[readonly]
161 #[can_move]
162 #[pointee(
163 #[readonly]
164 #[can_move]
165 TypeIdsArray as type_ids_array[ModuleInternedTypeIndex]:
166 VMSharedTypeIndex
167 )]
168 type_ids: VmPtr<VMSharedTypeIndex>
169 }
170 }
171
172 // Variable-width fields come after the fixed-width fields
173 // above. Memory-related items are placed first as they are some
174 // of the most frequently accessed items, and minimizing their
175 // offset can shrink the size of load/store instruction offset
176 // immediates on platforms like x64 and Pulley (e.g. fit in an
177 // 8-bit offset instead of needing a 32-bit offset).
178 dynamic {
179 array {
180 #[aggregate]
181 imported_memories[num_imported_memories; MemoryIndex]: VMMemoryImport
182 }
183
184 array {
185 #[readonly]
186 #[can_move]
187 memories[num_defined_memories; DefinedMemoryIndex]: VmPtr<VMMemoryDefinition>
188 }
189
190 array {
191 #[aggregate]
192 owned_memories[num_owned_memories; OwnedMemoryIndex]: VMMemoryDefinition
193 }
194
195 array {
196 #[readonly]
197 #[can_move]
198 shadow_memories[num_shadow_memories; MemoryIndex]: VmPtr<VMMemoryDefinition>
199 }
200
201 array {
202 #[aggregate]
203 imported_functions[num_imported_functions; FuncIndex]: VMFunctionImport
204 }
205
206 array {
207 #[aggregate]
208 imported_tables[num_imported_tables; TableIndex]: VMTableImport
209 }
210
211 array {
212 #[aggregate]
213 imported_globals[num_imported_globals; GlobalIndex]: VMGlobalImport
214 }
215
216 array {
217 #[aggregate]
218 imported_tags[num_imported_tags; TagIndex]: VMTagImport
219 }
220
221 array {
222 #[aggregate]
223 tables[num_defined_tables; DefinedTableIndex]: VMTableDefinition
224 }
225
226 align { 16 }
227
228 array {
229 #[aggregate]
230 globals[num_defined_globals; DefinedGlobalIndex]: VMGlobalDefinition
231 }
232
233 array {
234 #[aggregate]
235 tags[num_defined_tags; DefinedTagIndex]: VMTagDefinition
236 }
237
238 align { ptr }
239
240 array {
241 #[aggregate]
242 func_refs[num_escaped_funcs; FuncRefIndex]: VMFuncRef
243 }
244
245 optional {
246 #[aggregate]
247 startup_func_ref[if has_startup_func]: VMFuncRef
248 }
249
250 array {
251 runtime_data_bases[num_runtime_data; RuntimeDataIndex]: VmPtr<u8>
252 }
253
254 array {
255 runtime_data_lengths[num_runtime_data; RuntimeDataIndex]: u32
256 }
257 }
258 }
259
260 {
261 VMComponentContext vmcomponent
262
263 static {
264 // NB: `magic` must be at offset zero; this is relied upon by
265 // `VMComponentContext::from_opaque`.
266 field { #[readonly] #[can_move] magic: u32 }
267
268 align { ptr }
269
270 field {
271 #[readonly]
272 #[pointee(
273 #[readonly]
274 #[can_move]
275 ComponentBuiltinFunctionsArray as builtins_array[ComponentBuiltinFunctionIndex]:
276 unsafe extern "C" fn
277 )]
278 builtins: VmPtr<VMComponentBuiltins>
279 }
280
281 field { #[readonly] #[can_move] store_context: VmPtr<VMStoreContext> }
282 }
283
284 dynamic {
285 align { 16 }
286
287 // Each of these flags gets a whole `VMGlobalDefinition`'s
288 // worth of space, but only its first four bytes are ever
289 // accessed.
290 //
291 // NB: these flags come first, before any field whose offset
292 // depends on the component's shape, so that their offsets
293 // are a function of the target pointer size alone, as marked
294 // by `#[ptr_size_offset]`. Core Wasm compilation does not
295 // have the enclosing `VMComponentContext`'s offsets on hand,
296 // but must still be able to compute these flags' offsets to
297 // build the alias regions for accessing them.
298
299 array {
300 #[ptr_size_offset]
301 #[access_as = u32]
302 may_leave[num_runtime_component_instances; RuntimeComponentInstanceIndex]: VMGlobalDefinition
303 }
304
305 align { ptr }
306
307 // Each instance's `HandleTable::slots`, which a fused
308 // adapter reads to reach a handle's slot without calling
309 // into the host.
310 array {
311 #[aggregate]
312 handle_tables
313 [num_runtime_component_instances; RuntimeComponentInstanceIndex]:
314 VMHandleTable
315 }
316
317 array {
318 #[aggregate]
319 trampoline_func_refs[num_trampolines; TrampolineIndex]: VMFuncRef
320 }
321
322 array {
323 #[aggregate]
324 intrinsic_func_refs[num_unsafe_intrinsics; UnsafeIntrinsic]: VMFuncRef
325 }
326
327 array {
328 #[aggregate]
329 lowerings[num_lowerings; LoweredIndex]: VMLowering
330 }
331
332 array {
333 memories
334 [num_runtime_memories; RuntimeMemoryIndex]: VmPtr<VMMemoryDefinition>
335 }
336
337 array {
338 #[aggregate]
339 tables[num_runtime_tables; RuntimeTableIndex]: VMTableImport
340 }
341
342 array {
343 reallocs[num_runtime_reallocs; RuntimeReallocIndex]: VmPtr<VMFuncRef>
344 }
345
346 array {
347 callbacks[num_runtime_callbacks; RuntimeCallbackIndex]: VmPtr<VMFuncRef>
348 }
349
350 array {
351 post_returns[num_runtime_post_returns; RuntimePostReturnIndex]: VmPtr<VMFuncRef>
352 }
353
354 array {
355 #[readonly]
356 resource_destructors[num_resources; ResourceIndex]: VmPtr<VMFuncRef>
357 }
358 }
359 }
360 }
361 };
362}
363
364/// Round `offset` up to a multiple of `align`.
365#[inline]
366pub(crate) fn align_up(offset: u32, align: u32) -> u32 {
367 debug_assert!(align.is_power_of_two());
368 (offset + (align - 1)) & !(align - 1)
369}
370
371/// Add two offsets, panicking on overflow.
372#[inline]
373pub(crate) fn cadd(a: u32, b: u32) -> u32 {
374 a.checked_add(b).unwrap()
375}
376
377/// Multiply an element count by an element size, panicking on overflow.
378#[inline]
379pub(crate) fn cmul(count: u32, size: u32) -> u32 {
380 count.checked_mul(size).unwrap()
381}
382
383/// Classify one of the field types accepted by `for_each_vmctx_type!` to its
384/// size in bytes as a `u32`, given a `PtrSize`.
385#[allow(
386 unused_macro_rules,
387 reason = "some element types only appear in `VMComponentContext`, and so are \
388 unused when the `component-model` feature is disabled"
389)]
390macro_rules! vmctx_field_size {
391 (($p:expr) u32) => {
392 4u32
393 };
394 (($p:expr) VmPtr < $g:ident >) => {
395 u32::from($p)
396 };
397 (($p:expr) VmPtr < VmPtr < $g:ident >>) => {
398 u32::from($p)
399 };
400 // `VMLowering` is a pair of pointers, and is not itself defined by
401 // `for_each_vm_type!`.
402 (($p:expr) VMLowering) => {
403 2u32 * u32::from($p)
404 };
405 // `VMGlobalDefinition` is a union of the representations of every type a
406 // global can have, the largest being `v128`.
407 (($p:expr) VMGlobalDefinition) => {
408 16u32
409 };
410 // Anything else names one of the `VM*` types, and so has an
411 // `offsets::VMFoo` generated for it by `for_each_vm_type!`. Deferring to
412 // that keeps this macro from having to mirror the list of `VM*` types, and
413 // a type that has no such entry fails to resolve here.
414 (($p:expr) $Name:ident) => {
415 u32::from(crate::vmoffsets::offsets::$Name($p).size())
416 };
417}
418
419/// Classify a `for_each_vmctx_type!` alignment step to its alignment in bytes
420/// as a `u32`, given a `PtrSize`.
421macro_rules! vmctx_align_value {
422 (($p:expr) ptr) => {
423 u32::from($p)
424 };
425 (($p:expr) $n:literal) => {
426 $n
427 };
428}
429
430/// Generate the accessors for, and the layout computation of, the
431/// dynamically-positioned fields of one of the vmctx types.
432#[allow(
433 unused_macro_rules,
434 reason = "single dynamically-positioned fields only appear in \
435 `VMComponentContext`, and so are unused when the `component-model` \
436 feature is disabled"
437)]
438macro_rules! define_vmctx_dynamic_offsets {
439 (@accessors ($s:ident) [ $($kind:ident $entry:tt)* ]) => {
440 $( define_vmctx_dynamic_offsets!(@accessor ($s) $kind $entry); )*
441 };
442
443 (@accessor ($s:ident) align { $al:tt }) => {};
444
445 (@accessor ($s:ident) field { $(# $fattr:tt)* $fname:ident : $($fty:tt)* }) => {
446 #[doc = concat!("The offset of the `", stringify!($fname), "` field.")]
447 #[inline]
448 pub fn $fname(&$s) -> u32 {
449 $s.$fname
450 }
451 };
452
453 (@accessor ($s:ident) array {
454 $(# $fattr:tt)* $fname:ident [ $count:ident ; $Index:ident ] : $($fty:tt)*
455 }) => {
456 #[doc = concat!("The offsets of the `", stringify!($fname), "` array.")]
457 #[inline]
458 pub fn $fname(&$s) -> $crate::ArrayOffsets<$Index> {
459 $crate::ArrayOffsets::new(
460 $s.$fname,
461 vmctx_field_size!(($s.ptr.size()) $($fty)*),
462 $s.$count,
463 )
464 }
465 };
466
467 (@accessor ($s:ident) optional {
468 $(# $fattr:tt)* $fname:ident [ if $flag:ident ] : $($fty:tt)*
469 }) => {
470 #[doc = concat!(
471 "The offset of the `", stringify!($fname), "` field.\n\n",
472 "Panics if `", stringify!($flag), "` is false, in which case this \
473 field is not present at all."
474 )]
475 #[inline]
476 pub fn $fname(&$s) -> u32 {
477 assert!($s.$flag);
478 $s.$fname
479 }
480 };
481
482 (@compute_fn ($s:ident, $next:ident) $snake:ident [ $($kind:ident $entry:tt)* ]) => {
483 /// Compute the offset of each dynamically-positioned field, and this
484 /// vmctx's total size.
485 fn compute_field_offsets(&mut $s) {
486 let mut $next = u32::from($s.ptr.$snake().end_of_static_fields());
487 $( define_vmctx_dynamic_offsets!(@compute ($s, $next) $kind $entry); )*
488 $s.size = $next;
489 }
490 };
491
492 (@compute ($s:ident, $next:ident) align { $al:tt }) => {
493 $next = crate::vmctxtypes::align_up($next, vmctx_align_value!(($s.ptr.size()) $al));
494 };
495
496 (@compute ($s:ident, $next:ident) field {
497 $(# $fattr:tt)* $fname:ident : $($fty:tt)*
498 }) => {
499 $s.$fname = $next;
500 $next = crate::vmctxtypes::cadd($next, vmctx_field_size!(($s.ptr.size()) $($fty)*));
501 };
502
503 (@compute ($s:ident, $next:ident) array {
504 $(# $fattr:tt)* $fname:ident [ $count:ident ; $Index:ident ] : $($fty:tt)*
505 }) => {
506 $s.$fname = $next;
507 $next = crate::vmctxtypes::cadd(
508 $next,
509 crate::vmctxtypes::cmul($s.$count, vmctx_field_size!(($s.ptr.size()) $($fty)*)),
510 );
511 };
512
513 (@compute ($s:ident, $next:ident) optional {
514 $(# $fattr:tt)* $fname:ident [ if $flag:ident ] : $($fty:tt)*
515 }) => {
516 $s.$fname = $next;
517 $next = crate::vmctxtypes::cadd(
518 $next,
519 if $s.$flag {
520 vmctx_field_size!(($s.ptr.size()) $($fty)*)
521 } else {
522 0
523 },
524 );
525 };
526}
527
528/// The offsets of one array field within a vmctx.
529#[derive(Debug, Clone, Copy)]
530pub struct ArrayOffsets<I> {
531 begin: u32,
532 stride: u32,
533 count: u32,
534 _index: core::marker::PhantomData<I>,
535}
536
537impl<I> ArrayOffsets<I> {
538 /// Create the offsets for an array of `count` elements which begins at
539 /// `begin` within its vmctx and whose elements are `stride` bytes apart.
540 #[inline]
541 pub fn new(begin: u32, stride: u32, count: u32) -> Self {
542 ArrayOffsets {
543 begin,
544 stride,
545 count,
546 _index: core::marker::PhantomData,
547 }
548 }
549
550 /// The offset of the start of this array within its vmctx.
551 #[inline]
552 pub fn begin(&self) -> u32 {
553 self.begin
554 }
555
556 /// The number of bytes between the start of consecutive elements of this
557 /// array.
558 #[inline]
559 pub fn stride(&self) -> u32 {
560 self.stride
561 }
562
563 /// The number of elements in this array.
564 #[inline]
565 pub fn count(&self) -> u32 {
566 self.count
567 }
568}
569
570impl<I: VmctxArrayIndex> ArrayOffsets<I> {
571 /// The offset of the given element within this array's vmctx.
572 ///
573 /// Panics if `index` is out of bounds for this array.
574 #[inline]
575 pub fn at(&self, index: I) -> u32 {
576 let index = index.vmctx_array_index();
577 assert!(index < self.count);
578 self.begin + index * self.stride
579 }
580}
581
582/// An index type that can be used to index one of a vmctx's arrays.
583pub trait VmctxArrayIndex: Copy {
584 /// This index's position within its array.
585 fn vmctx_array_index(self) -> u32;
586}
587
588/// Implement `VmctxArrayIndex` for entity references.
589macro_rules! impl_vmctx_array_index {
590 ($($ty:ty),* $(,)?) => {
591 $(
592 impl $crate::VmctxArrayIndex for $ty {
593 #[inline]
594 fn vmctx_array_index(self) -> u32 {
595 self.as_u32()
596 }
597 }
598 )*
599 };
600}