Skip to main content

wasmtime/runtime/func/
typed.rs

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
15/// A statically typed WebAssembly function.
16///
17/// Values of this type represent statically type-checked WebAssembly functions.
18/// The function within a [`TypedFunc`] is statically known to have `Params` as its
19/// parameters and `Results` as its results.
20///
21/// This structure is created via [`Func::typed`] or [`TypedFunc::new_unchecked`].
22/// For more documentation about this see those methods.
23pub 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    /// An unchecked version of [`Func::typed`] which does not perform a
45    /// typecheck and simply assumes that the type declared here matches the
46    /// type of this function.
47    ///
48    /// The semantics of this function are the same as [`Func::typed`] except
49    /// that no error is returned because no typechecking is done.
50    ///
51    /// # Unsafety
52    ///
53    /// This function only safe to call if `typed` would otherwise return `Ok`
54    /// for the same `Params` and `Results` specified. If `typed` would return
55    /// an error then the returned `TypedFunc` is memory unsafe to invoke.
56    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    /// Returns the underlying [`Func`] that this is wrapping, losing the static
74    /// type information in the process.
75    pub fn func(&self) -> &Func {
76        &self.func
77    }
78
79    /// Invokes this WebAssembly function with the specified parameters.
80    ///
81    /// Returns either the results of the call, or a [`Trap`] if one happened.
82    ///
83    /// For more information, see the [`Func::typed`] and [`Func::call`]
84    /// documentation.
85    ///
86    /// # Errors
87    ///
88    /// For more information on errors see the documentation on [`Func::call`].
89    ///
90    /// # Panics
91    ///
92    /// Panics if `store` does not contain this function.
93    ///
94    /// [`Trap`]: crate::Trap
95    ///
96    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
97    /// memory allocation fails. See the `OutOfMemory` type's documentation for
98    /// details on Wasmtime's out-of-memory handling.
99    #[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    /// Invokes this WebAssembly function with the specified parameters.
116    ///
117    /// Returns either the results of the call, or a [`Trap`] if one happened.
118    ///
119    /// For more information, see the [`Func::typed`] and [`Func::call_async`]
120    /// documentation.
121    ///
122    /// # Errors
123    ///
124    /// For more information on errors see the documentation on [`Func::call`].
125    ///
126    /// # Panics
127    ///
128    /// This function will panic if it is called when the underlying [`Func`] is
129    /// connected to a synchronous store.
130    ///
131    /// [`Trap`]: crate::Trap
132    ///
133    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
134    /// memory allocation fails. See the `OutOfMemory` type's documentation for
135    /// details on Wasmtime's out-of-memory handling.
136    #[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    /// Do a raw call of a typed function.
159    ///
160    /// # Safety
161    ///
162    /// `func` must be of the given type, and it additionally must be a valid
163    /// store-owned pointer within the `store` provided.
164    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        // double-check that params/results match for this function's type in
172        // debug mode.
173        //
174        // SAFETY: this function requires that `ptr` is a valid function
175        // pointer.
176        unsafe {
177            if cfg!(debug_assertions) {
178                Self::debug_typecheck(store.0, func.as_ref().type_index);
179            }
180        }
181
182        // Validate that all runtime values flowing into this store indeed
183        // belong within this store, otherwise it would be unsafe for store
184        // values to cross each other.
185
186        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            // SAFETY: it's safe to use a union field here as the field itself
198            // is `MaybeUninit<_>` meaning nothing is accidentally considered
199            // initialized.
200            let dst: &mut MaybeUninit<_> = unsafe { &mut storage.params };
201            params.store(&mut store, ty, dst)?;
202        }
203
204        // Try to capture only a single variable (a tuple) in the closure below.
205        // This means the size of the closure is one pointer and is much more
206        // efficient to move in memory. This closure is actually invoked on the
207        // other side of a C++ shim, so it can never be inlined enough to make
208        // the memory go away, so the size matters here for performance.
209        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            // SAFETY: this function's own contract is that `func_ref` is safe
220            // to call and additionally that the params/results are correctly
221            // ascribed for this function call to be safe.
222            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        // SAFETY: this function is itself unsafe to ensure that the result type
230        // ascription is correct for `Results` and matches the actual function.
231        // Additionally given the correct type ascription all of the `results`
232        // accessed here should be validly initialized.
233        unsafe { Ok(Results::load(&mut store, &storage.results)) }
234    }
235
236    /// Purely a debug-mode assertion, not actually used in release builds.
237    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
253/// A trait implemented for types which can be arguments and results for
254/// closures passed to [`Func::wrap`] as well as parameters to [`Func::typed`].
255///
256/// This trait should not be implemented by user types. This trait may change at
257/// any time internally. The types which implement this trait, however, are
258/// stable over time.
259///
260/// For more information see [`Func::wrap`] and [`Func::typed`]
261pub unsafe trait WasmTy: Send {
262    // Do a "static" (aka at time of `func.typed::<P, R>()`) ahead-of-time type
263    // check for this type at the given position. You probably don't need to
264    // override this trait method.
265    #[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            // The caller is expecting to receive a `T` and the callee is
273            // actually returning a `U`, so ensure that `U <: T`.
274            TypeCheckPosition::Result => actual.ensure_matches(engine, &expected),
275            // The caller is expecting to pass a `T` and the callee is expecting
276            // to receive a `U`, so ensure that `T <: U`.
277            TypeCheckPosition::Param => match (expected.as_ref(), actual.as_ref()) {
278                // ... except that this technically-correct check would overly
279                // restrict the usefulness of our typed function APIs for the
280                // specific case of concrete reference types. Let's work through
281                // an example.
282                //
283                // Consider functions that take a `(ref param $some_func_type)`
284                // parameter:
285                //
286                // * We cannot have a static `wasmtime::SomeFuncTypeRef` type
287                //   that implements `WasmTy` specifically for `(ref null
288                //   $some_func_type)` because Wasm modules, and their types,
289                //   are loaded dynamically at runtime.
290                //
291                // * Therefore the embedder's only option for `T <: (ref null
292                //   $some_func_type)` is `T = (ref null nofunc)` aka
293                //   `Option<wasmtime::NoFunc>`.
294                //
295                // * But that static type means they can *only* pass in the null
296                //   function reference as an argument to the typed function.
297                //   This is way too restrictive! For ergonomics, we want them
298                //   to be able to pass in a `wasmtime::Func` whose type is
299                //   `$some_func_type`!
300                //
301                // To lift this constraint and enable better ergonomics for
302                // embedders, we allow `top(T) <: top(U)` -- i.e. they are part
303                // of the same type hierarchy and a dynamic cast could possibly
304                // succeed -- for the specific case of concrete heap type
305                // parameters, and fall back to dynamic type checks on the
306                // arguments passed to each invocation, as necessary.
307                (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    // The value type that this Type represents.
318    #[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    // Dynamic checks that this value is being used with the correct store
330    // context.
331    #[doc(hidden)]
332    fn compatible_with_store(&self, store: &StoreOpaque) -> bool;
333
334    // Dynamic checks that `self <: actual` for concrete type arguments. See the
335    // comment above in `WasmTy::typecheck`.
336    //
337    // Only ever called for concrete reference type arguments, so any type which
338    // is not in a type hierarchy with concrete reference types can implement
339    // this with `unreachable!()`.
340    #[doc(hidden)]
341    fn dynamic_concrete_type_check(
342        &self,
343        store: &StoreOpaque,
344        nullable: bool,
345        actual: &HeapType,
346    ) -> Result<()>;
347
348    // Is this a GC-managed reference that actually points to a GC object? That
349    // is, `self` is *not* an `i31`, null reference, or uninhabited type.
350    //
351    // Note that it is okay if this returns false positives (i.e. `true` for
352    // `Rooted<AnyRef>` without actually looking up the rooted `anyref` in the
353    // store and reflecting on it to determine whether it is actually an
354    // `i31`). However, it is not okay if this returns false negatives.
355    #[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    // Store `self` into `ptr`.
362    //
363    // NB: We _must not_ trigger a GC when passing refs from host code into Wasm
364    // (e.g. returned from a host function or passed as arguments to a Wasm
365    // function). After insertion into the activations table, the reference is
366    // no longer rooted. If multiple references are being sent from the host
367    // into Wasm and we allowed GCs during insertion, then the following events
368    // could happen:
369    //
370    // * Reference A is inserted into the activations table. This does not
371    //   trigger a GC, but does fill the table to capacity.
372    //
373    // * The caller's reference to A is removed. Now the only reference to A is
374    //   from the activations table.
375    //
376    // * Reference B is inserted into the activations table. Because the table
377    //   is at capacity, a GC is triggered.
378    //
379    // * A is reclaimed because the only reference keeping it alive was the
380    //   activation table's reference (it isn't inside any Wasm frames on the
381    //   stack yet, so stack scanning and stack maps don't increment its
382    //   reference count).
383    //
384    // * We transfer control to Wasm, giving it A and B. Wasm uses A. That's a
385    //   use-after-free bug.
386    //
387    // In conclusion, to prevent uses-after-free bugs, we cannot GC while
388    // converting types into their raw ABI forms.
389    #[doc(hidden)]
390    fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()>;
391
392    // Load a version of `Self` from the `ptr` provided.
393    //
394    // # Safety
395    //
396    // This function is unsafe as it's up to the caller to ensure that `ptr` is
397    // valid for this given type.
398    #[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            // `(ref null nofunc) <: (ref null $f)` for all function types `$f`.
522            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        // SAFETY: it's an unsafe contract of `load` that it's only provided
575        // valid wasm values owned by `store`.
576        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        // SAFETY: it's an unsafe contract of `load` that it's only provided
630        // valid wasm values owned by `store`.
631        unsafe { Some(Func::from_vm_func_ref(store.id(), ptr)) }
632    }
633}
634
635/// A trait used for [`Func::typed`] and with [`TypedFunc`] to represent the set of
636/// parameters for wasm functions.
637///
638/// This is implemented for bare types that can be passed to wasm as well as
639/// tuples of those types.
640pub 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
663// Forward an impl from `T` to `(T,)` for convenience if there's only one
664// parameter.
665unsafe 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
773/// A trait used for [`Func::typed`] and with [`TypedFunc`] to represent the set of
774/// results for wasm functions.
775pub unsafe trait WasmResults: WasmParams {
776    #[doc(hidden)]
777    unsafe fn load(store: &mut AutoAssertNoGc<'_>, abi: &Self::ValRawStorage) -> Self;
778}
779
780// Forwards from a bare type `T` to the 1-tuple type `(T,)`
781unsafe impl<T: WasmTy> WasmResults for T {
782    unsafe fn load(store: &mut AutoAssertNoGc<'_>, abi: &Self::ValRawStorage) -> Self {
783        // SAFETY: the one-element tuple and single-type impls behave the same
784        // way.
785        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                    // SAFETY: this is forwarding the unsafe contract of the outer
798                    // function to the inner functions here.
799                    $(unsafe { $t::load(_store, $t) },)*
800                )
801            }
802        }
803    };
804}
805
806for_each_function_signature!(impl_wasm_results);