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