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