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