Skip to main content

wasmtime/runtime/vm/
libcalls.rs

1//! Runtime library calls.
2//!
3//! Note that Wasm compilers may sometimes perform these inline rather than
4//! calling them, particularly when CPUs have special instructions which compute
5//! them directly.
6//!
7//! These functions are called by compiled Wasm code, and therefore must take
8//! certain care about some things:
9//!
10//! * They must only contain basic, raw i32/i64/f32/f64/pointer parameters that
11//!   are safe to pass across the system ABI.
12//!
13//! * If any nested function propagates an `Err(trap)` out to the library
14//!   function frame, we need to raise it. This involves some nasty and quite
15//!   unsafe code under the covers! Notably, after raising the trap, drops
16//!   **will not** be run for local variables! This can lead to things like
17//!   leaking `InstanceHandle`s which leads to never deallocating JIT code,
18//!   instances, and modules if we are not careful!
19//!
20//! * The libcall must be entered via a Wasm-to-libcall trampoline that saves
21//!   the last Wasm FP and PC for stack walking purposes. (For more details, see
22//!   `crates/wasmtime/src/runtime/vm/backtrace.rs`.)
23//!
24//! To make it easier to correctly handle all these things, **all** libcalls
25//! must be defined via the `libcall!` helper macro! See its doc comments below
26//! for an example, or just look at the rest of the file.
27//!
28//! ## Dealing with `externref`s
29//!
30//! When receiving a raw `*mut u8` that is actually a `VMExternRef` reference,
31//! convert it into a proper `VMExternRef` with `VMExternRef::clone_from_raw` as
32//! soon as apossible. Any GC before raw pointer is converted into a reference
33//! can potentially collect the referenced object, which could lead to use after
34//! free.
35//!
36//! Avoid this by eagerly converting into a proper `VMExternRef`! (Unfortunately
37//! there is no macro to help us automatically get this correct, so stay
38//! vigilant!)
39//!
40//! ```ignore
41//! pub unsafe extern "C" my_libcall_takes_ref(raw_extern_ref: *mut u8) {
42//!     // Before `clone_from_raw`, `raw_extern_ref` is potentially unrooted,
43//!     // and doing GC here could lead to use after free!
44//!
45//!     let my_extern_ref = if raw_extern_ref.is_null() {
46//!         None
47//!     } else {
48//!         Some(VMExternRef::clone_from_raw(raw_extern_ref))
49//!     };
50//!
51//!     // Now that we did `clone_from_raw`, it is safe to do a GC (or do
52//!     // anything else that might transitively GC, like call back into
53//!     // Wasm!)
54//! }
55//! ```
56
57use crate::bail_bug;
58use crate::prelude::*;
59use crate::runtime::store::{Asyncness, InstanceId, StoreOpaque};
60#[cfg(feature = "gc")]
61use crate::runtime::vm::VMGcRef;
62#[cfg(all(feature = "gc", feature = "stack-switching"))]
63use crate::runtime::vm::provenance::VmPtr;
64use crate::runtime::vm::{self, HostResultHasUnwindSentinel, VMStore, f32x4, f64x2, i8x16};
65#[cfg(all(feature = "gc", feature = "stack-switching"))]
66use crate::vm::vmcontext::VMRawContObj;
67use core::convert::Infallible;
68#[cfg(feature = "threads")]
69use core::time::Duration;
70use wasmtime_core::math::WasmFloat;
71use wasmtime_environ::{
72    CompiledTrap, DefinedMemoryIndex, DefinedTableIndex, PassiveElemIndex, RrCallKind, TableIndex,
73    Trap,
74};
75#[cfg(feature = "wmemcheck")]
76use wasmtime_wmemcheck::AccessError::{
77    DoubleMalloc, InvalidFree, InvalidRead, InvalidWrite, OutOfBounds,
78};
79
80/// Raw functions which are actually called from compiled code.
81///
82/// Invocation of a builtin currently looks like:
83///
84/// * A wasm function calls a cranelift-compiled trampoline that's generated
85///   once-per-builtin.
86/// * The cranelift-compiled trampoline performs any necessary actions to exit
87///   wasm, such as dealing with fp/pc/etc.
88/// * The cranelift-compiled trampoline loads a function pointer from an array
89///   stored in `VMContext` That function pointer is defined in this module.
90/// * This module runs, handling things like `catch_unwind` and `Result` and
91///   such.
92/// * This module delegates to the outer module (this file) which has the actual
93///   implementation.
94///
95/// For more information on converting from host-defined values to Cranelift ABI
96/// values see the `catch_unwind_and_record_trap` function.
97pub mod raw {
98    use crate::runtime::vm::{Instance, VMContext, f32x4, f64x2, i8x16};
99    use core::ptr::NonNull;
100
101    macro_rules! libcall {
102        (
103            $(
104                $( #[cfg($attr:meta)] )?
105                $name:ident( vmctx: vmctx $(, $pname:ident: $param:ident )* ) $(-> $result:ident)?;
106            )*
107        ) => {
108            $(
109                // This is the direct entrypoint from the compiled module which
110                // still has the raw signature.
111                //
112                // This will delegate to the outer module to the actual
113                // implementation and automatically perform `catch_unwind` along
114                // with conversion of the return value in the face of traps.
115                #[allow(improper_ctypes_definitions, reason = "__m128i known not FFI-safe")]
116                #[allow(unused_variables, reason = "macro-generated")]
117                #[allow(unreachable_code, reason = "some types uninhabited on some platforms")]
118                pub unsafe extern "C" fn $name(
119                    vmctx: NonNull<VMContext>,
120                    $( $pname : libcall!(@ty $param), )*
121                ) $(-> libcall!(@ty $result))? {
122                    $(#[cfg($attr)])?
123                    unsafe {
124                        Instance::enter_host_from_wasm(vmctx, |store, instance| {
125                            super::$name(store, instance, $($pname),*)
126                        })
127                    }
128                    $(
129                        #[cfg(not($attr))]
130                        {
131                            let _ = vmctx;
132                            unreachable!();
133                        }
134                    )?
135                }
136
137                // This works around a `rustc` bug where compiling with LTO
138                // will sometimes strip out some of these symbols resulting
139                // in a linking failure.
140                #[allow(improper_ctypes_definitions, reason = "__m128i known not FFI-safe")]
141                const _: () = {
142                    #[used]
143                    static I_AM_USED: unsafe extern "C" fn(
144                        NonNull<VMContext>,
145                        $( $pname : libcall!(@ty $param), )*
146                    ) $( -> libcall!(@ty $result))? = $name;
147                };
148            )*
149        };
150
151        (@ty u32) => (u32);
152        (@ty u64) => (u64);
153        (@ty f32) => (f32);
154        (@ty f64) => (f64);
155        (@ty u8) => (u8);
156        (@ty i8x16) => (i8x16);
157        (@ty f32x4) => (f32x4);
158        (@ty f64x2) => (f64x2);
159        (@ty bool) => (bool);
160        (@ty pointer) => (*mut u8);
161        (@ty size) => (usize);
162    }
163
164    wasmtime_environ::foreach_builtin_function!(libcall);
165}
166
167/// Uses the `$store` provided to invoke the async closure `$f` and block on the
168/// result.
169///
170/// This will internally multiplex on `$store.with_blocking(...)` vs simply
171/// asserting the closure is ready depending on whether a store's
172/// `can_block` flag is set or not.
173///
174/// FIXME: ideally this would be a function, not a macro. If this is a function
175/// though it would require placing a bound on the async closure $f where the
176/// returned future is itself `Send`. That's not possible in Rust right now,
177/// unfortunately.
178///
179/// As a workaround this takes advantage of the fact that we can assume that the
180/// compiler can infer that the future returned by `$f` is indeed `Send` so long
181/// as we don't try to name the type or place it behind a generic. In the future
182/// when we can bound the return future of async functions with `Send` this
183/// macro should be replaced with an equivalent function.
184macro_rules! block_on {
185    ($store:expr, $f:expr) => {{
186        let store: &mut StoreOpaque = $store;
187        let closure = assert_async_fn_closure($f);
188
189        if store.can_block() {
190            // If the store can block then that means it's on a fiber. We can
191            // forward to `block_on` and everything should be fine and dandy.
192            #[cfg(feature = "async")]
193            {
194                store.with_blocking(|store, cx| cx.block_on(closure(store, Asyncness::Yes)))
195            }
196            #[cfg(not(feature = "async"))]
197            {
198                unreachable!()
199            }
200        } else {
201            // If the store cannot block it's not on a fiber. That means that we get
202            // at most one poll of `closure(store)` here. In the typical case
203            // what this means is that nothing async is configured in the store
204            // and one poll should be all we need. There are niche cases where
205            // one poll is not sufficient though, for example:
206            //
207            // * Store is created.
208            // * Wasm is called.
209            // * Wasm calls host.
210            // * Host configures an async resource limiter, returns back to
211            //   wasm.
212            // * Wasm grows memory.
213            // * Limiter wants to block asynchronously.
214            //
215            // Technically there's nothing wrong with this, but it means that
216            // we're in wasm and one poll is not enough here. Given the niche
217            // nature of this scenario and how it's not really expected to work
218            // this translates failures in `closure` to a trap. This trap is
219            // only expected to show up in niche-ish scenarios, not for actual
220            // blocking work, as that would otherwise be too surprising.
221            vm::one_poll(closure(store, Asyncness::No)).ok_or_else(|| {
222                crate::format_err!(
223                    "
224
225A synchronously called wasm function invoked an async-defined libcall which
226failed to complete synchronously and is thus raising a trap. It's expected
227that this indicates that the store was configured to do async things after the
228original synchronous entrypoint to wasm was called. That's generally not
229supported in Wasmtime and async entrypoint should be used instead. If you're
230seeing this message in error please file an issue on Wasmtime.
231
232"
233                )
234            })
235        }
236    }};
237}
238
239fn assert_async_fn_closure<F, R>(f: F) -> F
240where
241    F: AsyncFnOnce(&mut StoreOpaque, Asyncness) -> R,
242{
243    f
244}
245
246fn memory_grow(
247    store: &mut dyn VMStore,
248    instance: InstanceId,
249    delta: u64,
250    memory_index: u32,
251) -> Result<Option<AllocationSize>> {
252    let memory_index = DefinedMemoryIndex::from_u32(memory_index);
253    let (mut limiter, store) = store.resource_limiter_and_store_opaque();
254    let limiter = limiter.as_mut();
255    block_on!(store, async |store, _| {
256        let instance = store.instance_mut(instance);
257        let module = instance.env_module();
258        let page_size_log2 = module.memories[module.memory_index(memory_index)].page_size_log2;
259
260        let result = instance
261            .memory_grow(limiter, memory_index, delta)
262            .await?
263            .map(|size_in_bytes| AllocationSize(size_in_bytes >> page_size_log2));
264
265        // Whether growth fails depends on the host, so replay must reproduce
266        // the failure, but the trace does not represent it yet.
267        if result.is_none() {
268            store.rr.poison("failed guest memory growth");
269        }
270
271        Ok(result)
272    })?
273}
274
275/// A helper structure to represent the return value of a memory or table growth
276/// call.
277///
278/// This represents a byte or element-based count of the size of an item on the
279/// host. For example a memory is how many bytes large the memory is, or a table
280/// is how many elements large it is. It's assumed that the value here is never
281/// -1 or -2 as that would mean the entire host address space is allocated which
282/// is not possible.
283struct AllocationSize(usize);
284
285/// Special implementation for growth-related libcalls.
286///
287/// Here the optional return value means:
288///
289/// * `Some(val)` - the growth succeeded and the previous size of the item was
290///   `val`.
291/// * `None` - the growth failed.
292///
293/// The failure case returns -1 (or `usize::MAX` as an unsigned integer) and the
294/// successful case returns the `val` itself. Note that -2 (`usize::MAX - 1`
295/// when unsigned) is unwind as a sentinel to indicate an unwind as no valid
296/// allocation can be that large.
297unsafe impl HostResultHasUnwindSentinel for Option<AllocationSize> {
298    type Abi = *mut u8;
299    const SENTINEL: *mut u8 = (usize::MAX - 1) as *mut u8;
300
301    fn into_abi(self) -> *mut u8 {
302        match self {
303            Some(size) => {
304                debug_assert!(size.0 < (usize::MAX - 1));
305                size.0 as *mut u8
306            }
307            None => usize::MAX as *mut u8,
308        }
309    }
310}
311
312/// Implementation of `table.grow`.
313unsafe fn table_grow(
314    store: &mut dyn VMStore,
315    instance: InstanceId,
316    defined_table_index: u32,
317    delta: u64,
318) -> Result<Option<AllocationSize>> {
319    let defined_table_index = DefinedTableIndex::from_u32(defined_table_index);
320    let (mut limiter, store) = store.resource_limiter_and_store_opaque();
321    let limiter = limiter.as_mut();
322    block_on!(store, async |store, _| unsafe {
323        let result = store
324            .instance_mut(instance)
325            .defined_table_grow(defined_table_index, limiter, delta)
326            .await?
327            .map(AllocationSize);
328        // Whether growth fails depends on the host, so replay must reproduce
329        // the failure, but the trace does not represent it yet.
330        if result.is_none() {
331            store.rr.poison("failed guest table growth");
332        }
333        Ok(result)
334    })?
335}
336
337fn passive_elem_segment_len(
338    store: &mut dyn VMStore,
339    instance: InstanceId,
340    elem_index: u32,
341) -> usize {
342    let elem_index = PassiveElemIndex::from_u32(elem_index);
343    store
344        .instance_mut(instance)
345        .passive_element_segment(elem_index)
346        .len()
347}
348
349fn passive_elem_segment_base(
350    store: &mut dyn VMStore,
351    instance: InstanceId,
352    elem_index: u32,
353) -> *mut u8 {
354    let elem_index = PassiveElemIndex::from_u32(elem_index);
355    store
356        .instance_mut(instance)
357        .passive_element_segment(elem_index)
358        .as_mut_ptr()
359        .cast()
360}
361
362// Implementation of `elem.drop`.
363fn passive_elem_segment_drop(
364    store: &mut dyn VMStore,
365    instance: InstanceId,
366    elem_index: u32,
367) -> Result<()> {
368    let elem_index = PassiveElemIndex::from_u32(elem_index);
369    let (gc_store, instance) = store.optional_gc_store_and_instance_mut(instance);
370    instance.passive_elem_drop(gc_store, elem_index)?;
371    Ok(())
372}
373
374// Implementation of `memory.copy`.
375#[inline]
376unsafe fn memory_copy(
377    _store: &mut dyn VMStore,
378    _instance: InstanceId,
379    dst: *mut u8,
380    src: *mut u8,
381    len: usize,
382) {
383    let src = src.cast_const();
384    // FIXME(#4203): this is known to not be sound in the presence of shared
385    // memories.
386    unsafe { src.copy_to(dst, len) }
387}
388
389#[inline]
390unsafe fn memory_fill(
391    _store: &mut dyn VMStore,
392    _instance: InstanceId,
393    dst: *mut u8,
394    val: u32,
395    len: usize,
396) {
397    // FIXME(#4203): this is known to not be sound in the presence of shared
398    // memories.
399    unsafe {
400        #[expect(
401            clippy::cast_possible_truncation,
402            reason = "the libcall intentionally takes the raw 32-bit value, \
403                      and semantically that's intentionally truncated"
404        )]
405        dst.write_bytes(val as u8, len);
406    }
407}
408
409// Returns a table entry after lazily initializing it.
410fn table_get_lazy_init_func_ref(
411    store: &mut dyn VMStore,
412    instance: InstanceId,
413    table_index: u32,
414    index: u64,
415) -> *mut u8 {
416    let table_index = TableIndex::from_u32(table_index);
417    let (instance, registry) = store.instance_and_module_registry_mut(instance);
418    let table = instance.get_table_with_lazy_init(registry, table_index, core::iter::once(index));
419    let elem = table
420        .get_func(index)
421        .expect("table access already bounds-checked");
422
423    match elem {
424        Some(ptr) => ptr.as_ptr().cast(),
425        None => core::ptr::null_mut(),
426    }
427}
428
429/// Drop a GC reference.
430#[cfg(feature = "gc-drc")]
431#[inline]
432fn drop_gc_ref(store: &mut dyn VMStore, _instance: InstanceId, gc_ref: u32) {
433    log::trace!("libcalls::drop_gc_ref({gc_ref:#x})");
434    let gc_ref = VMGcRef::from_raw_u32(gc_ref).expect("non-null VMGcRef");
435    store.unwrap_gc_store_mut().drop_gc_ref(gc_ref);
436}
437
438/// Force a DRC GC cycle.
439#[cfg(feature = "gc-drc")]
440#[inline]
441fn force_gc(store: &mut dyn VMStore, _instance: InstanceId) -> Result<()> {
442    let store = &mut **store;
443    block_on!(store, async |store, asyncness| {
444        store.gc(None, None, None, asyncness).await?;
445        Ok::<(), Error>(())
446    })??;
447    Ok(())
448}
449
450/// Grow the GC heap.
451#[cfg(feature = "gc-null")]
452#[inline]
453fn grow_gc_heap(store: &mut dyn VMStore, _instance: InstanceId, bytes_needed: u64) -> Result<()> {
454    let orig_len = u64::try_from(
455        store
456            .require_gc_store()?
457            .gc_heap
458            .get()
459            .vmmemory()
460            .current_length(),
461    )
462    .unwrap();
463
464    let (mut limiter, store) = store.resource_limiter_and_store_opaque();
465    block_on!(store, async |store, asyncness| {
466        // We error below if there's still not enough space; swallow
467        // any growth failures here.
468        let _ = store
469            .grow_gc_heap(limiter.as_mut(), bytes_needed, asyncness)
470            .await;
471    })?;
472
473    // JIT code relies on the memory having grown by `bytes_needed` bytes if
474    // this libcall returns successfully, so trap if we didn't grow that much.
475    let new_len = u64::try_from(
476        store
477            .require_gc_store()?
478            .gc_heap
479            .get()
480            .vmmemory()
481            .current_length(),
482    )
483    .unwrap();
484    if orig_len
485        .checked_add(bytes_needed)
486        .is_none_or(|expected_len| new_len < expected_len)
487    {
488        return Err(crate::Trap::AllocationTooLarge.into());
489    }
490
491    Ok(())
492}
493
494/// Allocate a raw, unininitialized GC object for Wasm code.
495///
496/// The Wasm code is responsible for initializing the object.
497#[cfg(any(feature = "gc-drc", feature = "gc-copying"))]
498#[inline]
499fn gc_alloc_raw(
500    store: &mut dyn VMStore,
501    _instance: InstanceId,
502    kind_and_reserved: u32,
503    shared_type_index: u32,
504    size: u32,
505    align: u32,
506) -> Result<core::num::NonZeroU32> {
507    use crate::vm::VMGcHeader;
508    use core::alloc::Layout;
509    use wasmtime_environ::{VMGcKind, VMSharedTypeIndex};
510
511    // NB: unlike most `VMGcKind`s, this one is a constant baked into compiled
512    // code by our own code generator, not a value out of the GC heap.
513    let Some(kind) = VMGcKind::from_high_bits_of_u32(kind_and_reserved) else {
514        bail_bug!("compiler emitted an invalid `VMGcKind`")
515    };
516    log::trace!("gc_alloc_raw(kind={kind:?}, size={size}, align={align})");
517
518    let shared_type_index = VMSharedTypeIndex::from_u32(shared_type_index);
519    let mut header = VMGcHeader::from_kind_and_index(kind, shared_type_index);
520    header.set_reserved_u26(kind_and_reserved & VMGcKind::UNUSED_MASK);
521
522    let size = usize::try_from(size).unwrap();
523    let align = usize::try_from(align).unwrap();
524    assert!(align.is_power_of_two());
525    let layout = Layout::from_size_align(size, align).map_err(|e| {
526        let err = Error::from(crate::Trap::AllocationTooLarge);
527        err.context(e)
528    })?;
529
530    // Fast path: when the GC store already exists, try to allocate directly to
531    // skip the async/fiber machinery.
532    let opaque = &mut **store;
533    if let Some(gc_store) = opaque.try_gc_store_mut() {
534        if let Ok(gc_ref) = gc_store.alloc_raw(header, layout)? {
535            let raw = gc_store.expose_gc_ref_to_wasm(gc_ref)?;
536            return Ok(raw);
537        }
538    }
539
540    let (mut limiter, store) = store.resource_limiter_and_store_opaque();
541    block_on!(store, async |store, asyncness| {
542        let gc_ref = store
543            .retry_after_gc_async(limiter.as_mut(), (), asyncness, |store, ()| {
544                store
545                    .unwrap_gc_store_mut()
546                    .alloc_raw(header, layout)?
547                    .map_err(|bytes_needed| crate::GcHeapOutOfMemory::new((), bytes_needed).into())
548            })
549            .await?;
550
551        store.unwrap_gc_store_mut().expose_gc_ref_to_wasm(gc_ref)
552    })?
553}
554
555// Intern a `funcref` into the GC heap, returning its `FuncRefTableId`.
556//
557// This libcall may not GC.
558#[cfg(feature = "gc")]
559#[inline]
560unsafe fn intern_func_ref_for_gc_heap(
561    store: &mut dyn VMStore,
562    _instance: InstanceId,
563    func_ref: *mut u8,
564) -> Result<u32> {
565    use crate::runtime::vm::vmcontext::VMFuncRef;
566    use crate::{store::AutoAssertNoGc, vm::SendSyncPtr};
567    use core::ptr::NonNull;
568
569    let mut store = AutoAssertNoGc::new(&mut **store);
570
571    let func_ref = func_ref.cast::<VMFuncRef>();
572    let func_ref = NonNull::new(func_ref).map(SendSyncPtr::new);
573
574    let func_ref_id = unsafe {
575        store
576            .require_gc_store_mut()?
577            .func_ref_table
578            .intern(func_ref)
579    };
580    Ok(func_ref_id.into_raw())
581}
582
583// Get the raw `VMFuncRef` pointer associated with a `FuncRefTableId` from an
584// earlier `intern_func_ref_for_gc_heap` call.
585//
586// This libcall may not GC.
587#[cfg(feature = "gc")]
588#[inline]
589fn get_interned_func_ref(
590    store: &mut dyn VMStore,
591    instance: InstanceId,
592    func_ref_id: u32,
593    module_interned_type_index: u32,
594) -> Result<*mut u8> {
595    use super::FuncRefTableId;
596    use crate::store::AutoAssertNoGc;
597    use wasmtime_environ::{ModuleInternedTypeIndex, packed_option::ReservedValue};
598
599    let store = AutoAssertNoGc::new(&mut **store);
600
601    let func_ref_id = match FuncRefTableId::from_raw(func_ref_id) {
602        Some(id) => id,
603        None => bail_bug!("bad FuncRefTableId"),
604    };
605    let module_interned_type_index = ModuleInternedTypeIndex::from_bits(module_interned_type_index);
606
607    let func_ref = if module_interned_type_index.is_reserved_value() {
608        store
609            .unwrap_gc_store()
610            .func_ref_table
611            .get_untyped(func_ref_id)?
612    } else {
613        let types = store.engine().signatures();
614        let engine_ty = store
615            .instance(instance)
616            .engine_type_index(module_interned_type_index);
617        store
618            .unwrap_gc_store()
619            .func_ref_table
620            .get_typed(types, func_ref_id, engine_ty)?
621    };
622
623    Ok(func_ref.map_or(core::ptr::null_mut(), |f| f.as_ptr().cast()))
624}
625
626// Intern a continuation reference into the GC heap's side table.
627//
628// This libcall may not GC.
629#[cfg(all(feature = "gc", feature = "stack-switching"))]
630unsafe fn intern_contref_for_gc_heap(
631    store: &mut dyn VMStore,
632    _instance: InstanceId,
633    contref: *mut u8,
634    revision: *mut u8,
635) -> Result<u32> {
636    use crate::store::AutoAssertNoGc;
637
638    let mut store = AutoAssertNoGc::new(&mut **store);
639    let contobj = unsafe { crate::vm::VMContObj::from_raw_parts(contref, revision.addr()) };
640    let id = unsafe { store.require_gc_store_mut()?.cont_ref_table.intern(contobj) };
641    Ok(id)
642}
643
644// Resolve a continuation reference ID loaded from the GC heap and
645// write its 16 bytes value into caller provided storage `out_result`.
646//
647// This libcall may not GC.
648#[cfg(all(feature = "gc", feature = "stack-switching"))]
649unsafe fn get_interned_contref(
650    store: &mut dyn VMStore,
651    _instance: InstanceId,
652    contref_id: u32,
653    out_result: *mut u8,
654) -> Result<()> {
655    use crate::store::AutoAssertNoGc;
656    use core::ptr::NonNull;
657
658    let store = AutoAssertNoGc::new(&mut **store);
659    let contobj = store.unwrap_gc_store().cont_ref_table.get(contref_id)?;
660    let raw = match contobj {
661        Some(contobj) => VMRawContObj {
662            contref: NonNull::new(contobj.contref.as_ptr().cast::<u8>()).map(VmPtr::from),
663            revision: contobj.revision,
664        },
665        None => VMRawContObj {
666            contref: None,
667            revision: 0,
668        },
669    };
670    unsafe { out_result.cast::<VMRawContObj>().write(raw) };
671    Ok(())
672}
673
674#[inline]
675fn is_subtype(
676    store: &mut dyn VMStore,
677    _instance: InstanceId,
678    actual_engine_type: u32,
679    expected_engine_type: u32,
680) -> u32 {
681    use wasmtime_environ::VMSharedTypeIndex;
682
683    let actual = VMSharedTypeIndex::from_u32(actual_engine_type);
684    let expected = VMSharedTypeIndex::from_u32(expected_engine_type);
685    let is_subtype = store.is_subtype_cached(actual, expected);
686
687    log::trace!("is_subtype(actual={actual:?}, expected={expected:?}) -> {is_subtype}",);
688    u32::from(is_subtype)
689}
690
691// Implementation of `memory.atomic.notify` for locally defined memories.
692#[cfg(feature = "threads")]
693fn memory_atomic_notify(
694    store: &mut dyn VMStore,
695    instance: InstanceId,
696    memory_index: u32,
697    addr_index: u64,
698    count: u32,
699) -> Result<u32, Trap> {
700    let memory = DefinedMemoryIndex::from_u32(memory_index);
701    store
702        .instance_mut(instance)
703        .get_defined_memory_mut(memory)
704        .atomic_notify(addr_index, count)
705}
706
707// Implementation of `memory.atomic.wait32` for locally defined memories.
708#[cfg(feature = "threads")]
709fn memory_atomic_wait32(
710    store: &mut dyn VMStore,
711    instance: InstanceId,
712    memory_index: u32,
713    addr_index: u64,
714    expected: u32,
715    timeout: u64,
716) -> Result<u32, Trap> {
717    let timeout = (timeout as i64 >= 0).then(|| Duration::from_nanos(timeout));
718    let memory = DefinedMemoryIndex::from_u32(memory_index);
719    Ok(store
720        .instance_mut(instance)
721        .get_defined_memory_mut(memory)
722        .atomic_wait32(addr_index, expected, timeout)? as u32)
723}
724
725// Implementation of `memory.atomic.wait64` for locally defined memories.
726#[cfg(feature = "threads")]
727fn memory_atomic_wait64(
728    store: &mut dyn VMStore,
729    instance: InstanceId,
730    memory_index: u32,
731    addr_index: u64,
732    expected: u64,
733    timeout: u64,
734) -> Result<u32, Trap> {
735    let timeout = (timeout as i64 >= 0).then(|| Duration::from_nanos(timeout));
736    let memory = DefinedMemoryIndex::from_u32(memory_index);
737    Ok(store
738        .instance_mut(instance)
739        .get_defined_memory_mut(memory)
740        .atomic_wait64(addr_index, expected, timeout)? as u32)
741}
742
743// Hook for when an instance runs out of fuel.
744fn out_of_gas(store: &mut dyn VMStore, _instance: InstanceId) -> Result<()> {
745    let result = block_on!(store, async |store, _| {
746        if !store.refuel() {
747            return Err(Trap::OutOfFuel.into());
748        }
749        #[cfg(feature = "async")]
750        if store.fuel_yield_interval.is_some() {
751            store.yield_now().await;
752        }
753        Ok(())
754    })
755    .and_then(|r| r);
756    // Running out of fuel, or being cancelled while yielding, stops the guest
757    // at a point between two of its calls to or returns from the host, which
758    // the trace cannot represent.
759    if result.is_err() {
760        store.rr.poison("guest execution stopping at a fuel check");
761    }
762    result
763}
764
765// Hook for when an instance observes that the epoch has changed.
766#[cfg(target_has_atomic = "64")]
767fn new_epoch(store: &mut dyn VMStore, _instance: InstanceId) -> Result<NextEpoch> {
768    use crate::UpdateDeadline;
769
770    #[cfg(feature = "debug")]
771    {
772        store.block_on_debug_handler(crate::DebugEvent::EpochYield)?;
773    }
774
775    let update_deadline = store.new_epoch_updated_deadline()?;
776    let result = block_on!(store, async move |store, asyncness| {
777        #[cfg(not(feature = "async"))]
778        let _ = asyncness;
779
780        let delta = match update_deadline {
781            UpdateDeadline::Interrupt => return Err(Trap::Interrupt.into()),
782            UpdateDeadline::Continue(delta) => delta,
783
784            // Note that custom errors are used here to avoid tripping up on the
785            // `block_on!` message that otherwise assumes
786            // async-configuration-after-the-fact.
787            #[cfg(feature = "async")]
788            UpdateDeadline::Yield(delta) => {
789                if asyncness != Asyncness::Yes {
790                    bail!(
791                        "cannot use `UpdateDeadline::Yield` without using \
792                         an async wasm entrypoint",
793                    );
794                }
795                store.yield_now().await;
796                delta
797            }
798            #[cfg(feature = "async")]
799            UpdateDeadline::YieldCustom(delta, future) => {
800                if asyncness != Asyncness::Yes {
801                    bail!(
802                        "cannot use `UpdateDeadline::YieldCustom` without using \
803                         an async wasm entrypoint",
804                    );
805                }
806                future.await;
807                delta
808            }
809        };
810
811        // Set a new deadline and return the new epoch deadline so
812        // the Wasm code doesn't have to reload it.
813        store.set_epoch_deadline(delta);
814        Ok(NextEpoch(store.get_epoch_deadline()))
815    })
816    .and_then(|r| r);
817    // An epoch interruption trap, or cancellation while yielding, stops the
818    // guest at a point between two of its calls to or returns from the host,
819    // which the trace cannot represent.
820    if result.is_err() {
821        store
822            .rr
823            .poison("guest execution stopping at an epoch check");
824    }
825    result
826}
827
828struct NextEpoch(u64);
829
830unsafe impl HostResultHasUnwindSentinel for NextEpoch {
831    type Abi = u64;
832    const SENTINEL: u64 = u64::MAX;
833    fn into_abi(self) -> u64 {
834        self.0
835    }
836}
837
838// Hook for validating malloc using wmemcheck_state.
839#[cfg(feature = "wmemcheck")]
840fn check_malloc(store: &mut dyn VMStore, instance: InstanceId, addr: u32, len: u32) -> Result<()> {
841    let instance = store.instance_mut(instance);
842    if let Some(wmemcheck_state) = instance.wmemcheck_state_mut() {
843        let result = wmemcheck_state.malloc(addr as usize, len as usize);
844        wmemcheck_state.memcheck_on();
845        match result {
846            Ok(()) => {}
847            Err(DoubleMalloc { addr, len }) => {
848                bail!("Double malloc at addr {:#x} of size {}", addr, len)
849            }
850            Err(OutOfBounds { addr, len }) => {
851                bail!("Malloc out of bounds at addr {:#x} of size {}", addr, len);
852            }
853            _ => {
854                panic!("unreachable")
855            }
856        }
857    }
858    Ok(())
859}
860
861// Hook for validating free using wmemcheck_state.
862#[cfg(feature = "wmemcheck")]
863fn check_free(store: &mut dyn VMStore, instance: InstanceId, addr: u32) -> Result<()> {
864    let instance = store.instance_mut(instance);
865    if let Some(wmemcheck_state) = instance.wmemcheck_state_mut() {
866        let result = wmemcheck_state.free(addr as usize);
867        wmemcheck_state.memcheck_on();
868        match result {
869            Ok(()) => {}
870            Err(InvalidFree { addr }) => {
871                bail!("Invalid free at addr {:#x}", addr)
872            }
873            _ => {
874                panic!("unreachable")
875            }
876        }
877    }
878    Ok(())
879}
880
881// Hook for validating load using wmemcheck_state.
882#[cfg(feature = "wmemcheck")]
883fn check_load(
884    store: &mut dyn VMStore,
885    instance: InstanceId,
886    num_bytes: u32,
887    addr: u32,
888    offset: u32,
889) -> Result<()> {
890    let instance = store.instance_mut(instance);
891    if let Some(wmemcheck_state) = instance.wmemcheck_state_mut() {
892        let result = wmemcheck_state.read(addr as usize + offset as usize, num_bytes as usize);
893        match result {
894            Ok(()) => {}
895            Err(InvalidRead { addr, len }) => {
896                bail!("Invalid load at addr {:#x} of size {}", addr, len);
897            }
898            Err(OutOfBounds { addr, len }) => {
899                bail!("Load out of bounds at addr {:#x} of size {}", addr, len);
900            }
901            _ => {
902                panic!("unreachable")
903            }
904        }
905    }
906    Ok(())
907}
908
909// Hook for validating store using wmemcheck_state.
910#[cfg(feature = "wmemcheck")]
911fn check_store(
912    store: &mut dyn VMStore,
913    instance: InstanceId,
914    num_bytes: u32,
915    addr: u32,
916    offset: u32,
917) -> Result<()> {
918    let instance = store.instance_mut(instance);
919    if let Some(wmemcheck_state) = instance.wmemcheck_state_mut() {
920        let result = wmemcheck_state.write(addr as usize + offset as usize, num_bytes as usize);
921        match result {
922            Ok(()) => {}
923            Err(InvalidWrite { addr, len }) => {
924                bail!("Invalid store at addr {:#x} of size {}", addr, len)
925            }
926            Err(OutOfBounds { addr, len }) => {
927                bail!("Store out of bounds at addr {:#x} of size {}", addr, len)
928            }
929            _ => {
930                panic!("unreachable")
931            }
932        }
933    }
934    Ok(())
935}
936
937// Hook for turning wmemcheck load/store validation off when entering a malloc function.
938#[cfg(feature = "wmemcheck")]
939fn malloc_start(store: &mut dyn VMStore, instance: InstanceId) {
940    let instance = store.instance_mut(instance);
941    if let Some(wmemcheck_state) = instance.wmemcheck_state_mut() {
942        wmemcheck_state.memcheck_off();
943    }
944}
945
946// Hook for turning wmemcheck load/store validation off when entering a free function.
947#[cfg(feature = "wmemcheck")]
948fn free_start(store: &mut dyn VMStore, instance: InstanceId) {
949    let instance = store.instance_mut(instance);
950    if let Some(wmemcheck_state) = instance.wmemcheck_state_mut() {
951        wmemcheck_state.memcheck_off();
952    }
953}
954
955// Hook for tracking wasm stack updates using wmemcheck_state.
956#[cfg(feature = "wmemcheck")]
957fn update_stack_pointer(_store: &mut dyn VMStore, _instance: InstanceId, _value: u32) {
958    // TODO: stack-tracing has yet to be finalized. All memory below
959    // the address of the top of the stack is marked as valid for
960    // loads and stores.
961    // if let Some(wmemcheck_state) = &mut instance.wmemcheck_state {
962    //     instance.wmemcheck_state.update_stack_pointer(value as usize);
963    // }
964}
965
966// Hook updating wmemcheck_state memory state vector every time memory.grow is called.
967#[cfg(feature = "wmemcheck")]
968fn update_mem_size(store: &mut dyn VMStore, instance: InstanceId, num_pages: u32) {
969    let instance = store.instance_mut(instance);
970    if let Some(wmemcheck_state) = instance.wmemcheck_state_mut() {
971        const KIB: usize = 1024;
972        let num_bytes = num_pages as usize * 64 * KIB;
973        wmemcheck_state.update_mem_size(num_bytes);
974    }
975}
976
977fn floor_f32(_store: &mut dyn VMStore, _instance: InstanceId, val: f32) -> f32 {
978    val.wasm_floor()
979}
980
981fn floor_f64(_store: &mut dyn VMStore, _instance: InstanceId, val: f64) -> f64 {
982    val.wasm_floor()
983}
984
985fn ceil_f32(_store: &mut dyn VMStore, _instance: InstanceId, val: f32) -> f32 {
986    val.wasm_ceil()
987}
988
989fn ceil_f64(_store: &mut dyn VMStore, _instance: InstanceId, val: f64) -> f64 {
990    val.wasm_ceil()
991}
992
993fn trunc_f32(_store: &mut dyn VMStore, _instance: InstanceId, val: f32) -> f32 {
994    val.wasm_trunc()
995}
996
997fn trunc_f64(_store: &mut dyn VMStore, _instance: InstanceId, val: f64) -> f64 {
998    val.wasm_trunc()
999}
1000
1001fn nearest_f32(_store: &mut dyn VMStore, _instance: InstanceId, val: f32) -> f32 {
1002    val.wasm_nearest()
1003}
1004
1005fn nearest_f64(_store: &mut dyn VMStore, _instance: InstanceId, val: f64) -> f64 {
1006    val.wasm_nearest()
1007}
1008
1009// This intrinsic is only used on x86_64 platforms as an implementation of
1010// the `i8x16.swizzle` instruction when `pshufb` in SSSE3 is not available.
1011#[cfg(all(target_arch = "x86_64", target_feature = "sse"))]
1012fn i8x16_swizzle(_store: &mut dyn VMStore, _instance: InstanceId, a: i8x16, b: i8x16) -> i8x16 {
1013    union U {
1014        reg: i8x16,
1015        mem: [u8; 16],
1016    }
1017
1018    unsafe {
1019        let a = U { reg: a }.mem;
1020        let b = U { reg: b }.mem;
1021
1022        // Use the `swizzle` semantics of returning 0 on any out-of-bounds
1023        // index, rather than the x86 pshufb semantics, since Wasmtime uses
1024        // this to implement `i8x16.swizzle`.
1025        let select = |arr: &[u8; 16], byte: u8| {
1026            if byte >= 16 { 0x00 } else { arr[byte as usize] }
1027        };
1028
1029        U {
1030            mem: [
1031                select(&a, b[0]),
1032                select(&a, b[1]),
1033                select(&a, b[2]),
1034                select(&a, b[3]),
1035                select(&a, b[4]),
1036                select(&a, b[5]),
1037                select(&a, b[6]),
1038                select(&a, b[7]),
1039                select(&a, b[8]),
1040                select(&a, b[9]),
1041                select(&a, b[10]),
1042                select(&a, b[11]),
1043                select(&a, b[12]),
1044                select(&a, b[13]),
1045                select(&a, b[14]),
1046                select(&a, b[15]),
1047            ],
1048        }
1049        .reg
1050    }
1051}
1052
1053#[cfg(not(all(target_arch = "x86_64", target_feature = "sse")))]
1054fn i8x16_swizzle(_store: &mut dyn VMStore, _instance: InstanceId, _a: i8x16, _b: i8x16) -> i8x16 {
1055    unreachable!()
1056}
1057
1058// This intrinsic is only used on x86_64 platforms as an implementation of
1059// the `i8x16.shuffle` instruction when `pshufb` in SSSE3 is not available.
1060#[cfg(all(target_arch = "x86_64", target_feature = "sse"))]
1061fn i8x16_shuffle(
1062    _store: &mut dyn VMStore,
1063    _instance: InstanceId,
1064    a: i8x16,
1065    b: i8x16,
1066    c: i8x16,
1067) -> i8x16 {
1068    union U {
1069        reg: i8x16,
1070        mem: [u8; 16],
1071    }
1072
1073    unsafe {
1074        let ab = [U { reg: a }.mem, U { reg: b }.mem];
1075        let c = U { reg: c }.mem;
1076
1077        // Use the `shuffle` semantics of returning 0 on any out-of-bounds
1078        // index, rather than the x86 pshufb semantics, since Wasmtime uses
1079        // this to implement `i8x16.shuffle`.
1080        let select = |arr: &[[u8; 16]; 2], byte: u8| {
1081            if byte >= 32 {
1082                0x00
1083            } else if byte >= 16 {
1084                arr[1][byte as usize - 16]
1085            } else {
1086                arr[0][byte as usize]
1087            }
1088        };
1089
1090        U {
1091            mem: [
1092                select(&ab, c[0]),
1093                select(&ab, c[1]),
1094                select(&ab, c[2]),
1095                select(&ab, c[3]),
1096                select(&ab, c[4]),
1097                select(&ab, c[5]),
1098                select(&ab, c[6]),
1099                select(&ab, c[7]),
1100                select(&ab, c[8]),
1101                select(&ab, c[9]),
1102                select(&ab, c[10]),
1103                select(&ab, c[11]),
1104                select(&ab, c[12]),
1105                select(&ab, c[13]),
1106                select(&ab, c[14]),
1107                select(&ab, c[15]),
1108            ],
1109        }
1110        .reg
1111    }
1112}
1113
1114#[cfg(not(all(target_arch = "x86_64", target_feature = "sse")))]
1115fn i8x16_shuffle(
1116    _store: &mut dyn VMStore,
1117    _instance: InstanceId,
1118    _a: i8x16,
1119    _b: i8x16,
1120    _c: i8x16,
1121) -> i8x16 {
1122    unreachable!()
1123}
1124
1125// The FMA intrinsics are used when the target has no native FMA, to provide
1126// the deterministic semantics of relaxed SIMD's `madd`/`nmadd`. NaN results
1127// are canonical, like those of the rounding intrinsics above, so that they
1128// match the native lowering's under NaN canonicalization, as record/replay
1129// requires.
1130fn fma_f32x4(
1131    _store: &mut dyn VMStore,
1132    _instance: InstanceId,
1133    x: f32x4,
1134    y: f32x4,
1135    z: f32x4,
1136) -> f32x4 {
1137    union U {
1138        reg: f32x4,
1139        mem: [f32; 4],
1140    }
1141
1142    unsafe {
1143        let x = U { reg: x }.mem;
1144        let y = U { reg: y }.mem;
1145        let z = U { reg: z }.mem;
1146
1147        U {
1148            mem: [
1149                canonical_f32(x[0].wasm_mul_add(y[0], z[0])),
1150                canonical_f32(x[1].wasm_mul_add(y[1], z[1])),
1151                canonical_f32(x[2].wasm_mul_add(y[2], z[2])),
1152                canonical_f32(x[3].wasm_mul_add(y[3], z[3])),
1153            ],
1154        }
1155        .reg
1156    }
1157}
1158
1159fn fma_f64x2(
1160    _store: &mut dyn VMStore,
1161    _instance: InstanceId,
1162    x: f64x2,
1163    y: f64x2,
1164    z: f64x2,
1165) -> f64x2 {
1166    union U {
1167        reg: f64x2,
1168        mem: [f64; 2],
1169    }
1170
1171    unsafe {
1172        let x = U { reg: x }.mem;
1173        let y = U { reg: y }.mem;
1174        let z = U { reg: z }.mem;
1175
1176        U {
1177            mem: [
1178                canonical_f64(x[0].wasm_mul_add(y[0], z[0])),
1179                canonical_f64(x[1].wasm_mul_add(y[1], z[1])),
1180            ],
1181        }
1182        .reg
1183    }
1184}
1185
1186fn canonical_f32(val: f32) -> f32 {
1187    if val.is_nan() { f32::NAN } else { val }
1188}
1189
1190fn canonical_f64(val: f64) -> f64 {
1191    if val.is_nan() { f64::NAN } else { val }
1192}
1193
1194/// This intrinsic is just used to record trap information.
1195///
1196/// The `Infallible` "ok" type here means that this never returns success, it
1197/// only ever returns an error, and this hooks into the machinery to handle
1198/// `Result` values to record such trap information.
1199fn trap(_store: &mut dyn VMStore, _instance: InstanceId, code: u8) -> Result<Infallible> {
1200    match CompiledTrap::from_u8(code).unwrap() {
1201        CompiledTrap::Normal(trap) => Err(trap.into()),
1202        CompiledTrap::InternalAssert => bail_bug!("internal assert hit in wasm"),
1203        CompiledTrap::GcHeapCorrupt => bail_bug!("GC heap corruption detected"),
1204    }
1205}
1206
1207fn raise(store: &mut dyn VMStore, _instance: InstanceId) {
1208    // SAFETY: this is only called from compiled wasm so we know that wasm has
1209    // already been entered. It's a dynamic safety precondition that the trap
1210    // information has already been arranged to be present.
1211    unsafe { crate::runtime::vm::traphandlers::raise_preexisting_trap(store) }
1212}
1213
1214/// Records a stack-overflow trap, which the trampoline then raises.
1215///
1216/// See the `stack_overflow` builtin's documentation for how this is reached.
1217fn stack_overflow(_store: &mut dyn VMStore, _instance: InstanceId) -> Result<()> {
1218    Err(Trap::StackOverflow.into())
1219}
1220
1221// Builtins for continuations. These are thin wrappers around the
1222// respective definitions in stack_switching.rs.
1223#[cfg(feature = "stack-switching")]
1224fn cont_new(
1225    store: &mut dyn VMStore,
1226    instance: InstanceId,
1227    func: *mut u8,
1228    param_count: u32,
1229    result_count: u32,
1230    gc_refs: u32,
1231) -> Result<Option<AllocationSize>> {
1232    let ans = crate::vm::stack_switching::cont_new(
1233        store,
1234        instance,
1235        func,
1236        param_count,
1237        result_count,
1238        gc_refs != 0,
1239    )?;
1240    Ok(Some(AllocationSize(ans.cast::<u8>() as usize)))
1241}
1242
1243#[cfg(feature = "stack-switching")]
1244unsafe fn asan_start_switch_fiber(
1245    _store: &mut dyn VMStore,
1246    _instance: InstanceId,
1247    fake_stack_save: *mut u8,
1248    source_csi: *mut u8,
1249    target_csi: *mut u8,
1250) {
1251    unsafe {
1252        crate::vm::stack_switching::asan::start_switch_fiber(
1253            fake_stack_save,
1254            source_csi,
1255            target_csi,
1256        )
1257    }
1258}
1259
1260#[cfg(feature = "stack-switching")]
1261unsafe fn asan_finish_switch_fiber(
1262    _store: &mut dyn VMStore,
1263    _instance: InstanceId,
1264    fake_stack: *mut u8,
1265    current_csi: *mut u8,
1266) {
1267    unsafe { crate::vm::stack_switching::asan::finish_switch_fiber(fake_stack, current_csi) }
1268}
1269
1270#[cfg(feature = "gc")]
1271fn get_instance_id(_store: &mut dyn VMStore, instance: InstanceId) -> u32 {
1272    instance.as_u32()
1273}
1274
1275#[cfg(feature = "gc")]
1276fn throw_ref(store: &mut dyn VMStore, _instance: InstanceId, exnref: u32) -> Result<()> {
1277    let exnref = VMGcRef::from_raw_u32(exnref).ok_or_else(|| Trap::NullReference)?;
1278    Err(store.set_pending_exception(&exnref))
1279}
1280
1281/// Handles a guest store of `len` bytes (with bits `hi:lo`) to watched bytes
1282/// of a linear memory, before it happens.
1283fn memory_watch_store(
1284    store: &mut dyn VMStore,
1285    instance: InstanceId,
1286    memory: u32,
1287    addr: u64,
1288    len: u32,
1289    lo: u64,
1290    hi: u64,
1291) -> Result<()> {
1292    let bits = (u128::from(hi) << 64) | u128::from(lo);
1293    let mask = u128::MAX >> (128 - 8 * len.min(16));
1294    watched_write(
1295        store,
1296        instance,
1297        memory,
1298        addr,
1299        u64::from(len),
1300        Some(bits & mask),
1301    )
1302}
1303
1304/// Handles a guest bulk write of `len` bytes to a linear memory, before it
1305/// happens, if any of the bytes are watched.
1306fn memory_watch_range(
1307    store: &mut dyn VMStore,
1308    instance: InstanceId,
1309    memory: u32,
1310    addr: u64,
1311    len: u64,
1312) -> Result<()> {
1313    watched_write(store, instance, memory, addr, len, None)
1314}
1315
1316fn watched_write(
1317    store: &mut dyn VMStore,
1318    instance: InstanceId,
1319    memory: u32,
1320    addr: u64,
1321    len: u64,
1322    value: Option<u128>,
1323) -> Result<()> {
1324    let opaque = &mut **store;
1325    let store_id = opaque.id();
1326    let memory = match opaque
1327        .instance_mut(instance)
1328        .get_exported_memory(store_id, wasmtime_environ::MemoryIndex::from_u32(memory))
1329    {
1330        crate::runtime::vm::ExportMemory::Unshared(memory) => memory,
1331        crate::runtime::vm::ExportMemory::Shared(..) => return Ok(()),
1332    };
1333    // An out-of-bounds bulk write traps after this returns.
1334    let Some(shadow) = memory.vm_shadow(opaque) else {
1335        return Ok(());
1336    };
1337    let start = usize::try_from(addr)
1338        .unwrap_or(usize::MAX)
1339        .min(shadow.bytes().len());
1340    let end = usize::try_from(addr.saturating_add(len))
1341        .unwrap_or(usize::MAX)
1342        .min(shadow.bytes().len());
1343    let bits = shadow.bytes()[start..end]
1344        .iter()
1345        .fold(0, |bits, byte| bits | *byte);
1346    #[cfg(feature = "debug")]
1347    if bits & crate::runtime::vm::WATCH_DEBUG != 0 {
1348        let hit = crate::WatchpointHit {
1349            memory,
1350            address: addr,
1351            len,
1352            value,
1353        };
1354        store.block_on_debug_handler(crate::DebugEvent::Watchpoint(hit))?;
1355    }
1356    let _ = (bits, value);
1357    Ok(())
1358}
1359
1360/// Records a call across the guest boundary, for the trampolines of
1361/// record/replay engines while their store records.
1362fn rr_enter(
1363    store: &mut dyn VMStore,
1364    _instance: InstanceId,
1365    func: *mut u8,
1366    values: *mut u8,
1367    kind: u8,
1368) -> Result<u32> {
1369    let func = core::ptr::NonNull::new(func.cast()).unwrap();
1370    let Some(kind) = RrCallKind::from_u8(kind) else {
1371        bail_bug!("invalid record/replay call kind");
1372    };
1373    // SAFETY: trampolines pass the callee's live function reference, which the
1374    // store owns, and its initialized arguments.
1375    unsafe { store.rr_enter(func, values.cast(), kind) }
1376}
1377
1378/// Records the return of a call from `rr_enter`.
1379fn rr_leave(
1380    store: &mut dyn VMStore,
1381    _instance: InstanceId,
1382    call: u32,
1383    values: *mut u8,
1384    kind: u8,
1385    succeeded: u8,
1386) -> Result<()> {
1387    let Some(kind) = RrCallKind::from_u8(kind) else {
1388        bail_bug!("invalid record/replay call kind");
1389    };
1390    // SAFETY: trampolines pass the ID that `rr_enter` returned for this call
1391    // and the initialized results of successful calls, and the error of failed
1392    // calls is pending in TLS.
1393    unsafe { store.rr_leave(call, values.cast(), kind, succeeded != 0) }
1394}
1395
1396fn breakpoint(store: &mut dyn VMStore, _instance: InstanceId) -> Result<()> {
1397    #[cfg(feature = "debug")]
1398    {
1399        store.block_on_debug_handler(crate::DebugEvent::Breakpoint)?;
1400    }
1401    // Avoid unused-argument warning in no-debugger builds.
1402    let _ = store;
1403    Ok(())
1404}