1use super::invoke_wasm_and_catch_traps;
2use crate::prelude::*;
3use crate::runtime::vm::{UncaughtException, VMFuncRef};
4use crate::store::{AutoAssertNoGc, StoreOpaque};
5use crate::{
6 AsContext, AsContextMut, Engine, Func, FuncType, HeapType, NoFunc, RefType, StoreContextMut,
7 ValRaw, ValType,
8};
9use core::ffi::c_void;
10use core::marker;
11use core::mem::{self, MaybeUninit};
12use core::ptr::{self, NonNull};
13use wasmtime_environ::VMSharedTypeIndex;
14
15pub struct TypedFunc<Params, Results> {
24 _a: marker::PhantomData<fn(Params) -> Results>,
25 ty: FuncType,
26 func: Func,
27}
28
29impl<Params, Results> Clone for TypedFunc<Params, Results> {
30 fn clone(&self) -> TypedFunc<Params, Results> {
31 Self {
32 _a: marker::PhantomData,
33 ty: self.ty.clone(),
34 func: self.func,
35 }
36 }
37}
38
39impl<Params, Results> TypedFunc<Params, Results>
40where
41 Params: WasmParams,
42 Results: WasmResults,
43{
44 pub unsafe fn new_unchecked(store: impl AsContext, func: Func) -> TypedFunc<Params, Results> {
57 let store = store.as_context().0;
58 unsafe { Self::_new_unchecked(store, func) }
59 }
60
61 pub(crate) unsafe fn _new_unchecked(
62 store: &StoreOpaque,
63 func: Func,
64 ) -> TypedFunc<Params, Results> {
65 let ty = func.load_ty(store);
66 TypedFunc {
67 _a: marker::PhantomData,
68 ty,
69 func,
70 }
71 }
72
73 pub fn func(&self) -> &Func {
76 &self.func
77 }
78
79 #[inline]
100 pub fn call(&self, mut store: impl AsContextMut, params: Params) -> Result<Results> {
101 let mut store = store.as_context_mut();
102 store.0.validate_sync_call()?;
103 let func = self.func.vm_func_ref(store.0);
104 unsafe {
105 Self::call_raw(
106 &mut store,
107 &self.ty,
108 func,
109 params,
110 UncaughtException::Propagate,
111 )
112 }
113 }
114
115 #[cfg(feature = "async")]
137 pub async fn call_async(
138 &self,
139 mut store: impl AsContextMut<Data: Send>,
140 params: Params,
141 ) -> Result<Results>
142 where
143 Params: Sync,
144 Results: Sync,
145 {
146 let mut store = store.as_context_mut();
147
148 store
149 .on_fiber(|store| {
150 let func = self.func.vm_func_ref(store.0);
151 unsafe {
152 Self::call_raw(store, &self.ty, func, params, UncaughtException::Propagate)
153 }
154 })
155 .await?
156 }
157
158 pub(crate) unsafe fn call_raw<T>(
165 store: &mut StoreContextMut<'_, T>,
166 ty: &FuncType,
167 func: ptr::NonNull<VMFuncRef>,
168 params: Params,
169 uncaught_exception: UncaughtException,
170 ) -> Result<Results> {
171 unsafe {
177 if cfg!(debug_assertions) {
178 Self::debug_typecheck(store.0, func.as_ref().type_index);
179 }
180 }
181
182 union Storage<T: Copy, U: Copy> {
187 params: MaybeUninit<T>,
188 results: U,
189 }
190
191 let mut storage = Storage::<Params::ValRawStorage, Results::ValRawStorage> {
192 params: MaybeUninit::uninit(),
193 };
194
195 {
196 let mut store = AutoAssertNoGc::new(store.0);
197 let dst: &mut MaybeUninit<_> = unsafe { &mut storage.params };
201 params.store(&mut store, ty, dst)?;
202 }
203
204 let mut captures = (func, storage);
210
211 let result = invoke_wasm_and_catch_traps(store, uncaught_exception, |caller, vm| {
212 let (func_ref, storage) = &mut captures;
213 let storage_len = mem::size_of_val::<Storage<_, _>>(storage) / mem::size_of::<ValRaw>();
214 let storage: *mut Storage<_, _> = storage;
215 let storage = storage.cast::<ValRaw>();
216 let storage = core::ptr::slice_from_raw_parts_mut(storage, storage_len);
217 let storage = NonNull::new(storage).unwrap();
218
219 unsafe { VMFuncRef::array_call(*func_ref, vm, caller, storage) }
223 });
224
225 let (_, storage) = captures;
226 result?;
227
228 let mut store = AutoAssertNoGc::new(store.0);
229 unsafe { Ok(Results::load(&mut store, &storage.results)) }
234 }
235
236 fn debug_typecheck(store: &StoreOpaque, func: VMSharedTypeIndex) {
238 let ty = FuncType::from_shared_type_index(store.engine(), func).unwrap();
239 Params::typecheck(store.engine(), ty.params(), TypeCheckPosition::Param)
240 .expect("params should match");
241 Results::typecheck(store.engine(), ty.results(), TypeCheckPosition::Result)
242 .expect("results should match");
243 }
244}
245
246#[doc(hidden)]
247#[derive(Copy, Clone)]
248pub enum TypeCheckPosition {
249 Param,
250 Result,
251}
252
253pub unsafe trait WasmTy: Send {
262 #[doc(hidden)]
266 #[inline]
267 fn typecheck(engine: &Engine, actual: ValType, position: TypeCheckPosition) -> Result<()> {
268 let expected = Self::valtype();
269 debug_assert!(expected.comes_from_same_engine(engine));
270 debug_assert!(actual.comes_from_same_engine(engine));
271 match position {
272 TypeCheckPosition::Result => actual.ensure_matches(engine, &expected),
275 TypeCheckPosition::Param => match (expected.as_ref(), actual.as_ref()) {
278 (Some(expected_ref), Some(actual_ref)) if actual_ref.heap_type().is_concrete() => {
308 let expected_top = HeapType::from(expected_ref.heap_type().top());
309 let actual_top = HeapType::from(actual_ref.heap_type().top());
310 expected_top.ensure_matches(engine, &actual_top)
311 }
312 _ => expected.ensure_matches(engine, &actual),
313 },
314 }
315 }
316
317 #[doc(hidden)]
319 fn valtype() -> ValType;
320
321 #[doc(hidden)]
322 fn may_gc() -> bool {
323 match Self::valtype() {
324 ValType::Ref(_) => true,
325 ValType::I32 | ValType::I64 | ValType::F32 | ValType::F64 | ValType::V128 => false,
326 }
327 }
328
329 #[doc(hidden)]
332 fn compatible_with_store(&self, store: &StoreOpaque) -> bool;
333
334 #[doc(hidden)]
341 fn dynamic_concrete_type_check(
342 &self,
343 store: &StoreOpaque,
344 nullable: bool,
345 actual: &HeapType,
346 ) -> Result<()>;
347
348 #[doc(hidden)]
356 #[inline]
357 fn is_vmgcref_and_points_to_object(&self) -> bool {
358 Self::valtype().is_vmgcref_type_and_points_to_object()
359 }
360
361 #[doc(hidden)]
390 fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()>;
391
392 #[doc(hidden)]
399 unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self;
400}
401
402macro_rules! integers {
403 ($($primitive:ident/$get_primitive:ident => $ty:ident)*) => ($(
404 unsafe impl WasmTy for $primitive {
405 #[inline]
406 fn valtype() -> ValType {
407 ValType::$ty
408 }
409 #[inline]
410 fn compatible_with_store(&self, _: &StoreOpaque) -> bool {
411 true
412 }
413 #[inline]
414 fn dynamic_concrete_type_check(&self, _: &StoreOpaque, _: bool, _: &HeapType) -> Result<()> {
415 unreachable!()
416 }
417 #[inline]
418 fn store(self, _store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
419 ptr.write(ValRaw::$primitive(self));
420 Ok(())
421 }
422 #[inline]
423 unsafe fn load(_store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
424 ptr.$get_primitive()
425 }
426 }
427 )*)
428}
429
430integers! {
431 i32/get_i32 => I32
432 i64/get_i64 => I64
433 u32/get_u32 => I32
434 u64/get_u64 => I64
435}
436
437macro_rules! floats {
438 ($($float:ident/$int:ident/$get_float:ident => $ty:ident)*) => ($(
439 unsafe impl WasmTy for $float {
440 #[inline]
441 fn valtype() -> ValType {
442 ValType::$ty
443 }
444 #[inline]
445 fn compatible_with_store(&self, _: &StoreOpaque) -> bool {
446 true
447 }
448 #[inline]
449 fn dynamic_concrete_type_check(&self, _: &StoreOpaque, _: bool, _: &HeapType) -> Result<()> {
450 unreachable!()
451 }
452 #[inline]
453 fn store(self, _store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
454 ptr.write(ValRaw::$float(self.to_bits()));
455 Ok(())
456 }
457 #[inline]
458 unsafe fn load(_store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
459 $float::from_bits(ptr.$get_float())
460 }
461 }
462 )*)
463}
464
465floats! {
466 f32/u32/get_f32 => F32
467 f64/u64/get_f64 => F64
468}
469
470unsafe impl WasmTy for NoFunc {
471 #[inline]
472 fn valtype() -> ValType {
473 ValType::Ref(RefType::new(false, HeapType::NoFunc))
474 }
475
476 #[inline]
477 fn compatible_with_store(&self, _store: &StoreOpaque) -> bool {
478 match self._inner {}
479 }
480
481 #[inline]
482 fn dynamic_concrete_type_check(&self, _: &StoreOpaque, _: bool, _: &HeapType) -> Result<()> {
483 match self._inner {}
484 }
485
486 #[inline]
487 fn is_vmgcref_and_points_to_object(&self) -> bool {
488 match self._inner {}
489 }
490
491 #[inline]
492 fn store(self, _store: &mut AutoAssertNoGc<'_>, _ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
493 match self._inner {}
494 }
495
496 #[inline]
497 unsafe fn load(_store: &mut AutoAssertNoGc<'_>, _ptr: &ValRaw) -> Self {
498 unreachable!("NoFunc is uninhabited")
499 }
500}
501
502unsafe impl WasmTy for Option<NoFunc> {
503 #[inline]
504 fn valtype() -> ValType {
505 ValType::Ref(RefType::new(true, HeapType::NoFunc))
506 }
507
508 #[inline]
509 fn compatible_with_store(&self, _store: &StoreOpaque) -> bool {
510 true
511 }
512
513 #[inline]
514 fn dynamic_concrete_type_check(
515 &self,
516 _: &StoreOpaque,
517 nullable: bool,
518 ty: &HeapType,
519 ) -> Result<()> {
520 if nullable {
521 Ok(())
523 } else {
524 bail!("argument type mismatch: expected non-nullable (ref {ty}), found null reference")
525 }
526 }
527
528 #[inline]
529 fn store(self, _store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
530 ptr.write(ValRaw::funcref(ptr::null_mut()));
531 Ok(())
532 }
533
534 #[inline]
535 unsafe fn load(_store: &mut AutoAssertNoGc<'_>, _ptr: &ValRaw) -> Self {
536 None
537 }
538}
539
540unsafe impl WasmTy for Func {
541 #[inline]
542 fn valtype() -> ValType {
543 ValType::Ref(RefType::new(false, HeapType::Func))
544 }
545
546 #[inline]
547 fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
548 self.store == store.id()
549 }
550
551 #[inline]
552 fn dynamic_concrete_type_check(
553 &self,
554 store: &StoreOpaque,
555 _nullable: bool,
556 expected: &HeapType,
557 ) -> Result<()> {
558 let expected = expected.unwrap_concrete_func();
559 self.ensure_matches_ty(store, expected)
560 .context("argument type mismatch for reference to concrete type")
561 }
562
563 #[inline]
564 fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
565 let abi = self.vm_func_ref(store);
566 ptr.write(ValRaw::funcref(abi.cast::<c_void>().as_ptr()));
567 Ok(())
568 }
569
570 #[inline]
571 unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
572 let p = NonNull::new(ptr.get_funcref()).unwrap().cast();
573
574 unsafe { Func::from_vm_func_ref(store.id(), p) }
577 }
578}
579
580unsafe impl WasmTy for Option<Func> {
581 #[inline]
582 fn valtype() -> ValType {
583 ValType::FUNCREF
584 }
585
586 #[inline]
587 fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
588 if let Some(f) = self {
589 f.compatible_with_store(store)
590 } else {
591 true
592 }
593 }
594
595 fn dynamic_concrete_type_check(
596 &self,
597 store: &StoreOpaque,
598 nullable: bool,
599 expected: &HeapType,
600 ) -> Result<()> {
601 if let Some(f) = self {
602 let expected = expected.unwrap_concrete_func();
603 f.ensure_matches_ty(store, expected)
604 .context("argument type mismatch for reference to concrete type")
605 } else if nullable {
606 Ok(())
607 } else {
608 bail!(
609 "argument type mismatch: expected non-nullable (ref {expected}), found null reference"
610 )
611 }
612 }
613
614 #[inline]
615 fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
616 let raw = if let Some(f) = self {
617 f.vm_func_ref(store).as_ptr()
618 } else {
619 ptr::null_mut()
620 };
621 ptr.write(ValRaw::funcref(raw.cast::<c_void>()));
622 Ok(())
623 }
624
625 #[inline]
626 unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
627 let ptr = NonNull::new(ptr.get_funcref())?.cast();
628
629 unsafe { Some(Func::from_vm_func_ref(store.id(), ptr)) }
632 }
633}
634
635pub unsafe trait WasmParams: Send {
641 #[doc(hidden)]
642 type ValRawStorage: Copy;
643
644 #[doc(hidden)]
645 fn typecheck(
646 engine: &Engine,
647 params: impl ExactSizeIterator<Item = crate::ValType>,
648 position: TypeCheckPosition,
649 ) -> Result<()>;
650
651 #[doc(hidden)]
652 fn vmgcref_pointing_to_object_count(&self) -> usize;
653
654 #[doc(hidden)]
655 fn store(
656 self,
657 store: &mut AutoAssertNoGc<'_>,
658 func_ty: &FuncType,
659 dst: &mut MaybeUninit<Self::ValRawStorage>,
660 ) -> Result<()>;
661}
662
663unsafe impl<T> WasmParams for T
666where
667 T: WasmTy,
668{
669 type ValRawStorage = <(T,) as WasmParams>::ValRawStorage;
670
671 fn typecheck(
672 engine: &Engine,
673 params: impl ExactSizeIterator<Item = crate::ValType>,
674 position: TypeCheckPosition,
675 ) -> Result<()> {
676 <(T,) as WasmParams>::typecheck(engine, params, position)
677 }
678
679 #[inline]
680 fn vmgcref_pointing_to_object_count(&self) -> usize {
681 T::is_vmgcref_and_points_to_object(self) as usize
682 }
683
684 #[inline]
685 fn store(
686 self,
687 store: &mut AutoAssertNoGc<'_>,
688 func_ty: &FuncType,
689 dst: &mut MaybeUninit<Self::ValRawStorage>,
690 ) -> Result<()> {
691 <(T,) as WasmParams>::store((self,), store, func_ty, dst)
692 }
693}
694
695macro_rules! impl_wasm_params {
696 ($n:tt $($t:ident)*) => {
697 #[allow(non_snake_case, reason = "macro-generated code")]
698 unsafe impl<$($t: WasmTy,)*> WasmParams for ($($t,)*) {
699 type ValRawStorage = [ValRaw; $n];
700
701 fn typecheck(
702 _engine: &Engine,
703 mut params: impl ExactSizeIterator<Item = crate::ValType>,
704 _position: TypeCheckPosition,
705 ) -> Result<()> {
706 let mut _n = 0;
707
708 $(
709 match params.next() {
710 Some(t) => {
711 _n += 1;
712 $t::typecheck(_engine, t, _position)?
713 },
714 None => bail!("expected {} types, found {}", $n, params.len() + _n),
715 }
716 )*
717
718 match params.next() {
719 None => Ok(()),
720 Some(_) => {
721 _n += 1;
722 bail!("expected {} types, found {}", $n, params.len() + _n)
723 },
724 }
725 }
726
727 #[inline]
728 fn vmgcref_pointing_to_object_count(&self) -> usize {
729 let ($($t,)*) = self;
730 0 $(
731 + $t.is_vmgcref_and_points_to_object() as usize
732 )*
733 }
734
735
736 #[inline]
737 fn store(
738 self,
739 _store: &mut AutoAssertNoGc<'_>,
740 _func_ty: &FuncType,
741 _ptr: &mut MaybeUninit<Self::ValRawStorage>,
742 ) -> Result<()> {
743 let ($($t,)*) = self;
744
745 let mut _i = 0;
746 $(
747 if !$t.compatible_with_store(_store) {
748 bail!("attempt to pass cross-`Store` value to Wasm as function argument");
749 }
750
751 if $t::valtype().is_ref() {
752 let param_ty = _func_ty.param(_i).unwrap();
753 let ref_ty = param_ty.unwrap_ref();
754 let heap_ty = ref_ty.heap_type();
755 if heap_ty.is_concrete() {
756 $t.dynamic_concrete_type_check(_store, ref_ty.is_nullable(), heap_ty)?;
757 }
758 }
759
760 let dst = map_maybe_uninit!(_ptr[_i]);
761 $t.store(_store, dst)?;
762
763 _i += 1;
764 )*
765 Ok(())
766 }
767 }
768 };
769}
770
771for_each_function_signature!(impl_wasm_params);
772
773pub unsafe trait WasmResults: WasmParams {
776 #[doc(hidden)]
777 unsafe fn load(store: &mut AutoAssertNoGc<'_>, abi: &Self::ValRawStorage) -> Self;
778}
779
780unsafe impl<T: WasmTy> WasmResults for T {
782 unsafe fn load(store: &mut AutoAssertNoGc<'_>, abi: &Self::ValRawStorage) -> Self {
783 unsafe { <(T,) as WasmResults>::load(store, abi).0 }
786 }
787}
788
789macro_rules! impl_wasm_results {
790 ($n:tt $($t:ident)*) => {
791 #[allow(non_snake_case, reason = "macro-generated code")]
792 unsafe impl<$($t: WasmTy,)*> WasmResults for ($($t,)*) {
793 unsafe fn load(_store: &mut AutoAssertNoGc<'_>, abi: &Self::ValRawStorage) -> Self {
794 let [$($t,)*] = abi;
795
796 (
797 $(unsafe { $t::load(_store, $t) },)*
800 )
801 }
802 }
803 };
804}
805
806for_each_function_signature!(impl_wasm_results);