Skip to main content

wasmtime/runtime/
func.rs

1use crate::error::OutOfMemory;
2use crate::prelude::*;
3use crate::runtime::vm::{
4    self, InterpreterRef, SendSyncPtr, StoreBox, UncaughtException, VMArrayCallHostFuncContext,
5    VMCommonStackInformation, VMContext, VMFuncRef, VMFunctionImport, VMOpaqueContext,
6    VMStoreContext, VmPtr,
7};
8use crate::store::{Asyncness, AutoAssertNoGc, InstanceId, StoreId, StoreOpaque};
9use crate::type_registry::RegisteredType;
10use crate::{
11    AsContext, AsContextMut, CallHook, Engine, Extern, FuncType, Instance, ModuleExport, Ref,
12    StoreContext, StoreContextMut, Val, ValRaw, ValType,
13};
14use alloc::sync::Arc;
15use core::convert::Infallible;
16use core::ffi::c_void;
17#[cfg(feature = "async")]
18use core::future::Future;
19use core::mem::{self, MaybeUninit};
20use core::ptr::NonNull;
21use wasmtime_environ::{PanicOnOom as _, VMSharedTypeIndex};
22
23/// A reference to the abstract `nofunc` heap value.
24///
25/// The are no instances of `(ref nofunc)`: it is an uninhabited type.
26///
27/// There is precisely one instance of `(ref null nofunc)`, aka `nullfuncref`:
28/// the null reference.
29///
30/// This `NoFunc` Rust type's sole purpose is for use with [`Func::wrap`]- and
31/// [`Func::typed`]-style APIs for statically typing a function as taking or
32/// returning a `(ref null nofunc)` (aka `Option<NoFunc>`) which is always
33/// `None`.
34///
35/// # Example
36///
37/// ```
38/// # use wasmtime::*;
39/// # fn _foo() -> Result<()> {
40/// let mut config = Config::new();
41/// config.wasm_function_references(true);
42/// let engine = Engine::new(&config)?;
43///
44/// let module = Module::new(
45///     &engine,
46///     r#"
47///         (module
48///             (func (export "f") (param (ref null nofunc))
49///                 ;; If the reference is null, return.
50///                 local.get 0
51///                 ref.is_null nofunc
52///                 br_if 0
53///
54///                 ;; If the reference was not null (which is impossible)
55///                 ;; then raise a trap.
56///                 unreachable
57///             )
58///         )
59///     "#,
60/// )?;
61///
62/// let mut store = Store::new(&engine, ());
63/// let instance = Instance::new(&mut store, &module, &[])?;
64/// let f = instance.get_func(&mut store, "f").unwrap();
65///
66/// // We can cast a `(ref null nofunc)`-taking function into a typed function that
67/// // takes an `Option<NoFunc>` via the `Func::typed` method.
68/// let f = f.typed::<Option<NoFunc>, ()>(&store)?;
69///
70/// // We can call the typed function, passing the null `nofunc` reference.
71/// let result = f.call(&mut store, NoFunc::null());
72///
73/// // The function should not have trapped, because the reference we gave it was
74/// // null (as it had to be, since `NoFunc` is uninhabited).
75/// assert!(result.is_ok());
76/// # Ok(())
77/// # }
78/// ```
79#[derive(Copy, Clone, Debug, PartialEq, Eq)]
80pub struct NoFunc {
81    _inner: Infallible,
82}
83
84impl NoFunc {
85    /// Get the null `(ref null nofunc)` (aka `nullfuncref`) reference.
86    #[inline]
87    pub fn null() -> Option<NoFunc> {
88        None
89    }
90
91    /// Get the null `(ref null nofunc)` (aka `nullfuncref`) reference as a
92    /// [`Ref`].
93    #[inline]
94    pub fn null_ref() -> Ref {
95        Ref::Func(None)
96    }
97
98    /// Get the null `(ref null nofunc)` (aka `nullfuncref`) reference as a
99    /// [`Val`].
100    #[inline]
101    pub fn null_val() -> Val {
102        Val::FuncRef(None)
103    }
104}
105
106/// A WebAssembly function which can be called.
107///
108/// This type typically represents an exported function from a WebAssembly
109/// module instance. In this case a [`Func`] belongs to an [`Instance`] and is
110/// loaded from there. A [`Func`] may also represent a host function as well in
111/// some cases, too.
112///
113/// Functions can be called in a few different ways, either synchronous or async
114/// and either typed or untyped (more on this below). Note that host functions
115/// are normally inserted directly into a [`Linker`](crate::Linker) rather than
116/// using this directly, but both options are available.
117///
118/// # `Func` and `async`
119///
120/// Functions from the perspective of WebAssembly are always synchronous. You
121/// might have an `async` function in Rust, however, which you'd like to make
122/// available from WebAssembly. Wasmtime supports asynchronously calling
123/// WebAssembly through native stack switching. You can get some more
124/// information about [asynchronous configs](crate#async), but
125/// from the perspective of `Func` it's important to know that whether or not
126/// your [`Store`](crate::Store) is asynchronous will dictate whether you call
127/// functions through [`Func::call`] or [`Func::call_async`] (or the typed
128/// wrappers such as [`TypedFunc::call`] vs [`TypedFunc::call_async`]).
129///
130/// # To `Func::call` or to `Func::typed().call()`
131///
132/// There's a 2x2 matrix of methods to call [`Func`]. Invocations can either be
133/// asynchronous or synchronous. They can also be statically typed or not.
134/// Whether or not an invocation is asynchronous is indicated via the method
135/// being `async` and [`call_async`](Func::call_async) being the entry point.
136/// Otherwise for statically typed or not your options are:
137///
138/// * Dynamically typed - if you don't statically know the signature of the
139///   function that you're calling you'll be using [`Func::call`] or
140///   [`Func::call_async`]. These functions take a variable-length slice of
141///   "boxed" arguments in their [`Val`] representation. Additionally the
142///   results are returned as an owned slice of [`Val`]. These methods are not
143///   optimized due to the dynamic type checks that must occur, in addition to
144///   some dynamic allocations for where to put all the arguments. While this
145///   allows you to call all possible wasm function signatures, if you're
146///   looking for a speedier alternative you can also use...
147///
148/// * Statically typed - if you statically know the type signature of the wasm
149///   function you're calling, then you'll want to use the [`Func::typed`]
150///   method to acquire an instance of [`TypedFunc`]. This structure is static proof
151///   that the underlying wasm function has the ascripted type, and type
152///   validation is only done once up-front. The [`TypedFunc::call`] and
153///   [`TypedFunc::call_async`] methods are much more efficient than [`Func::call`]
154///   and [`Func::call_async`] because the type signature is statically known.
155///   This eschews runtime checks as much as possible to get into wasm as fast
156///   as possible.
157///
158/// # Examples
159///
160/// One way to get a `Func` is from an [`Instance`] after you've instantiated
161/// it:
162///
163/// ```
164/// # use wasmtime::*;
165/// # fn main() -> Result<()> {
166/// let engine = Engine::default();
167/// let module = Module::new(&engine, r#"(module (func (export "foo")))"#)?;
168/// let mut store = Store::new(&engine, ());
169/// let instance = Instance::new(&mut store, &module, &[])?;
170/// let foo = instance.get_func(&mut store, "foo").expect("export wasn't a function");
171///
172/// // Work with `foo` as a `Func` at this point, such as calling it
173/// // dynamically...
174/// match foo.call(&mut store, &[], &mut []) {
175///     Ok(()) => { /* ... */ }
176///     Err(trap) => {
177///         panic!("execution of `foo` resulted in a wasm trap: {}", trap);
178///     }
179/// }
180/// foo.call(&mut store, &[], &mut [])?;
181///
182/// // ... or we can make a static assertion about its signature and call it.
183/// // Our first call here can fail if the signatures don't match, and then the
184/// // second call can fail if the function traps (like the `match` above).
185/// let foo = foo.typed::<(), ()>(&store)?;
186/// foo.call(&mut store, ())?;
187/// # Ok(())
188/// # }
189/// ```
190///
191/// You can also use the [`wrap` function](Func::wrap) to create a
192/// `Func`
193///
194/// ```
195/// # use wasmtime::*;
196/// # fn main() -> Result<()> {
197/// let mut store = Store::<()>::default();
198///
199/// // Create a custom `Func` which can execute arbitrary code inside of the
200/// // closure.
201/// let add = Func::wrap(&mut store, |a: i32, b: i32| -> i32 { a + b });
202///
203/// // Next we can hook that up to a wasm module which uses it.
204/// let module = Module::new(
205///     store.engine(),
206///     r#"
207///         (module
208///             (import "" "" (func $add (param i32 i32) (result i32)))
209///             (func (export "call_add_twice") (result i32)
210///                 i32.const 1
211///                 i32.const 2
212///                 call $add
213///                 i32.const 3
214///                 i32.const 4
215///                 call $add
216///                 i32.add))
217///     "#,
218/// )?;
219/// let instance = Instance::new(&mut store, &module, &[add.into()])?;
220/// let call_add_twice = instance.get_typed_func::<(), i32>(&mut store, "call_add_twice")?;
221///
222/// assert_eq!(call_add_twice.call(&mut store, ())?, 10);
223/// # Ok(())
224/// # }
225/// ```
226///
227/// Or you could also create an entirely dynamic `Func`!
228///
229/// ```
230/// # use wasmtime::*;
231/// # fn main() -> Result<()> {
232/// let mut store = Store::<()>::default();
233///
234/// // Here we need to define the type signature of our `Double` function and
235/// // then wrap it up in a `Func`
236/// let double_type = wasmtime::FuncType::new(
237///     store.engine(),
238///     [wasmtime::ValType::I32].iter().cloned(),
239///     [wasmtime::ValType::I32].iter().cloned(),
240/// );
241/// let double = Func::new(&mut store, double_type, |_, params, results| {
242///     let mut value = params[0].unwrap_i32();
243///     value *= 2;
244///     results[0] = value.into();
245///     Ok(())
246/// });
247///
248/// let module = Module::new(
249///     store.engine(),
250///     r#"
251///         (module
252///             (import "" "" (func $double (param i32) (result i32)))
253///             (func $start
254///                 i32.const 1
255///                 call $double
256///                 drop)
257///             (start $start))
258///     "#,
259/// )?;
260/// let instance = Instance::new(&mut store, &module, &[double.into()])?;
261/// // .. work with `instance` if necessary
262/// # Ok(())
263/// # }
264/// ```
265#[derive(Copy, Clone, Debug)]
266#[repr(C)] // here for the C API
267pub struct Func {
268    /// The store that the below pointer belongs to.
269    ///
270    /// It's only safe to look at the contents of the pointer below when the
271    /// `StoreOpaque` matching this id is in-scope.
272    store: StoreId,
273
274    /// The raw `VMFuncRef`, whose lifetime is bound to the store this func
275    /// belongs to.
276    ///
277    /// Note that this field has an `unsafe_*` prefix to discourage use of it.
278    /// This is only safe to read/use if `self.store` is validated to belong to
279    /// an ambiently provided `StoreOpaque` or similar. Use the
280    /// `self.vm_func_ref()` method instead of this field to perform this check.
281    unsafe_func_ref: SendSyncPtr<VMFuncRef>,
282}
283
284// Double-check that the C representation in `extern.h` matches our in-Rust
285// representation here in terms of size/alignment/etc.
286const _: () = {
287    #[repr(C)]
288    struct C(u64, *mut u8);
289    assert!(core::mem::size_of::<C>() == core::mem::size_of::<Func>());
290    assert!(core::mem::align_of::<C>() == core::mem::align_of::<Func>());
291    assert!(core::mem::offset_of!(Func, store) == 0);
292};
293
294macro_rules! for_each_function_signature {
295    ($mac:ident) => {
296        $mac!(0);
297        $mac!(1 A1);
298        $mac!(2 A1 A2);
299        $mac!(3 A1 A2 A3);
300        $mac!(4 A1 A2 A3 A4);
301        $mac!(5 A1 A2 A3 A4 A5);
302        $mac!(6 A1 A2 A3 A4 A5 A6);
303        $mac!(7 A1 A2 A3 A4 A5 A6 A7);
304        $mac!(8 A1 A2 A3 A4 A5 A6 A7 A8);
305        $mac!(9 A1 A2 A3 A4 A5 A6 A7 A8 A9);
306        $mac!(10 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10);
307        $mac!(11 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11);
308        $mac!(12 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12);
309        $mac!(13 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13);
310        $mac!(14 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14);
311        $mac!(15 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 A15);
312        $mac!(16 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 A15 A16);
313        $mac!(17 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 A15 A16 A17);
314    };
315}
316
317mod typed;
318use crate::runtime::vm::VMStackChain;
319pub use typed::*;
320
321impl Func {
322    /// Creates a new `Func` with the given arguments, typically to create a
323    /// host-defined function to pass as an import to a module.
324    ///
325    /// * `store` - the store in which to create this [`Func`], which will own
326    ///   the return value.
327    ///
328    /// * `ty` - the signature of this function, used to indicate what the
329    ///   inputs and outputs are.
330    ///
331    /// * `func` - the native code invoked whenever this `Func` will be called.
332    ///   This closure is provided a [`Caller`] as its first argument to learn
333    ///   information about the caller, and then it's passed a list of
334    ///   parameters as a slice along with a mutable slice of where to write
335    ///   results.
336    ///
337    /// Note that the implementation of `func` must adhere to the `ty` signature
338    /// given, error or traps may occur if it does not respect the `ty`
339    /// signature. For example if the function type declares that it returns one
340    /// i32 but the `func` closures does not write anything into the results
341    /// slice then a trap may be generated.
342    ///
343    /// Additionally note that this is quite a dynamic function since signatures
344    /// are not statically known. For a more performant and ergonomic `Func`
345    /// it's recommended to use [`Func::wrap`] if you can because with
346    /// statically known signatures Wasmtime can optimize the implementation
347    /// much more.
348    ///
349    /// For more information about `Send + Sync + 'static` requirements on the
350    /// `func`, see [`Func::wrap`](#why-send--sync--static).
351    ///
352    /// # Errors
353    ///
354    /// The host-provided function here returns a
355    /// [`Result<()>`](crate::Result). If the function returns `Ok(())` then
356    /// that indicates that the host function completed successfully and wrote
357    /// the result into the `&mut [Val]` argument.
358    ///
359    /// If the function returns `Err(e)`, however, then this is equivalent to
360    /// the host function triggering a trap for wasm. WebAssembly execution is
361    /// immediately halted and the original caller of [`Func::call`], for
362    /// example, will receive the error returned here (possibly with
363    /// [`WasmBacktrace`](crate::WasmBacktrace) context information attached).
364    ///
365    /// For more information about errors in Wasmtime see the [`Trap`]
366    /// documentation.
367    ///
368    /// [`Trap`]: crate::Trap
369    ///
370    /// # Panics
371    ///
372    /// Panics if the given function type is not associated with this store's
373    /// engine.
374    pub fn new<T: 'static>(
375        store: impl AsContextMut<Data = T>,
376        ty: FuncType,
377        func: impl Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()> + Send + Sync + 'static,
378    ) -> Self {
379        Self::try_new_(store, ty, func).panic_on_oom()
380    }
381
382    /// Same as [`Func::new`] but returns an error instead of panicking on
383    /// allocation failure.
384    ///
385    /// # Errors
386    ///
387    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
388    /// memory allocation fails. See the `OutOfMemory` type's documentation for
389    /// details on Wasmtime's out-of-memory handling.
390    pub fn try_new<T: 'static>(
391        store: impl AsContextMut<Data = T>,
392        ty: FuncType,
393        func: impl Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()> + Send + Sync + 'static,
394    ) -> Result<Self> {
395        Ok(Self::try_new_(store, ty, func)?)
396    }
397
398    fn try_new_<T: 'static>(
399        mut store: impl AsContextMut<Data = T>,
400        ty: FuncType,
401        func: impl Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()> + Send + Sync + 'static,
402    ) -> Result<Self, OutOfMemory> {
403        let store = store.as_context_mut().0;
404        let host = HostFunc::new(store.engine(), ty, func)?;
405
406        // SAFETY: the `T` used by `func` matches the `T` of the store we're
407        // inserting into via this function's type signature.
408        unsafe { host.into_func(store) }
409    }
410
411    /// Creates a new [`Func`] with the given arguments, although has fewer
412    /// runtime checks than [`Func::new`].
413    ///
414    /// This function takes a callback of a different signature than
415    /// [`Func::new`], instead receiving a raw pointer with a list of [`ValRaw`]
416    /// structures. These values have no type information associated with them
417    /// so it's up to the caller to provide a function that will correctly
418    /// interpret the list of values as those coming from the `ty` specified.
419    ///
420    /// If you're calling this from Rust it's recommended to either instead use
421    /// [`Func::new`] or [`Func::wrap`]. The [`Func::wrap`] API, in particular,
422    /// is both safer and faster than this API.
423    ///
424    /// # Errors
425    ///
426    /// See [`Func::new`] for the behavior of returning an error from the host
427    /// function provided here.
428    ///
429    /// # Unsafety
430    ///
431    /// This function is not safe because it's not known at compile time that
432    /// the `func` provided correctly interprets the argument types provided to
433    /// it, or that the results it produces will be of the correct type.
434    ///
435    /// # Panics
436    ///
437    /// Panics if the given function type is not associated with this store's
438    /// engine.
439    pub unsafe fn new_unchecked<T: 'static>(
440        mut store: impl AsContextMut<Data = T>,
441        ty: FuncType,
442        func: impl Fn(Caller<'_, T>, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync + 'static,
443    ) -> Self {
444        let store = store.as_context_mut().0;
445
446        // SAFETY: the contract required by `new_unchecked` is the same as the
447        // contract required by this function itself.
448        let host = unsafe { HostFunc::new_unchecked(store.engine(), ty, func).panic_on_oom() };
449
450        // SAFETY: the `T` used by `func` matches the `T` of the store we're
451        // inserting into via this function's type signature.
452        unsafe { host.into_func(store).panic_on_oom() }
453    }
454
455    /// Creates a new host-defined WebAssembly function which, when called,
456    /// will run the asynchronous computation defined by `func` to completion
457    /// and then return the result to WebAssembly.
458    ///
459    /// This function is the asynchronous analogue of [`Func::new`] and much of
460    /// that documentation applies to this as well. The key difference is that
461    /// `func` returns a future instead of simply a `Result`. Note that the
462    /// returned future can close over any of the arguments, but it cannot close
463    /// over the state of the closure itself. It's recommended to store any
464    /// necessary async state in the `T` of the [`Store<T>`](crate::Store) which
465    /// can be accessed through [`Caller::data`] or [`Caller::data_mut`].
466    ///
467    /// For more information on `Send + Sync + 'static`, see
468    /// [`Func::wrap`](#why-send--sync--static).
469    ///
470    /// # Panics
471    ///
472    /// Panics if the given function type is not associated with this store's
473    /// engine.
474    ///
475    /// # Errors
476    ///
477    /// See [`Func::new`] for the behavior of returning an error from the host
478    /// function provided here.
479    ///
480    /// # Examples
481    ///
482    /// ```
483    /// # use wasmtime::*;
484    /// # fn main() -> Result<()> {
485    /// // Simulate some application-specific state as well as asynchronous
486    /// // functions to query that state.
487    /// struct MyDatabase {
488    ///     // ...
489    /// }
490    ///
491    /// impl MyDatabase {
492    ///     async fn get_row_count(&self) -> u32 {
493    ///         // ...
494    /// #       100
495    ///     }
496    /// }
497    ///
498    /// let my_database = MyDatabase {
499    ///     // ...
500    /// };
501    ///
502    /// // Using `new_async` we can hook up into calling our async
503    /// // `get_row_count` function.
504    /// let engine = Engine::default();
505    /// let mut store = Store::new(&engine, MyDatabase {
506    ///     // ...
507    /// });
508    /// let get_row_count_type = wasmtime::FuncType::new(
509    ///     &engine,
510    ///     None,
511    ///     Some(wasmtime::ValType::I32),
512    /// );
513    /// let get = Func::new_async(&mut store, get_row_count_type, |caller, _params, results| {
514    ///     Box::new(async move {
515    ///         let count = caller.data().get_row_count().await;
516    ///         results[0] = Val::I32(count as i32);
517    ///         Ok(())
518    ///     })
519    /// });
520    /// // ...
521    /// # Ok(())
522    /// # }
523    /// ```
524    #[cfg(feature = "async")]
525    pub fn new_async<T, F>(mut store: impl AsContextMut<Data = T>, ty: FuncType, func: F) -> Func
526    where
527        F: for<'a> Fn(
528                Caller<'a, T>,
529                &'a [Val],
530                &'a mut [Val],
531            ) -> Box<dyn Future<Output = Result<()>> + Send + 'a>
532            + Send
533            + Sync
534            + 'static,
535        T: Send + 'static,
536    {
537        let store = store.as_context_mut().0;
538
539        let host = HostFunc::new_async(store.engine(), ty, func).panic_on_oom();
540
541        // SAFETY: the `T` used by `func` matches the `T` of the store we're
542        // inserting into via this function's type signature.
543        unsafe { host.into_func(store).panic_on_oom() }
544    }
545
546    /// Creates a new `Func` from a store and a funcref within that store.
547    ///
548    /// # Safety
549    ///
550    /// The safety of this function requires that `func_ref` is a valid function
551    /// pointer owned by `store`.
552    pub(crate) unsafe fn from_vm_func_ref(store: StoreId, func_ref: NonNull<VMFuncRef>) -> Func {
553        // SAFETY: given the contract of this function it's safe to read the
554        // `type_index` field.
555        unsafe {
556            debug_assert!(func_ref.as_ref().type_index != VMSharedTypeIndex::default());
557        }
558        Func {
559            store,
560            unsafe_func_ref: func_ref.into(),
561        }
562    }
563
564    /// Creates a new `Func` from the given Rust closure.
565    ///
566    /// This function will create a new `Func` which, when called, will
567    /// execute the given Rust closure. Unlike [`Func::new`] the target
568    /// function being called is known statically so the type signature can
569    /// be inferred. Rust types will map to WebAssembly types as follows:
570    ///
571    /// | Rust Argument Type                | WebAssembly Type                          |
572    /// |-----------------------------------|-------------------------------------------|
573    /// | `i32`                             | `i32`                                     |
574    /// | `u32`                             | `i32`                                     |
575    /// | `i64`                             | `i64`                                     |
576    /// | `u64`                             | `i64`                                     |
577    /// | `f32`                             | `f32`                                     |
578    /// | `f64`                             | `f64`                                     |
579    /// | `V128` on x86-64 and aarch64 only | `v128`                                    |
580    /// | `Option<Func>`                    | `funcref` aka `(ref null func)`           |
581    /// | `Func`                            | `(ref func)`                              |
582    /// | `Option<Nofunc>`                  | `nullfuncref` aka `(ref null nofunc)`     |
583    /// | `NoFunc`                          | `(ref nofunc)`                            |
584    /// | `Option<Rooted<ExternRef>>`       | `externref` aka `(ref null extern)`       |
585    /// | `Rooted<ExternRef>`               | `(ref extern)`                            |
586    /// | `Option<NoExtern>`                | `nullexternref` aka `(ref null noextern)` |
587    /// | `NoExtern`                        | `(ref noextern)`                          |
588    /// | `Option<Rooted<AnyRef>>`          | `anyref` aka `(ref null any)`             |
589    /// | `Rooted<AnyRef>`                  | `(ref any)`                               |
590    /// | `Option<Rooted<EqRef>>`           | `eqref` aka `(ref null eq)`               |
591    /// | `Rooted<EqRef>`                   | `(ref eq)`                                |
592    /// | `Option<I31>`                     | `i31ref` aka `(ref null i31)`             |
593    /// | `I31`                             | `(ref i31)`                               |
594    /// | `Option<Rooted<StructRef>>`       | `(ref null struct)`                       |
595    /// | `Rooted<StructRef>`               | `(ref struct)`                            |
596    /// | `Option<Rooted<ArrayRef>>`        | `(ref null array)`                        |
597    /// | `Rooted<ArrayRef>`                | `(ref array)`                             |
598    /// | `Option<NoneRef>`                 | `nullref` aka `(ref null none)`           |
599    /// | `NoneRef`                         | `(ref none)`                              |
600    ///
601    /// Note that anywhere a `Rooted<T>` appears, a `OwnedRooted<T>` may also
602    /// be used.
603    ///
604    /// Any of the Rust types can be returned from the closure as well, in
605    /// addition to some extra types
606    ///
607    /// | Rust Return Type  | WebAssembly Return Type | Meaning               |
608    /// |-------------------|-------------------------|-----------------------|
609    /// | `()`              | nothing                 | no return value       |
610    /// | `T`               | `T`                     | a single return value |
611    /// | `(T1, T2, ...)`   | `T1 T2 ...`             | multiple returns      |
612    ///
613    /// Note that all return types can also be wrapped in `Result<_>` to
614    /// indicate that the host function can generate a trap as well as possibly
615    /// returning a value.
616    ///
617    /// Finally you can also optionally take [`Caller`] as the first argument of
618    /// your closure. If inserted then you're able to inspect the caller's
619    /// state, for example the [`Memory`](crate::Memory) it has exported so you
620    /// can read what pointers point to.
621    ///
622    /// Note that when using this API, the intention is to create as thin of a
623    /// layer as possible for when WebAssembly calls the function provided. With
624    /// sufficient inlining and optimization the WebAssembly will call straight
625    /// into `func` provided, with no extra fluff entailed.
626    ///
627    /// # Why `Send + Sync + 'static`?
628    ///
629    /// All host functions defined in a [`Store`](crate::Store) (including
630    /// those from [`Func::new`] and other constructors) require that the
631    /// `func` provided is `Send + Sync + 'static`. Additionally host functions
632    /// always are `Fn` as opposed to `FnMut` or `FnOnce`. This can at-a-glance
633    /// feel restrictive since the closure cannot close over as many types as
634    /// before. The reason for this, though, is to ensure that
635    /// [`Store<T>`](crate::Store) can implement both the `Send` and `Sync`
636    /// traits.
637    ///
638    /// Fear not, however, because this isn't as restrictive as it seems! Host
639    /// functions are provided a [`Caller<'_, T>`](crate::Caller) argument which
640    /// allows access to the host-defined data within the
641    /// [`Store`](crate::Store). The `T` type is not required to be any of
642    /// `Send`, `Sync`, or `'static`! This means that you can store whatever
643    /// you'd like in `T` and have it accessible by all host functions.
644    /// Additionally mutable access to `T` is allowed through
645    /// [`Caller::data_mut`].
646    ///
647    /// Most host-defined [`Func`] values provide closures that end up not
648    /// actually closing over any values. These zero-sized types will use the
649    /// context from [`Caller`] for host-defined information.
650    ///
651    /// # Errors
652    ///
653    /// The closure provided here to `wrap` can optionally return a
654    /// [`Result<T>`](crate::Result). Returning `Ok(t)` represents the host
655    /// function successfully completing with the `t` result. Returning
656    /// `Err(e)`, however, is equivalent to raising a custom wasm trap.
657    /// Execution of WebAssembly does not resume and the stack is unwound to the
658    /// original caller of the function where the error is returned.
659    ///
660    /// For more information about errors in Wasmtime see the [`Trap`]
661    /// documentation.
662    ///
663    /// [`Trap`]: crate::Trap
664    ///
665    /// # Examples
666    ///
667    /// First up we can see how simple wasm imports can be implemented, such
668    /// as a function that adds its two arguments and returns the result.
669    ///
670    /// ```
671    /// # use wasmtime::*;
672    /// # fn main() -> Result<()> {
673    /// # let mut store = Store::<()>::default();
674    /// let add = Func::wrap(&mut store, |a: i32, b: i32| a + b);
675    /// let module = Module::new(
676    ///     store.engine(),
677    ///     r#"
678    ///         (module
679    ///             (import "" "" (func $add (param i32 i32) (result i32)))
680    ///             (func (export "foo") (param i32 i32) (result i32)
681    ///                 local.get 0
682    ///                 local.get 1
683    ///                 call $add))
684    ///     "#,
685    /// )?;
686    /// let instance = Instance::new(&mut store, &module, &[add.into()])?;
687    /// let foo = instance.get_typed_func::<(i32, i32), i32>(&mut store, "foo")?;
688    /// assert_eq!(foo.call(&mut store, (1, 2))?, 3);
689    /// # Ok(())
690    /// # }
691    /// ```
692    ///
693    /// We can also do the same thing, but generate a trap if the addition
694    /// overflows:
695    ///
696    /// ```
697    /// # use wasmtime::*;
698    /// # fn main() -> Result<()> {
699    /// # let mut store = Store::<()>::default();
700    /// let add = Func::wrap(&mut store, |a: i32, b: i32| {
701    ///     match a.checked_add(b) {
702    ///         Some(i) => Ok(i),
703    ///         None => bail!("overflow"),
704    ///     }
705    /// });
706    /// let module = Module::new(
707    ///     store.engine(),
708    ///     r#"
709    ///         (module
710    ///             (import "" "" (func $add (param i32 i32) (result i32)))
711    ///             (func (export "foo") (param i32 i32) (result i32)
712    ///                 local.get 0
713    ///                 local.get 1
714    ///                 call $add))
715    ///     "#,
716    /// )?;
717    /// let instance = Instance::new(&mut store, &module, &[add.into()])?;
718    /// let foo = instance.get_typed_func::<(i32, i32), i32>(&mut store, "foo")?;
719    /// assert_eq!(foo.call(&mut store, (1, 2))?, 3);
720    /// assert!(foo.call(&mut store, (i32::MAX, 1)).is_err());
721    /// # Ok(())
722    /// # }
723    /// ```
724    ///
725    /// And don't forget all the wasm types are supported!
726    ///
727    /// ```
728    /// # use wasmtime::*;
729    /// # fn main() -> Result<()> {
730    /// # let mut store = Store::<()>::default();
731    /// let debug = Func::wrap(&mut store, |a: i32, b: u32, c: f32, d: i64, e: u64, f: f64| {
732    ///
733    ///     println!("a={}", a);
734    ///     println!("b={}", b);
735    ///     println!("c={}", c);
736    ///     println!("d={}", d);
737    ///     println!("e={}", e);
738    ///     println!("f={}", f);
739    /// });
740    /// let module = Module::new(
741    ///     store.engine(),
742    ///     r#"
743    ///         (module
744    ///             (import "" "" (func $debug (param i32 i32 f32 i64 i64 f64)))
745    ///             (func (export "foo")
746    ///                 i32.const -1
747    ///                 i32.const 1
748    ///                 f32.const 2
749    ///                 i64.const -3
750    ///                 i64.const 3
751    ///                 f64.const 4
752    ///                 call $debug))
753    ///     "#,
754    /// )?;
755    /// let instance = Instance::new(&mut store, &module, &[debug.into()])?;
756    /// let foo = instance.get_typed_func::<(), ()>(&mut store, "foo")?;
757    /// foo.call(&mut store, ())?;
758    /// # Ok(())
759    /// # }
760    /// ```
761    ///
762    /// Finally if you want to get really fancy you can also implement
763    /// imports that read/write wasm module's memory
764    ///
765    /// ```
766    /// use std::str;
767    ///
768    /// # use wasmtime::*;
769    /// # fn main() -> Result<()> {
770    /// # let mut store = Store::default();
771    /// let log_str = Func::wrap(&mut store, |mut caller: Caller<'_, ()>, ptr: i32, len: i32| {
772    ///     let mem = match caller.get_export("memory") {
773    ///         Some(Extern::Memory(mem)) => mem,
774    ///         _ => bail!("failed to find host memory"),
775    ///     };
776    ///     let data = mem.data(&caller)
777    ///         .get(ptr as u32 as usize..)
778    ///         .and_then(|arr| arr.get(..len as u32 as usize));
779    ///     let string = match data {
780    ///         Some(data) => match str::from_utf8(data) {
781    ///             Ok(s) => s,
782    ///             Err(_) => bail!("invalid utf-8"),
783    ///         },
784    ///         None => bail!("pointer/length out of bounds"),
785    ///     };
786    ///     assert_eq!(string, "Hello, world!");
787    ///     println!("{}", string);
788    ///     Ok(())
789    /// });
790    /// let module = Module::new(
791    ///     store.engine(),
792    ///     r#"
793    ///         (module
794    ///             (import "" "" (func $log_str (param i32 i32)))
795    ///             (func (export "foo")
796    ///                 i32.const 4   ;; ptr
797    ///                 i32.const 13  ;; len
798    ///                 call $log_str)
799    ///             (memory (export "memory") 1)
800    ///             (data (i32.const 4) "Hello, world!"))
801    ///     "#,
802    /// )?;
803    /// let instance = Instance::new(&mut store, &module, &[log_str.into()])?;
804    /// let foo = instance.get_typed_func::<(), ()>(&mut store, "foo")?;
805    /// foo.call(&mut store, ())?;
806    /// # Ok(())
807    /// # }
808    /// ```
809    pub fn wrap<T, Params, Results>(
810        store: impl AsContextMut<Data = T>,
811        func: impl IntoFunc<T, Params, Results>,
812    ) -> Func
813    where
814        T: 'static,
815    {
816        Self::try_wrap(store, func).expect(
817            "allocation failure during `Func::wrap` (use `Func::try_wrap` to handle such errors)",
818        )
819    }
820
821    /// Fallible version of [`Func::wrap`] that returns an error on
822    /// out-of-memory instead of panicking.
823    ///
824    /// # Errors
825    ///
826    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
827    /// memory allocation fails. See the `OutOfMemory` type's documentation for
828    /// details on Wasmtime's out-of-memory handling.
829    pub fn try_wrap<T, Params, Results>(
830        mut store: impl AsContextMut<Data = T>,
831        func: impl IntoFunc<T, Params, Results>,
832    ) -> Result<Func>
833    where
834        T: 'static,
835    {
836        let store = store.as_context_mut().0;
837        let engine = store.engine();
838        let host = func.into_func(engine)?;
839
840        // SAFETY: The `T` the closure takes is the same as the `T` of the store
841        // we're inserting into via the type signature above.
842        Ok(unsafe { host.into_func(store)? })
843    }
844
845    /// Same as [`Func::wrap`], except the closure asynchronously produces the
846    /// result and the arguments are passed within a tuple. For more information
847    /// see the [`Func`] documentation.
848    #[cfg(feature = "async")]
849    pub fn wrap_async<T, F, P, R>(mut store: impl AsContextMut<Data = T>, func: F) -> Func
850    where
851        F: for<'a> Fn(Caller<'a, T>, P) -> Box<dyn Future<Output = R> + Send + 'a>
852            + Send
853            + Sync
854            + 'static,
855        P: WasmTyList,
856        R: WasmRet,
857        T: Send + 'static,
858    {
859        let store = store.as_context_mut().0;
860        let host = HostFunc::wrap_async(store.engine(), func).panic_on_oom();
861
862        // SAFETY: The `T` the closure takes is the same as the `T` of the store
863        // we're inserting into via the type signature above.
864        unsafe { host.into_func(store).panic_on_oom() }
865    }
866
867    /// Returns the underlying wasm type that this `Func` has.
868    ///
869    /// # Panics
870    ///
871    /// Panics if `store` does not own this function.
872    pub fn ty(&self, store: impl AsContext) -> FuncType {
873        self.load_ty(&store.as_context().0)
874    }
875
876    /// Forcibly loads the type of this function from the `Engine`.
877    ///
878    /// Note that this is a somewhat expensive method since it requires taking a
879    /// lock as well as cloning a type.
880    pub(crate) fn load_ty(&self, store: &StoreOpaque) -> FuncType {
881        FuncType::from_shared_type_index(store.engine(), self.type_index(store)).unwrap()
882    }
883
884    /// Does this function match the given type?
885    ///
886    /// That is, is this function's type a subtype of the given type?
887    ///
888    /// # Panics
889    ///
890    /// Panics if this function is not associated with the given store or if the
891    /// function type is not associated with the store's engine.
892    pub fn matches_ty(&self, store: impl AsContext, func_ty: &FuncType) -> bool {
893        self._matches_ty(store.as_context().0, func_ty)
894    }
895
896    pub(crate) fn _matches_ty(&self, store: &StoreOpaque, func_ty: &FuncType) -> bool {
897        let actual_ty = self.load_ty(store);
898        actual_ty.matches(func_ty)
899    }
900
901    pub(crate) fn ensure_matches_ty(&self, store: &StoreOpaque, func_ty: &FuncType) -> Result<()> {
902        if !self.comes_from_same_store(store) {
903            bail!("function used with wrong store");
904        }
905        if self._matches_ty(store, func_ty) {
906            Ok(())
907        } else {
908            let actual_ty = self.load_ty(store);
909            bail!("type mismatch: expected {func_ty}, found {actual_ty}")
910        }
911    }
912
913    pub(crate) fn type_index(&self, data: &StoreOpaque) -> VMSharedTypeIndex {
914        unsafe { self.vm_func_ref(data).as_ref().type_index }
915    }
916
917    /// Invokes this function with the `params` given and writes returned values
918    /// to `results`.
919    ///
920    /// The `params` here must match the type signature of this `Func`, or an
921    /// error will occur. Additionally `results` must have the same
922    /// length as the number of results for this function. Calling this function
923    /// will synchronously execute the WebAssembly function referenced to get
924    /// the results.
925    ///
926    /// This function will return `Ok(())` if execution completed without a trap
927    /// or error of any kind. In this situation the results will be written to
928    /// the provided `results` array.
929    ///
930    /// GC references in `params` must be rooted (see [`Val::ensure_rooted`]).
931    /// GC references in `results` are written as unrooted references
932    /// ([`MaybeRooted::Unrooted`](crate::MaybeRooted::Unrooted)), valid until
933    /// the store's GC heap next changes; root them, all at once, with
934    /// [`Val::ensure_all_rooted`] to keep them for longer.
935    ///
936    /// # Errors
937    ///
938    /// Any error which occurs throughout the execution of the function will be
939    /// returned as `Err(e)`. The [`Error`](crate::Error) type can be inspected
940    /// for the precise error cause such as:
941    ///
942    /// * [`Trap`] - indicates that a wasm trap happened and execution was
943    ///   halted.
944    /// * [`WasmBacktrace`] - optionally included on errors for backtrace
945    ///   information of the trap/error.
946    /// * Other string-based errors to indicate issues such as type errors with
947    ///   `params`.
948    /// * Any host-originating error originally returned from a function defined
949    ///   via [`Func::new`], for example.
950    /// * The `store` provided is configured to require `call_async` to be used
951    ///   instead, such as with epochs or fuel.
952    /// * The call is recursive from within e.g. a `call_async` invocation.
953    ///
954    /// Errors typically indicate that execution of WebAssembly was halted
955    /// mid-way and did not complete after the error condition happened.
956    ///
957    /// [`Trap`]: crate::Trap
958    ///
959    /// # Panics
960    ///
961    /// Panics if `store` does not own this function.
962    ///
963    /// [`WasmBacktrace`]: crate::WasmBacktrace
964    ///
965    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
966    /// memory allocation fails. See the `OutOfMemory` type's documentation for
967    /// details on Wasmtime's out-of-memory handling.
968    pub fn call(
969        &self,
970        mut store: impl AsContextMut,
971        params: &[Val],
972        results: &mut [Val],
973    ) -> Result<()> {
974        let mut store = store.as_context_mut();
975        store.0.validate_sync_call()?;
976
977        self.call_impl_check_args(&mut store, params, results)?;
978
979        unsafe { self.call_impl_do_call(&mut store, params, results) }
980    }
981
982    /// Invokes this function in an "unchecked" fashion, reading parameters and
983    /// writing results to `params_and_returns`.
984    ///
985    /// This function is the same as [`Func::call`] except that the arguments
986    /// and results both use a different representation. If possible it's
987    /// recommended to use [`Func::call`] if safety isn't necessary or to use
988    /// [`Func::typed`] in conjunction with [`TypedFunc::call`] since that's
989    /// both safer and faster than this method of invoking a function.
990    ///
991    /// Note that if this function takes `externref` arguments then it will
992    /// **not** automatically GC unlike the [`Func::call`] and
993    /// [`TypedFunc::call`] functions. This means that if this function is
994    /// invoked many times with new `ExternRef` values and no other GC happens
995    /// via any other means then no values will get collected.
996    ///
997    /// # Errors
998    ///
999    /// For more information about errors see the [`Func::call`] documentation.
1000    ///
1001    /// # Unsafety
1002    ///
1003    /// This function is unsafe because the `params_and_returns` argument is not
1004    /// validated at all. It must uphold invariants such as:
1005    ///
1006    /// * It's a valid pointer to an array
1007    /// * It has enough space to store all parameters
1008    /// * It has enough space to store all results (not at the same time as
1009    ///   parameters)
1010    /// * Parameters are initially written to the array and have the correct
1011    ///   types and such.
1012    /// * Reference types like `externref` and `funcref` are valid at the
1013    ///   time of this call and for the `store` specified.
1014    /// * The call is _not_ recursive from within e.g. a `call_async` invocation.
1015    ///
1016    /// These invariants are all upheld for you with [`Func::call`] and
1017    /// [`TypedFunc::call`].
1018    pub unsafe fn call_unchecked(
1019        &self,
1020        mut store: impl AsContextMut,
1021        params_and_returns: *mut [ValRaw],
1022    ) -> Result<()> {
1023        let mut store = store.as_context_mut();
1024        let func_ref = self.vm_func_ref(store.0);
1025        let params_and_returns = NonNull::new(params_and_returns).unwrap_or(NonNull::from(&mut []));
1026
1027        // SAFETY: the safety of this function call is the same as the contract
1028        // of this function.
1029        unsafe {
1030            Self::call_unchecked_raw(
1031                &mut store,
1032                func_ref,
1033                params_and_returns,
1034                UncaughtException::Propagate,
1035            )
1036        }
1037    }
1038
1039    pub(crate) unsafe fn call_unchecked_raw<T>(
1040        store: &mut StoreContextMut<'_, T>,
1041        func_ref: NonNull<VMFuncRef>,
1042        params_and_returns: NonNull<[ValRaw]>,
1043        uncaught_exception: UncaughtException,
1044    ) -> Result<()> {
1045        // SAFETY: the safety of this function call is the same as the contract
1046        // of this function.
1047        invoke_wasm_and_catch_traps(store, uncaught_exception, |caller, vm| unsafe {
1048            VMFuncRef::array_call(func_ref, vm, caller, params_and_returns)
1049        })
1050    }
1051
1052    /// Converts the raw representation of a `funcref` into an `Option<Func>`
1053    ///
1054    /// This is intended to be used in conjunction with [`Func::new_unchecked`],
1055    /// [`Func::call_unchecked`], and [`ValRaw`] with its `funcref` field. This
1056    /// is the dual of [`Func::to_raw`].
1057    ///
1058    /// # Unsafety
1059    ///
1060    /// This function is not safe because `raw` is not validated at all. The
1061    /// caller must guarantee that `raw` is owned by the `store` provided and is
1062    /// valid within the `store`.
1063    pub unsafe fn from_raw(mut store: impl AsContextMut, raw: *mut c_void) -> Option<Func> {
1064        // SAFETY: this function's own contract is that `raw` is owned by store
1065        // to make this safe.
1066        unsafe { Self::_from_raw(store.as_context_mut().0, raw) }
1067    }
1068
1069    /// Same as `from_raw`, but with the internal `StoreOpaque` type.
1070    pub(crate) unsafe fn _from_raw(store: &mut StoreOpaque, raw: *mut c_void) -> Option<Func> {
1071        // SAFETY: this function's own contract is that `raw` is owned by store
1072        // to make this safe.
1073        unsafe {
1074            Some(Func::from_vm_func_ref(
1075                store.id(),
1076                NonNull::new(raw.cast())?,
1077            ))
1078        }
1079    }
1080
1081    /// Extracts the raw value of this `Func`, which is owned by `store`.
1082    ///
1083    /// This function returns a value that's suitable for writing into the
1084    /// `funcref` field of the [`ValRaw`] structure.
1085    ///
1086    /// # Safety
1087    ///
1088    /// The returned value is only valid for as long as the store is alive.
1089    /// This value is safe to pass to [`Func::from_raw`] so long as the same
1090    /// `store` is provided.
1091    pub fn to_raw(&self, store: impl AsContext) -> *mut c_void {
1092        self.to_raw_(store.as_context().0)
1093    }
1094
1095    pub(crate) fn to_raw_(&self, store: &StoreOpaque) -> *mut c_void {
1096        self.vm_func_ref(store).as_ptr().cast()
1097    }
1098
1099    /// Invokes this function with the `params` given, returning the results
1100    /// asynchronously.
1101    ///
1102    /// This function is the same as [`Func::call`] except that it is
1103    /// asynchronous.
1104    ///
1105    /// It's important to note that the execution of WebAssembly will happen
1106    /// synchronously in the `poll` method of the future returned from this
1107    /// function. Wasmtime does not manage its own thread pool or similar to
1108    /// execute WebAssembly in. Future `poll` methods are generally expected to
1109    /// resolve quickly, so it's recommended that you run or poll this future
1110    /// in a "blocking context".
1111    ///
1112    /// For more information see the documentation on [asynchronous
1113    /// configs](crate#async).
1114    ///
1115    /// # Errors
1116    ///
1117    /// For more information on errors see the [`Func::call`] documentation.
1118    ///
1119    /// # Panics
1120    ///
1121    /// Panics if this is called on a function in a synchronous store. This
1122    /// only works with functions defined within an asynchronous store. Also
1123    /// panics if `store` does not own this function.
1124    ///
1125    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
1126    /// memory allocation fails. See the `OutOfMemory` type's documentation for
1127    /// details on Wasmtime's out-of-memory handling.
1128    #[cfg(feature = "async")]
1129    pub async fn call_async(
1130        &self,
1131        mut store: impl AsContextMut<Data: Send>,
1132        params: &[Val],
1133        results: &mut [Val],
1134    ) -> Result<()> {
1135        let mut store = store.as_context_mut();
1136
1137        self.call_impl_check_args(&mut store, params, results)?;
1138
1139        let result = store
1140            .on_fiber(|store| unsafe { self.call_impl_do_call(store, params, results) })
1141            .await??;
1142        Ok(result)
1143    }
1144
1145    /// Perform dynamic checks that the arguments given to us match
1146    /// the signature of this function and are appropriate to pass to this
1147    /// function.
1148    ///
1149    /// This involves checking to make sure we have the right number and types
1150    /// of arguments as well as making sure everything is from the same `Store`.
1151    ///
1152    /// This must be called just before `call_impl_do_call`.
1153    fn call_impl_check_args<T>(
1154        &self,
1155        store: &mut StoreContextMut<'_, T>,
1156        params: &[Val],
1157        results: &mut [Val],
1158    ) -> Result<()> {
1159        let ty = self.load_ty(store.0);
1160        if ty.params().len() != params.len() {
1161            bail!(
1162                "expected {} arguments, got {}",
1163                ty.params().len(),
1164                params.len()
1165            );
1166        }
1167        if ty.results().len() != results.len() {
1168            bail!(
1169                "expected {} results, got {}",
1170                ty.results().len(),
1171                results.len()
1172            );
1173        }
1174
1175        for (ty, arg) in ty.params().zip(params) {
1176            arg.validate_rooted().context("unrooted argument")?;
1177            arg.ensure_matches_ty(store.0, &ty)
1178                .context("argument type mismatch")?;
1179            if !arg.comes_from_same_store(store.0) {
1180                bail!("cross-`Store` values are not currently supported");
1181            }
1182        }
1183
1184        Ok(())
1185    }
1186
1187    /// Do the actual call into Wasm.
1188    ///
1189    /// # Safety
1190    ///
1191    /// You must have type checked the arguments by calling
1192    /// `call_impl_check_args` immediately before calling this function. It is
1193    /// only safe to call this function if that one did not return an error.
1194    unsafe fn call_impl_do_call<T>(
1195        &self,
1196        store: &mut StoreContextMut<'_, T>,
1197        params: &[Val],
1198        results: &mut [Val],
1199    ) -> Result<()> {
1200        // Store the argument values into `values_vec`.
1201        let ty = self.load_ty(store.0);
1202        let values_vec_size = params.len().max(ty.results().len());
1203        let mut values_vec = store.0.take_wasm_val_raw_storage();
1204        debug_assert!(values_vec.is_empty());
1205        values_vec.resize_with(values_vec_size, || ValRaw::v128(0))?;
1206        for (arg, slot) in params.iter().cloned().zip(&mut values_vec) {
1207            *slot = arg.to_raw(&mut *store)?;
1208        }
1209
1210        unsafe {
1211            self.call_unchecked(
1212                &mut *store,
1213                core::ptr::slice_from_raw_parts_mut(values_vec.as_mut_ptr(), values_vec_size),
1214            )?;
1215        }
1216
1217        // Read the results as unrooted references, so that the caller can
1218        // choose whether and how to root them. Nothing below may change the GC
1219        // heap, since that would invalidate them.
1220        for ((i, slot), val) in results.iter_mut().enumerate().zip(&values_vec) {
1221            let ty = ty.results().nth(i).unwrap();
1222            *slot = unsafe { Val::from_raw_unrooted_(store.0, *val, &ty) };
1223        }
1224        values_vec.truncate(0);
1225        store.0.save_wasm_val_raw_storage(values_vec);
1226        Ok(())
1227    }
1228
1229    #[inline]
1230    pub(crate) fn vm_func_ref(&self, store: &StoreOpaque) -> NonNull<VMFuncRef> {
1231        self.store.assert_belongs_to(store.id());
1232        self.unsafe_func_ref.as_non_null()
1233    }
1234
1235    pub(crate) fn vmimport(&self, store: &StoreOpaque) -> VMFunctionImport {
1236        // Safety: it should be fine to dereference the funcref pointer while we
1237        // borrow the store.
1238        let func_ref = unsafe { self.vm_func_ref(store).as_ref() };
1239
1240        // Note that this is a load-bearing `unwrap` here, but is never expected
1241        // to trip at runtime. The general problem is that host functions do not
1242        // have a `wasm_call` function so the `VMFuncRef` type has an optional
1243        // pointer there. This is only able to be filled out when a function is
1244        // "paired" with a module where trampolines are present to fill out
1245        // `wasm_call` pointers.
1246        //
1247        // This pairing of modules doesn't happen explicitly but is instead
1248        // managed lazily throughout Wasmtime. Specifically the way this works
1249        // is one of:
1250        //
1251        // * When a host function is created the store's list of modules are
1252        //   searched for a wasm trampoline. If not found the `wasm_call` field
1253        //   is left blank.
1254        //
1255        // * When a module instantiation happens, which uses this function, the
1256        //   module will be used to fill any outstanding holes that it has
1257        //   trampolines for.
1258        //
1259        // This means that by the time we get to this point any relevant holes
1260        // should be filled out. Thus if this panic actually triggers then it's
1261        // indicative of a missing `fill` call somewhere else.
1262        let func_import = func_ref.as_vm_function_import().unwrap();
1263
1264        func_import.clone()
1265    }
1266
1267    pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
1268        self.store == store.id()
1269    }
1270
1271    /// Attempts to extract a typed object from this `Func` through which the
1272    /// function can be called.
1273    ///
1274    /// This function serves as an alternative to [`Func::call`] and
1275    /// [`Func::call_async`]. This method performs a static type check (using
1276    /// the `Params` and `Results` type parameters on the underlying wasm
1277    /// function. If the type check passes then a `TypedFunc` object is returned,
1278    /// otherwise an error is returned describing the typecheck failure.
1279    ///
1280    /// The purpose of this relative to [`Func::call`] is that it's much more
1281    /// efficient when used to invoke WebAssembly functions. With the types
1282    /// statically known far less setup/teardown is required when invoking
1283    /// WebAssembly. If speed is desired then this function is recommended to be
1284    /// used instead of [`Func::call`] (which is more general, hence its
1285    /// slowdown).
1286    ///
1287    /// The `Params` type parameter is used to describe the parameters of the
1288    /// WebAssembly function. This can either be a single type (like `i32`), or
1289    /// a tuple of types representing the list of parameters (like `(i32, f32,
1290    /// f64)`). Additionally you can use `()` to represent that the function has
1291    /// no parameters.
1292    ///
1293    /// The `Results` type parameter is used to describe the results of the
1294    /// function. This behaves the same way as `Params`, but just for the
1295    /// results of the function.
1296    ///
1297    /// # Translating Between WebAssembly and Rust Types
1298    ///
1299    /// Translation between Rust types and WebAssembly types looks like:
1300    ///
1301    /// | WebAssembly                               | Rust                                  |
1302    /// |-------------------------------------------|---------------------------------------|
1303    /// | `i32`                                     | `i32` or `u32`                        |
1304    /// | `i64`                                     | `i64` or `u64`                        |
1305    /// | `f32`                                     | `f32`                                 |
1306    /// | `f64`                                     | `f64`                                 |
1307    /// | `externref` aka `(ref null extern)`       | `Option<Rooted<ExternRef>>`           |
1308    /// | `(ref extern)`                            | `Rooted<ExternRef>`                   |
1309    /// | `nullexternref` aka `(ref null noextern)` | `Option<NoExtern>`                    |
1310    /// | `(ref noextern)`                          | `NoExtern`                            |
1311    /// | `anyref` aka `(ref null any)`             | `Option<Rooted<AnyRef>>`              |
1312    /// | `(ref any)`                               | `Rooted<AnyRef>`                      |
1313    /// | `eqref` aka `(ref null eq)`               | `Option<Rooted<EqRef>>`               |
1314    /// | `(ref eq)`                                | `Rooted<EqRef>`                       |
1315    /// | `i31ref` aka `(ref null i31)`             | `Option<I31>`                         |
1316    /// | `(ref i31)`                               | `I31`                                 |
1317    /// | `structref` aka `(ref null struct)`       | `Option<Rooted<StructRef>>`           |
1318    /// | `(ref struct)`                            | `Rooted<StructRef>`                   |
1319    /// | `arrayref` aka `(ref null array)`         | `Option<Rooted<ArrayRef>>`            |
1320    /// | `(ref array)`                             | `Rooted<ArrayRef>`                    |
1321    /// | `nullref` aka `(ref null none)`           | `Option<NoneRef>`                     |
1322    /// | `(ref none)`                              | `NoneRef`                             |
1323    /// | `funcref` aka `(ref null func)`           | `Option<Func>`                        |
1324    /// | `(ref func)`                              | `Func`                                |
1325    /// | `(ref null <func type index>)`            | `Option<Func>`                        |
1326    /// | `(ref <func type index>)`                 | `Func`                                |
1327    /// | `nullfuncref` aka `(ref null nofunc)`     | `Option<NoFunc>`                      |
1328    /// | `(ref nofunc)`                            | `NoFunc`                              |
1329    /// | `v128`                                    | `V128` on `x86-64` and `aarch64` only |
1330    ///
1331    /// (Note that this mapping is the same as that of [`Func::wrap`], and that
1332    /// anywhere a `Rooted<T>` appears, a `OwnedRooted<T>` may also appear).
1333    ///
1334    /// Note that once the [`TypedFunc`] return value is acquired you'll use either
1335    /// [`TypedFunc::call`] or [`TypedFunc::call_async`] as necessary to actually invoke
1336    /// the function. This method does not invoke any WebAssembly code, it
1337    /// simply performs a typecheck before returning the [`TypedFunc`] value.
1338    ///
1339    /// This method also has a convenience wrapper as
1340    /// [`Instance::get_typed_func`](crate::Instance::get_typed_func) to
1341    /// directly get a typed function value from an
1342    /// [`Instance`](crate::Instance).
1343    ///
1344    /// ## Subtyping
1345    ///
1346    /// For result types, you can always use a supertype of the WebAssembly
1347    /// function's actual declared result type. For example, if the WebAssembly
1348    /// function was declared with type `(func (result nullfuncref))` you could
1349    /// successfully call `f.typed::<(), Option<Func>>()` because `Option<Func>`
1350    /// corresponds to `funcref`, which is a supertype of `nullfuncref`.
1351    ///
1352    /// For parameter types, you can always use a subtype of the WebAssembly
1353    /// function's actual declared parameter type. For example, if the
1354    /// WebAssembly function was declared with type `(func (param (ref null
1355    /// func)))` you could successfully call `f.typed::<Func, ()>()` because
1356    /// `Func` corresponds to `(ref func)`, which is a subtype of `(ref null
1357    /// func)`.
1358    ///
1359    /// Additionally, for functions which take a reference to a concrete type as
1360    /// a parameter, you can also use the concrete type's supertype. Consider a
1361    /// WebAssembly function that takes a reference to a function with a
1362    /// concrete type: `(ref null <func type index>)`. In this scenario, there
1363    /// is no static `wasmtime::Foo` Rust type that corresponds to that
1364    /// particular Wasm-defined concrete reference type because Wasm modules are
1365    /// loaded dynamically at runtime. You *could* do `f.typed::<Option<NoFunc>,
1366    /// ()>()`, and while that is correctly typed and valid, it is often overly
1367    /// restrictive. The only value you could call the resulting typed function
1368    /// with is the null function reference, but we'd like to call it with
1369    /// non-null function references that happen to be of the correct
1370    /// type. Therefore, `f.typed<Option<Func>, ()>()` is also allowed in this
1371    /// case, even though `Option<Func>` represents `(ref null func)` which is
1372    /// the supertype, not subtype, of `(ref null <func type index>)`. This does
1373    /// imply some minimal dynamic type checks in this case, but it is supported
1374    /// for better ergonomics, to enable passing non-null references into the
1375    /// function.
1376    ///
1377    /// # Errors
1378    ///
1379    /// This function will return an error if `Params` or `Results` does not
1380    /// match the native type of this WebAssembly function.
1381    ///
1382    /// # Panics
1383    ///
1384    /// This method will panic if `store` does not own this function.
1385    ///
1386    /// # Examples
1387    ///
1388    /// An end-to-end example of calling a function which takes no parameters
1389    /// and has no results:
1390    ///
1391    /// ```
1392    /// # use wasmtime::*;
1393    /// # fn main() -> Result<()> {
1394    /// let engine = Engine::default();
1395    /// let mut store = Store::new(&engine, ());
1396    /// let module = Module::new(&engine, r#"(module (func (export "foo")))"#)?;
1397    /// let instance = Instance::new(&mut store, &module, &[])?;
1398    /// let foo = instance.get_func(&mut store, "foo").expect("export wasn't a function");
1399    ///
1400    /// // Note that this call can fail due to the typecheck not passing, but
1401    /// // in our case we statically know the module so we know this should
1402    /// // pass.
1403    /// let typed = foo.typed::<(), ()>(&store)?;
1404    ///
1405    /// // Note that this can fail if the wasm traps at runtime.
1406    /// typed.call(&mut store, ())?;
1407    /// # Ok(())
1408    /// # }
1409    /// ```
1410    ///
1411    /// You can also pass in multiple parameters and get a result back
1412    ///
1413    /// ```
1414    /// # use wasmtime::*;
1415    /// # fn foo(add: &Func, mut store: Store<()>) -> Result<()> {
1416    /// let typed = add.typed::<(i32, i64), f32>(&store)?;
1417    /// assert_eq!(typed.call(&mut store, (1, 2))?, 3.0);
1418    /// # Ok(())
1419    /// # }
1420    /// ```
1421    ///
1422    /// and similarly if a function has multiple results you can bind that too
1423    ///
1424    /// ```
1425    /// # use wasmtime::*;
1426    /// # fn foo(add_with_overflow: &Func, mut store: Store<()>) -> Result<()> {
1427    /// let typed = add_with_overflow.typed::<(u32, u32), (u32, i32)>(&store)?;
1428    /// let (result, overflow) = typed.call(&mut store, (u32::MAX, 2))?;
1429    /// assert_eq!(result, 1);
1430    /// assert_eq!(overflow, 1);
1431    /// # Ok(())
1432    /// # }
1433    /// ```
1434    pub fn typed<Params, Results>(
1435        &self,
1436        store: impl AsContext,
1437    ) -> Result<TypedFunc<Params, Results>>
1438    where
1439        Params: WasmParams,
1440        Results: WasmResults,
1441    {
1442        // Type-check that the params/results are all valid
1443        let store = store.as_context().0;
1444        let ty = self.load_ty(store);
1445        Params::typecheck(store.engine(), ty.params(), TypeCheckPosition::Param)
1446            .context("type mismatch with parameters")?;
1447        Results::typecheck(store.engine(), ty.results(), TypeCheckPosition::Result)
1448            .context("type mismatch with results")?;
1449
1450        // and then we can construct the typed version of this function
1451        // (unsafely), which should be safe since we just did the type check above.
1452        unsafe { Ok(TypedFunc::_new_unchecked(store, *self)) }
1453    }
1454
1455    /// Get a stable hash key for this function.
1456    ///
1457    /// Even if the same underlying function is added to the `StoreData`
1458    /// multiple times and becomes multiple `wasmtime::Func`s, this hash key
1459    /// will be consistent across all of these functions.
1460    #[cfg_attr(
1461        not(test),
1462        expect(dead_code, reason = "Not used yet, but added for consistency")
1463    )]
1464    pub(crate) fn hash_key(&self, store: &mut StoreOpaque) -> impl core::hash::Hash + Eq + use<> {
1465        self.vm_func_ref(store).as_ptr().addr()
1466    }
1467}
1468
1469/// Prepares for entrance into WebAssembly.
1470///
1471/// This function will set up context such that `closure` is allowed to call a
1472/// raw trampoline or a raw WebAssembly function. This *must* be called to do
1473/// things like catch traps and set up GC properly.
1474///
1475/// The `closure` provided receives a default "caller" `VMContext` parameter it
1476/// can pass to the called wasm function, if desired.
1477pub(crate) fn invoke_wasm_and_catch_traps<T>(
1478    store: &mut StoreContextMut<'_, T>,
1479    uncaught_exception: crate::runtime::vm::UncaughtException,
1480    closure: impl FnMut(NonNull<VMContext>, Option<InterpreterRef<'_>>) -> bool,
1481) -> Result<()> {
1482    // A store containing components is poisoned once anything in it traps, and
1483    // no wasm may run in it afterwards.
1484    #[cfg(feature = "component-model")]
1485    if !store.0.may_enter() {
1486        return Err(crate::Trap::CannotEnterComponent.into());
1487    }
1488
1489    // The `enter_wasm` call below will reset the store context's
1490    // `stack_chain` to a new `InitialStack`, pointing to the
1491    // stack-allocated `initial_stack_csi`.
1492    let mut initial_stack_csi = VMCommonStackInformation::running_default();
1493    // Stores some state of the runtime just before entering Wasm. Will be
1494    // restored upon exiting Wasm. Note that the `CallThreadState` that is
1495    // created by the `catch_traps` call below will store a pointer to this
1496    // stack-allocated `previous_runtime_state`.
1497    let mut previous_runtime_state = EntryStoreContext::enter_wasm(store, &mut initial_stack_csi);
1498
1499    if let Err(trap) = store.0.call_hook(CallHook::CallingWasm) {
1500        // `previous_runtime_state` implicitly dropped here
1501        return Err(trap);
1502    }
1503    let result = crate::runtime::vm::catch_traps(
1504        store,
1505        &mut previous_runtime_state,
1506        uncaught_exception,
1507        closure,
1508    );
1509    if result.is_err() {
1510        store.0.set_trapped();
1511    }
1512    core::mem::drop(previous_runtime_state);
1513    store.0.call_hook(CallHook::ReturningFromWasm)?;
1514    result
1515}
1516
1517/// This type helps managing the state of the runtime when entering and exiting
1518/// Wasm. To this end, it contains a subset of the data in `VMStoreContext`.
1519/// Upon entering Wasm, it updates various runtime fields and their
1520/// original values saved in this struct. Upon exiting Wasm, the previous values
1521/// are restored.
1522pub(crate) struct EntryStoreContext {
1523    /// If set, contains value of `stack_limit` field to restore in
1524    /// `VMStoreContext` when exiting Wasm.
1525    pub stack_limit: Option<usize>,
1526    pub last_wasm_exit_pc: usize,
1527    pub last_wasm_exit_trampoline_fp: usize,
1528    pub last_wasm_entry_fp: usize,
1529    pub last_wasm_entry_sp: usize,
1530    pub last_wasm_entry_trap_handler: usize,
1531    pub stack_chain: VMStackChain,
1532
1533    /// We need a pointer to the runtime limits, so we can update them from
1534    /// `drop`/`exit_wasm`.
1535    vm_store_context: *const VMStoreContext,
1536}
1537
1538impl EntryStoreContext {
1539    /// This function is called to update and save state when
1540    /// WebAssembly is entered within the `Store`.
1541    ///
1542    /// This updates various fields such as:
1543    ///
1544    /// * The stack limit. This is what ensures that we limit the stack space
1545    ///   allocated by WebAssembly code and it's relative to the initial stack
1546    ///   pointer that called into wasm.
1547    ///
1548    /// It also saves the different last_wasm_* values in the `VMStoreContext`.
1549    pub fn enter_wasm<T>(
1550        store: &mut StoreContextMut<'_, T>,
1551        initial_stack_information: *mut VMCommonStackInformation,
1552    ) -> Self {
1553        let stack_limit;
1554
1555        // If this is a recursive call, e.g. our stack limit is already set, then
1556        // we may be able to skip this function.
1557        //
1558        // For synchronous stores there's nothing else to do because all wasm calls
1559        // happen synchronously and on the same stack. This means that the previous
1560        // stack limit will suffice for the next recursive call.
1561        //
1562        // For asynchronous stores then each call happens on a separate native
1563        // stack. This means that the previous stack limit is no longer relevant
1564        // because we're on a separate stack.
1565        if unsafe { *store.0.vm_store_context().stack_limit.get() } != usize::MAX
1566            && !store.0.can_block()
1567        {
1568            stack_limit = None;
1569        }
1570        // Ignore this stack pointer business on miri since we can't execute wasm
1571        // anyway and the concept of a stack pointer on miri is a bit nebulous
1572        // regardless.
1573        else if cfg!(miri) {
1574            stack_limit = None;
1575        } else {
1576            // When Cranelift has support for the host then we might be running native
1577            // compiled code meaning we need to read the actual stack pointer. If
1578            // Cranelift can't be used though then we're guaranteed to be running pulley
1579            // in which case this stack pointer isn't actually used as Pulley has custom
1580            // mechanisms for stack overflow.
1581            #[cfg(has_host_compiler_backend)]
1582            let stack_pointer = crate::runtime::vm::get_stack_pointer();
1583            #[cfg(not(has_host_compiler_backend))]
1584            let stack_pointer = {
1585                use wasmtime_environ::TripleExt;
1586                debug_assert!(store.engine().target().is_pulley());
1587                usize::MAX
1588            };
1589
1590            // Determine the stack pointer where, after which, any wasm code will
1591            // immediately trap. This is checked on the entry to all wasm functions.
1592            //
1593            // Note that this isn't 100% precise. We are requested to give wasm
1594            // `max_wasm_stack` bytes, but what we're actually doing is giving wasm
1595            // probably a little less than `max_wasm_stack` because we're
1596            // calculating the limit relative to this function's approximate stack
1597            // pointer. Wasm will be executed on a frame beneath this one (or next
1598            // to it). In any case it's expected to be at most a few hundred bytes
1599            // of slop one way or another. When wasm is typically given a MB or so
1600            // (a million bytes) the slop shouldn't matter too much.
1601            //
1602            // After we've got the stack limit then we store it into the `stack_limit`
1603            // variable.
1604            //
1605            // Also note that `saturating_sub` is used here since if the user
1606            // said that the function gets nigh-infinite stack well then by
1607            // golly it'll get nigh-infinite stack in which case the limit is 0.
1608            let wasm_stack_limit =
1609                stack_pointer.saturating_sub(store.engine().config().max_wasm_stack);
1610            let prev_stack = unsafe {
1611                mem::replace(
1612                    &mut *store.0.vm_store_context().stack_limit.get(),
1613                    wasm_stack_limit,
1614                )
1615            };
1616            stack_limit = Some(prev_stack);
1617        }
1618
1619        unsafe {
1620            let vm_store_context = store.0.vm_store_context();
1621            let initial_stack_information = VmPtr::from(
1622                NonNull::new(initial_stack_information)
1623                    .expect("expected non-null stack information"),
1624            );
1625            let new_stack_chain = VMStackChain::InitialStack(initial_stack_information);
1626            let stack_chain =
1627                mem::replace(&mut *vm_store_context.stack_chain.get(), new_stack_chain);
1628
1629            // Zero these out, rather than leave the previous activation's
1630            // values behind, so that if we call into a host function callee
1631            // (which never runs an entry trampoline to overwrite them) and it
1632            // walks the stack, we don't see these values both while walking
1633            // activations and in the saved state.
1634            let take = |field: &core::cell::UnsafeCell<usize>| mem::replace(&mut *field.get(), 0);
1635
1636            Self {
1637                stack_limit,
1638                last_wasm_exit_pc: take(&vm_store_context.last_wasm_exit_pc),
1639                last_wasm_exit_trampoline_fp: take(&vm_store_context.last_wasm_exit_trampoline_fp),
1640                last_wasm_entry_fp: take(&vm_store_context.last_wasm_entry_fp),
1641                last_wasm_entry_sp: take(&vm_store_context.last_wasm_entry_sp),
1642                last_wasm_entry_trap_handler: take(&vm_store_context.last_wasm_entry_trap_handler),
1643                stack_chain,
1644                vm_store_context,
1645            }
1646        }
1647    }
1648
1649    /// This function restores the values stored in this struct. We invoke this
1650    /// function through this type's `Drop` implementation. This ensures that we
1651    /// even restore the values if we unwind the stack (e.g., because we are
1652    /// panicking out of a Wasm execution).
1653    #[inline]
1654    fn exit_wasm(&mut self) {
1655        unsafe {
1656            if let Some(limit) = self.stack_limit {
1657                *(&*self.vm_store_context).stack_limit.get() = limit;
1658            }
1659
1660            *(*self.vm_store_context).last_wasm_exit_trampoline_fp.get() =
1661                self.last_wasm_exit_trampoline_fp;
1662            *(*self.vm_store_context).last_wasm_exit_pc.get() = self.last_wasm_exit_pc;
1663            *(*self.vm_store_context).last_wasm_entry_fp.get() = self.last_wasm_entry_fp;
1664            *(*self.vm_store_context).last_wasm_entry_sp.get() = self.last_wasm_entry_sp;
1665            *(*self.vm_store_context).last_wasm_entry_trap_handler.get() =
1666                self.last_wasm_entry_trap_handler;
1667            *(*self.vm_store_context).stack_chain.get() = self.stack_chain.clone();
1668        }
1669    }
1670}
1671
1672impl Drop for EntryStoreContext {
1673    #[inline]
1674    fn drop(&mut self) {
1675        self.exit_wasm();
1676    }
1677}
1678
1679/// A trait implemented for types which can be returned from closures passed to
1680/// [`Func::wrap`] and friends.
1681///
1682/// This trait should not be implemented by user types. This trait may change at
1683/// any time internally. The types which implement this trait, however, are
1684/// stable over time.
1685///
1686/// For more information see [`Func::wrap`]
1687pub unsafe trait WasmRet {
1688    // Same as `WasmTy::compatible_with_store`.
1689    #[doc(hidden)]
1690    fn compatible_with_store(&self, store: &StoreOpaque) -> bool;
1691
1692    /// Stores this return value into the `ptr` specified using the rooted
1693    /// `store`.
1694    ///
1695    /// Traps are communicated through the `Result<_>` return value.
1696    ///
1697    /// # Unsafety
1698    ///
1699    /// This method is unsafe as `ptr` must have the correct length to store
1700    /// this result. This property is only checked in debug mode, not in release
1701    /// mode.
1702    #[doc(hidden)]
1703    unsafe fn store(
1704        self,
1705        store: &mut AutoAssertNoGc<'_>,
1706        ptr: &mut [MaybeUninit<ValRaw>],
1707    ) -> Result<()>;
1708
1709    #[doc(hidden)]
1710    fn func_type(
1711        engine: &Engine,
1712        params: impl Iterator<Item = ValType>,
1713    ) -> Result<FuncType, OutOfMemory>;
1714    #[doc(hidden)]
1715    fn may_gc() -> bool;
1716
1717    // Utilities used to convert an instance of this type to a `Result`
1718    // explicitly, used when wrapping async functions which always bottom-out
1719    // in a function that returns a trap because futures can be cancelled.
1720    #[doc(hidden)]
1721    type Fallible: WasmRet;
1722    #[doc(hidden)]
1723    fn into_fallible(self) -> Self::Fallible;
1724    #[doc(hidden)]
1725    fn fallible_from_error(error: Error) -> Self::Fallible;
1726}
1727
1728unsafe impl<T> WasmRet for T
1729where
1730    T: WasmTy,
1731{
1732    type Fallible = Result<T>;
1733
1734    fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
1735        <Self as WasmTy>::compatible_with_store(self, store)
1736    }
1737
1738    unsafe fn store(
1739        self,
1740        store: &mut AutoAssertNoGc<'_>,
1741        ptr: &mut [MaybeUninit<ValRaw>],
1742    ) -> Result<()> {
1743        debug_assert!(ptr.len() > 0);
1744        // SAFETY: the contract of this function/trait combo is such that `ptr`
1745        // is valid to store this type's value, thus this lookup should be safe.
1746        unsafe { <Self as WasmTy>::store(self, store, ptr.get_unchecked_mut(0)) }
1747    }
1748
1749    fn may_gc() -> bool {
1750        T::may_gc()
1751    }
1752
1753    fn func_type(
1754        engine: &Engine,
1755        params: impl Iterator<Item = ValType>,
1756    ) -> Result<FuncType, OutOfMemory> {
1757        FuncType::try_new(engine, params, Some(<Self as WasmTy>::valtype()))
1758    }
1759
1760    fn into_fallible(self) -> Result<T> {
1761        Ok(self)
1762    }
1763
1764    fn fallible_from_error(error: Error) -> Result<T> {
1765        Err(error)
1766    }
1767}
1768
1769unsafe impl<T> WasmRet for Result<T>
1770where
1771    T: WasmRet,
1772{
1773    type Fallible = Self;
1774
1775    fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
1776        match self {
1777            Ok(x) => <T as WasmRet>::compatible_with_store(x, store),
1778            Err(_) => true,
1779        }
1780    }
1781
1782    unsafe fn store(
1783        self,
1784        store: &mut AutoAssertNoGc<'_>,
1785        ptr: &mut [MaybeUninit<ValRaw>],
1786    ) -> Result<()> {
1787        // SAFETY: the safety of calling this function is the same as calling
1788        // the inner `store`.
1789        unsafe { self.and_then(|val| val.store(store, ptr)) }
1790    }
1791
1792    fn may_gc() -> bool {
1793        T::may_gc()
1794    }
1795
1796    fn func_type(
1797        engine: &Engine,
1798        params: impl Iterator<Item = ValType>,
1799    ) -> Result<FuncType, OutOfMemory> {
1800        T::func_type(engine, params)
1801    }
1802
1803    fn into_fallible(self) -> Result<T> {
1804        self
1805    }
1806
1807    fn fallible_from_error(error: Error) -> Result<T> {
1808        Err(error)
1809    }
1810}
1811
1812macro_rules! impl_wasm_host_results {
1813    ($n:tt $($t:ident)*) => (
1814        #[allow(non_snake_case, reason = "macro-generated code")]
1815        unsafe impl<$($t),*> WasmRet for ($($t,)*)
1816        where
1817            $($t: WasmTy,)*
1818        {
1819            type Fallible = Result<Self>;
1820
1821            #[inline]
1822            fn compatible_with_store(&self, _store: &StoreOpaque) -> bool {
1823                let ($($t,)*) = self;
1824                $( $t.compatible_with_store(_store) && )* true
1825            }
1826
1827            #[inline]
1828            unsafe fn store(
1829                self,
1830                _store: &mut AutoAssertNoGc<'_>,
1831                _ptr: &mut [MaybeUninit<ValRaw>],
1832            ) -> Result<()> {
1833                let ($($t,)*) = self;
1834                let mut _cur = 0;
1835                $(
1836                    debug_assert!(_cur < _ptr.len());
1837                    // SAFETY: `store`'s unsafe contract is that `_ptr` is
1838                    // appropriately sized and additionally safe to call `store`
1839                    // for sub-types.
1840                    unsafe {
1841                        let val = _ptr.get_unchecked_mut(_cur);
1842                        _cur += 1;
1843                        WasmTy::store($t, _store, val)?;
1844                    }
1845                )*
1846                Ok(())
1847            }
1848
1849            #[doc(hidden)]
1850            fn may_gc() -> bool {
1851                $( $t::may_gc() || )* false
1852            }
1853
1854            fn func_type(
1855                engine: &Engine,
1856                params: impl Iterator<Item = ValType>,
1857            ) -> Result<FuncType, OutOfMemory> {
1858                FuncType::try_new(
1859                    engine,
1860                    params,
1861                    IntoIterator::into_iter([$($t::valtype(),)*]),
1862                )
1863            }
1864
1865            #[inline]
1866            fn into_fallible(self) -> Result<Self> {
1867                Ok(self)
1868            }
1869
1870            #[inline]
1871            fn fallible_from_error(error: Error) -> Result<Self> {
1872                Err(error)
1873            }
1874        }
1875    )
1876}
1877
1878for_each_function_signature!(impl_wasm_host_results);
1879
1880/// Internal trait implemented for all arguments that can be passed to
1881/// [`Func::wrap`] and [`Linker::func_wrap`](crate::Linker::func_wrap).
1882///
1883/// This trait should not be implemented by external users, it's only intended
1884/// as an implementation detail of this crate.
1885pub trait IntoFunc<T, Params, Results>: Send + Sync + 'static {
1886    /// Convert this function into a `VM{Array,Native}CallHostFuncContext` and
1887    /// internal `VMFuncRef`.
1888    #[doc(hidden)]
1889    fn into_func(self, engine: &Engine) -> Result<HostFunc, OutOfMemory>;
1890}
1891
1892macro_rules! impl_into_func {
1893    ($num:tt $arg:ident) => {
1894        // Implement for functions without a leading `Caller` parameter,
1895        // delegating to the implementation below which does have the leading
1896        // `Caller` parameter.
1897        #[expect(non_snake_case, reason = "macro-generated code")]
1898        impl<T, F, $arg, R> IntoFunc<T, $arg, R> for F
1899        where
1900            F: Fn($arg) -> R + Send + Sync + 'static,
1901            $arg: WasmTy,
1902            R: WasmRet,
1903            T: 'static,
1904        {
1905            fn into_func(self, engine: &Engine) -> Result<HostFunc, OutOfMemory> {
1906                let f = move |_: Caller<'_, T>, $arg: $arg| {
1907                    self($arg)
1908                };
1909
1910                f.into_func(engine)
1911            }
1912        }
1913
1914        #[expect(non_snake_case, reason = "macro-generated code")]
1915        impl<T, F, $arg, R> IntoFunc<T, (Caller<'_, T>, $arg), R> for F
1916        where
1917            F: Fn(Caller<'_, T>, $arg) -> R + Send + Sync + 'static,
1918            $arg: WasmTy,
1919            R: WasmRet,
1920            T: 'static,
1921        {
1922            fn into_func(self, engine: &Engine) -> Result<HostFunc, OutOfMemory> {
1923                HostFunc::wrap(engine, move |caller: Caller<'_, T>, ($arg,)| {
1924                    self(caller, $arg)
1925                })
1926            }
1927        }
1928    };
1929    ($num:tt $($args:ident)*) => {
1930        // Implement for functions without a leading `Caller` parameter,
1931        // delegating to the implementation below which does have the leading
1932        // `Caller` parameter.
1933        #[allow(non_snake_case, reason = "macro-generated code")]
1934        impl<T, F, $($args,)* R> IntoFunc<T, ($($args,)*), R> for F
1935        where
1936            F: Fn($($args),*) -> R + Send + Sync + 'static,
1937            $($args: WasmTy,)*
1938            R: WasmRet,
1939            T: 'static,
1940        {
1941            fn into_func(self, engine: &Engine) -> Result<HostFunc, OutOfMemory> {
1942                let f = move |_: Caller<'_, T>, $($args:$args),*| {
1943                    self($($args),*)
1944                };
1945
1946                f.into_func(engine)
1947            }
1948        }
1949
1950        #[allow(non_snake_case, reason = "macro-generated code")]
1951        impl<T, F, $($args,)* R> IntoFunc<T, (Caller<'_, T>, $($args,)*), R> for F
1952        where
1953            F: Fn(Caller<'_, T>, $($args),*) -> R + Send + Sync + 'static,
1954            $($args: WasmTy,)*
1955            R: WasmRet,
1956            T: 'static,
1957        {
1958            fn into_func(self, engine: &Engine) -> Result<HostFunc, OutOfMemory> {
1959                HostFunc::wrap(engine, move |caller: Caller<'_, T>, ( $( $args ),* )| {
1960                    self(caller, $( $args ),* )
1961                })
1962            }
1963        }
1964    }
1965}
1966
1967for_each_function_signature!(impl_into_func);
1968
1969/// Trait implemented for various tuples made up of types which implement
1970/// [`WasmTy`] that can be passed to [`Func::wrap_async`].
1971pub unsafe trait WasmTyList {
1972    /// Get the value type that each Type in the list represents.
1973    fn valtypes() -> impl Iterator<Item = ValType>;
1974
1975    // Load a version of `Self` from the `values` provided.
1976    //
1977    // # Safety
1978    //
1979    // This function is unsafe as it's up to the caller to ensure that `values` are
1980    // valid for this given type.
1981    #[doc(hidden)]
1982    unsafe fn load(store: &mut AutoAssertNoGc<'_>, values: &mut [MaybeUninit<ValRaw>]) -> Self;
1983
1984    #[doc(hidden)]
1985    fn may_gc() -> bool;
1986}
1987
1988macro_rules! impl_wasm_ty_list {
1989    ($num:tt $($args:ident)*) => (
1990        #[allow(non_snake_case, reason = "macro-generated code")]
1991        unsafe impl<$($args),*> WasmTyList for ($($args,)*)
1992        where
1993            $($args: WasmTy,)*
1994        {
1995            fn valtypes() -> impl Iterator<Item = ValType> {
1996                IntoIterator::into_iter([$($args::valtype(),)*])
1997            }
1998
1999            unsafe fn load(_store: &mut AutoAssertNoGc<'_>, _values: &mut [MaybeUninit<ValRaw>]) -> Self {
2000                let mut _cur = 0;
2001                ($({
2002                    debug_assert!(_cur < _values.len());
2003                    // SAFETY: this function's own contract means that `_values`
2004                    // is appropriately sized/typed for the internal loads.
2005                    unsafe {
2006                        let ptr = _values.get_unchecked(_cur).assume_init_ref();
2007                        _cur += 1;
2008                        $args::load(_store, ptr)
2009                    }
2010                },)*)
2011            }
2012
2013            fn may_gc() -> bool {
2014                $( $args::may_gc() || )* false
2015            }
2016        }
2017    );
2018}
2019
2020for_each_function_signature!(impl_wasm_ty_list);
2021
2022/// A structure representing the caller's context when creating a function
2023/// via [`Func::wrap`].
2024///
2025/// This structure can be taken as the first parameter of a closure passed to
2026/// [`Func::wrap`] or other constructors, and serves two purposes:
2027///
2028/// * First consumers can use [`Caller<'_, T>`](crate::Caller) to get access to
2029///   [`StoreContextMut<'_, T>`](crate::StoreContextMut) and/or get access to
2030///   `T` itself. This means that the [`Caller`] type can serve as a proxy to
2031///   the original [`Store`](crate::Store) itself and is used to satisfy
2032///   [`AsContext`] and [`AsContextMut`] bounds.
2033///
2034/// * Second a [`Caller`] can be used as the name implies, learning about the
2035///   caller's context, namely it's exported memory and exported functions. This
2036///   allows functions which take pointers as arguments to easily read the
2037///   memory the pointers point into, or if a function is expected to call
2038///   malloc in the wasm module to reserve space for the output you can do that.
2039///
2040/// Host functions which want access to [`Store`](crate::Store)-level state are
2041/// recommended to use this type.
2042pub struct Caller<'a, T: 'static> {
2043    pub(crate) store: StoreContextMut<'a, T>,
2044    caller: Instance,
2045}
2046
2047impl<T> Caller<'_, T> {
2048    fn sub_caller(&mut self) -> Caller<'_, T> {
2049        Caller {
2050            store: self.store.as_context_mut(),
2051            caller: self.caller,
2052        }
2053    }
2054
2055    /// Looks up an export from the caller's module by the `name` given.
2056    ///
2057    /// This is a low-level function that's typically used to implement passing
2058    /// of pointers or indices between core Wasm instances, where the callee
2059    /// needs to consult the caller's exports to perform memory management and
2060    /// resolve the references.
2061    ///
2062    /// For comparison, in components, the component model handles translating
2063    /// arguments from one component instance to another and managing memory, so
2064    /// that callees don't need to be aware of their callers, which promotes
2065    /// virtualizability of APIs.
2066    ///
2067    /// # Return
2068    ///
2069    /// If an export with the `name` provided was found, then it is returned as an
2070    /// `Extern`. There are a number of situations, however, where the export may not
2071    /// be available:
2072    ///
2073    /// * The caller instance may not have an export named `name`
2074    /// * There may not be a caller available, for example if `Func` was called
2075    ///   directly from host code.
2076    ///
2077    /// It's recommended to take care when calling this API and gracefully
2078    /// handling a `None` return value.
2079    pub fn get_export(&mut self, name: &str) -> Option<Extern> {
2080        // All instances created have a `host_state` with a pointer pointing
2081        // back to themselves. If this caller doesn't have that `host_state`
2082        // then it probably means it was a host-created object like `Func::new`
2083        // which doesn't have any exports we want to return anyway.
2084        self.caller.get_export(&mut self.store, name)
2085    }
2086
2087    /// Looks up an exported [`Extern`] value by a [`ModuleExport`] value.
2088    ///
2089    /// This is similar to [`Self::get_export`] but uses a [`ModuleExport`]
2090    /// value to avoid string lookups where possible. [`ModuleExport`]s can be
2091    /// obtained by calling [`Module::get_export_index`] on the [`Module`] that
2092    /// an instance was instantiated with.
2093    ///
2094    /// This method will search the module for an export with a matching entity index and return
2095    /// the value, if found.
2096    ///
2097    /// Returns `None` if there was no export with a matching entity index.
2098    ///
2099    /// [`Module::get_export_index`]: crate::Module::get_export_index
2100    /// [`Module`]: crate::Module
2101    ///
2102    /// # Panics
2103    ///
2104    /// Panics if `store` does not own this instance.
2105    ///
2106    /// # Usage
2107    /// ```
2108    /// use std::str;
2109    ///
2110    /// # use wasmtime::*;
2111    /// # fn main() -> Result<()> {
2112    /// # let mut store = Store::default();
2113    ///
2114    /// let module = Module::new(
2115    ///     store.engine(),
2116    ///     r#"
2117    ///         (module
2118    ///             (import "" "" (func $log_str (param i32 i32)))
2119    ///             (func (export "foo")
2120    ///                 i32.const 4   ;; ptr
2121    ///                 i32.const 13  ;; len
2122    ///                 call $log_str)
2123    ///             (memory (export "memory") 1)
2124    ///             (data (i32.const 4) "Hello, world!"))
2125    ///     "#,
2126    /// )?;
2127    ///
2128    /// let Some(module_export) = module.get_export_index("memory") else {
2129    ///    bail!("failed to find `memory` export in module");
2130    /// };
2131    ///
2132    /// let log_str = Func::wrap(&mut store, move |mut caller: Caller<'_, ()>, ptr: i32, len: i32| {
2133    ///     let mem = match caller.get_module_export(&module_export) {
2134    ///         Some(Extern::Memory(mem)) => mem,
2135    ///         _ => bail!("failed to find host memory"),
2136    ///     };
2137    ///     let data = mem.data(&caller)
2138    ///         .get(ptr as u32 as usize..)
2139    ///         .and_then(|arr| arr.get(..len as u32 as usize));
2140    ///     let string = match data {
2141    ///         Some(data) => match str::from_utf8(data) {
2142    ///             Ok(s) => s,
2143    ///             Err(_) => bail!("invalid utf-8"),
2144    ///         },
2145    ///         None => bail!("pointer/length out of bounds"),
2146    ///     };
2147    ///     assert_eq!(string, "Hello, world!");
2148    ///     println!("{}", string);
2149    ///     Ok(())
2150    /// });
2151    /// let instance = Instance::new(&mut store, &module, &[log_str.into()])?;
2152    /// let foo = instance.get_typed_func::<(), ()>(&mut store, "foo")?;
2153    /// foo.call(&mut store, ())?;
2154    /// # Ok(())
2155    /// # }
2156    /// ```
2157    pub fn get_module_export(&mut self, export: &ModuleExport) -> Option<Extern> {
2158        self.caller.get_module_export(&mut self.store, export)
2159    }
2160
2161    /// Access the underlying data owned by this `Store`.
2162    ///
2163    /// Same as [`Store::data`](crate::Store::data)
2164    pub fn data(&self) -> &T {
2165        self.store.data()
2166    }
2167
2168    /// Access the underlying data owned by this `Store`.
2169    ///
2170    /// Same as [`Store::data_mut`](crate::Store::data_mut)
2171    pub fn data_mut(&mut self) -> &mut T {
2172        self.store.data_mut()
2173    }
2174
2175    /// Returns the underlying [`Engine`] this store is connected to.
2176    pub fn engine(&self) -> &Engine {
2177        self.store.engine()
2178    }
2179
2180    /// Perform garbage collection.
2181    ///
2182    /// Same as [`Store::gc`](crate::Store::gc).
2183    #[cfg(feature = "gc")]
2184    pub fn gc(&mut self, why: Option<&crate::GcHeapOutOfMemory<()>>) -> Result<()> {
2185        self.store.gc(why)
2186    }
2187
2188    /// Returns the current capacity of the GC heap in bytes.
2189    ///
2190    /// Same as [`Store::gc_heap_capacity`](crate::Store::gc_heap_capacity).
2191    #[cfg(feature = "gc")]
2192    pub fn gc_heap_capacity(&self) -> usize {
2193        self.store.0.gc_heap_capacity()
2194    }
2195
2196    /// Perform garbage collection asynchronously.
2197    ///
2198    /// Same as [`Store::gc_async`](crate::Store::gc_async).
2199    #[cfg(all(feature = "async", feature = "gc"))]
2200    pub async fn gc_async(&mut self, why: Option<&crate::GcHeapOutOfMemory<()>>) -> Result<()>
2201    where
2202        T: Send + 'static,
2203    {
2204        self.store.gc_async(why).await
2205    }
2206
2207    /// Returns the remaining fuel in the store.
2208    ///
2209    /// For more information see [`Store::get_fuel`](crate::Store::get_fuel)
2210    pub fn get_fuel(&self) -> Result<u64> {
2211        self.store.get_fuel()
2212    }
2213
2214    /// Set the amount of fuel in this store to be consumed when executing wasm code.
2215    ///
2216    /// For more information see [`Store::set_fuel`](crate::Store::set_fuel)
2217    pub fn set_fuel(&mut self, fuel: u64) -> Result<()> {
2218        self.store.set_fuel(fuel)
2219    }
2220
2221    /// Configures this `Store` to yield while executing futures every N units of fuel.
2222    ///
2223    /// For more information see
2224    /// [`Store::fuel_async_yield_interval`](crate::Store::fuel_async_yield_interval)
2225    #[cfg(feature = "async")]
2226    pub fn fuel_async_yield_interval(&mut self, interval: Option<u64>) -> Result<()> {
2227        self.store.fuel_async_yield_interval(interval)
2228    }
2229}
2230
2231impl<T: 'static> AsContext for Caller<'_, T> {
2232    type Data = T;
2233    fn as_context(&self) -> StoreContext<'_, T> {
2234        self.store.as_context()
2235    }
2236}
2237
2238impl<T: 'static> AsContextMut for Caller<'_, T> {
2239    fn as_context_mut(&mut self) -> StoreContextMut<'_, T> {
2240        self.store.as_context_mut()
2241    }
2242}
2243
2244impl<'a, T: 'static> From<Caller<'a, T>> for StoreContextMut<'a, T> {
2245    fn from(caller: Caller<'a, T>) -> Self {
2246        caller.store
2247    }
2248}
2249
2250/// Representation of a host-defined function.
2251///
2252/// This is used for `Func::new` but also for `Linker`-defined functions. For
2253/// `Func::new` this is stored within a `Store`, and for `Linker`-defined
2254/// functions they wrap this up in `Arc` to enable shared ownership of this
2255/// across many stores.
2256///
2257/// Technically this structure needs a `<T>` type parameter to connect to the
2258/// `Store<T>` itself, but that's an unsafe contract of using this for now
2259/// rather than part of the struct type (to avoid `Func<T>` in the API).
2260#[doc(hidden)]
2261pub struct HostFunc {
2262    ctx: StoreBox<VMArrayCallHostFuncContext>,
2263
2264    /// Whether or not this function was defined with an `async` host function,
2265    /// meaning that it is only invocable when wasm is itself on a fiber to
2266    /// support suspension on `Poll::Pending`.
2267    ///
2268    /// This is used to propagate to an `InstancePre` and then eventually into a
2269    /// `Store` as to whether the store requires async entrypoints.
2270    asyncness: Asyncness,
2271
2272    // Stored to unregister this function's signature with the engine when this
2273    // is dropped.
2274    engine: Engine,
2275}
2276
2277// State stored inside a `VMArrayCallHostFuncContext`.
2278struct HostFuncState<F> {
2279    // The actual host function.
2280    func: F,
2281
2282    // NB: We have to keep our `VMSharedTypeIndex` registered in the engine for
2283    // as long as this function exists.
2284    _ty: RegisteredType,
2285}
2286
2287impl core::fmt::Debug for HostFunc {
2288    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2289        f.debug_struct("HostFunc").finish_non_exhaustive()
2290    }
2291}
2292
2293impl HostFunc {
2294    /// Requires that the signature in `ctx` is already registered
2295    /// within `Engine`, which is done by [`Self::vmctx_sync`] and
2296    /// [`Self::vmctx_async`].
2297    ///
2298    /// This is an internal private constructor for this type intended to only
2299    /// be used by other constructors of this type below.
2300    fn new_raw(
2301        engine: &Engine,
2302        ctx: StoreBox<VMArrayCallHostFuncContext>,
2303        asyncness: Asyncness,
2304    ) -> Self {
2305        HostFunc {
2306            ctx,
2307            engine: engine.clone(),
2308            asyncness,
2309        }
2310    }
2311
2312    /// Constructor of a host function's `VMContext` for synchronous functions.
2313    ///
2314    /// This creates a `VMArrayCallHostFuncContext` which under the hood will
2315    /// be viewed as `VMContext` in the eventually created `VMFuncRef`.
2316    fn vmctx_sync<F, T>(
2317        engine: &Engine,
2318        ty: FuncType,
2319        func: F,
2320    ) -> Result<StoreBox<VMArrayCallHostFuncContext>, OutOfMemory>
2321    where
2322        F: Fn(Caller<'_, T>, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync + 'static,
2323        T: 'static,
2324    {
2325        assert!(ty.comes_from_same_engine(engine));
2326
2327        unsafe {
2328            VMArrayCallHostFuncContext::new(
2329                Self::array_call_trampoline::<T, F>,
2330                ty.type_index(),
2331                try_new::<Box<_>>(HostFuncState {
2332                    func,
2333                    _ty: ty.into_registered_type(),
2334                })?,
2335            )
2336        }
2337    }
2338
2339    /// Constructor of a host function's `VMContext` for asynchronous functions.
2340    ///
2341    /// This creates a `VMArrayCallHostFuncContext` which under the hood will
2342    /// be viewed as `VMContext` in the eventually created `VMFuncRef`.
2343    ///
2344    /// Note that `ctx: U` is forwarded directly to `func`. This is subtly
2345    /// different than closing over data in `F` because the future returned by
2346    /// `F` can't refer to any data it closes over. The purpose of `U` is to
2347    /// enable the returned future to be able to close over data generally
2348    /// captured in the closures generated here.
2349    #[cfg(feature = "async")]
2350    fn vmctx_async<F, T, U>(
2351        engine: &Engine,
2352        ty: FuncType,
2353        ctx: U,
2354        func: F,
2355    ) -> Result<StoreBox<VMArrayCallHostFuncContext>, OutOfMemory>
2356    where
2357        F: for<'a> Fn(
2358                Caller<'a, T>,
2359                &'a mut [MaybeUninit<ValRaw>],
2360                &'a U,
2361            ) -> Box<dyn Future<Output = Result<()>> + Send + 'a>
2362            + Send
2363            + Sync
2364            + 'static,
2365        T: 'static,
2366        U: Send + Sync + 'static,
2367    {
2368        // Eventually we want to remove `with_blocking` + `block_on` from
2369        // Wasmtime. For now this is the attempt to keep it as low-level as
2370        // possible.
2371        //
2372        // Generally it's a lie to run async things on top of sync things and
2373        // it's caused many headaches. For now it's the best that can be done.
2374        Self::vmctx_sync(engine, ty, move |Caller { store, caller }, args| {
2375            store.with_blocking(|store, cx| {
2376                cx.block_on(core::pin::Pin::from(func(
2377                    Caller { store, caller },
2378                    args,
2379                    &ctx,
2380                )))
2381            })?
2382        })
2383    }
2384
2385    /// Entrypoint of WebAssembly back into the host.
2386    ///
2387    /// This is the standard wasmtime "array call signature" which then
2388    /// delegates internally to the host. This assumes that `callee_vmctx` is a
2389    /// `VMArrayCallHostFuncContext` which was built above with
2390    /// `HostFuncState<F>` internally. This internal function is then used to
2391    /// dispatch based on the arguments.
2392    ///
2393    /// Details handled by this wrapper are:
2394    ///
2395    /// * Host panics are handled (`enter_host_from_wasm`)
2396    /// * `F` is loaded from `callee_vmctx`
2397    /// * `Caller` is constructed to pass to `F`
2398    /// * A GC LIFO scope is maintained around the execution of `F`.
2399    /// * Call hooks for entering/leaving the host are maintained.
2400    unsafe extern "C" fn array_call_trampoline<T, F>(
2401        callee_vmctx: NonNull<VMOpaqueContext>,
2402        caller_vmctx: NonNull<VMContext>,
2403        args: NonNull<ValRaw>,
2404        args_len: usize,
2405    ) -> bool
2406    where
2407        F: Fn(Caller<'_, T>, &mut [MaybeUninit<ValRaw>]) -> Result<()> + 'static,
2408        T: 'static,
2409    {
2410        let run = |store: &mut dyn crate::vm::VMStore, instance: InstanceId| {
2411            // SAFETY: correct usage of this trampoline requires correct
2412            // ascription of `T`, so it's the caller's responsibility to line
2413            // this up.
2414            let mut store = unsafe { store.unchecked_context_mut() };
2415
2416            // SAFETY: this function itself requires that the `vmctx` is
2417            // valid to use here.
2418            let state = unsafe {
2419                let vmctx = VMArrayCallHostFuncContext::from_opaque(callee_vmctx);
2420                vmctx.as_ref().host_state()
2421            };
2422
2423            // Double-check ourselves in debug mode, but we control the
2424            // `Any` here so an unsafe downcast should also work.
2425            //
2426            // SAFETY: this function is only usable with `F`.
2427            let state = unsafe {
2428                debug_assert!(state.is::<HostFuncState<F>>());
2429                &*(state as *const _ as *const HostFuncState<F>)
2430            };
2431
2432            let (gc_lifo_scope, ret) = {
2433                let gc_lifo_scope = store.0.enter_gc_lifo_scope();
2434
2435                let mut args = NonNull::slice_from_raw_parts(args.cast(), args_len);
2436                // SAFETY: it's a contract of this function itself that the values
2437                // provided are valid to view as a slice.
2438                let args = unsafe { args.as_mut() };
2439
2440                let ret = (state.func)(
2441                    Caller {
2442                        caller: Instance::from_wasmtime(instance, store.0),
2443                        store: store.as_context_mut(),
2444                    },
2445                    args,
2446                );
2447
2448                (gc_lifo_scope, ret)
2449            };
2450
2451            store.0.exit_gc_lifo_scope(gc_lifo_scope);
2452
2453            ret
2454        };
2455
2456        // SAFETY: this is an entrypoint of wasm which requires correct type
2457        // ascription of `T` itself, meaning that this should be safe to call
2458        // both `enter_host_from_wasm` as well as `unchecked_context_mut`.
2459        unsafe { vm::Instance::enter_host_from_wasm(caller_vmctx, run) }
2460    }
2461    /// Analog of [`Func::new_unchecked`]
2462    ///
2463    /// # Panics
2464    ///
2465    /// Panics if the given function type is not associated with the given
2466    /// engine.
2467    ///
2468    /// # Safety
2469    ///
2470    /// The `func` provided must operate according to the `ty` provided to
2471    /// ensure it's reading the correctly-typed parameters and writing the
2472    /// correctly-typed results.
2473    pub unsafe fn new_unchecked<T>(
2474        engine: &Engine,
2475        ty: FuncType,
2476        func: impl Fn(Caller<'_, T>, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync + 'static,
2477    ) -> Result<Self, OutOfMemory>
2478    where
2479        T: 'static,
2480    {
2481        Ok(HostFunc::new_raw(
2482            engine,
2483            Self::vmctx_sync(engine, ty, func)?,
2484            Asyncness::No,
2485        ))
2486    }
2487
2488    /// Analog of [`Func::new`]
2489    ///
2490    /// # Panics
2491    ///
2492    /// Panics if the given function type is not associated with the given
2493    /// engine.
2494    pub fn new<T>(
2495        engine: &Engine,
2496        ty: FuncType,
2497        func: impl Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()> + Send + Sync + 'static,
2498    ) -> Result<Self, OutOfMemory>
2499    where
2500        T: 'static,
2501    {
2502        // NB: this is "duplicated" below in `new_async`, so try to keep the
2503        // two in sync.
2504        Ok(HostFunc::new_raw(
2505            engine,
2506            Self::vmctx_sync(engine, ty.clone(), move |mut caller, values| {
2507                // SAFETY: Wasmtime in general provides the guarantee that
2508                // `values` matches `ty`, so this should be safe.
2509                let mut vec = unsafe { Self::load_untyped_params(caller.store.0, &ty, values)? };
2510                let (params, results) = vec.split_at_mut(ty.params().len());
2511                func(caller.sub_caller(), params, results)?;
2512                Self::store_untyped_results(caller.store, &ty, vec, values)
2513            })?,
2514            Asyncness::No,
2515        ))
2516    }
2517
2518    /// Analog of [`Func::new_async`]
2519    ///
2520    /// # Panics
2521    ///
2522    /// Panics if the given function type is not associated with the given
2523    /// engine.
2524    #[cfg(feature = "async")]
2525    pub fn new_async<T, F>(engine: &Engine, ty: FuncType, func: F) -> Result<Self, OutOfMemory>
2526    where
2527        F: for<'a> Fn(
2528                Caller<'a, T>,
2529                &'a [Val],
2530                &'a mut [Val],
2531            ) -> Box<dyn Future<Output = Result<()>> + Send + 'a>
2532            + Send
2533            + Sync
2534            + 'static,
2535        T: Send + 'static,
2536    {
2537        // NB: this is "duplicated" above in `new`, so try to keep the two in
2538        // sync.
2539        Ok(HostFunc::new_raw(
2540            engine,
2541            Self::vmctx_async(
2542                engine,
2543                ty.clone(),
2544                (ty, func),
2545                move |mut caller, values, (ty, func)| {
2546                    Box::new(async move {
2547                        // SAFETY: Wasmtime in general provides the guarantee that
2548                        // `values` matches `ty`, so this should be safe.
2549                        let mut vec =
2550                            unsafe { Self::load_untyped_params(caller.store.0, &ty, values)? };
2551                        let (params, results) = vec.split_at_mut(ty.params().len());
2552                        core::pin::Pin::from(func(caller.sub_caller(), params, results)).await?;
2553                        Self::store_untyped_results(caller.store, &ty, vec, values)
2554                    })
2555                },
2556            )?,
2557            Asyncness::Yes,
2558        ))
2559    }
2560
2561    /// Loads the the parameters of `ty` from `params` into a vector.
2562    ///
2563    /// This additionally pushes space onto the vector for all results to split
2564    /// the vector into params/results halves.
2565    ///
2566    /// # Safety
2567    ///
2568    /// Requires that `params` matches the parameters loaded by `P`.
2569    unsafe fn load_untyped_params(
2570        store: &mut StoreOpaque,
2571        ty: &FuncType,
2572        params: &mut [MaybeUninit<ValRaw>],
2573    ) -> Result<Vec<Val>> {
2574        let val_vec = store.take_hostcall_val_storage();
2575        debug_assert!(val_vec.is_empty());
2576
2577        let mut val_vec = TryVec::from(val_vec);
2578        let nparams = ty.params().len();
2579        let total = nparams + ty.results().len();
2580        val_vec.reserve(total)?;
2581
2582        let mut store = AutoAssertNoGc::new(store);
2583        for (i, ty) in ty.params().enumerate() {
2584            val_vec.push(unsafe { Val::_from_raw(&mut store, params[i].assume_init(), &ty) })?;
2585        }
2586
2587        val_vec.try_extend((0..ty.results().len()).map(|_| Val::null_func_ref()))?;
2588        Ok(val_vec.into())
2589    }
2590
2591    /// Stores the results, at the end of `args_then_results` according to `ty`,
2592    /// into `storage`.
2593    fn store_untyped_results<T>(
2594        mut store: StoreContextMut<'_, T>,
2595        ty: &FuncType,
2596        mut args_then_results: Vec<Val>,
2597        storage: &mut [MaybeUninit<ValRaw>],
2598    ) -> Result<()> {
2599        // Unlike our arguments we need to dynamically check that the return
2600        // values produced are correct. There could be a bug in `func` that
2601        // produces the wrong number, wrong types, or wrong stores of
2602        // values, and we need to catch that here.
2603        let results = &args_then_results[ty.params().len()..];
2604        for (i, (ret, ty)) in results.iter().zip(ty.results()).enumerate() {
2605            ret.validate_rooted()
2606                .context("function attempted to return an unrooted value")?;
2607            ret.ensure_matches_ty(store.0, &ty)
2608                .context("function attempted to return an incompatible value")?;
2609            storage[i].write(ret.to_raw(store.as_context_mut())?);
2610        }
2611
2612        // Restore our `val_vec` back into the store so it's usable for the next
2613        // hostcall to reuse our own storage.
2614        args_then_results.truncate(0);
2615        store.0.save_hostcall_val_storage(args_then_results);
2616        Ok(())
2617    }
2618
2619    /// Analog of [`Func::wrap`]
2620    pub fn wrap<T, F, P, R>(engine: &Engine, func: F) -> Result<Self, OutOfMemory>
2621    where
2622        F: Fn(Caller<'_, T>, P) -> R + Send + Sync + 'static,
2623        P: WasmTyList,
2624        R: WasmRet,
2625        T: 'static,
2626    {
2627        // NB: this entire function is "duplicated" below in `wrap_async`, so
2628        // try to keep the two in sync.
2629        let ty = R::func_type(engine, None::<ValType>.into_iter().chain(P::valtypes()))?;
2630
2631        let ctx = Self::vmctx_sync(engine, ty, move |mut caller, args| {
2632            // SAFETY: `args` matching `ty` is provided by `HostFunc` and
2633            // wasmtime's ambient correctness.
2634            let params = unsafe { Self::load_typed_params(caller.store.0, args) };
2635            let ret = func(caller.sub_caller(), params).into_fallible();
2636            // SAFETY: `args` matching `ty` is provided by `HostFunc` and
2637            // wasmtime's ambient correctness.
2638            unsafe { Self::store_typed_results(caller.store.0, ret, args) }
2639        })?;
2640        Ok(HostFunc::new_raw(engine, ctx, Asyncness::No))
2641    }
2642
2643    /// Analog of [`Func::wrap_async`]
2644    #[cfg(feature = "async")]
2645    pub fn wrap_async<T, F, P, R>(engine: &Engine, func: F) -> Result<Self, OutOfMemory>
2646    where
2647        F: for<'a> Fn(Caller<'a, T>, P) -> Box<dyn Future<Output = R> + Send + 'a>
2648            + Send
2649            + Sync
2650            + 'static,
2651        P: WasmTyList,
2652        R: WasmRet,
2653        T: Send + 'static,
2654    {
2655        // NB: this entire function is "duplicated" above in `wrap`, so try to
2656        // keep the two in sync.
2657        let ty = R::func_type(engine, None::<ValType>.into_iter().chain(P::valtypes()))?;
2658
2659        let ctx = Self::vmctx_async(engine, ty, func, move |mut caller, args, func| {
2660            Box::new(async move {
2661                // SAFETY: `args` matching `ty` is provided by `HostFunc` and
2662                // wasmtime's ambient correctness.
2663                let params = unsafe { Self::load_typed_params(caller.store.0, args) };
2664                let ret = core::pin::Pin::from(func(caller.sub_caller(), params)).await;
2665                // SAFETY: `args` matching `ty` is provided by `HostFunc` and
2666                // wasmtime's ambient correctness.
2667                unsafe { Self::store_typed_results(caller.store.0, ret.into_fallible(), args) }
2668            })
2669        })?;
2670        Ok(HostFunc::new_raw(engine, ctx, Asyncness::Yes))
2671    }
2672
2673    /// Loads the typed parameters from `params`
2674    ///
2675    /// # Safety
2676    ///
2677    /// Requires that `params` matches the parameters loaded by `P`.
2678    unsafe fn load_typed_params<P>(store: &mut StoreOpaque, params: &mut [MaybeUninit<ValRaw>]) -> P
2679    where
2680        P: WasmTyList,
2681    {
2682        let mut store = if P::may_gc() {
2683            AutoAssertNoGc::new(store)
2684        } else {
2685            unsafe { AutoAssertNoGc::disabled(store) }
2686        };
2687        // SAFETY: this function's own safety contract is the same as `P::load`.
2688        unsafe { P::load(&mut store, params) }
2689    }
2690
2691    /// Stores the results of `R` into the array provided.
2692    ///
2693    /// # Safety
2694    ///
2695    /// Requires that `ret` matches the result `storage` space. See `WasmRet`
2696    /// for more safety info.
2697    unsafe fn store_typed_results<R>(
2698        store: &mut StoreOpaque,
2699        ret: R,
2700        storage: &mut [MaybeUninit<ValRaw>],
2701    ) -> Result<()>
2702    where
2703        R: WasmRet,
2704    {
2705        ensure!(
2706            ret.compatible_with_store(store),
2707            "host function attempted to return cross-`Store` value to Wasm",
2708        );
2709
2710        let mut store = if R::may_gc() {
2711            AutoAssertNoGc::new(store)
2712        } else {
2713            unsafe { AutoAssertNoGc::disabled(store) }
2714        };
2715        // SAFETY: this safety contract is the same as this own function's
2716        // safety contract.
2717        unsafe {
2718            ret.store(&mut store, storage)?;
2719        }
2720        Ok(())
2721    }
2722
2723    /// Inserts this `HostFunc` into a `Store`, returning the `Func` pointing to
2724    /// it.
2725    ///
2726    /// # Unsafety
2727    ///
2728    /// Can only be inserted into stores with a matching `T` relative to when
2729    /// this `HostFunc` was first created.
2730    pub unsafe fn to_func(self: &Arc<Self>, store: &mut StoreOpaque) -> Result<Func, OutOfMemory> {
2731        self.validate_store(store);
2732        let (funcrefs, modules) = store.func_refs_and_modules();
2733        let funcref = funcrefs.push_arc_host(self.clone(), modules)?;
2734        // SAFETY: this funcref was just pushed within the store, so it's safe
2735        // to say this store owns it.
2736        Ok(unsafe { Func::from_vm_func_ref(store.id(), funcref) })
2737    }
2738
2739    /// Inserts this `HostFunc` into a `Store`, returning the `Func` pointing to
2740    /// it.
2741    ///
2742    /// This function is similar to, but not equivalent, to `HostFunc::to_func`.
2743    /// Notably this function requires that the `Arc<Self>` pointer is otherwise
2744    /// rooted within the `StoreOpaque` via another means. When in doubt use
2745    /// `to_func` above as it's safer.
2746    ///
2747    /// # Unsafety
2748    ///
2749    /// Can only be inserted into stores with a matching `T` relative to when
2750    /// this `HostFunc` was first created.
2751    ///
2752    /// Additionally the `&Arc<Self>` is not cloned in this function. Instead a
2753    /// raw pointer to `Self` is stored within the `Store` for this function.
2754    /// The caller must arrange for the `Arc<Self>` to be "rooted" in the store
2755    /// provided via another means, probably by pushing to
2756    /// `StoreOpaque::rooted_host_funcs`.
2757    ///
2758    /// Similarly, the caller must arrange for `rooted_func_ref` to be rooted in
2759    /// the same store and additionally be a valid pointer.
2760    pub unsafe fn to_func_store_rooted(
2761        self: &Arc<Self>,
2762        store: &mut StoreOpaque,
2763        rooted_func_ref: Option<NonNull<VMFuncRef>>,
2764    ) -> Func {
2765        self.validate_store(store);
2766
2767        match rooted_func_ref {
2768            Some(funcref) => {
2769                // SAFETY: it's a contract of this function itself that
2770                // `funcref` is safe to read.
2771                unsafe {
2772                    debug_assert!(funcref.as_ref().wasm_call.is_some());
2773                }
2774                // SAFETY: it's a contract of this function that `funcref` is
2775                // owned by `store`.
2776                unsafe { Func::from_vm_func_ref(store.id(), funcref) }
2777            }
2778            None => {
2779                debug_assert!(self.func_ref().wasm_call.is_some());
2780
2781                // SAFETY: it's an unsafe contract of this function that we are
2782                // rooted within the store to say that the store owns a copy of
2783                // this funcref.
2784                unsafe { Func::from_vm_func_ref(store.id(), self.func_ref().into()) }
2785            }
2786        }
2787    }
2788
2789    /// Same as [`HostFunc::to_func`], different ownership.
2790    unsafe fn into_func(self, store: &mut StoreOpaque) -> Result<Func, OutOfMemory> {
2791        self.validate_store(store);
2792
2793        let (funcrefs, modules) = store.func_refs_and_modules();
2794        let funcref = funcrefs.push_box_host(try_new::<Box<_>>(self)?, modules)?;
2795        // SAFETY: this funcref was just pushed within `store`, so it's safe to
2796        // say it's owned by the store's id.
2797        Ok(unsafe { Func::from_vm_func_ref(store.id(), funcref) })
2798    }
2799
2800    fn validate_store(&self, store: &mut StoreOpaque) {
2801        // This assert is required to ensure that we can indeed safely insert
2802        // `self` into the `store` provided, otherwise the type information we
2803        // have listed won't be correct. This is possible to hit with the public
2804        // API of Wasmtime, and should be documented in relevant functions.
2805        assert!(
2806            Engine::same(&self.engine, store.engine()),
2807            "cannot use a store with a different engine than a linker was created with",
2808        );
2809
2810        // This function could be called by a guest at any time, and it requires
2811        // fibers, so the store now required async entrypoints.
2812        store.set_async_required(self.asyncness);
2813    }
2814
2815    pub(crate) fn engine(&self) -> &Engine {
2816        &self.engine
2817    }
2818
2819    pub(crate) fn sig_index(&self) -> VMSharedTypeIndex {
2820        self.func_ref().type_index
2821    }
2822
2823    pub(crate) fn func_ref(&self) -> &VMFuncRef {
2824        unsafe { self.ctx.get().as_ref().func_ref() }
2825    }
2826
2827    pub(crate) fn asyncness(&self) -> Asyncness {
2828        self.asyncness
2829    }
2830}
2831
2832#[cfg(test)]
2833mod tests {
2834    use super::*;
2835    use crate::{Module, Store};
2836
2837    #[test]
2838    #[cfg_attr(miri, ignore)]
2839    fn hash_key_is_stable_across_duplicate_store_data_entries() -> Result<()> {
2840        let mut store = Store::<()>::default();
2841        let module = Module::new(
2842            store.engine(),
2843            r#"
2844                (module
2845                    (func (export "f")
2846                        nop
2847                    )
2848                )
2849            "#,
2850        )?;
2851        let instance = Instance::new(&mut store, &module, &[])?;
2852
2853        // Each time we `get_func`, we call `Func::from_wasmtime` which adds a
2854        // new entry to `StoreData`, so `f1` and `f2` will have different
2855        // indices into `StoreData`.
2856        let f1 = instance.get_func(&mut store, "f").unwrap();
2857        let f2 = instance.get_func(&mut store, "f").unwrap();
2858
2859        // But their hash keys are the same.
2860        assert!(
2861            f1.hash_key(&mut store.as_context_mut().0)
2862                == f2.hash_key(&mut store.as_context_mut().0)
2863        );
2864
2865        // But the hash keys are different from different funcs.
2866        let instance2 = Instance::new(&mut store, &module, &[])?;
2867        let f3 = instance2.get_func(&mut store, "f").unwrap();
2868        assert!(
2869            f1.hash_key(&mut store.as_context_mut().0)
2870                != f3.hash_key(&mut store.as_context_mut().0)
2871        );
2872
2873        Ok(())
2874    }
2875}