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::{VMContinuationStack, VMStackChain, VMStackState};
11use core::cell::UnsafeCell;
12use core::ffi::c_void;
13use core::fmt;
14use core::marker::{self, PhantomPinned};
15use core::mem::{self, MaybeUninit};
16#[cfg(feature = "gc-null")]
17use core::num::NonZeroU32;
18use core::ops::Range;
19use core::ptr::{self, NonNull};
20use core::sync::atomic::{AtomicUsize, Ordering};
21use wasmtime_environ::{
22    BuiltinFunctionIndex, DefinedGlobalIndex, DefinedMemoryIndex, DefinedTableIndex,
23    DefinedTagIndex, NUM_COMPONENT_CONTEXT_SLOTS, VMCONTEXT_MAGIC, VMSharedTypeIndex,
24};
25
26/// A function pointer that exposes the array calling convention.
27///
28/// Regardless of the underlying Wasm function type, all functions using the
29/// array calling convention have the same Rust signature.
30///
31/// Arguments:
32///
33/// * Callee `vmctx` for the function itself.
34///
35/// * Caller's `vmctx` (so that host functions can access the linear memory of
36///   their Wasm callers).
37///
38/// * A pointer to a buffer of `ValRaw`s where both arguments are passed into
39///   this function, and where results are returned from this function.
40///
41/// * The capacity of the `ValRaw` buffer. Must always be at least
42///   `max(len(wasm_params), len(wasm_results))`.
43///
44/// Return value:
45///
46/// * `true` if this call succeeded.
47/// * `false` if this call failed and a trap was recorded in TLS.
48pub type VMArrayCallNative = unsafe extern "C" fn(
49    NonNull<VMOpaqueContext>,
50    NonNull<VMContext>,
51    NonNull<ValRaw>,
52    usize,
53) -> bool;
54
55/// An opaque function pointer which might be `VMArrayCallNative` or it might be
56/// pulley bytecode. Requires external knowledge to determine what kind of
57/// function pointer this is.
58#[repr(transparent)]
59pub struct VMArrayCallFunction(VMFunctionBody);
60
61/// A function pointer that exposes the Wasm calling convention.
62///
63/// In practice, different Wasm function types end up mapping to different Rust
64/// function types, so this isn't simply a type alias the way that
65/// `VMArrayCallFunction` is. However, the exact details of the calling
66/// convention are left to the Wasm compiler (e.g. Cranelift or Winch). Runtime
67/// code never does anything with these function pointers except shuffle them
68/// around and pass them back to Wasm.
69#[repr(transparent)]
70pub struct VMWasmCallFunction(VMFunctionBody);
71
72// SAFETY: `VMFunctionImport` is generated with `#[repr(C)]` and only contains
73// `VmSafe` fields.
74unsafe impl VmSafe for VMFunctionImport {}
75
76impl VMFunctionImport {
77    /// Convert `&VMFunctionImport` into `&VMFuncRef`.
78    pub fn as_func_ref(&self) -> &VMFuncRef {
79        // Safety: `VMFunctionImport` and `VMFuncRef` have the same
80        // representation.
81        unsafe { Self::as_non_null_func_ref(NonNull::from(self)).as_ref() }
82    }
83
84    /// Convert `NonNull<VMFunctionImport>` into `NonNull<VMFuncRef>`.
85    pub fn as_non_null_func_ref(p: NonNull<VMFunctionImport>) -> NonNull<VMFuncRef> {
86        p.cast()
87    }
88
89    /// Convert `*mut VMFunctionImport` into `*mut VMFuncRef`.
90    pub fn as_func_ref_ptr(p: *mut VMFunctionImport) -> *mut VMFuncRef {
91        p.cast()
92    }
93}
94
95#[cfg(test)]
96mod test_vmfunction_import {
97    use super::{VMFuncRef, VMFunctionImport};
98    use core::mem::offset_of;
99    use std::mem::size_of;
100
101    #[test]
102    fn vmfunction_import_and_vmfunc_ref_have_same_layout() {
103        assert_eq!(size_of::<VMFunctionImport>(), size_of::<VMFuncRef>());
104        assert_eq!(
105            offset_of!(VMFunctionImport, array_call),
106            offset_of!(VMFuncRef, array_call),
107        );
108        assert_eq!(
109            offset_of!(VMFunctionImport, wasm_call),
110            offset_of!(VMFuncRef, wasm_call),
111        );
112        assert_eq!(
113            offset_of!(VMFunctionImport, type_index),
114            offset_of!(VMFuncRef, type_index),
115        );
116        assert_eq!(
117            offset_of!(VMFunctionImport, vmctx),
118            offset_of!(VMFuncRef, vmctx),
119        );
120    }
121}
122
123/// A placeholder byte-sized type which is just used to provide some amount of type
124/// safety when dealing with pointers to JIT-compiled function bodies. Note that it's
125/// deliberately not Copy, as we shouldn't be carelessly copying function body bytes
126/// around.
127#[repr(C)]
128pub struct VMFunctionBody(u8);
129
130// SAFETY: this structure is never read and is safe to pass to jit code.
131unsafe impl VmSafe for VMFunctionBody {}
132
133#[cfg(test)]
134mod test_vmfunction_body {
135    use super::VMFunctionBody;
136    use std::mem::size_of;
137
138    #[test]
139    fn check_vmfunction_body_offsets() {
140        assert_eq!(size_of::<VMFunctionBody>(), 1);
141    }
142}
143
144// SAFETY: `VMTableImport` is generated with `#[repr(C)]` and only contains
145// `VmSafe` fields.
146unsafe impl VmSafe for VMTableImport {}
147
148#[cfg(test)]
149mod test_vmtable {
150    use wasmtime_environ::component::{Component, VMComponentOffsets};
151    use wasmtime_environ::{HostPtr, Module, PtrSize, StaticModuleIndex, VMOffsets};
152
153    #[test]
154    fn ensure_sizes_match() {
155        // Because we use `VMTableImport` for recording tables used by components, we
156        // want to make sure that the size calculations between `VMOffsets` and
157        // `VMComponentOffsets` stay the same.
158        let module = Module::new(StaticModuleIndex::from_u32(0));
159        let vm_offsets = VMOffsets::new(HostPtr, &module);
160        let component = Component::default();
161        let vm_component_offsets = VMComponentOffsets::new(HostPtr, &component);
162        assert_eq!(
163            vm_offsets.ptr.vm_table_import().size(),
164            vm_component_offsets.ptr.vm_table_import().size()
165        );
166    }
167}
168
169// SAFETY: `VMMemoryImport` is generated with `#[repr(C)]` and only contains
170// `VmSafe` fields.
171unsafe impl VmSafe for VMMemoryImport {}
172
173// SAFETY: `VMGlobalImport` is generated with `#[repr(C)]` and only contains
174// `VmSafe` fields.
175unsafe impl VmSafe for VMGlobalImport {}
176
177/// The kinds of globals that Wasmtime has.
178#[derive(Debug, Copy, Clone)]
179#[repr(C, u32)]
180pub enum VMGlobalKind {
181    /// Host globals, stored in a `StoreOpaque`.
182    Host(DefinedGlobalIndex),
183    /// Instance globals, stored in `VMContext`s
184    Instance(DefinedGlobalIndex),
185    /// Flags for a component instance, stored in `VMComponentContext`.
186    #[cfg(feature = "component-model")]
187    ComponentFlags(wasmtime_environ::component::RuntimeComponentInstanceIndex),
188}
189
190// SAFETY: the above enum is repr(C) and stores nothing else
191unsafe impl VmSafe for VMGlobalKind {}
192
193// SAFETY: `VMTagImport` is generated with `#[repr(C)]` and only contains
194// `VmSafe` fields.
195unsafe impl VmSafe for VMTagImport {}
196
197/// Define the runtime definitions of the shared `VM*` types.
198#[cfg_attr(
199    not(test),
200    allow(
201        unused_macro_rules,
202        reason = "the `@test` arms are only expanded inside the `#[cfg(test)]` \
203                  layout-test module"
204    )
205)]
206macro_rules! define_vm_types {
207    (@test [ $($cfg:tt)* ] $Name:ident $snake:ident [ $($fname:ident)* ]) => {
208        $($cfg)*
209        #[test]
210        fn $snake() {
211            use super::$Name;
212
213            let host = HostPtr;
214            let offsets = host.$snake();
215
216            let expected = usize::from(offsets.size());
217            let actual = size_of::<$Name>();
218            assert_eq!(
219                expected,
220                actual,
221                "size of {} failed: {expected} (expected) != {actual} (actual)",
222                stringify!($Name),
223            );
224
225            let expected = usize::from(offsets.align());
226            let actual = align_of::<$Name>();
227            assert_eq!(
228                expected,
229                actual,
230                "alignment of {} failed: {expected} (expected) != {actual} (actual)",
231                stringify!($Name),
232            );
233
234            $(
235                let expected = usize::from(offsets.$fname());
236                let actual = offset_of!($Name, $fname);
237                assert_eq!(
238                    expected,
239                    actual,
240                    "offset of {}::{} failed: {expected} (expected) != {actual} (actual)",
241                    stringify!($Name),
242                    stringify!($fname),
243                );
244            )*
245        }
246    };
247
248    ( $(
249        $(#[doc = $sdoc:literal])*
250        $(#[cfg($($scfg:tt)*)])?
251        $(#[derive($($d:ident),*)])?
252        #[repr($($repr:tt)*)]
253        #[snake_name = $snake:ident]
254        $svis:vis struct $Name:ident {
255            $(
256                $(#[doc = $fdoc:literal])*
257                $(#[aggregate])?
258                $(#[indexed])?
259                $(#[readonly])?
260                $(#[can_move])?
261                // Unlike the offsets and alias-region consumers, this one only
262                // ever re-emits a field's type verbatim, so it can capture the
263                // whole type as one fragment instead of taking it apart.
264                $fvis:vis $fname:ident : $fty:ty ,
265            )*
266        }
267    )* ) => {
268        $(
269            $(#[doc = $sdoc])*
270            $(#[cfg($($scfg)*)])?
271            $(#[derive($($d),*)])?
272            #[repr($($repr)*)]
273            $svis struct $Name {
274                $(
275                    $(#[doc = $fdoc])*
276                    $fvis $fname: $fty,
277                )*
278            }
279        )*
280
281        #[cfg(test)]
282        mod test_vm_type_layouts {
283            use core::mem::{align_of, offset_of, size_of};
284            use wasmtime_environ::{HostPtr, PtrSize};
285
286            $(
287                define_vm_types!(
288                    @test
289                    [ $(#[cfg($($scfg)*)])? ]
290                    $Name $snake
291                    [ $($fname)* ]
292                );
293            )*
294        }
295    };
296}
297wasmtime_environ::for_each_vm_type!(define_vm_types);
298
299// SAFETY: `VMMemoryDefinition` is generated with `#[repr(C)]` and each field
300// individually implements `VmSafe`, which satisfies the requirements of this
301// trait.
302unsafe impl VmSafe for VMMemoryDefinition {}
303
304impl VMMemoryDefinition {
305    /// Return the current length (in bytes) of the [`VMMemoryDefinition`] by
306    /// performing a relaxed load; do not use this function for situations in
307    /// which a precise length is needed. Owned memories (i.e., non-shared) will
308    /// always return a precise result (since no concurrent modification is
309    /// possible) but shared memories may see an imprecise value--a
310    /// `current_length` potentially smaller than what some other thread
311    /// observes. Since Wasm memory only grows, this under-estimation may be
312    /// acceptable in certain cases.
313    #[inline]
314    pub fn current_length(&self) -> usize {
315        self.current_length.load(Ordering::Relaxed)
316    }
317
318    /// Return a copy of the [`VMMemoryDefinition`] using the relaxed value of
319    /// `current_length`; see [`VMMemoryDefinition::current_length()`].
320    #[inline]
321    pub unsafe fn load(ptr: *mut Self) -> Self {
322        let other = unsafe { &*ptr };
323        VMMemoryDefinition {
324            base: other.base,
325            current_length: other.current_length().into(),
326        }
327    }
328}
329
330// SAFETY: `VMTableDefinition` is generated with `#[repr(C)]` and only contains
331// `VmSafe` fields.
332unsafe impl VmSafe for VMTableDefinition {}
333
334// SAFETY: `VMGlobalDefinition` is generated with `#[repr(C)]` and only contains
335// `VmSafe` fields.
336unsafe impl VmSafe for VMGlobalDefinition {}
337
338#[cfg(test)]
339mod test_vmglobal_definition {
340    use super::VMGlobalDefinition;
341    use std::mem::{align_of, size_of};
342    use wasmtime_environ::{HostPtr, Module, StaticModuleIndex, VMOffsets};
343
344    #[test]
345    fn check_vmglobal_definition_alignment() {
346        assert!(align_of::<VMGlobalDefinition>() >= align_of::<i32>());
347        assert!(align_of::<VMGlobalDefinition>() >= align_of::<i64>());
348        assert!(align_of::<VMGlobalDefinition>() >= align_of::<f32>());
349        assert!(align_of::<VMGlobalDefinition>() >= align_of::<f64>());
350        assert!(align_of::<VMGlobalDefinition>() >= align_of::<[u8; 16]>());
351        assert!(align_of::<VMGlobalDefinition>() >= align_of::<[f32; 4]>());
352        assert!(align_of::<VMGlobalDefinition>() >= align_of::<[f64; 2]>());
353    }
354
355    #[test]
356    fn check_vmglobal_begins_aligned() {
357        let module = Module::new(StaticModuleIndex::from_u32(0));
358        let offsets = VMOffsets::new(HostPtr, &module);
359        assert_eq!(offsets.globals().begin() % 16, 0);
360    }
361
362    #[test]
363    #[cfg(feature = "gc")]
364    fn check_vmglobal_can_contain_gc_ref() {
365        assert!(size_of::<crate::runtime::vm::VMGcRef>() <= size_of::<VMGlobalDefinition>());
366    }
367}
368
369impl VMGlobalDefinition {
370    /// Construct a `VMGlobalDefinition`.
371    pub fn new() -> Self {
372        Self { storage: [0; 16] }
373    }
374
375    /// Return a reference to the value as an i32.
376    pub unsafe fn as_i32(&self) -> &i32 {
377        unsafe { &*(self.storage.as_ref().as_ptr().cast::<i32>()) }
378    }
379
380    /// Return a mutable reference to the value as an i32.
381    pub unsafe fn as_i32_mut(&mut self) -> &mut i32 {
382        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<i32>()) }
383    }
384
385    /// Return a reference to the value as a u32.
386    pub unsafe fn as_u32(&self) -> &u32 {
387        unsafe { &*(self.storage.as_ref().as_ptr().cast::<u32>()) }
388    }
389
390    /// Return a mutable reference to the value as an u32.
391    pub unsafe fn as_u32_mut(&mut self) -> &mut u32 {
392        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<u32>()) }
393    }
394
395    /// Return a reference to the value as an i64.
396    pub unsafe fn as_i64(&self) -> &i64 {
397        unsafe { &*(self.storage.as_ref().as_ptr().cast::<i64>()) }
398    }
399
400    /// Return a mutable reference to the value as an i64.
401    pub unsafe fn as_i64_mut(&mut self) -> &mut i64 {
402        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<i64>()) }
403    }
404
405    /// Return a reference to the value as an u64.
406    pub unsafe fn as_u64(&self) -> &u64 {
407        unsafe { &*(self.storage.as_ref().as_ptr().cast::<u64>()) }
408    }
409
410    /// Return a mutable reference to the value as an u64.
411    pub unsafe fn as_u64_mut(&mut self) -> &mut u64 {
412        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<u64>()) }
413    }
414
415    /// Return a reference to the value as an f32.
416    pub unsafe fn as_f32(&self) -> &f32 {
417        unsafe { &*(self.storage.as_ref().as_ptr().cast::<f32>()) }
418    }
419
420    /// Return a mutable reference to the value as an f32.
421    pub unsafe fn as_f32_mut(&mut self) -> &mut f32 {
422        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<f32>()) }
423    }
424
425    /// Return a reference to the value as f32 bits.
426    pub unsafe fn as_f32_bits(&self) -> &u32 {
427        unsafe { &*(self.storage.as_ref().as_ptr().cast::<u32>()) }
428    }
429
430    /// Return a mutable reference to the value as f32 bits.
431    pub unsafe fn as_f32_bits_mut(&mut self) -> &mut u32 {
432        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<u32>()) }
433    }
434
435    /// Return a reference to the value as an f64.
436    pub unsafe fn as_f64(&self) -> &f64 {
437        unsafe { &*(self.storage.as_ref().as_ptr().cast::<f64>()) }
438    }
439
440    /// Return a mutable reference to the value as an f64.
441    pub unsafe fn as_f64_mut(&mut self) -> &mut f64 {
442        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<f64>()) }
443    }
444
445    /// Return a reference to the value as f64 bits.
446    pub unsafe fn as_f64_bits(&self) -> &u64 {
447        unsafe { &*(self.storage.as_ref().as_ptr().cast::<u64>()) }
448    }
449
450    /// Return a mutable reference to the value as f64 bits.
451    pub unsafe fn as_f64_bits_mut(&mut self) -> &mut u64 {
452        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<u64>()) }
453    }
454
455    /// Gets the underlying 128-bit vector value.
456    //
457    // Note that vectors are stored in little-endian format while other types
458    // are stored in native-endian format.
459    pub unsafe fn get_u128(&self) -> u128 {
460        unsafe { u128::from_le(*(self.storage.as_ref().as_ptr().cast::<u128>())) }
461    }
462
463    /// Sets the 128-bit vector values.
464    //
465    // Note that vectors are stored in little-endian format while other types
466    // are stored in native-endian format.
467    pub unsafe fn set_u128(&mut self, val: u128) {
468        unsafe {
469            *self.storage.as_mut().as_mut_ptr().cast::<u128>() = val.to_le();
470        }
471    }
472
473    /// Return a reference to the value as u128 bits.
474    pub unsafe fn as_u128_bits(&self) -> &[u8; 16] {
475        unsafe { &*(self.storage.as_ref().as_ptr().cast::<[u8; 16]>()) }
476    }
477
478    /// Return a mutable reference to the value as u128 bits.
479    pub unsafe fn as_u128_bits_mut(&mut self) -> &mut [u8; 16] {
480        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<[u8; 16]>()) }
481    }
482
483    /// Return a reference to the global value as a borrowed GC reference.
484    pub unsafe fn as_gc_ref(&self) -> Option<&VMGcRef> {
485        let raw_ptr = self.storage.as_ref().as_ptr().cast::<Option<VMGcRef>>();
486        let ret = unsafe { (*raw_ptr).as_ref() };
487        assert!(cfg!(feature = "gc") || ret.is_none());
488        ret
489    }
490
491    /// Return a reference to the global value as a borrowed GC reference.
492    pub unsafe fn as_gc_ref_mut(&mut self) -> Option<&mut VMGcRef> {
493        let raw_ptr = self.storage.as_mut().as_mut_ptr().cast::<Option<VMGcRef>>();
494        let ret = unsafe { (*raw_ptr).as_mut() };
495        assert!(cfg!(feature = "gc") || ret.is_none());
496        ret
497    }
498
499    /// Initialize a global to the given GC reference.
500    pub unsafe fn init_gc_ref(
501        &mut self,
502        store: &mut StoreOpaque,
503        gc_ref: Option<&VMGcRef>,
504    ) -> Result<()> {
505        let dest = unsafe {
506            &mut *(self
507                .storage
508                .as_mut()
509                .as_mut_ptr()
510                .cast::<MaybeUninit<Option<VMGcRef>>>())
511        };
512
513        store.init_gc_ref(dest, gc_ref)
514    }
515
516    /// Write a GC reference into this global value.
517    pub unsafe fn write_gc_ref(
518        &mut self,
519        store: &mut StoreOpaque,
520        gc_ref: Option<&VMGcRef>,
521    ) -> Result<()> {
522        let dest = unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<Option<VMGcRef>>()) };
523        store.write_gc_ref(dest, gc_ref)
524    }
525
526    /// Return a reference to the value as a `VMFuncRef`.
527    pub unsafe fn as_func_ref(&self) -> *mut VMFuncRef {
528        unsafe { *(self.storage.as_ref().as_ptr().cast::<*mut VMFuncRef>()) }
529    }
530
531    /// Return a mutable reference to the value as a `VMFuncRef`.
532    pub unsafe fn as_func_ref_mut(&mut self) -> &mut *mut VMFuncRef {
533        unsafe { &mut *(self.storage.as_mut().as_mut_ptr().cast::<*mut VMFuncRef>()) }
534    }
535}
536
537#[cfg(test)]
538mod test_vmshared_type_index {
539    use super::VMSharedTypeIndex;
540    use std::mem::size_of;
541    use wasmtime_environ::{HostPtr, Module, StaticModuleIndex, VMOffsets};
542
543    #[test]
544    fn check_vmshared_type_index() {
545        let module = Module::new(StaticModuleIndex::from_u32(0));
546        let offsets = VMOffsets::new(HostPtr, &module);
547        assert_eq!(
548            size_of::<VMSharedTypeIndex>(),
549            usize::from(offsets.size_of_vmshared_type_index())
550        );
551    }
552}
553
554impl VMTagDefinition {
555    pub fn new(type_index: VMSharedTypeIndex) -> Self {
556        Self { type_index }
557    }
558}
559
560// SAFETY: `VMTagDefinition` is generated with `#[repr(C)]` and only contains
561// `VmSafe` fields.
562unsafe impl VmSafe for VMTagDefinition {}
563
564#[cfg(test)]
565mod test_vmtag_definition {
566    use wasmtime_environ::{HostPtr, Module, StaticModuleIndex, VMOffsets};
567
568    #[test]
569    fn check_vmtag_begins_aligned() {
570        let module = Module::new(StaticModuleIndex::from_u32(0));
571        let offsets = VMOffsets::new(HostPtr, &module);
572        assert_eq!(offsets.tags().begin() % 16, 0);
573    }
574}
575
576// SAFETY: `VMFuncRef` is generated with `#[repr(C)]` and only contains
577// `VmSafe` fields.
578unsafe impl VmSafe for VMFuncRef {}
579
580impl VMFuncRef {
581    /// Invokes the `array_call` field of this `VMFuncRef` with the supplied
582    /// arguments.
583    ///
584    /// This will invoke the function pointer in the `array_call` field with:
585    ///
586    /// * the `callee` vmctx as `self.vmctx`
587    /// * the `caller` as `caller` specified here
588    /// * the args pointer as `args_and_results`
589    /// * the args length as `args_and_results`
590    ///
591    /// The `args_and_results` area must be large enough to both load all
592    /// arguments from and store all results to.
593    ///
594    /// Returns whether a trap was recorded in TLS for raising.
595    ///
596    /// # Unsafety
597    ///
598    /// This method is unsafe because it can be called with any pointers. They
599    /// must all be valid for this wasm function call to proceed. For example
600    /// the `caller` must be valid machine code if `pulley` is `None` or it must
601    /// be valid bytecode if `pulley` is `Some`. Additionally `args_and_results`
602    /// must be large enough to handle all the arguments/results for this call.
603    ///
604    /// Note that the unsafety invariants to maintain here are not currently
605    /// exhaustively documented.
606    #[inline]
607    pub unsafe fn array_call(
608        me: NonNull<VMFuncRef>,
609        pulley: Option<InterpreterRef<'_>>,
610        caller: NonNull<VMContext>,
611        args_and_results: NonNull<[ValRaw]>,
612    ) -> bool {
613        match pulley {
614            Some(vm) => unsafe { Self::array_call_interpreted(me, vm, caller, args_and_results) },
615            None => unsafe { Self::array_call_native(me, caller, args_and_results) },
616        }
617    }
618
619    unsafe fn array_call_interpreted(
620        me: NonNull<VMFuncRef>,
621        vm: InterpreterRef<'_>,
622        caller: NonNull<VMContext>,
623        args_and_results: NonNull<[ValRaw]>,
624    ) -> bool {
625        // If `caller` is actually a `VMArrayCallHostFuncContext` then skip the
626        // interpreter, even though it's available, as `array_call` will be
627        // native code.
628        unsafe {
629            if me.as_ref().vmctx.as_non_null().as_ref().magic
630                == wasmtime_environ::VM_ARRAY_CALL_HOST_FUNC_MAGIC
631            {
632                return Self::array_call_native(me, caller, args_and_results);
633            }
634            vm.call(
635                me.as_ref().array_call.as_non_null().cast(),
636                me.as_ref().vmctx.as_non_null(),
637                caller,
638                args_and_results,
639            )
640        }
641    }
642
643    #[inline]
644    unsafe fn array_call_native(
645        me: NonNull<VMFuncRef>,
646        caller: NonNull<VMContext>,
647        args_and_results: NonNull<[ValRaw]>,
648    ) -> bool {
649        unsafe {
650            union GetNativePointer {
651                native: VMArrayCallNative,
652                ptr: NonNull<VMArrayCallFunction>,
653            }
654            let native = GetNativePointer {
655                ptr: me.as_ref().array_call.as_non_null(),
656            }
657            .native;
658            native(
659                me.as_ref().vmctx.as_non_null(),
660                caller,
661                args_and_results.cast(),
662                args_and_results.len(),
663            )
664        }
665    }
666
667    pub(crate) fn as_vm_function_import(&self) -> Option<&VMFunctionImport> {
668        if self.wasm_call.is_some() {
669            // Safety: `VMFuncRef` and `VMFunctionImport` have the same layout
670            // and `wasm_call` is non-null.
671            Some(unsafe { NonNull::from(self).cast::<VMFunctionImport>().as_ref() })
672        } else {
673            None
674        }
675    }
676}
677
678macro_rules! define_builtin_array {
679    (
680        $(
681            $( #[$attr:meta] )*
682            $name:ident( $( $pname:ident: $param:ident ),* ) $( -> $result:ident )?;
683        )*
684    ) => {
685        /// An array that stores addresses of builtin functions. We translate code
686        /// to use indirect calls. This way, we don't have to patch the code.
687        #[repr(C)]
688        #[allow(improper_ctypes_definitions, reason = "__m128i known not FFI-safe")]
689        pub struct VMBuiltinFunctionsArray {
690            $(
691                $name: unsafe extern "C" fn(
692                    $(define_builtin_array!(@ty $param)),*
693                ) $( -> define_builtin_array!(@ty $result))?,
694            )*
695        }
696
697        impl VMBuiltinFunctionsArray {
698            pub const INIT: VMBuiltinFunctionsArray = VMBuiltinFunctionsArray {
699                $(
700                    $name: crate::runtime::vm::libcalls::raw::$name,
701                )*
702            };
703
704            /// Helper to call `expose_provenance()` on all contained pointers.
705            ///
706            /// This is required to be called at least once before entering wasm
707            /// to inform the compiler that these function pointers may all be
708            /// loaded/stored and used on the "other end" to reacquire
709            /// provenance in Pulley. Pulley models hostcalls with a host
710            /// pointer as the first parameter that's a function pointer under
711            /// the hood, and this call ensures that the use of the function
712            /// pointer is considered valid.
713            pub fn expose_provenance(&self) -> NonNull<Self>{
714                $(
715                    (self.$name as *mut u8).expose_provenance();
716                )*
717                NonNull::from(self)
718            }
719        }
720    };
721
722    (@ty u32) => (u32);
723    (@ty u64) => (u64);
724    (@ty f32) => (f32);
725    (@ty f64) => (f64);
726    (@ty u8) => (u8);
727    (@ty i8x16) => (i8x16);
728    (@ty f32x4) => (f32x4);
729    (@ty f64x2) => (f64x2);
730    (@ty bool) => (bool);
731    (@ty pointer) => (*mut u8);
732    (@ty size) => (usize);
733    (@ty vmctx) => (NonNull<VMContext>);
734}
735
736// SAFETY: the above structure is repr(C) and only contains `VmSafe` fields.
737unsafe impl VmSafe for VMBuiltinFunctionsArray {}
738
739wasmtime_environ::foreach_builtin_function!(define_builtin_array);
740
741const _: () = {
742    assert!(
743        mem::size_of::<VMBuiltinFunctionsArray>()
744            == mem::size_of::<usize>() * (BuiltinFunctionIndex::len() as usize)
745    )
746};
747
748impl VMStoreContext {
749    /// From the current saved trampoline FP, get the FP of the last
750    /// Wasm frame. If the current saved trampoline FP is null, return
751    /// null.
752    ///
753    /// We store only the trampoline FP, because (i) we need the
754    /// trampoline FP, so we know the size (bottom) of the last Wasm
755    /// frame; and (ii) the last Wasm frame, just above the trampoline
756    /// frame, can be recovered via the FP chain.
757    ///
758    /// # Safety
759    ///
760    /// This function requires that the `last_wasm_exit_trampoline_fp`
761    /// field either points to an active trampoline frame or is a null
762    /// pointer.
763    pub(crate) unsafe fn last_wasm_exit_fp(&self) -> usize {
764        // SAFETY: the unsafe cell is safe to load (no other threads
765        // will be writing our store when we have control), and the
766        // helper function's safety condition is the same as ours.
767        unsafe {
768            let trampoline_fp = *self.last_wasm_exit_trampoline_fp.get();
769            Self::wasm_exit_fp_from_trampoline_fp(trampoline_fp)
770        }
771    }
772
773    /// From any saved trampoline FP, get the FP of the last Wasm
774    /// frame. If the given trampoline FP is null, return null.
775    ///
776    /// This differs from `last_wasm_exit_fp()` above in that it
777    /// allows accessing activations further up the stack as well,
778    /// e.g. via `CallThreadState::old_state`.
779    ///
780    /// # Safety
781    ///
782    /// This function requires that the provided FP value is valid,
783    /// and points to an active trampoline frame, or is null.
784    ///
785    /// This function depends on the invariant that on all supported
786    /// architectures, we store the previous FP value under the
787    /// current FP. This is a property of our ABI that we control and
788    /// ensure.
789    pub(crate) unsafe fn wasm_exit_fp_from_trampoline_fp(trampoline_fp: usize) -> usize {
790        if trampoline_fp != 0 {
791            // SAFETY: We require that trampoline_fp points to a valid
792            // frame, which will (by definition) contain an old FP value
793            // that we can load.
794            unsafe { *(trampoline_fp as *const usize) }
795        } else {
796            0
797        }
798    }
799
800    #[cfg(feature = "component-model-async")]
801    pub(crate) fn component_context_mut(&mut self) -> &mut [u32; NUM_COMPONENT_CONTEXT_SLOTS] {
802        self.component_context.get_mut()
803    }
804
805    #[cfg(feature = "component-model-async")]
806    pub(crate) fn current_thread_mut(&mut self) -> &mut VMLazyThread {
807        self.current_thread.get_mut()
808    }
809}
810
811// The `VMStoreContext` type is a pod-type with no destructor, and we don't
812// access any fields from other threads, so add in these trait impls which are
813// otherwise not available due to the `fuel_consumed` and `epoch_deadline`
814// variables in `VMStoreContext`.
815unsafe impl Send for VMStoreContext {}
816unsafe impl Sync for VMStoreContext {}
817
818// SAFETY: the above structure is repr(C) and only contains `VmSafe` fields.
819unsafe impl VmSafe for VMStoreContext {}
820
821impl Default for VMStoreContext {
822    fn default() -> VMStoreContext {
823        VMStoreContext {
824            fuel_consumed: UnsafeCell::new(0),
825            epoch_deadline: UnsafeCell::new(0),
826            execution_version: 0,
827            stack_limit: UnsafeCell::new(usize::MAX),
828            gc_heap: UnsafeCell::new(VMMemoryDefinition {
829                base: NonNull::dangling().into(),
830                current_length: AtomicUsize::new(0),
831            }),
832            last_wasm_exit_trampoline_fp: UnsafeCell::new(0),
833            last_wasm_exit_pc: UnsafeCell::new(0),
834            last_wasm_entry_fp: UnsafeCell::new(0),
835            last_wasm_entry_sp: UnsafeCell::new(0),
836            last_wasm_entry_trap_handler: UnsafeCell::new(0),
837            stack_chain: UnsafeCell::new(VMStackChain::Absent),
838            async_guard_range: ptr::null_mut()..ptr::null_mut(),
839            store_data: VmPtr::dangling(),
840            component_context: UnsafeCell::new([0; NUM_COMPONENT_CONTEXT_SLOTS]),
841            current_thread: UnsafeCell::new(VMLazyThread::none()),
842        }
843    }
844}
845
846#[cfg(test)]
847mod test_vmstore_context {
848    use super::{VMMemoryDefinition, VMStoreContext};
849    use core::mem::offset_of;
850    use wasmtime_environ::{HostPtr, Module, PtrSize, StaticModuleIndex, VMOffsets};
851
852    /// Check the `VMStoreContext` offsets that `for_each_vm_type!` does *not*
853    /// generate: the offsets reaching into the inlined `gc_heap`.
854    ///
855    /// Every field offset, plus the size and alignment of the type, is already
856    /// checked by the generated `test_vm_type_layouts::vm_store_context`.
857    #[test]
858    fn derived_field_offsets() {
859        let module = Module::new(StaticModuleIndex::from_u32(0));
860        let offsets = VMOffsets::new(HostPtr, &module);
861        assert_eq!(
862            offset_of!(VMStoreContext, gc_heap) + offset_of!(VMMemoryDefinition, base),
863            usize::from(offsets.ptr.vm_store_context().gc_heap_base())
864        );
865        assert_eq!(
866            offset_of!(VMStoreContext, gc_heap) + offset_of!(VMMemoryDefinition, current_length),
867            usize::from(offsets.ptr.vm_store_context().gc_heap_current_length())
868        );
869    }
870}
871
872#[cfg(test)]
873mod test_vm_cont_ref {
874    use wasmtime_environ::PtrSize;
875
876    /// Check the one `VMContRef` property that `for_each_vm_type!` does *not*
877    /// generate an assertion for: that `revision` lands at an eight-aligned
878    /// offset for every target pointer width, not just the host's.
879    ///
880    /// Some 32-bit platforms need it to be 8-byte aligned and some don't, so we
881    /// make sure that it always is, without padding to get there.
882    ///
883    /// Every field offset, plus the size and alignment of the type, is already
884    /// checked by the generated `test_vm_type_layouts::vm_cont_ref`.
885    #[test]
886    fn revision_is_eight_aligned() {
887        assert_eq!(4u8.vm_cont_ref().revision() % 8, 0);
888        assert_eq!(8u8.vm_cont_ref().revision() % 8, 0);
889    }
890}
891
892impl VMLazyThread {
893    const _ASSERT_SIZE: () = assert!(
894        core::mem::size_of::<VMLazyThread>() == core::mem::size_of::<*mut VMDeferredThread>()
895    );
896    const _ASSERT_ALIGN: () = assert!(
897        core::mem::align_of::<VMLazyThread>() == core::mem::align_of::<*mut VMDeferredThread>()
898    );
899
900    const FORCED: VmPtr<VMDeferredThread> = VmPtr::<u8>::dangling().cast();
901
902    /// There is no current thread.
903    pub const fn none() -> Self {
904        Self { thread: None }
905    }
906
907    /// A lazy thread that has already been promoted.
908    pub const fn forced() -> Self {
909        Self {
910            thread: Some(Self::FORCED),
911        }
912    }
913
914    /// A deferred thread referencing the given on-stack [`VMDeferredThread`].
915    pub fn deferred(ptr: NonNull<VMDeferredThread>) -> Self {
916        debug_assert_eq!(ptr.addr().get() & Self::FORCED.addr().get(), 0);
917        Self {
918            thread: Some(ptr.into()),
919        }
920    }
921
922    /// Returns `true` if there is no current thread.
923    pub fn is_none(self) -> bool {
924        self.thread.is_none()
925    }
926
927    /// Returns `true` if a deferred thread has been forced/promoted.
928    pub fn is_forced(self) -> bool {
929        self.thread.is_some_and(|p| p == Self::FORCED)
930    }
931
932    /// Returns `true` if this is a deferred thread (i.e. neither `None` nor
933    /// forced).
934    pub fn is_deferred(self) -> bool {
935        self.thread.is_some_and(|p| p != Self::FORCED)
936    }
937
938    /// Returns the deferred [`VMDeferredThread`] pointer if this is a deferred
939    /// thread.
940    pub fn as_deferred(self) -> Option<VmPtr<VMDeferredThread>> {
941        self.thread
942            .and_then(|p| if p == Self::FORCED { None } else { Some(p) })
943    }
944}
945
946#[cfg(test)]
947mod test_vmlazy_thread {
948    use super::*;
949
950    #[test]
951    fn vmlazy_thread_forced() {
952        assert_eq!(
953            VMLazyThread::forced().thread.unwrap().addr().get(),
954            usize::try_from(wasmtime_environ::VM_LAZY_THREAD_FORCED).unwrap()
955        );
956    }
957}
958
959/// The VM "context", which is pointed to by the `vmctx` arg in Cranelift.
960/// This has information about globals, memories, tables, and other runtime
961/// state associated with the current instance.
962///
963/// The struct here is empty, as the sizes of these fields are dynamic, and
964/// we can't describe them in Rust's type system. Sufficient memory is
965/// allocated at runtime.
966#[derive(Debug)]
967#[repr(C, align(16))] // align 16 since globals are aligned to that and contained inside
968pub struct VMContext {
969    _magic: u32,
970}
971
972impl VMContext {
973    /// Helper function to cast between context types using a debug assertion to
974    /// protect against some mistakes.
975    #[inline]
976    pub unsafe fn from_opaque(opaque: NonNull<VMOpaqueContext>) -> NonNull<VMContext> {
977        // Note that in general the offset of the "magic" field is stored in
978        // `VMContext::magic`. Given though that this is a sanity check
979        // about converting this pointer to another type we ideally don't want
980        // to read the offset from potentially corrupt memory. Instead it would
981        // be better to catch errors here as soon as possible.
982        //
983        // To accomplish this the `VMContext` structure is laid out with the
984        // magic field at a statically known offset (here it's 0 for now). This
985        // static offset is asserted in `VMOffsets::from` and needs to be kept
986        // in sync with this line for this debug assertion to work.
987        //
988        // Also note that this magic is only ever invalid in the presence of
989        // bugs, meaning we don't actually read the magic and act differently
990        // at runtime depending what it is, so this is a debug assertion as
991        // opposed to a regular assertion.
992        unsafe {
993            debug_assert_eq!(opaque.as_ref().magic, VMCONTEXT_MAGIC);
994        }
995        opaque.cast()
996    }
997}
998
999/// A "raw" and unsafe representation of a WebAssembly value.
1000///
1001/// This is provided for use with the `Func::new_unchecked` and
1002/// `Func::call_unchecked` APIs. In general it's unlikely you should be using
1003/// this from Rust, rather using APIs like `Func::wrap` and `TypedFunc::call`.
1004///
1005/// This is notably an "unsafe" way to work with `Val` and it's recommended to
1006/// instead use `Val` where possible. An important note about this union is that
1007/// fields are all stored in little-endian format, regardless of the endianness
1008/// of the host system.
1009#[repr(C)]
1010#[derive(Copy, Clone)]
1011pub union ValRaw {
1012    /// A WebAssembly `i32` value.
1013    ///
1014    /// Note that the payload here is a Rust `i32` but the WebAssembly `i32`
1015    /// type does not assign an interpretation of the upper bit as either signed
1016    /// or unsigned. The Rust type `i32` is simply chosen for convenience.
1017    ///
1018    /// This value is always stored in a little-endian format.
1019    i32: i32,
1020
1021    /// A WebAssembly `i64` value.
1022    ///
1023    /// Note that the payload here is a Rust `i64` but the WebAssembly `i64`
1024    /// type does not assign an interpretation of the upper bit as either signed
1025    /// or unsigned. The Rust type `i64` is simply chosen for convenience.
1026    ///
1027    /// This value is always stored in a little-endian format.
1028    i64: i64,
1029
1030    /// A WebAssembly `f32` value.
1031    ///
1032    /// Note that the payload here is a Rust `u32`. This is to allow passing any
1033    /// representation of NaN into WebAssembly without risk of changing NaN
1034    /// payload bits as its gets passed around the system. Otherwise though this
1035    /// `u32` value is the return value of `f32::to_bits` in Rust.
1036    ///
1037    /// This value is always stored in a little-endian format.
1038    f32: u32,
1039
1040    /// A WebAssembly `f64` value.
1041    ///
1042    /// Note that the payload here is a Rust `u64`. This is to allow passing any
1043    /// representation of NaN into WebAssembly without risk of changing NaN
1044    /// payload bits as its gets passed around the system. Otherwise though this
1045    /// `u64` value is the return value of `f64::to_bits` in Rust.
1046    ///
1047    /// This value is always stored in a little-endian format.
1048    f64: u64,
1049
1050    /// A WebAssembly `v128` value.
1051    ///
1052    /// The payload here is a Rust `[u8; 16]` which has the same number of bits
1053    /// but note that `v128` in WebAssembly is often considered a vector type
1054    /// such as `i32x4` or `f64x2`. This means that the actual interpretation
1055    /// of the underlying bits is left up to the instructions which consume
1056    /// this value.
1057    ///
1058    /// This value is always stored in a little-endian format.
1059    v128: [u8; 16],
1060
1061    /// A WebAssembly `funcref` value (or one of its subtypes).
1062    ///
1063    /// The payload here is a pointer which is runtime-defined. This is one of
1064    /// the main points of unsafety about the `ValRaw` type as the validity of
1065    /// the pointer here is not easily verified and must be preserved by
1066    /// carefully calling the correct functions throughout the runtime.
1067    ///
1068    /// This value is always stored in a little-endian format.
1069    funcref: *mut c_void,
1070
1071    /// A WebAssembly `externref` value (or one of its subtypes).
1072    ///
1073    /// The payload here is a compressed pointer value which is
1074    /// runtime-defined. This is one of the main points of unsafety about the
1075    /// `ValRaw` type as the validity of the pointer here is not easily verified
1076    /// and must be preserved by carefully calling the correct functions
1077    /// throughout the runtime.
1078    ///
1079    /// This value is always stored in a little-endian format.
1080    externref: u32,
1081
1082    /// A WebAssembly `anyref` value (or one of its subtypes).
1083    ///
1084    /// The payload here is a compressed pointer value which is
1085    /// runtime-defined. This is one of the main points of unsafety about the
1086    /// `ValRaw` type as the validity of the pointer here is not easily verified
1087    /// and must be preserved by carefully calling the correct functions
1088    /// throughout the runtime.
1089    ///
1090    /// This value is always stored in a little-endian format.
1091    anyref: u32,
1092
1093    /// A WebAssembly `exnref` value (or one of its subtypes).
1094    ///
1095    /// The payload here is a compressed pointer value which is
1096    /// runtime-defined. This is one of the main points of unsafety about the
1097    /// `ValRaw` type as the validity of the pointer here is not easily verified
1098    /// and must be preserved by carefully calling the correct functions
1099    /// throughout the runtime.
1100    ///
1101    /// This value is always stored in a little-endian format.
1102    exnref: u32,
1103}
1104
1105// The `ValRaw` type is matched as `wasmtime_val_raw_t` in the C API so these
1106// are some simple assertions about the shape of the type which are additionally
1107// matched in C.
1108const _: () = {
1109    assert!(mem::size_of::<ValRaw>() == 16);
1110    assert!(mem::align_of::<ValRaw>() == mem::align_of::<u64>());
1111};
1112
1113// This type is just a bag-of-bits so it's up to the caller to figure out how
1114// to safely deal with threading concerns and safely access interior bits.
1115unsafe impl Send for ValRaw {}
1116unsafe impl Sync for ValRaw {}
1117
1118impl fmt::Debug for ValRaw {
1119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1120        struct Hex<T>(T);
1121        impl<T: fmt::LowerHex> fmt::Debug for Hex<T> {
1122            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1123                let bytes = mem::size_of::<T>();
1124                let hex_digits_per_byte = 2;
1125                let hex_digits = bytes * hex_digits_per_byte;
1126                write!(f, "0x{:0width$x}", self.0, width = hex_digits)
1127            }
1128        }
1129
1130        unsafe {
1131            f.debug_struct("ValRaw")
1132                .field("i32", &Hex(self.i32))
1133                .field("i64", &Hex(self.i64))
1134                .field("f32", &Hex(self.f32))
1135                .field("f64", &Hex(self.f64))
1136                .field("v128", &Hex(u128::from_le_bytes(self.v128)))
1137                .field("funcref", &self.funcref)
1138                .field("externref", &Hex(self.externref))
1139                .field("anyref", &Hex(self.anyref))
1140                .field("exnref", &Hex(self.exnref))
1141                .finish()
1142        }
1143    }
1144}
1145
1146impl ValRaw {
1147    /// Create a null reference that is compatible with any of
1148    /// `{any,extern,func,exn}ref`.
1149    pub fn null() -> ValRaw {
1150        unsafe {
1151            let raw = mem::MaybeUninit::<Self>::zeroed().assume_init();
1152            debug_assert_eq!(raw.get_anyref(), 0);
1153            debug_assert_eq!(raw.get_exnref(), 0);
1154            debug_assert_eq!(raw.get_externref(), 0);
1155            debug_assert_eq!(raw.get_funcref(), ptr::null_mut());
1156            raw
1157        }
1158    }
1159
1160    /// Creates a WebAssembly `i32` value
1161    #[inline]
1162    pub fn i32(i: i32) -> ValRaw {
1163        // Note that this is intentionally not setting the `i32` field, instead
1164        // setting the `i64` field with a zero-extended version of `i`. For more
1165        // information on this see the comments on `Lower for Result` in the
1166        // `wasmtime` crate. Otherwise though all `ValRaw` constructors are
1167        // otherwise constrained to guarantee that the initial 64-bits are
1168        // always initialized.
1169        ValRaw::u64(i.cast_unsigned().into())
1170    }
1171
1172    /// Creates a WebAssembly `i64` value
1173    #[inline]
1174    pub fn i64(i: i64) -> ValRaw {
1175        ValRaw { i64: i.to_le() }
1176    }
1177
1178    /// Creates a WebAssembly `i32` value
1179    #[inline]
1180    pub fn u32(i: u32) -> ValRaw {
1181        // See comments in `ValRaw::i32` for why this is setting the upper
1182        // 32-bits as well.
1183        ValRaw::u64(i.into())
1184    }
1185
1186    /// Creates a WebAssembly `i64` value
1187    #[inline]
1188    pub fn u64(i: u64) -> ValRaw {
1189        ValRaw::i64(i as i64)
1190    }
1191
1192    /// Creates a WebAssembly `f32` value
1193    #[inline]
1194    pub fn f32(i: u32) -> ValRaw {
1195        // See comments in `ValRaw::i32` for why this is setting the upper
1196        // 32-bits as well.
1197        ValRaw::u64(i.into())
1198    }
1199
1200    /// Creates a WebAssembly `f64` value
1201    #[inline]
1202    pub fn f64(i: u64) -> ValRaw {
1203        ValRaw { f64: i.to_le() }
1204    }
1205
1206    /// Creates a WebAssembly `v128` value
1207    #[inline]
1208    pub fn v128(i: u128) -> ValRaw {
1209        ValRaw {
1210            v128: i.to_le_bytes(),
1211        }
1212    }
1213
1214    /// Creates a WebAssembly `funcref` value
1215    #[inline]
1216    pub fn funcref(i: *mut c_void) -> ValRaw {
1217        ValRaw {
1218            funcref: i.map_addr(|i| i.to_le()),
1219        }
1220    }
1221
1222    /// Creates a WebAssembly `externref` value
1223    #[inline]
1224    pub fn externref(e: u32) -> ValRaw {
1225        assert!(cfg!(feature = "gc") || e == 0);
1226        ValRaw {
1227            externref: e.to_le(),
1228        }
1229    }
1230
1231    /// Creates a WebAssembly `anyref` value
1232    #[inline]
1233    pub fn anyref(r: u32) -> ValRaw {
1234        assert!(cfg!(feature = "gc") || r == 0);
1235        ValRaw { anyref: r.to_le() }
1236    }
1237
1238    /// Creates a WebAssembly `exnref` value
1239    #[inline]
1240    pub fn exnref(r: u32) -> ValRaw {
1241        assert!(cfg!(feature = "gc") || r == 0);
1242        ValRaw { exnref: r.to_le() }
1243    }
1244
1245    #[inline]
1246    pub(crate) fn vmgcref(r: Option<VMGcRef>) -> ValRaw {
1247        let raw = r.map_or(0, |r| r.as_raw_u32());
1248
1249        // NB: All `VMGcRef`-based `ValRaw`s are the same.
1250        debug_assert_eq!(raw, ValRaw::anyref(raw).get_exnref());
1251        debug_assert_eq!(raw, ValRaw::exnref(raw).get_externref());
1252        debug_assert_eq!(raw, ValRaw::externref(raw).get_anyref());
1253
1254        ValRaw::anyref(raw)
1255    }
1256
1257    /// Gets the WebAssembly `i32` value
1258    #[inline]
1259    pub fn get_i32(&self) -> i32 {
1260        unsafe { i32::from_le(self.i32) }
1261    }
1262
1263    /// Gets the WebAssembly `i64` value
1264    #[inline]
1265    pub fn get_i64(&self) -> i64 {
1266        unsafe { i64::from_le(self.i64) }
1267    }
1268
1269    /// Gets the WebAssembly `i32` value
1270    #[inline]
1271    pub fn get_u32(&self) -> u32 {
1272        self.get_i32().cast_unsigned()
1273    }
1274
1275    /// Gets the WebAssembly `i64` value
1276    #[inline]
1277    pub fn get_u64(&self) -> u64 {
1278        self.get_i64().cast_unsigned()
1279    }
1280
1281    /// Gets the WebAssembly `f32` value
1282    #[inline]
1283    pub fn get_f32(&self) -> u32 {
1284        unsafe { u32::from_le(self.f32) }
1285    }
1286
1287    /// Gets the WebAssembly `f64` value
1288    #[inline]
1289    pub fn get_f64(&self) -> u64 {
1290        unsafe { u64::from_le(self.f64) }
1291    }
1292
1293    /// Gets the WebAssembly `v128` value
1294    #[inline]
1295    pub fn get_v128(&self) -> u128 {
1296        unsafe { u128::from_le_bytes(self.v128) }
1297    }
1298
1299    /// Gets the WebAssembly `funcref` value
1300    #[inline]
1301    pub fn get_funcref(&self) -> *mut c_void {
1302        let addr = unsafe { usize::from_le(self.funcref.addr()) };
1303        core::ptr::with_exposed_provenance_mut(addr)
1304    }
1305
1306    /// Gets the WebAssembly `externref` value
1307    #[inline]
1308    pub fn get_externref(&self) -> u32 {
1309        let externref = u32::from_le(unsafe { self.externref });
1310        assert!(cfg!(feature = "gc") || externref == 0);
1311        externref
1312    }
1313
1314    /// Gets the WebAssembly `anyref` value
1315    #[inline]
1316    pub fn get_anyref(&self) -> u32 {
1317        let anyref = u32::from_le(unsafe { self.anyref });
1318        assert!(cfg!(feature = "gc") || anyref == 0);
1319        anyref
1320    }
1321
1322    /// Gets the WebAssembly `exnref` value
1323    #[inline]
1324    pub fn get_exnref(&self) -> u32 {
1325        let exnref = u32::from_le(unsafe { self.exnref });
1326        assert!(cfg!(feature = "gc") || exnref == 0);
1327        exnref
1328    }
1329
1330    /// Get the inner `VMGcRef`.
1331    pub(crate) fn get_vmgcref(&self) -> Option<crate::vm::VMGcRef> {
1332        debug_assert_eq!(self.get_anyref(), self.get_exnref());
1333        debug_assert_eq!(self.get_anyref(), self.get_externref());
1334        VMGcRef::from_raw_u32(self.get_anyref())
1335    }
1336}
1337
1338/// An "opaque" version of `VMContext` which must be explicitly casted to a
1339/// target context.
1340///
1341/// This context is used to represent that contexts specified in
1342/// `VMFuncRef` can have any type and don't have an implicit
1343/// structure. Neither wasmtime nor cranelift-generated code can rely on the
1344/// structure of an opaque context in general and only the code which configured
1345/// the context is able to rely on a particular structure. This is because the
1346/// context pointer configured for `VMFuncRef` is guaranteed to be
1347/// the first parameter passed.
1348///
1349/// Note that Wasmtime currently has a layout where all contexts that are casted
1350/// to an opaque context start with a 32-bit "magic" which can be used in debug
1351/// mode to debug-assert that the casts here are correct and have at least a
1352/// little protection against incorrect casts.
1353pub struct VMOpaqueContext {
1354    pub(crate) magic: u32,
1355    _marker: marker::PhantomPinned,
1356}
1357
1358impl VMOpaqueContext {
1359    /// Helper function to clearly indicate that casts are desired.
1360    #[inline]
1361    pub fn from_vmcontext(ptr: NonNull<VMContext>) -> NonNull<VMOpaqueContext> {
1362        ptr.cast()
1363    }
1364
1365    /// Helper function to clearly indicate that casts are desired.
1366    #[inline]
1367    pub fn from_vm_array_call_host_func_context(
1368        ptr: NonNull<VMArrayCallHostFuncContext>,
1369    ) -> NonNull<VMOpaqueContext> {
1370        ptr.cast()
1371    }
1372}