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