Skip to main content

wasmtime/runtime/vm/
vmcontext.rs

1//! This file declares `VMContext` and several related structs which contain
2//! fields that compiled wasm code accesses directly.
3
4mod vm_host_func_context;
5
6pub use self::vm_host_func_context::VMArrayCallHostFuncContext;
7use crate::prelude::*;
8use crate::runtime::vm::{InterpreterRef, VMGcRef, VmPtr, VmSafe, f32x4, f64x2, i8x16};
9use crate::store::StoreOpaque;
10use crate::vm::stack_switching::VMStackChain;
11use core::cell::UnsafeCell;
12use core::ffi::c_void;
13use core::fmt;
14use core::marker;
15use core::mem::{self, MaybeUninit};
16use core::ops::Range;
17use core::ptr::{self, NonNull};
18use core::sync::atomic::{AtomicUsize, Ordering};
19use wasmtime_environ::{
20    BuiltinFunctionIndex, DefinedGlobalIndex, DefinedMemoryIndex, DefinedTableIndex,
21    DefinedTagIndex, NUM_COMPONENT_CONTEXT_SLOTS, VMCONTEXT_MAGIC, VMSharedTypeIndex,
22};
23
24/// A function pointer that exposes the array calling convention.
25///
26/// Regardless of the underlying Wasm function type, all functions using the
27/// array calling convention have the same Rust signature.
28///
29/// Arguments:
30///
31/// * Callee `vmctx` for the function itself.
32///
33/// * Caller's `vmctx` (so that host functions can access the linear memory of
34///   their Wasm callers).
35///
36/// * A pointer to a buffer of `ValRaw`s where both arguments are passed into
37///   this function, and where results are returned from this function.
38///
39/// * The capacity of the `ValRaw` buffer. Must always be at least
40///   `max(len(wasm_params), len(wasm_results))`.
41///
42/// Return value:
43///
44/// * `true` if this call succeeded.
45/// * `false` if this call failed and a trap was recorded in TLS.
46pub type VMArrayCallNative = unsafe extern "C" fn(
47    NonNull<VMOpaqueContext>,
48    NonNull<VMContext>,
49    NonNull<ValRaw>,
50    usize,
51) -> bool;
52
53/// An opaque function pointer which might be `VMArrayCallNative` or it might be
54/// pulley bytecode. Requires external knowledge to determine what kind of
55/// function pointer this is.
56#[repr(transparent)]
57pub struct VMArrayCallFunction(VMFunctionBody);
58
59/// A function pointer that exposes the Wasm calling convention.
60///
61/// In practice, different Wasm function types end up mapping to different Rust
62/// function types, so this isn't simply a type alias the way that
63/// `VMArrayCallFunction` is. However, the exact details of the calling
64/// convention are left to the Wasm compiler (e.g. Cranelift or Winch). Runtime
65/// code never does anything with these function pointers except shuffle them
66/// around and pass them back to Wasm.
67#[repr(transparent)]
68pub struct VMWasmCallFunction(VMFunctionBody);
69
70/// An imported function.
71///
72/// Basically the same as `VMFuncRef`, except that `wasm_call` is not optional.
73#[derive(Debug, Clone)]
74#[repr(C)]
75pub struct VMFunctionImport {
76    /// Same as `VMFuncRef::array_call`.
77    pub array_call: VmPtr<VMArrayCallFunction>,
78
79    /// Same as `VMFuncRef::wasm_call`, except always non-null. Must be filled
80    /// in by the time Wasm is importing this function!
81    pub wasm_call: VmPtr<VMWasmCallFunction>,
82
83    /// Function signature's _actual_ type id.
84    ///
85    /// This is the type that the function was defined with, not the type that
86    /// it was imported as. These two can be different in the face of subtyping
87    /// and we need the former for to correctly implement dynamic downcasts.
88    pub type_index: VMSharedTypeIndex,
89
90    /// Same as `VMFuncRef::vmctx`.
91    pub vmctx: VmPtr<VMOpaqueContext>,
92    // If more elements are added here, remember to add offset_of tests below!
93}
94
95// SAFETY: the above structure is repr(C) and only contains `VmSafe` fields.
96unsafe impl VmSafe for VMFunctionImport {}
97
98impl VMFunctionImport {
99    /// Convert `&VMFunctionImport` into `&VMFuncRef`.
100    pub fn as_func_ref(&self) -> &VMFuncRef {
101        // Safety: `VMFunctionImport` and `VMFuncRef` have the same
102        // representation.
103        unsafe { Self::as_non_null_func_ref(NonNull::from(self)).as_ref() }
104    }
105
106    /// Convert `NonNull<VMFunctionImport>` into `NonNull<VMFuncRef>`.
107    pub fn as_non_null_func_ref(p: NonNull<VMFunctionImport>) -> NonNull<VMFuncRef> {
108        p.cast()
109    }
110
111    /// Convert `*mut VMFunctionImport` into `*mut VMFuncRef`.
112    pub fn as_func_ref_ptr(p: *mut VMFunctionImport) -> *mut VMFuncRef {
113        p.cast()
114    }
115}
116
117#[cfg(test)]
118mod test_vmfunction_import {
119    use super::{VMFuncRef, VMFunctionImport};
120    use core::mem::offset_of;
121    use std::mem::size_of;
122    use wasmtime_environ::{HostPtr, Module, StaticModuleIndex, VMOffsets};
123
124    #[test]
125    fn check_vmfunction_import_offsets() {
126        let module = Module::new(StaticModuleIndex::from_u32(0));
127        let offsets = VMOffsets::new(HostPtr, &module);
128        assert_eq!(
129            size_of::<VMFunctionImport>(),
130            usize::from(offsets.size_of_vmfunction_import())
131        );
132        assert_eq!(
133            offset_of!(VMFunctionImport, array_call),
134            usize::from(offsets.vmfunction_import_array_call())
135        );
136        assert_eq!(
137            offset_of!(VMFunctionImport, wasm_call),
138            usize::from(offsets.vmfunction_import_wasm_call())
139        );
140        assert_eq!(
141            offset_of!(VMFunctionImport, type_index),
142            usize::from(offsets.vmfunction_import_type_index())
143        );
144        assert_eq!(
145            offset_of!(VMFunctionImport, vmctx),
146            usize::from(offsets.vmfunction_import_vmctx())
147        );
148    }
149
150    #[test]
151    fn vmfunction_import_and_vmfunc_ref_have_same_layout() {
152        assert_eq!(size_of::<VMFunctionImport>(), size_of::<VMFuncRef>());
153        assert_eq!(
154            offset_of!(VMFunctionImport, array_call),
155            offset_of!(VMFuncRef, array_call),
156        );
157        assert_eq!(
158            offset_of!(VMFunctionImport, wasm_call),
159            offset_of!(VMFuncRef, wasm_call),
160        );
161        assert_eq!(
162            offset_of!(VMFunctionImport, type_index),
163            offset_of!(VMFuncRef, type_index),
164        );
165        assert_eq!(
166            offset_of!(VMFunctionImport, vmctx),
167            offset_of!(VMFuncRef, vmctx),
168        );
169    }
170}
171
172/// A placeholder byte-sized type which is just used to provide some amount of type
173/// safety when dealing with pointers to JIT-compiled function bodies. Note that it's
174/// deliberately not Copy, as we shouldn't be carelessly copying function body bytes
175/// around.
176#[repr(C)]
177pub struct VMFunctionBody(u8);
178
179// SAFETY: this structure is never read and is safe to pass to jit code.
180unsafe impl VmSafe for VMFunctionBody {}
181
182#[cfg(test)]
183mod test_vmfunction_body {
184    use super::VMFunctionBody;
185    use std::mem::size_of;
186
187    #[test]
188    fn check_vmfunction_body_offsets() {
189        assert_eq!(size_of::<VMFunctionBody>(), 1);
190    }
191}
192
193/// The fields compiled code needs to access to utilize a WebAssembly table
194/// imported from another instance.
195#[derive(Debug, Copy, Clone)]
196#[repr(C)]
197pub struct VMTableImport {
198    /// A pointer to the imported table description.
199    pub from: VmPtr<VMTableDefinition>,
200
201    /// A pointer to the `VMContext` that owns the table description.
202    pub vmctx: VmPtr<VMContext>,
203
204    /// The table index, within `vmctx`, this definition resides at.
205    pub index: DefinedTableIndex,
206}
207
208// SAFETY: the above structure is repr(C) and only contains `VmSafe` fields.
209unsafe impl VmSafe for VMTableImport {}
210
211#[cfg(test)]
212mod test_vmtable {
213    use super::VMTableImport;
214    use core::mem::offset_of;
215    use std::mem::size_of;
216    use wasmtime_environ::component::{Component, VMComponentOffsets};
217    use wasmtime_environ::{HostPtr, Module, StaticModuleIndex, VMOffsets};
218
219    #[test]
220    fn check_vmtable_offsets() {
221        let module = Module::new(StaticModuleIndex::from_u32(0));
222        let offsets = VMOffsets::new(HostPtr, &module);
223        assert_eq!(
224            size_of::<VMTableImport>(),
225            usize::from(offsets.size_of_vmtable_import())
226        );
227        assert_eq!(
228            offset_of!(VMTableImport, from),
229            usize::from(offsets.vmtable_import_from())
230        );
231        assert_eq!(
232            offset_of!(VMTableImport, vmctx),
233            usize::from(offsets.vmtable_import_vmctx())
234        );
235        assert_eq!(
236            offset_of!(VMTableImport, index),
237            usize::from(offsets.vmtable_import_index())
238        );
239    }
240
241    #[test]
242    fn ensure_sizes_match() {
243        // Because we use `VMTableImport` for recording tables used by components, we
244        // want to make sure that the size calculations between `VMOffsets` and
245        // `VMComponentOffsets` stay the same.
246        let module = Module::new(StaticModuleIndex::from_u32(0));
247        let vm_offsets = VMOffsets::new(HostPtr, &module);
248        let component = Component::default();
249        let vm_component_offsets = VMComponentOffsets::new(HostPtr, &component);
250        assert_eq!(
251            vm_offsets.size_of_vmtable_import(),
252            vm_component_offsets.size_of_vmtable_import()
253        );
254    }
255}
256
257/// The fields compiled code needs to access to utilize a WebAssembly linear
258/// memory imported from another instance.
259#[derive(Debug, Copy, Clone)]
260#[repr(C)]
261pub struct VMMemoryImport {
262    /// A pointer to the imported memory description.
263    pub from: VmPtr<VMMemoryDefinition>,
264
265    /// A pointer to the `VMContext` that owns the memory description.
266    pub vmctx: VmPtr<VMContext>,
267
268    /// The index of the memory in the containing `vmctx`.
269    pub index: DefinedMemoryIndex,
270}
271
272// SAFETY: the above structure is repr(C) and only contains `VmSafe` fields.
273unsafe impl VmSafe for VMMemoryImport {}
274
275#[cfg(test)]
276mod test_vmmemory_import {
277    use super::VMMemoryImport;
278    use core::mem::offset_of;
279    use std::mem::size_of;
280    use wasmtime_environ::{HostPtr, Module, StaticModuleIndex, VMOffsets};
281
282    #[test]
283    fn check_vmmemory_import_offsets() {
284        let module = Module::new(StaticModuleIndex::from_u32(0));
285        let offsets = VMOffsets::new(HostPtr, &module);
286        assert_eq!(
287            size_of::<VMMemoryImport>(),
288            usize::from(offsets.size_of_vmmemory_import())
289        );
290        assert_eq!(
291            offset_of!(VMMemoryImport, from),
292            usize::from(offsets.vmmemory_import_from())
293        );
294        assert_eq!(
295            offset_of!(VMMemoryImport, vmctx),
296            usize::from(offsets.vmmemory_import_vmctx())
297        );
298        assert_eq!(
299            offset_of!(VMMemoryImport, index),
300            usize::from(offsets.vmmemory_import_index())
301        );
302    }
303}
304
305/// The fields compiled code needs to access to utilize a WebAssembly global
306/// variable imported from another instance.
307///
308/// Note that unlike with functions, tables, and memories, `VMGlobalImport`
309/// doesn't include a `vmctx` pointer. Globals are never resized, and don't
310/// require a `vmctx` pointer to access.
311#[derive(Debug, Copy, Clone)]
312#[repr(C)]
313pub struct VMGlobalImport {
314    /// A pointer to the imported global variable description.
315    pub from: VmPtr<VMGlobalDefinition>,
316
317    /// A pointer to the context that owns the global.
318    ///
319    /// Exactly what's stored here is dictated by `kind` below. This is `None`
320    /// for `VMGlobalKind::Host`, it's a `VMContext` for
321    /// `VMGlobalKind::Instance`, and it's `VMComponentContext` for
322    /// `VMGlobalKind::ComponentFlags`.
323    pub vmctx: Option<VmPtr<VMOpaqueContext>>,
324
325    /// The kind of global, and extra location information in addition to
326    /// `vmctx` above.
327    pub kind: VMGlobalKind,
328}
329
330// SAFETY: the above structure is repr(C) and only contains `VmSafe` fields.
331unsafe impl VmSafe for VMGlobalImport {}
332
333/// The kinds of globals that Wasmtime has.
334#[derive(Debug, Copy, Clone)]
335#[repr(C, u32)]
336pub enum VMGlobalKind {
337    /// Host globals, stored in a `StoreOpaque`.
338    Host(DefinedGlobalIndex),
339    /// Instance globals, stored in `VMContext`s
340    Instance(DefinedGlobalIndex),
341    /// Flags for a component instance, stored in `VMComponentContext`.
342    #[cfg(feature = "component-model")]
343    ComponentFlags(wasmtime_environ::component::RuntimeComponentInstanceIndex),
344    #[cfg(feature = "component-model")]
345    TaskMayBlock,
346}
347
348// SAFETY: the above enum is repr(C) and stores nothing else
349unsafe impl VmSafe for VMGlobalKind {}
350
351#[cfg(test)]
352mod test_vmglobal_import {
353    use super::VMGlobalImport;
354    use core::mem::offset_of;
355    use std::mem::size_of;
356    use wasmtime_environ::{HostPtr, Module, StaticModuleIndex, VMOffsets};
357
358    #[test]
359    fn check_vmglobal_import_offsets() {
360        let module = Module::new(StaticModuleIndex::from_u32(0));
361        let offsets = VMOffsets::new(HostPtr, &module);
362        assert_eq!(
363            size_of::<VMGlobalImport>(),
364            usize::from(offsets.size_of_vmglobal_import())
365        );
366        assert_eq!(
367            offset_of!(VMGlobalImport, from),
368            usize::from(offsets.vmglobal_import_from())
369        );
370    }
371}
372
373/// The fields compiled code needs to access to utilize a WebAssembly
374/// tag imported from another instance.
375#[derive(Debug, Copy, Clone)]
376#[repr(C)]
377pub struct VMTagImport {
378    /// A pointer to the imported tag description.
379    pub from: VmPtr<VMTagDefinition>,
380
381    /// The instance that owns this tag.
382    pub vmctx: VmPtr<VMContext>,
383
384    /// The index of the tag in the containing `vmctx`.
385    pub index: DefinedTagIndex,
386}
387
388// SAFETY: the above structure is repr(C) and only contains `VmSafe` fields.
389unsafe impl VmSafe for VMTagImport {}
390
391#[cfg(test)]
392mod test_vmtag_import {
393    use super::VMTagImport;
394    use core::mem::{offset_of, size_of};
395    use wasmtime_environ::{HostPtr, Module, StaticModuleIndex, VMOffsets};
396
397    #[test]
398    fn check_vmtag_import_offsets() {
399        let module = Module::new(StaticModuleIndex::from_u32(0));
400        let offsets = VMOffsets::new(HostPtr, &module);
401        assert_eq!(
402            size_of::<VMTagImport>(),
403            usize::from(offsets.size_of_vmtag_import())
404        );
405        assert_eq!(
406            offset_of!(VMTagImport, from),
407            usize::from(offsets.vmtag_import_from())
408        );
409        assert_eq!(
410            offset_of!(VMTagImport, vmctx),
411            usize::from(offsets.vmtag_import_vmctx())
412        );
413        assert_eq!(
414            offset_of!(VMTagImport, index),
415            usize::from(offsets.vmtag_import_index())
416        );
417    }
418}
419
420/// The fields compiled code needs to access to utilize a WebAssembly linear
421/// memory defined within the instance, namely the start address and the
422/// size in bytes.
423#[derive(Debug)]
424#[repr(C)]
425pub struct VMMemoryDefinition {
426    /// The start address.
427    pub base: VmPtr<u8>,
428
429    /// The current logical size of this linear memory in bytes.
430    ///
431    /// This is atomic because shared memories must be able to grow their length
432    /// atomically. For relaxed access, see
433    /// [`VMMemoryDefinition::current_length()`].
434    pub current_length: AtomicUsize,
435}
436
437// SAFETY: the above definition has `repr(C)` and each field individually
438// implements `VmSafe`, which satisfies the requirements of this trait.
439unsafe impl VmSafe for VMMemoryDefinition {}
440
441impl VMMemoryDefinition {
442    /// Return the current length (in bytes) of the [`VMMemoryDefinition`] by
443    /// performing a relaxed load; do not use this function for situations in
444    /// which a precise length is needed. Owned memories (i.e., non-shared) will
445    /// always return a precise result (since no concurrent modification is
446    /// possible) but shared memories may see an imprecise value--a
447    /// `current_length` potentially smaller than what some other thread
448    /// observes. Since Wasm memory only grows, this under-estimation may be
449    /// acceptable in certain cases.
450    #[inline]
451    pub fn current_length(&self) -> usize {
452        self.current_length.load(Ordering::Relaxed)
453    }
454
455    /// Return a copy of the [`VMMemoryDefinition`] using the relaxed value of
456    /// `current_length`; see [`VMMemoryDefinition::current_length()`].
457    #[inline]
458    pub unsafe fn load(ptr: *mut Self) -> Self {
459        let other = unsafe { &*ptr };
460        VMMemoryDefinition {
461            base: other.base,
462            current_length: other.current_length().into(),
463        }
464    }
465}
466
467#[cfg(test)]
468mod test_vmmemory_definition {
469    use super::VMMemoryDefinition;
470    use core::mem::offset_of;
471    use std::mem::size_of;
472    use wasmtime_environ::{HostPtr, Module, PtrSize, StaticModuleIndex, VMOffsets};
473
474    #[test]
475    fn check_vmmemory_definition_offsets() {
476        let module = Module::new(StaticModuleIndex::from_u32(0));
477        let offsets = VMOffsets::new(HostPtr, &module);
478        assert_eq!(
479            size_of::<VMMemoryDefinition>(),
480            usize::from(offsets.ptr.size_of_vmmemory_definition())
481        );
482        assert_eq!(
483            offset_of!(VMMemoryDefinition, base),
484            usize::from(offsets.ptr.vmmemory_definition_base())
485        );
486        assert_eq!(
487            offset_of!(VMMemoryDefinition, current_length),
488            usize::from(offsets.ptr.vmmemory_definition_current_length())
489        );
490        /* TODO: Assert that the size of `current_length` matches.
491        assert_eq!(
492            size_of::<VMMemoryDefinition::current_length>(),
493            usize::from(offsets.size_of_vmmemory_definition_current_length())
494        );
495        */
496    }
497}
498
499/// The fields compiled code needs to access to utilize a WebAssembly table
500/// defined within the instance.
501#[derive(Debug, Copy, Clone)]
502#[repr(C)]
503pub struct VMTableDefinition {
504    /// Pointer to the table data.
505    pub base: VmPtr<u8>,
506
507    /// The current number of elements in the table.
508    pub current_elements: usize,
509}
510
511// SAFETY: the above structure is repr(C) and only contains `VmSafe` fields.
512unsafe impl VmSafe for VMTableDefinition {}
513
514#[cfg(test)]
515mod test_vmtable_definition {
516    use super::VMTableDefinition;
517    use core::mem::offset_of;
518    use std::mem::size_of;
519    use wasmtime_environ::{HostPtr, Module, StaticModuleIndex, VMOffsets};
520
521    #[test]
522    fn check_vmtable_definition_offsets() {
523        let module = Module::new(StaticModuleIndex::from_u32(0));
524        let offsets = VMOffsets::new(HostPtr, &module);
525        assert_eq!(
526            size_of::<VMTableDefinition>(),
527            usize::from(offsets.size_of_vmtable_definition())
528        );
529        assert_eq!(
530            offset_of!(VMTableDefinition, base),
531            usize::from(offsets.vmtable_definition_base())
532        );
533        assert_eq!(
534            offset_of!(VMTableDefinition, current_elements),
535            usize::from(offsets.vmtable_definition_current_elements())
536        );
537    }
538}
539
540/// The storage for a WebAssembly global defined within the instance.
541///
542/// TODO: Pack the globals more densely, rather than using the same size
543/// for every type.
544#[derive(Debug)]
545#[repr(C, align(16))]
546pub struct VMGlobalDefinition {
547    storage: [u8; 16],
548    // If more elements are added here, remember to add offset_of tests below!
549}
550
551// SAFETY: the above structure is repr(C) and only contains `VmSafe` fields.
552unsafe impl VmSafe for VMGlobalDefinition {}
553
554#[cfg(test)]
555mod test_vmglobal_definition {
556    use super::VMGlobalDefinition;
557    use std::mem::{align_of, size_of};
558    use wasmtime_environ::{HostPtr, Module, PtrSize, StaticModuleIndex, VMOffsets};
559
560    #[test]
561    fn check_vmglobal_definition_alignment() {
562        assert!(align_of::<VMGlobalDefinition>() >= align_of::<i32>());
563        assert!(align_of::<VMGlobalDefinition>() >= align_of::<i64>());
564        assert!(align_of::<VMGlobalDefinition>() >= align_of::<f32>());
565        assert!(align_of::<VMGlobalDefinition>() >= align_of::<f64>());
566        assert!(align_of::<VMGlobalDefinition>() >= align_of::<[u8; 16]>());
567        assert!(align_of::<VMGlobalDefinition>() >= align_of::<[f32; 4]>());
568        assert!(align_of::<VMGlobalDefinition>() >= align_of::<[f64; 2]>());
569    }
570
571    #[test]
572    fn check_vmglobal_definition_offsets() {
573        let module = Module::new(StaticModuleIndex::from_u32(0));
574        let offsets = VMOffsets::new(HostPtr, &module);
575        assert_eq!(
576            size_of::<VMGlobalDefinition>(),
577            usize::from(offsets.ptr.size_of_vmglobal_definition())
578        );
579    }
580
581    #[test]
582    fn check_vmglobal_begins_aligned() {
583        let module = Module::new(StaticModuleIndex::from_u32(0));
584        let offsets = VMOffsets::new(HostPtr, &module);
585        assert_eq!(offsets.vmctx_globals_begin() % 16, 0);
586    }
587
588    #[test]
589    #[cfg(feature = "gc")]
590    fn check_vmglobal_can_contain_gc_ref() {
591        assert!(size_of::<crate::runtime::vm::VMGcRef>() <= size_of::<VMGlobalDefinition>());
592    }
593}
594
595impl VMGlobalDefinition {
596    /// Construct a `VMGlobalDefinition`.
597    pub fn new() -> Self {
598        Self { storage: [0; 16] }
599    }
600
601    /// Return a reference to the value as an i32.
602    pub unsafe fn as_i32(&self) -> &i32 {
603        unsafe { &*(self.storage.as_ref().as_ptr().cast::<i32>()) }
604    }
605
606    /// Return a mutable reference to the value as an i32.
607    pub unsafe fn as_i32_mut(&mut self) -> &mut i32 {
608        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<i32>()) }
609    }
610
611    /// Return a reference to the value as a u32.
612    pub unsafe fn as_u32(&self) -> &u32 {
613        unsafe { &*(self.storage.as_ref().as_ptr().cast::<u32>()) }
614    }
615
616    /// Return a mutable reference to the value as an u32.
617    pub unsafe fn as_u32_mut(&mut self) -> &mut u32 {
618        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<u32>()) }
619    }
620
621    /// Return a reference to the value as an i64.
622    pub unsafe fn as_i64(&self) -> &i64 {
623        unsafe { &*(self.storage.as_ref().as_ptr().cast::<i64>()) }
624    }
625
626    /// Return a mutable reference to the value as an i64.
627    pub unsafe fn as_i64_mut(&mut self) -> &mut i64 {
628        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<i64>()) }
629    }
630
631    /// Return a reference to the value as an u64.
632    pub unsafe fn as_u64(&self) -> &u64 {
633        unsafe { &*(self.storage.as_ref().as_ptr().cast::<u64>()) }
634    }
635
636    /// Return a mutable reference to the value as an u64.
637    pub unsafe fn as_u64_mut(&mut self) -> &mut u64 {
638        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<u64>()) }
639    }
640
641    /// Return a reference to the value as an f32.
642    pub unsafe fn as_f32(&self) -> &f32 {
643        unsafe { &*(self.storage.as_ref().as_ptr().cast::<f32>()) }
644    }
645
646    /// Return a mutable reference to the value as an f32.
647    pub unsafe fn as_f32_mut(&mut self) -> &mut f32 {
648        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<f32>()) }
649    }
650
651    /// Return a reference to the value as f32 bits.
652    pub unsafe fn as_f32_bits(&self) -> &u32 {
653        unsafe { &*(self.storage.as_ref().as_ptr().cast::<u32>()) }
654    }
655
656    /// Return a mutable reference to the value as f32 bits.
657    pub unsafe fn as_f32_bits_mut(&mut self) -> &mut u32 {
658        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<u32>()) }
659    }
660
661    /// Return a reference to the value as an f64.
662    pub unsafe fn as_f64(&self) -> &f64 {
663        unsafe { &*(self.storage.as_ref().as_ptr().cast::<f64>()) }
664    }
665
666    /// Return a mutable reference to the value as an f64.
667    pub unsafe fn as_f64_mut(&mut self) -> &mut f64 {
668        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<f64>()) }
669    }
670
671    /// Return a reference to the value as f64 bits.
672    pub unsafe fn as_f64_bits(&self) -> &u64 {
673        unsafe { &*(self.storage.as_ref().as_ptr().cast::<u64>()) }
674    }
675
676    /// Return a mutable reference to the value as f64 bits.
677    pub unsafe fn as_f64_bits_mut(&mut self) -> &mut u64 {
678        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<u64>()) }
679    }
680
681    /// Gets the underlying 128-bit vector value.
682    //
683    // Note that vectors are stored in little-endian format while other types
684    // are stored in native-endian format.
685    pub unsafe fn get_u128(&self) -> u128 {
686        unsafe { u128::from_le(*(self.storage.as_ref().as_ptr().cast::<u128>())) }
687    }
688
689    /// Sets the 128-bit vector values.
690    //
691    // Note that vectors are stored in little-endian format while other types
692    // are stored in native-endian format.
693    pub unsafe fn set_u128(&mut self, val: u128) {
694        unsafe {
695            *self.storage.as_mut().as_mut_ptr().cast::<u128>() = val.to_le();
696        }
697    }
698
699    /// Return a reference to the value as u128 bits.
700    pub unsafe fn as_u128_bits(&self) -> &[u8; 16] {
701        unsafe { &*(self.storage.as_ref().as_ptr().cast::<[u8; 16]>()) }
702    }
703
704    /// Return a mutable reference to the value as u128 bits.
705    pub unsafe fn as_u128_bits_mut(&mut self) -> &mut [u8; 16] {
706        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<[u8; 16]>()) }
707    }
708
709    /// Return a reference to the global value as a borrowed GC reference.
710    pub unsafe fn as_gc_ref(&self) -> Option<&VMGcRef> {
711        let raw_ptr = self.storage.as_ref().as_ptr().cast::<Option<VMGcRef>>();
712        let ret = unsafe { (*raw_ptr).as_ref() };
713        assert!(cfg!(feature = "gc") || ret.is_none());
714        ret
715    }
716
717    /// Return a reference to the global value as a borrowed GC reference.
718    pub unsafe fn as_gc_ref_mut(&mut self) -> Option<&mut VMGcRef> {
719        let raw_ptr = self.storage.as_mut().as_mut_ptr().cast::<Option<VMGcRef>>();
720        let ret = unsafe { (*raw_ptr).as_mut() };
721        assert!(cfg!(feature = "gc") || ret.is_none());
722        ret
723    }
724
725    /// Initialize a global to the given GC reference.
726    pub unsafe fn init_gc_ref(
727        &mut self,
728        store: &mut StoreOpaque,
729        gc_ref: Option<&VMGcRef>,
730    ) -> Result<()> {
731        let dest = unsafe {
732            &mut *(self
733                .storage
734                .as_mut()
735                .as_mut_ptr()
736                .cast::<MaybeUninit<Option<VMGcRef>>>())
737        };
738
739        store.init_gc_ref(dest, gc_ref)
740    }
741
742    /// Write a GC reference into this global value.
743    pub unsafe fn write_gc_ref(
744        &mut self,
745        store: &mut StoreOpaque,
746        gc_ref: Option<&VMGcRef>,
747    ) -> Result<()> {
748        let dest = unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<Option<VMGcRef>>()) };
749        store.write_gc_ref(dest, gc_ref)
750    }
751
752    /// Return a reference to the value as a `VMFuncRef`.
753    pub unsafe fn as_func_ref(&self) -> *mut VMFuncRef {
754        unsafe { *(self.storage.as_ref().as_ptr().cast::<*mut VMFuncRef>()) }
755    }
756
757    /// Return a mutable reference to the value as a `VMFuncRef`.
758    pub unsafe fn as_func_ref_mut(&mut self) -> &mut *mut VMFuncRef {
759        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<*mut VMFuncRef>()) }
760    }
761}
762
763#[cfg(test)]
764mod test_vmshared_type_index {
765    use super::VMSharedTypeIndex;
766    use std::mem::size_of;
767    use wasmtime_environ::{HostPtr, Module, StaticModuleIndex, VMOffsets};
768
769    #[test]
770    fn check_vmshared_type_index() {
771        let module = Module::new(StaticModuleIndex::from_u32(0));
772        let offsets = VMOffsets::new(HostPtr, &module);
773        assert_eq!(
774            size_of::<VMSharedTypeIndex>(),
775            usize::from(offsets.size_of_vmshared_type_index())
776        );
777    }
778}
779
780/// A WebAssembly tag defined within the instance.
781///
782#[derive(Debug)]
783#[repr(C)]
784pub struct VMTagDefinition {
785    /// Function signature's type id.
786    pub type_index: VMSharedTypeIndex,
787}
788
789impl VMTagDefinition {
790    pub fn new(type_index: VMSharedTypeIndex) -> Self {
791        Self { type_index }
792    }
793}
794
795// SAFETY: the above structure is repr(C) and only contains VmSafe
796// fields.
797unsafe impl VmSafe for VMTagDefinition {}
798
799#[cfg(test)]
800mod test_vmtag_definition {
801    use super::VMTagDefinition;
802    use std::mem::size_of;
803    use wasmtime_environ::{HostPtr, Module, PtrSize, StaticModuleIndex, VMOffsets};
804
805    #[test]
806    fn check_vmtag_definition_offsets() {
807        let module = Module::new(StaticModuleIndex::from_u32(0));
808        let offsets = VMOffsets::new(HostPtr, &module);
809        assert_eq!(
810            size_of::<VMTagDefinition>(),
811            usize::from(offsets.ptr.size_of_vmtag_definition())
812        );
813    }
814
815    #[test]
816    fn check_vmtag_begins_aligned() {
817        let module = Module::new(StaticModuleIndex::from_u32(0));
818        let offsets = VMOffsets::new(HostPtr, &module);
819        assert_eq!(offsets.vmctx_tags_begin() % 16, 0);
820    }
821}
822
823/// The VM caller-checked "funcref" record, for caller-side signature checking.
824///
825/// It consists of function pointer(s), a type id to be checked by the
826/// caller, and the vmctx closure associated with this function.
827#[derive(Debug, Clone)]
828#[repr(C)]
829pub struct VMFuncRef {
830    /// Function pointer for this funcref if being called via the "array"
831    /// calling convention that `Func::new` et al use.
832    pub array_call: VmPtr<VMArrayCallFunction>,
833
834    /// Function pointer for this funcref if being called via the calling
835    /// convention we use when compiling Wasm.
836    ///
837    /// Most functions come with a function pointer that we can use when they
838    /// are called from Wasm. The notable exception is when we `Func::wrap` a
839    /// host function, and we don't have a Wasm compiler on hand to compile a
840    /// Wasm-to-native trampoline for the function. In this case, we leave
841    /// `wasm_call` empty until the function is passed as an import to Wasm (or
842    /// otherwise exposed to Wasm via tables/globals). At this point, we look up
843    /// a Wasm-to-native trampoline for the function in the Wasm's compiled
844    /// module and use that fill in `VMFunctionImport::wasm_call`. **However**
845    /// there is no guarantee that the Wasm module has a trampoline for this
846    /// function's signature. The Wasm module only has trampolines for its
847    /// types, and if this function isn't of one of those types, then the Wasm
848    /// module will not have a trampoline for it. This is actually okay, because
849    /// it means that the Wasm cannot actually call this function. But it does
850    /// mean that this field needs to be an `Option` even though it is non-null
851    /// the vast vast vast majority of the time.
852    pub wasm_call: Option<VmPtr<VMWasmCallFunction>>,
853
854    /// Function signature's type id.
855    pub type_index: VMSharedTypeIndex,
856
857    /// The VM state associated with this function.
858    ///
859    /// The actual definition of what this pointer points to depends on the
860    /// function being referenced: for core Wasm functions, this is a `*mut
861    /// VMContext`, for host functions it is a `*mut VMHostFuncContext`, and for
862    /// component functions it is a `*mut VMComponentContext`.
863    pub vmctx: VmPtr<VMOpaqueContext>,
864    // If more elements are added here, remember to add offset_of tests below!
865}
866
867// SAFETY: the above structure is repr(C) and only contains `VmSafe` fields.
868unsafe impl VmSafe for VMFuncRef {}
869
870impl VMFuncRef {
871    /// Invokes the `array_call` field of this `VMFuncRef` with the supplied
872    /// arguments.
873    ///
874    /// This will invoke the function pointer in the `array_call` field with:
875    ///
876    /// * the `callee` vmctx as `self.vmctx`
877    /// * the `caller` as `caller` specified here
878    /// * the args pointer as `args_and_results`
879    /// * the args length as `args_and_results`
880    ///
881    /// The `args_and_results` area must be large enough to both load all
882    /// arguments from and store all results to.
883    ///
884    /// Returns whether a trap was recorded in TLS for raising.
885    ///
886    /// # Unsafety
887    ///
888    /// This method is unsafe because it can be called with any pointers. They
889    /// must all be valid for this wasm function call to proceed. For example
890    /// the `caller` must be valid machine code if `pulley` is `None` or it must
891    /// be valid bytecode if `pulley` is `Some`. Additionally `args_and_results`
892    /// must be large enough to handle all the arguments/results for this call.
893    ///
894    /// Note that the unsafety invariants to maintain here are not currently
895    /// exhaustively documented.
896    #[inline]
897    pub unsafe fn array_call(
898        me: NonNull<VMFuncRef>,
899        pulley: Option<InterpreterRef<'_>>,
900        caller: NonNull<VMContext>,
901        args_and_results: NonNull<[ValRaw]>,
902    ) -> bool {
903        match pulley {
904            Some(vm) => unsafe { Self::array_call_interpreted(me, vm, caller, args_and_results) },
905            None => unsafe { Self::array_call_native(me, caller, args_and_results) },
906        }
907    }
908
909    unsafe fn array_call_interpreted(
910        me: NonNull<VMFuncRef>,
911        vm: InterpreterRef<'_>,
912        caller: NonNull<VMContext>,
913        args_and_results: NonNull<[ValRaw]>,
914    ) -> bool {
915        // If `caller` is actually a `VMArrayCallHostFuncContext` then skip the
916        // interpreter, even though it's available, as `array_call` will be
917        // native code.
918        unsafe {
919            if me.as_ref().vmctx.as_non_null().as_ref().magic
920                == wasmtime_environ::VM_ARRAY_CALL_HOST_FUNC_MAGIC
921            {
922                return Self::array_call_native(me, caller, args_and_results);
923            }
924            vm.call(
925                me.as_ref().array_call.as_non_null().cast(),
926                me.as_ref().vmctx.as_non_null(),
927                caller,
928                args_and_results,
929            )
930        }
931    }
932
933    #[inline]
934    unsafe fn array_call_native(
935        me: NonNull<VMFuncRef>,
936        caller: NonNull<VMContext>,
937        args_and_results: NonNull<[ValRaw]>,
938    ) -> bool {
939        unsafe {
940            union GetNativePointer {
941                native: VMArrayCallNative,
942                ptr: NonNull<VMArrayCallFunction>,
943            }
944            let native = GetNativePointer {
945                ptr: me.as_ref().array_call.as_non_null(),
946            }
947            .native;
948            native(
949                me.as_ref().vmctx.as_non_null(),
950                caller,
951                args_and_results.cast(),
952                args_and_results.len(),
953            )
954        }
955    }
956
957    pub(crate) fn as_vm_function_import(&self) -> Option<&VMFunctionImport> {
958        if self.wasm_call.is_some() {
959            // Safety: `VMFuncRef` and `VMFunctionImport` have the same layout
960            // and `wasm_call` is non-null.
961            Some(unsafe { NonNull::from(self).cast::<VMFunctionImport>().as_ref() })
962        } else {
963            None
964        }
965    }
966}
967
968#[cfg(test)]
969mod test_vm_func_ref {
970    use super::VMFuncRef;
971    use core::mem::offset_of;
972    use std::mem::size_of;
973    use wasmtime_environ::{HostPtr, Module, PtrSize, StaticModuleIndex, VMOffsets};
974
975    #[test]
976    fn check_vm_func_ref_offsets() {
977        let module = Module::new(StaticModuleIndex::from_u32(0));
978        let offsets = VMOffsets::new(HostPtr, &module);
979        assert_eq!(
980            size_of::<VMFuncRef>(),
981            usize::from(offsets.ptr.size_of_vm_func_ref())
982        );
983        assert_eq!(
984            offset_of!(VMFuncRef, array_call),
985            usize::from(offsets.ptr.vm_func_ref_array_call())
986        );
987        assert_eq!(
988            offset_of!(VMFuncRef, wasm_call),
989            usize::from(offsets.ptr.vm_func_ref_wasm_call())
990        );
991        assert_eq!(
992            offset_of!(VMFuncRef, type_index),
993            usize::from(offsets.ptr.vm_func_ref_type_index())
994        );
995        assert_eq!(
996            offset_of!(VMFuncRef, vmctx),
997            usize::from(offsets.ptr.vm_func_ref_vmctx())
998        );
999    }
1000}
1001
1002macro_rules! define_builtin_array {
1003    (
1004        $(
1005            $( #[$attr:meta] )*
1006            $name:ident( $( $pname:ident: $param:ident ),* ) $( -> $result:ident )?;
1007        )*
1008    ) => {
1009        /// An array that stores addresses of builtin functions. We translate code
1010        /// to use indirect calls. This way, we don't have to patch the code.
1011        #[repr(C)]
1012        #[allow(improper_ctypes_definitions, reason = "__m128i known not FFI-safe")]
1013        pub struct VMBuiltinFunctionsArray {
1014            $(
1015                $name: unsafe extern "C" fn(
1016                    $(define_builtin_array!(@ty $param)),*
1017                ) $( -> define_builtin_array!(@ty $result))?,
1018            )*
1019        }
1020
1021        impl VMBuiltinFunctionsArray {
1022            pub const INIT: VMBuiltinFunctionsArray = VMBuiltinFunctionsArray {
1023                $(
1024                    $name: crate::runtime::vm::libcalls::raw::$name,
1025                )*
1026            };
1027
1028            /// Helper to call `expose_provenance()` on all contained pointers.
1029            ///
1030            /// This is required to be called at least once before entering wasm
1031            /// to inform the compiler that these function pointers may all be
1032            /// loaded/stored and used on the "other end" to reacquire
1033            /// provenance in Pulley. Pulley models hostcalls with a host
1034            /// pointer as the first parameter that's a function pointer under
1035            /// the hood, and this call ensures that the use of the function
1036            /// pointer is considered valid.
1037            pub fn expose_provenance(&self) -> NonNull<Self>{
1038                $(
1039                    (self.$name as *mut u8).expose_provenance();
1040                )*
1041                NonNull::from(self)
1042            }
1043        }
1044    };
1045
1046    (@ty u32) => (u32);
1047    (@ty u64) => (u64);
1048    (@ty f32) => (f32);
1049    (@ty f64) => (f64);
1050    (@ty u8) => (u8);
1051    (@ty i8x16) => (i8x16);
1052    (@ty f32x4) => (f32x4);
1053    (@ty f64x2) => (f64x2);
1054    (@ty bool) => (bool);
1055    (@ty pointer) => (*mut u8);
1056    (@ty size) => (usize);
1057    (@ty vmctx) => (NonNull<VMContext>);
1058}
1059
1060// SAFETY: the above structure is repr(C) and only contains `VmSafe` fields.
1061unsafe impl VmSafe for VMBuiltinFunctionsArray {}
1062
1063wasmtime_environ::foreach_builtin_function!(define_builtin_array);
1064
1065const _: () = {
1066    assert!(
1067        mem::size_of::<VMBuiltinFunctionsArray>()
1068            == mem::size_of::<usize>() * (BuiltinFunctionIndex::len() as usize)
1069    )
1070};
1071
1072/// Structure that holds all mutable context that is shared across all instances
1073/// in a store, for example data related to fuel or epochs.
1074///
1075/// `VMStoreContext`s are one-to-one with `wasmtime::Store`s, the same way that
1076/// `VMContext`s are one-to-one with `wasmtime::Instance`s. And the same way
1077/// that multiple `wasmtime::Instance`s may be associated with the same
1078/// `wasmtime::Store`, multiple `VMContext`s hold a pointer to the same
1079/// `VMStoreContext` when they are associated with the same `wasmtime::Store`.
1080#[derive(Debug)]
1081#[repr(C)]
1082pub struct VMStoreContext {
1083    // NB: 64-bit integer fields are located first with pointer-sized fields
1084    // trailing afterwards. That makes the offsets in this structure easier to
1085    // calculate on 32-bit platforms as we don't have to worry about the
1086    // alignment of 64-bit integers.
1087    //
1088    /// Indicator of how much fuel has been consumed and is remaining to
1089    /// WebAssembly.
1090    ///
1091    /// This field is typically negative and increments towards positive. Upon
1092    /// turning positive a wasm trap will be generated. This field is only
1093    /// modified if wasm is configured to consume fuel.
1094    pub fuel_consumed: UnsafeCell<i64>,
1095
1096    /// Deadline epoch for interruption: if epoch-based interruption
1097    /// is enabled and the global (per engine) epoch counter is
1098    /// observed to reach or exceed this value, the guest code will
1099    /// yield if running asynchronously.
1100    pub epoch_deadline: UnsafeCell<u64>,
1101
1102    /// The "store version".
1103    ///
1104    /// This is used to test whether stack-frame handles referring to
1105    /// suspended stack frames remain valid.
1106    ///
1107    /// The invariant that this upward-counting number must satisfy
1108    /// is: the number must be incremented whenever execution starts
1109    /// or resumes in the `Store` or when any stack is
1110    /// dropped/freed. That way, if we take a reference to some
1111    /// suspended stack frame and track the "version" at the time we
1112    /// took that reference, if the version still matches, we can be
1113    /// sure that nothing could have unwound the referenced Wasm
1114    /// frame.
1115    ///
1116    /// This version number is incremented in exactly one place: the
1117    /// Wasm-to-host trampolines, after return from host code. Note
1118    /// that this captures both the normal "return into Wasm" case
1119    /// (where Wasm frames can subsequently return normally and thus
1120    /// invalidate frames), and the "trap/exception unwinds Wasm
1121    /// frames" case, which is done internally via the `raise` libcall
1122    /// invoked after the main hostcall returns an error, and after we
1123    /// increment this version number.
1124    ///
1125    /// Note that this also handles the fiber/future-drop case because
1126    /// because we *always* return into the trampoline to clean up;
1127    /// that trampoline immediately raises an error and uses the
1128    /// longjmp-like unwind within Cranelift frames to skip over all
1129    /// the guest Wasm frames, but not before it increments the
1130    /// store's execution version number.
1131    ///
1132    /// This field is in use only if guest debugging is enabled.
1133    pub execution_version: u64,
1134
1135    /// Current stack limit of the wasm module.
1136    ///
1137    /// For more information see `crates/cranelift/src/lib.rs`.
1138    pub stack_limit: UnsafeCell<usize>,
1139
1140    /// The `VMMemoryDefinition` for this store's GC heap.
1141    pub gc_heap: UnsafeCell<VMMemoryDefinition>,
1142
1143    /// The value of the frame pointer register in the trampoline used
1144    /// to call from Wasm to the host.
1145    ///
1146    /// Maintained by our Wasm-to-host trampoline, and cleared just
1147    /// before calling into Wasm in `catch_traps`.
1148    ///
1149    /// This member is `0` when Wasm is actively running and has not called out
1150    /// to the host.
1151    ///
1152    /// Used to find the start of a contiguous sequence of Wasm frames
1153    /// when walking the stack. Note that we record the FP of the
1154    /// *trampoline*'s frame, not the last Wasm frame, because we need
1155    /// to know the SP (bottom of frame) of the last Wasm frame as
1156    /// well in case we need to resume to an exception handler in that
1157    /// frame. The FP of the last Wasm frame can be recovered by
1158    /// loading the saved FP value at this FP address.
1159    pub last_wasm_exit_trampoline_fp: UnsafeCell<usize>,
1160
1161    /// The last Wasm program counter before we called from Wasm to the host.
1162    ///
1163    /// Maintained by our Wasm-to-host trampoline, and cleared just before
1164    /// calling into Wasm in `catch_traps`.
1165    ///
1166    /// This member is `0` when Wasm is actively running and has not called out
1167    /// to the host.
1168    ///
1169    /// Used when walking a contiguous sequence of Wasm frames.
1170    pub last_wasm_exit_pc: UnsafeCell<usize>,
1171
1172    /// The last host stack pointer before we called into Wasm from the host.
1173    ///
1174    /// Maintained by our host-to-Wasm trampoline. This member is `0` when Wasm
1175    /// is not running, and it's set to nonzero once a host-to-wasm trampoline
1176    /// is executed.
1177    ///
1178    /// When a host function is wrapped into a `wasmtime::Func`, and is then
1179    /// called from the host, then this member is not changed meaning that the
1180    /// previous activation in pointed to by `last_wasm_exit_trampoline_fp` is
1181    /// still the last wasm set of frames on the stack.
1182    ///
1183    /// This field is saved/restored during fiber suspension/resumption
1184    /// resumption as part of `CallThreadState::swap`.
1185    ///
1186    /// This field is used to find the end of a contiguous sequence of Wasm
1187    /// frames when walking the stack. Additionally it's used when a trap is
1188    /// raised as part of the set of parameters used to resume in the entry
1189    /// trampoline's "catch" block.
1190    pub last_wasm_entry_sp: UnsafeCell<usize>,
1191
1192    /// Same as `last_wasm_entry_sp`, but for the `fp` of the trampoline.
1193    pub last_wasm_entry_fp: UnsafeCell<usize>,
1194
1195    /// The last trap handler from a host-to-wasm entry trampoline on the stack.
1196    ///
1197    /// This field is configured when the host calls into wasm by the trampoline
1198    /// itself. It stores the `pc` of an exception handler suitable to handle
1199    /// all traps (or uncaught exceptions).
1200    pub last_wasm_entry_trap_handler: UnsafeCell<usize>,
1201
1202    /// Stack information used by stack switching instructions. See documentation
1203    /// on `VMStackChain` for details.
1204    pub stack_chain: UnsafeCell<VMStackChain>,
1205
1206    /// A pointer to the embedder's `T` inside a `Store<T>`, for use with the
1207    /// `store-data-address` unsafe intrinsic.
1208    pub store_data: VmPtr<()>,
1209
1210    /// The range, in addresses, of the guard page that is currently in use.
1211    ///
1212    /// This field is used when signal handlers are run to determine whether a
1213    /// faulting address lies within the guard page of an async stack for
1214    /// example. If this happens then the signal handler aborts with a stack
1215    /// overflow message similar to what would happen had the stack overflow
1216    /// happened on the main thread. This field is, by default a null..null
1217    /// range indicating that no async guard is in use (aka no fiber). In such a
1218    /// situation while this field is read it'll never classify a fault as an
1219    /// guard page fault.
1220    pub async_guard_range: Range<*mut u8>,
1221
1222    /// The `context.{get,set}` values for the current thread in the component
1223    /// model. This is only used for `component-model-async` and slot[1] is only
1224    /// used for `component-model-threading`. Despite the conditional use nature
1225    /// this is unconditionally present as it avoids the need to make logic in
1226    /// `VMOffsets` conditional.
1227    ///
1228    /// This is saved/restored when threads are swapped in the component model.
1229    ///
1230    /// NB: `UnsafeCell` because JIT code writes to the slots.
1231    pub component_context: UnsafeCell<[u32; NUM_COMPONENT_CONTEXT_SLOTS]>,
1232
1233    /// JIT-visible current thread for the component model's sync-to-sync
1234    /// adapter fast path.
1235    ///
1236    /// Like `component_context`, this is unconditionally present to keep
1237    /// `VMOffsets` logic unconditional even though it is only used when
1238    /// `component-model-async` is enabled.
1239    ///
1240    /// NB: `UnsafeCell` because JIT code writes to this field.
1241    pub current_thread: UnsafeCell<VMLazyThread>,
1242}
1243
1244impl VMStoreContext {
1245    /// From the current saved trampoline FP, get the FP of the last
1246    /// Wasm frame. If the current saved trampoline FP is null, return
1247    /// null.
1248    ///
1249    /// We store only the trampoline FP, because (i) we need the
1250    /// trampoline FP, so we know the size (bottom) of the last Wasm
1251    /// frame; and (ii) the last Wasm frame, just above the trampoline
1252    /// frame, can be recovered via the FP chain.
1253    ///
1254    /// # Safety
1255    ///
1256    /// This function requires that the `last_wasm_exit_trampoline_fp`
1257    /// field either points to an active trampoline frame or is a null
1258    /// pointer.
1259    pub(crate) unsafe fn last_wasm_exit_fp(&self) -> usize {
1260        // SAFETY: the unsafe cell is safe to load (no other threads
1261        // will be writing our store when we have control), and the
1262        // helper function's safety condition is the same as ours.
1263        unsafe {
1264            let trampoline_fp = *self.last_wasm_exit_trampoline_fp.get();
1265            Self::wasm_exit_fp_from_trampoline_fp(trampoline_fp)
1266        }
1267    }
1268
1269    /// From any saved trampoline FP, get the FP of the last Wasm
1270    /// frame. If the given trampoline FP is null, return null.
1271    ///
1272    /// This differs from `last_wasm_exit_fp()` above in that it
1273    /// allows accessing activations further up the stack as well,
1274    /// e.g. via `CallThreadState::old_state`.
1275    ///
1276    /// # Safety
1277    ///
1278    /// This function requires that the provided FP value is valid,
1279    /// and points to an active trampoline frame, or is null.
1280    ///
1281    /// This function depends on the invariant that on all supported
1282    /// architectures, we store the previous FP value under the
1283    /// current FP. This is a property of our ABI that we control and
1284    /// ensure.
1285    pub(crate) unsafe fn wasm_exit_fp_from_trampoline_fp(trampoline_fp: usize) -> usize {
1286        if trampoline_fp != 0 {
1287            // SAFETY: We require that trampoline_fp points to a valid
1288            // frame, which will (by definition) contain an old FP value
1289            // that we can load.
1290            unsafe { *(trampoline_fp as *const usize) }
1291        } else {
1292            0
1293        }
1294    }
1295
1296    #[cfg(feature = "component-model-async")]
1297    pub(crate) fn component_context_mut(&mut self) -> &mut [u32; NUM_COMPONENT_CONTEXT_SLOTS] {
1298        self.component_context.get_mut()
1299    }
1300
1301    #[cfg(feature = "component-model-async")]
1302    pub(crate) fn current_thread_mut(&mut self) -> &mut VMLazyThread {
1303        self.current_thread.get_mut()
1304    }
1305}
1306
1307// The `VMStoreContext` type is a pod-type with no destructor, and we don't
1308// access any fields from other threads, so add in these trait impls which are
1309// otherwise not available due to the `fuel_consumed` and `epoch_deadline`
1310// variables in `VMStoreContext`.
1311unsafe impl Send for VMStoreContext {}
1312unsafe impl Sync for VMStoreContext {}
1313
1314// SAFETY: the above structure is repr(C) and only contains `VmSafe` fields.
1315unsafe impl VmSafe for VMStoreContext {}
1316
1317impl Default for VMStoreContext {
1318    fn default() -> VMStoreContext {
1319        VMStoreContext {
1320            fuel_consumed: UnsafeCell::new(0),
1321            epoch_deadline: UnsafeCell::new(0),
1322            execution_version: 0,
1323            stack_limit: UnsafeCell::new(usize::max_value()),
1324            gc_heap: UnsafeCell::new(VMMemoryDefinition {
1325                base: NonNull::dangling().into(),
1326                current_length: AtomicUsize::new(0),
1327            }),
1328            last_wasm_exit_trampoline_fp: UnsafeCell::new(0),
1329            last_wasm_exit_pc: UnsafeCell::new(0),
1330            last_wasm_entry_fp: UnsafeCell::new(0),
1331            last_wasm_entry_sp: UnsafeCell::new(0),
1332            last_wasm_entry_trap_handler: UnsafeCell::new(0),
1333            stack_chain: UnsafeCell::new(VMStackChain::Absent),
1334            async_guard_range: ptr::null_mut()..ptr::null_mut(),
1335            store_data: VmPtr::dangling(),
1336            component_context: UnsafeCell::new([0; NUM_COMPONENT_CONTEXT_SLOTS]),
1337            current_thread: UnsafeCell::new(VMLazyThread::none()),
1338        }
1339    }
1340}
1341
1342#[cfg(test)]
1343mod test_vmstore_context {
1344    use super::{VMMemoryDefinition, VMStoreContext};
1345    use core::mem::offset_of;
1346    use wasmtime_environ::{HostPtr, Module, PtrSize, StaticModuleIndex, VMOffsets};
1347
1348    #[test]
1349    fn field_offsets() {
1350        let module = Module::new(StaticModuleIndex::from_u32(0));
1351        let offsets = VMOffsets::new(HostPtr, &module);
1352        assert_eq!(
1353            offset_of!(VMStoreContext, stack_limit),
1354            usize::from(offsets.ptr.vmstore_context_stack_limit())
1355        );
1356        assert_eq!(
1357            offset_of!(VMStoreContext, fuel_consumed),
1358            usize::from(offsets.ptr.vmstore_context_fuel_consumed())
1359        );
1360        assert_eq!(
1361            offset_of!(VMStoreContext, epoch_deadline),
1362            usize::from(offsets.ptr.vmstore_context_epoch_deadline())
1363        );
1364        assert_eq!(
1365            offset_of!(VMStoreContext, execution_version),
1366            usize::from(offsets.ptr.vmstore_context_execution_version())
1367        );
1368        assert_eq!(
1369            offset_of!(VMStoreContext, gc_heap),
1370            usize::from(offsets.ptr.vmstore_context_gc_heap())
1371        );
1372        assert_eq!(
1373            offset_of!(VMStoreContext, gc_heap) + offset_of!(VMMemoryDefinition, base),
1374            usize::from(offsets.ptr.vmstore_context_gc_heap_base())
1375        );
1376        assert_eq!(
1377            offset_of!(VMStoreContext, gc_heap) + offset_of!(VMMemoryDefinition, current_length),
1378            usize::from(offsets.ptr.vmstore_context_gc_heap_current_length())
1379        );
1380        assert_eq!(
1381            offset_of!(VMStoreContext, last_wasm_exit_trampoline_fp),
1382            usize::from(offsets.ptr.vmstore_context_last_wasm_exit_trampoline_fp())
1383        );
1384        assert_eq!(
1385            offset_of!(VMStoreContext, last_wasm_exit_pc),
1386            usize::from(offsets.ptr.vmstore_context_last_wasm_exit_pc())
1387        );
1388        assert_eq!(
1389            offset_of!(VMStoreContext, last_wasm_entry_fp),
1390            usize::from(offsets.ptr.vmstore_context_last_wasm_entry_fp())
1391        );
1392        assert_eq!(
1393            offset_of!(VMStoreContext, last_wasm_entry_sp),
1394            usize::from(offsets.ptr.vmstore_context_last_wasm_entry_sp())
1395        );
1396        assert_eq!(
1397            offset_of!(VMStoreContext, last_wasm_entry_trap_handler),
1398            usize::from(offsets.ptr.vmstore_context_last_wasm_entry_trap_handler())
1399        );
1400        assert_eq!(
1401            offset_of!(VMStoreContext, stack_chain),
1402            usize::from(offsets.ptr.vmstore_context_stack_chain())
1403        );
1404        assert_eq!(
1405            offset_of!(VMStoreContext, store_data),
1406            usize::from(offsets.ptr.vmstore_context_store_data())
1407        );
1408        assert_eq!(
1409            offset_of!(VMStoreContext, component_context),
1410            usize::from(offsets.ptr.vmstore_context_component_context_slot(0))
1411        );
1412        assert_eq!(
1413            offset_of!(VMStoreContext, current_thread),
1414            usize::from(offsets.ptr.vmstore_context_current_thread())
1415        );
1416
1417        // Make sure that the calculation for the size of a slot is also
1418        // accurate.
1419        let slot_width = offsets.ptr.vmstore_context_component_context_slot(1)
1420            - offsets.ptr.vmstore_context_component_context_slot(0);
1421        let mut default = VMStoreContext::default();
1422        assert_eq!(
1423            size_of_val(&default.component_context.get_mut()[0]),
1424            usize::from(slot_width)
1425        );
1426    }
1427}
1428
1429/// JIT-visible representation of the store's current thread for the component
1430/// model, encoded as a single pointer-sized integer so that generated JIT code
1431/// can load, store, and compare it with a handful of instructions.
1432///
1433/// This is the inline fast-path counterpart to the host-side `CurrentThread`: a
1434/// fused sync-to-sync adapter records a lazy deferred thread here (a pointer to
1435/// a `VMDeferredThread` on its own stack frame) instead of eagerly allocating a
1436/// `GuestTask`/`GuestThread` in the host. Host code promotes the deferred
1437/// thread into a real one only when it actually needs it; see
1438/// `StoreOpaque::force_current_thread`.
1439///
1440/// This type is a bitpacked equivalent of the following logical `enum`:
1441///
1442/// ```ignore
1443/// enum VMLazyThread {
1444///     /// No thread.
1445///     None,
1446///
1447///     /// The lazy thread was promoted and materialized; get it from
1448///     /// `ConcurrentState::current_thread`.
1449///     Forced,
1450///
1451///     /// The lazy thread has not been materialized, here is a pointer to the
1452///     /// stack-allocated data needed to do force that promotion.
1453///     Deferred(*mut VMDeferredThread),
1454/// }
1455/// ```
1456//
1457// Bitpacking details:
1458//
1459// * `None`: `0`
1460//
1461// * `Forced`: A non-zero value with its low-bit set.
1462//
1463// * `Deferred`: A non-zero value with its low-bit clear.
1464#[derive(Debug, Copy, Clone, PartialEq, Eq)]
1465#[repr(transparent)]
1466pub struct VMLazyThread(Option<VmPtr<VMDeferredThread>>);
1467
1468impl VMLazyThread {
1469    const _ASSERT_SIZE: () = assert!(
1470        core::mem::size_of::<VMLazyThread>() == core::mem::size_of::<*mut VMDeferredThread>()
1471    );
1472    const _ASSERT_ALIGN: () = assert!(
1473        core::mem::align_of::<VMLazyThread>() == core::mem::align_of::<*mut VMDeferredThread>()
1474    );
1475
1476    const FORCED: VmPtr<VMDeferredThread> = VmPtr::<u8>::dangling().cast();
1477
1478    /// There is no current thread.
1479    pub const fn none() -> Self {
1480        Self(None)
1481    }
1482
1483    /// A lazy thread that has already been promoted.
1484    pub const fn forced() -> Self {
1485        Self(Some(Self::FORCED))
1486    }
1487
1488    /// A deferred thread referencing the given on-stack [`VMDeferredThread`].
1489    pub fn deferred(ptr: NonNull<VMDeferredThread>) -> Self {
1490        debug_assert_eq!(ptr.addr().get() & Self::FORCED.addr().get(), 0);
1491        Self(Some(ptr.into()))
1492    }
1493
1494    /// Returns `true` if there is no current thread.
1495    pub fn is_none(self) -> bool {
1496        self.0.is_none()
1497    }
1498
1499    /// Returns `true` if a deferred thread has been forced/promoted.
1500    pub fn is_forced(self) -> bool {
1501        self.0.is_some_and(|p| p == Self::FORCED)
1502    }
1503
1504    /// Returns `true` if this is a deferred thread (i.e. neither `None` nor
1505    /// forced).
1506    pub fn is_deferred(self) -> bool {
1507        self.0.is_some_and(|p| p != Self::FORCED)
1508    }
1509
1510    /// Returns the deferred [`VMDeferredThread`] pointer if this is a deferred
1511    /// thread.
1512    pub fn as_deferred(self) -> Option<VmPtr<VMDeferredThread>> {
1513        self.0
1514            .and_then(|p| if p == Self::FORCED { None } else { Some(p) })
1515    }
1516}
1517
1518#[cfg(test)]
1519mod test_vmlazy_thread {
1520    use super::*;
1521
1522    #[test]
1523    fn vmlazy_thread_forced() {
1524        assert_eq!(
1525            VMLazyThread::forced().0.unwrap().addr().get(),
1526            usize::try_from(wasmtime_environ::VM_LAZY_THREAD_FORCED).unwrap()
1527        );
1528    }
1529}
1530
1531/// A deferred component-model thread.
1532///
1533/// This is an on-stack record pushed by a fused sync-to-sync adapter's fast
1534/// path to defer the work that the `enter_sync_call` libcall would otherwise do
1535/// eagerly.
1536///
1537/// The adapter allocates one of these in its own stack frame, links the
1538/// previous current-thread value to it via `parent`, and finally points
1539/// `VMStoreContext::current_thread` at it. When host code actually needs the
1540/// real thread, it walks the `parent` chain to materialize thread state (see
1541/// `StoreOpaque::force_current_thread`).
1542#[derive(Debug)]
1543#[repr(C)]
1544pub struct VMDeferredThread {
1545    /// The previous value of `VMStoreContext::current_thread`.
1546    pub parent: VMLazyThread,
1547    /// The caller component instance (a deferred `enter_sync_call` argument).
1548    pub caller_instance: u32,
1549    /// Whether the callee is async-lifted (a deferred `enter_sync_call` arg).
1550    pub callee_async: u32,
1551    /// The callee component instance (a deferred `enter_sync_call` argument).
1552    pub callee_instance: u32,
1553    /// The caller thread's `context.{get,set}` slots, saved on entry and
1554    /// restored on the fast-path exit (or recovered while forcing).
1555    pub saved_context: [u32; NUM_COMPONENT_CONTEXT_SLOTS],
1556}
1557
1558#[cfg(test)]
1559mod test_vmdeferred_thread {
1560    use super::*;
1561    use core::mem::offset_of;
1562    use wasmtime_environ::{HostPtr, Module, PtrSize, StaticModuleIndex, VMOffsets};
1563
1564    #[test]
1565    fn deferred_thread_field_offsets() {
1566        let module = Module::new(StaticModuleIndex::from_u32(0));
1567        let offsets = VMOffsets::new(HostPtr, &module);
1568        let ptr = offsets.ptr;
1569        assert_eq!(
1570            offset_of!(VMDeferredThread, parent),
1571            usize::from(ptr.vmdeferred_thread_parent())
1572        );
1573        assert_eq!(
1574            offset_of!(VMDeferredThread, caller_instance),
1575            usize::from(ptr.vmdeferred_thread_caller_instance())
1576        );
1577        assert_eq!(
1578            offset_of!(VMDeferredThread, callee_async),
1579            usize::from(ptr.vmdeferred_thread_callee_async())
1580        );
1581        assert_eq!(
1582            offset_of!(VMDeferredThread, callee_instance),
1583            usize::from(ptr.vmdeferred_thread_callee_instance())
1584        );
1585        assert_eq!(
1586            offset_of!(VMDeferredThread, saved_context),
1587            usize::from(ptr.vmdeferred_thread_saved_context(0))
1588        );
1589        assert_eq!(
1590            size_of::<VMDeferredThread>(),
1591            usize::from(ptr.size_of_vmdeferred_thread())
1592        );
1593    }
1594}
1595
1596/// The VM "context", which is pointed to by the `vmctx` arg in Cranelift.
1597/// This has information about globals, memories, tables, and other runtime
1598/// state associated with the current instance.
1599///
1600/// The struct here is empty, as the sizes of these fields are dynamic, and
1601/// we can't describe them in Rust's type system. Sufficient memory is
1602/// allocated at runtime.
1603#[derive(Debug)]
1604#[repr(C, align(16))] // align 16 since globals are aligned to that and contained inside
1605pub struct VMContext {
1606    _magic: u32,
1607}
1608
1609impl VMContext {
1610    /// Helper function to cast between context types using a debug assertion to
1611    /// protect against some mistakes.
1612    #[inline]
1613    pub unsafe fn from_opaque(opaque: NonNull<VMOpaqueContext>) -> NonNull<VMContext> {
1614        // Note that in general the offset of the "magic" field is stored in
1615        // `VMOffsets::vmctx_magic`. Given though that this is a sanity check
1616        // about converting this pointer to another type we ideally don't want
1617        // to read the offset from potentially corrupt memory. Instead it would
1618        // be better to catch errors here as soon as possible.
1619        //
1620        // To accomplish this the `VMContext` structure is laid out with the
1621        // magic field at a statically known offset (here it's 0 for now). This
1622        // static offset is asserted in `VMOffsets::from` and needs to be kept
1623        // in sync with this line for this debug assertion to work.
1624        //
1625        // Also note that this magic is only ever invalid in the presence of
1626        // bugs, meaning we don't actually read the magic and act differently
1627        // at runtime depending what it is, so this is a debug assertion as
1628        // opposed to a regular assertion.
1629        unsafe {
1630            debug_assert_eq!(opaque.as_ref().magic, VMCONTEXT_MAGIC);
1631        }
1632        opaque.cast()
1633    }
1634}
1635
1636/// A "raw" and unsafe representation of a WebAssembly value.
1637///
1638/// This is provided for use with the `Func::new_unchecked` and
1639/// `Func::call_unchecked` APIs. In general it's unlikely you should be using
1640/// this from Rust, rather using APIs like `Func::wrap` and `TypedFunc::call`.
1641///
1642/// This is notably an "unsafe" way to work with `Val` and it's recommended to
1643/// instead use `Val` where possible. An important note about this union is that
1644/// fields are all stored in little-endian format, regardless of the endianness
1645/// of the host system.
1646#[repr(C)]
1647#[derive(Copy, Clone)]
1648pub union ValRaw {
1649    /// A WebAssembly `i32` value.
1650    ///
1651    /// Note that the payload here is a Rust `i32` but the WebAssembly `i32`
1652    /// type does not assign an interpretation of the upper bit as either signed
1653    /// or unsigned. The Rust type `i32` is simply chosen for convenience.
1654    ///
1655    /// This value is always stored in a little-endian format.
1656    i32: i32,
1657
1658    /// A WebAssembly `i64` value.
1659    ///
1660    /// Note that the payload here is a Rust `i64` but the WebAssembly `i64`
1661    /// type does not assign an interpretation of the upper bit as either signed
1662    /// or unsigned. The Rust type `i64` is simply chosen for convenience.
1663    ///
1664    /// This value is always stored in a little-endian format.
1665    i64: i64,
1666
1667    /// A WebAssembly `f32` value.
1668    ///
1669    /// Note that the payload here is a Rust `u32`. This is to allow passing any
1670    /// representation of NaN into WebAssembly without risk of changing NaN
1671    /// payload bits as its gets passed around the system. Otherwise though this
1672    /// `u32` value is the return value of `f32::to_bits` in Rust.
1673    ///
1674    /// This value is always stored in a little-endian format.
1675    f32: u32,
1676
1677    /// A WebAssembly `f64` value.
1678    ///
1679    /// Note that the payload here is a Rust `u64`. This is to allow passing any
1680    /// representation of NaN into WebAssembly without risk of changing NaN
1681    /// payload bits as its gets passed around the system. Otherwise though this
1682    /// `u64` value is the return value of `f64::to_bits` in Rust.
1683    ///
1684    /// This value is always stored in a little-endian format.
1685    f64: u64,
1686
1687    /// A WebAssembly `v128` value.
1688    ///
1689    /// The payload here is a Rust `[u8; 16]` which has the same number of bits
1690    /// but note that `v128` in WebAssembly is often considered a vector type
1691    /// such as `i32x4` or `f64x2`. This means that the actual interpretation
1692    /// of the underlying bits is left up to the instructions which consume
1693    /// this value.
1694    ///
1695    /// This value is always stored in a little-endian format.
1696    v128: [u8; 16],
1697
1698    /// A WebAssembly `funcref` value (or one of its subtypes).
1699    ///
1700    /// The payload here is a pointer which is runtime-defined. This is one of
1701    /// the main points of unsafety about the `ValRaw` type as the validity of
1702    /// the pointer here is not easily verified and must be preserved by
1703    /// carefully calling the correct functions throughout the runtime.
1704    ///
1705    /// This value is always stored in a little-endian format.
1706    funcref: *mut c_void,
1707
1708    /// A WebAssembly `externref` value (or one of its subtypes).
1709    ///
1710    /// The payload here is a compressed pointer value which is
1711    /// runtime-defined. This is one of the main points of unsafety about the
1712    /// `ValRaw` type as the validity of the pointer here is not easily verified
1713    /// and must be preserved by carefully calling the correct functions
1714    /// throughout the runtime.
1715    ///
1716    /// This value is always stored in a little-endian format.
1717    externref: u32,
1718
1719    /// A WebAssembly `anyref` value (or one of its subtypes).
1720    ///
1721    /// The payload here is a compressed pointer value which is
1722    /// runtime-defined. This is one of the main points of unsafety about the
1723    /// `ValRaw` type as the validity of the pointer here is not easily verified
1724    /// and must be preserved by carefully calling the correct functions
1725    /// throughout the runtime.
1726    ///
1727    /// This value is always stored in a little-endian format.
1728    anyref: u32,
1729
1730    /// A WebAssembly `exnref` value (or one of its subtypes).
1731    ///
1732    /// The payload here is a compressed pointer value which is
1733    /// runtime-defined. This is one of the main points of unsafety about the
1734    /// `ValRaw` type as the validity of the pointer here is not easily verified
1735    /// and must be preserved by carefully calling the correct functions
1736    /// throughout the runtime.
1737    ///
1738    /// This value is always stored in a little-endian format.
1739    exnref: u32,
1740}
1741
1742// The `ValRaw` type is matched as `wasmtime_val_raw_t` in the C API so these
1743// are some simple assertions about the shape of the type which are additionally
1744// matched in C.
1745const _: () = {
1746    assert!(mem::size_of::<ValRaw>() == 16);
1747    assert!(mem::align_of::<ValRaw>() == mem::align_of::<u64>());
1748};
1749
1750// This type is just a bag-of-bits so it's up to the caller to figure out how
1751// to safely deal with threading concerns and safely access interior bits.
1752unsafe impl Send for ValRaw {}
1753unsafe impl Sync for ValRaw {}
1754
1755impl fmt::Debug for ValRaw {
1756    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1757        struct Hex<T>(T);
1758        impl<T: fmt::LowerHex> fmt::Debug for Hex<T> {
1759            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1760                let bytes = mem::size_of::<T>();
1761                let hex_digits_per_byte = 2;
1762                let hex_digits = bytes * hex_digits_per_byte;
1763                write!(f, "0x{:0width$x}", self.0, width = hex_digits)
1764            }
1765        }
1766
1767        unsafe {
1768            f.debug_struct("ValRaw")
1769                .field("i32", &Hex(self.i32))
1770                .field("i64", &Hex(self.i64))
1771                .field("f32", &Hex(self.f32))
1772                .field("f64", &Hex(self.f64))
1773                .field("v128", &Hex(u128::from_le_bytes(self.v128)))
1774                .field("funcref", &self.funcref)
1775                .field("externref", &Hex(self.externref))
1776                .field("anyref", &Hex(self.anyref))
1777                .field("exnref", &Hex(self.exnref))
1778                .finish()
1779        }
1780    }
1781}
1782
1783impl ValRaw {
1784    /// Create a null reference that is compatible with any of
1785    /// `{any,extern,func,exn}ref`.
1786    pub fn null() -> ValRaw {
1787        unsafe {
1788            let raw = mem::MaybeUninit::<Self>::zeroed().assume_init();
1789            debug_assert_eq!(raw.get_anyref(), 0);
1790            debug_assert_eq!(raw.get_exnref(), 0);
1791            debug_assert_eq!(raw.get_externref(), 0);
1792            debug_assert_eq!(raw.get_funcref(), ptr::null_mut());
1793            raw
1794        }
1795    }
1796
1797    /// Creates a WebAssembly `i32` value
1798    #[inline]
1799    pub fn i32(i: i32) -> ValRaw {
1800        // Note that this is intentionally not setting the `i32` field, instead
1801        // setting the `i64` field with a zero-extended version of `i`. For more
1802        // information on this see the comments on `Lower for Result` in the
1803        // `wasmtime` crate. Otherwise though all `ValRaw` constructors are
1804        // otherwise constrained to guarantee that the initial 64-bits are
1805        // always initialized.
1806        ValRaw::u64(i.cast_unsigned().into())
1807    }
1808
1809    /// Creates a WebAssembly `i64` value
1810    #[inline]
1811    pub fn i64(i: i64) -> ValRaw {
1812        ValRaw { i64: i.to_le() }
1813    }
1814
1815    /// Creates a WebAssembly `i32` value
1816    #[inline]
1817    pub fn u32(i: u32) -> ValRaw {
1818        // See comments in `ValRaw::i32` for why this is setting the upper
1819        // 32-bits as well.
1820        ValRaw::u64(i.into())
1821    }
1822
1823    /// Creates a WebAssembly `i64` value
1824    #[inline]
1825    pub fn u64(i: u64) -> ValRaw {
1826        ValRaw::i64(i as i64)
1827    }
1828
1829    /// Creates a WebAssembly `f32` value
1830    #[inline]
1831    pub fn f32(i: u32) -> ValRaw {
1832        // See comments in `ValRaw::i32` for why this is setting the upper
1833        // 32-bits as well.
1834        ValRaw::u64(i.into())
1835    }
1836
1837    /// Creates a WebAssembly `f64` value
1838    #[inline]
1839    pub fn f64(i: u64) -> ValRaw {
1840        ValRaw { f64: i.to_le() }
1841    }
1842
1843    /// Creates a WebAssembly `v128` value
1844    #[inline]
1845    pub fn v128(i: u128) -> ValRaw {
1846        ValRaw {
1847            v128: i.to_le_bytes(),
1848        }
1849    }
1850
1851    /// Creates a WebAssembly `funcref` value
1852    #[inline]
1853    pub fn funcref(i: *mut c_void) -> ValRaw {
1854        ValRaw {
1855            funcref: i.map_addr(|i| i.to_le()),
1856        }
1857    }
1858
1859    /// Creates a WebAssembly `externref` value
1860    #[inline]
1861    pub fn externref(e: u32) -> ValRaw {
1862        assert!(cfg!(feature = "gc") || e == 0);
1863        ValRaw {
1864            externref: e.to_le(),
1865        }
1866    }
1867
1868    /// Creates a WebAssembly `anyref` value
1869    #[inline]
1870    pub fn anyref(r: u32) -> ValRaw {
1871        assert!(cfg!(feature = "gc") || r == 0);
1872        ValRaw { anyref: r.to_le() }
1873    }
1874
1875    /// Creates a WebAssembly `exnref` value
1876    #[inline]
1877    pub fn exnref(r: u32) -> ValRaw {
1878        assert!(cfg!(feature = "gc") || r == 0);
1879        ValRaw { exnref: r.to_le() }
1880    }
1881
1882    #[inline]
1883    pub(crate) fn vmgcref(r: Option<VMGcRef>) -> ValRaw {
1884        let raw = r.map_or(0, |r| r.as_raw_u32());
1885
1886        // NB: All `VMGcRef`-based `ValRaw`s are the same.
1887        debug_assert_eq!(raw, ValRaw::anyref(raw).get_exnref());
1888        debug_assert_eq!(raw, ValRaw::exnref(raw).get_externref());
1889        debug_assert_eq!(raw, ValRaw::externref(raw).get_anyref());
1890
1891        ValRaw::anyref(raw)
1892    }
1893
1894    /// Gets the WebAssembly `i32` value
1895    #[inline]
1896    pub fn get_i32(&self) -> i32 {
1897        unsafe { i32::from_le(self.i32) }
1898    }
1899
1900    /// Gets the WebAssembly `i64` value
1901    #[inline]
1902    pub fn get_i64(&self) -> i64 {
1903        unsafe { i64::from_le(self.i64) }
1904    }
1905
1906    /// Gets the WebAssembly `i32` value
1907    #[inline]
1908    pub fn get_u32(&self) -> u32 {
1909        self.get_i32().cast_unsigned()
1910    }
1911
1912    /// Gets the WebAssembly `i64` value
1913    #[inline]
1914    pub fn get_u64(&self) -> u64 {
1915        self.get_i64().cast_unsigned()
1916    }
1917
1918    /// Gets the WebAssembly `f32` value
1919    #[inline]
1920    pub fn get_f32(&self) -> u32 {
1921        unsafe { u32::from_le(self.f32) }
1922    }
1923
1924    /// Gets the WebAssembly `f64` value
1925    #[inline]
1926    pub fn get_f64(&self) -> u64 {
1927        unsafe { u64::from_le(self.f64) }
1928    }
1929
1930    /// Gets the WebAssembly `v128` value
1931    #[inline]
1932    pub fn get_v128(&self) -> u128 {
1933        unsafe { u128::from_le_bytes(self.v128) }
1934    }
1935
1936    /// Gets the WebAssembly `funcref` value
1937    #[inline]
1938    pub fn get_funcref(&self) -> *mut c_void {
1939        let addr = unsafe { usize::from_le(self.funcref.addr()) };
1940        core::ptr::with_exposed_provenance_mut(addr)
1941    }
1942
1943    /// Gets the WebAssembly `externref` value
1944    #[inline]
1945    pub fn get_externref(&self) -> u32 {
1946        let externref = u32::from_le(unsafe { self.externref });
1947        assert!(cfg!(feature = "gc") || externref == 0);
1948        externref
1949    }
1950
1951    /// Gets the WebAssembly `anyref` value
1952    #[inline]
1953    pub fn get_anyref(&self) -> u32 {
1954        let anyref = u32::from_le(unsafe { self.anyref });
1955        assert!(cfg!(feature = "gc") || anyref == 0);
1956        anyref
1957    }
1958
1959    /// Gets the WebAssembly `exnref` value
1960    #[inline]
1961    pub fn get_exnref(&self) -> u32 {
1962        let exnref = u32::from_le(unsafe { self.exnref });
1963        assert!(cfg!(feature = "gc") || exnref == 0);
1964        exnref
1965    }
1966
1967    /// Get the inner `VMGcRef`.
1968    pub(crate) fn get_vmgcref(&self) -> Option<crate::vm::VMGcRef> {
1969        debug_assert_eq!(self.get_anyref(), self.get_exnref());
1970        debug_assert_eq!(self.get_anyref(), self.get_externref());
1971        VMGcRef::from_raw_u32(self.get_anyref())
1972    }
1973}
1974
1975/// An "opaque" version of `VMContext` which must be explicitly casted to a
1976/// target context.
1977///
1978/// This context is used to represent that contexts specified in
1979/// `VMFuncRef` can have any type and don't have an implicit
1980/// structure. Neither wasmtime nor cranelift-generated code can rely on the
1981/// structure of an opaque context in general and only the code which configured
1982/// the context is able to rely on a particular structure. This is because the
1983/// context pointer configured for `VMFuncRef` is guaranteed to be
1984/// the first parameter passed.
1985///
1986/// Note that Wasmtime currently has a layout where all contexts that are casted
1987/// to an opaque context start with a 32-bit "magic" which can be used in debug
1988/// mode to debug-assert that the casts here are correct and have at least a
1989/// little protection against incorrect casts.
1990pub struct VMOpaqueContext {
1991    pub(crate) magic: u32,
1992    _marker: marker::PhantomPinned,
1993}
1994
1995impl VMOpaqueContext {
1996    /// Helper function to clearly indicate that casts are desired.
1997    #[inline]
1998    pub fn from_vmcontext(ptr: NonNull<VMContext>) -> NonNull<VMOpaqueContext> {
1999        ptr.cast()
2000    }
2001
2002    /// Helper function to clearly indicate that casts are desired.
2003    #[inline]
2004    pub fn from_vm_array_call_host_func_context(
2005        ptr: NonNull<VMArrayCallHostFuncContext>,
2006    ) -> NonNull<VMOpaqueContext> {
2007        ptr.cast()
2008    }
2009}