1use 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
80pub 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 #[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 #[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
167macro_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 #[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 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 if result.is_none() {
268 store.rr.poison("failed guest memory growth");
269 }
270
271 Ok(result)
272 })?
273}
274
275struct AllocationSize(usize);
284
285unsafe 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
312unsafe 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 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
362fn 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#[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 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 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
409fn 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#[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#[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#[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 let _ = store
469 .grow_gc_heap(limiter.as_mut(), bytes_needed, asyncness)
470 .await;
471 })?;
472
473 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#[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 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 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#[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#[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#[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#[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#[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#[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#[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
743fn 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 if result.is_err() {
760 store.rr.poison("guest execution stopping at a fuel check");
761 }
762 result
763}
764
765#[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 #[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 store.set_epoch_deadline(delta);
814 Ok(NextEpoch(store.get_epoch_deadline()))
815 })
816 .and_then(|r| r);
817 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#[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#[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#[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#[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#[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#[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#[cfg(feature = "wmemcheck")]
957fn update_stack_pointer(_store: &mut dyn VMStore, _instance: InstanceId, _value: u32) {
958 }
965
966#[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#[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 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#[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 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
1125fn 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
1194fn 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 unsafe { crate::runtime::vm::traphandlers::raise_preexisting_trap(store) }
1212}
1213
1214fn stack_overflow(_store: &mut dyn VMStore, _instance: InstanceId) -> Result<()> {
1218 Err(Trap::StackOverflow.into())
1219}
1220
1221#[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
1281fn 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
1304fn 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 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
1360fn 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 unsafe { store.rr_enter(func, values.cast(), kind) }
1376}
1377
1378fn 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 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 let _ = store;
1403 Ok(())
1404}