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