1c2112959SNick Fitzgerald use crate::error::OutOfMemory;
281a89169SAlex Crichton use crate::prelude::*;
372004aadSNick Fitzgerald use crate::runtime::vm::{
482941262SAlex Crichton     self, InterpreterRef, SendSyncPtr, StoreBox, VMArrayCallHostFuncContext,
582941262SAlex Crichton     VMCommonStackInformation, VMContext, VMFuncRef, VMFunctionImport, VMOpaqueContext,
682941262SAlex Crichton     VMStoreContext,
772004aadSNick Fitzgerald };
8cc8d04f4SAlex Crichton use crate::store::{Asyncness, AutoAssertNoGc, InstanceId, StoreId, StoreOpaque};
98652011fSNick Fitzgerald use crate::type_registry::RegisteredType;
10d4242001SAdam Bratschi-Kaye use crate::{
114fcfe17aSAlex Crichton     AsContext, AsContextMut, CallHook, Engine, Extern, FuncType, Instance, ModuleExport, Ref,
124fcfe17aSAlex Crichton     StoreContext, StoreContextMut, Val, ValRaw, ValType,
13d4242001SAdam Bratschi-Kaye };
1481a89169SAlex Crichton use alloc::sync::Arc;
151d738975SNick Fitzgerald use core::convert::Infallible;
1681a89169SAlex Crichton use core::ffi::c_void;
17421136d0SJoel Dice #[cfg(feature = "async")]
18421136d0SJoel Dice use core::future::Future;
191d11b265SAlex Crichton use core::mem::{self, MaybeUninit};
202e6b18f0SAlex Crichton use core::ptr::NonNull;
21c2112959SNick Fitzgerald use wasmtime_environ::{PanicOnOom as _, VMSharedTypeIndex};
22d4242001SAdam Bratschi-Kaye 
23ff93bce0SNick Fitzgerald /// A reference to the abstract `nofunc` heap value.
24ff93bce0SNick Fitzgerald ///
25ff93bce0SNick Fitzgerald /// The are no instances of `(ref nofunc)`: it is an uninhabited type.
26ff93bce0SNick Fitzgerald ///
27ff93bce0SNick Fitzgerald /// There is precisely one instance of `(ref null nofunc)`, aka `nullfuncref`:
28ff93bce0SNick Fitzgerald /// the null reference.
29ff93bce0SNick Fitzgerald ///
30ff93bce0SNick Fitzgerald /// This `NoFunc` Rust type's sole purpose is for use with [`Func::wrap`]- and
31ff93bce0SNick Fitzgerald /// [`Func::typed`]-style APIs for statically typing a function as taking or
32ff93bce0SNick Fitzgerald /// returning a `(ref null nofunc)` (aka `Option<NoFunc>`) which is always
33ff93bce0SNick Fitzgerald /// `None`.
34ff93bce0SNick Fitzgerald ///
35ff93bce0SNick Fitzgerald /// # Example
36ff93bce0SNick Fitzgerald ///
37ff93bce0SNick Fitzgerald /// ```
38ff93bce0SNick Fitzgerald /// # use wasmtime::*;
39ff93bce0SNick Fitzgerald /// # fn _foo() -> Result<()> {
40ff93bce0SNick Fitzgerald /// let mut config = Config::new();
41ff93bce0SNick Fitzgerald /// config.wasm_function_references(true);
42ff93bce0SNick Fitzgerald /// let engine = Engine::new(&config)?;
43ff93bce0SNick Fitzgerald ///
44ff93bce0SNick Fitzgerald /// let module = Module::new(
45ff93bce0SNick Fitzgerald ///     &engine,
46ff93bce0SNick Fitzgerald ///     r#"
47ff93bce0SNick Fitzgerald ///         (module
48ff93bce0SNick Fitzgerald ///             (func (export "f") (param (ref null nofunc))
49ff93bce0SNick Fitzgerald ///                 ;; If the reference is null, return.
50ff93bce0SNick Fitzgerald ///                 local.get 0
51ff93bce0SNick Fitzgerald ///                 ref.is_null nofunc
52ff93bce0SNick Fitzgerald ///                 br_if 0
53ff93bce0SNick Fitzgerald ///
54ff93bce0SNick Fitzgerald ///                 ;; If the reference was not null (which is impossible)
55ff93bce0SNick Fitzgerald ///                 ;; then raise a trap.
56ff93bce0SNick Fitzgerald ///                 unreachable
57ff93bce0SNick Fitzgerald ///             )
58ff93bce0SNick Fitzgerald ///         )
59ff93bce0SNick Fitzgerald ///     "#,
60ff93bce0SNick Fitzgerald /// )?;
61ff93bce0SNick Fitzgerald ///
62ff93bce0SNick Fitzgerald /// let mut store = Store::new(&engine, ());
63ff93bce0SNick Fitzgerald /// let instance = Instance::new(&mut store, &module, &[])?;
64ff93bce0SNick Fitzgerald /// let f = instance.get_func(&mut store, "f").unwrap();
65ff93bce0SNick Fitzgerald ///
66ff93bce0SNick Fitzgerald /// // We can cast a `(ref null nofunc)`-taking function into a typed function that
67ff93bce0SNick Fitzgerald /// // takes an `Option<NoFunc>` via the `Func::typed` method.
68ff93bce0SNick Fitzgerald /// let f = f.typed::<Option<NoFunc>, ()>(&store)?;
69ff93bce0SNick Fitzgerald ///
70ff93bce0SNick Fitzgerald /// // We can call the typed function, passing the null `nofunc` reference.
71ff93bce0SNick Fitzgerald /// let result = f.call(&mut store, NoFunc::null());
72ff93bce0SNick Fitzgerald ///
73ff93bce0SNick Fitzgerald /// // The function should not have trapped, because the reference we gave it was
74ff93bce0SNick Fitzgerald /// // null (as it had to be, since `NoFunc` is uninhabited).
75ff93bce0SNick Fitzgerald /// assert!(result.is_ok());
76ff93bce0SNick Fitzgerald /// # Ok(())
77ff93bce0SNick Fitzgerald /// # }
78ff93bce0SNick Fitzgerald /// ```
79ff93bce0SNick Fitzgerald #[derive(Copy, Clone, Debug, PartialEq, Eq)]
80ff93bce0SNick Fitzgerald pub struct NoFunc {
811d738975SNick Fitzgerald     _inner: Infallible,
82ff93bce0SNick Fitzgerald }
83ff93bce0SNick Fitzgerald 
84ff93bce0SNick Fitzgerald impl NoFunc {
85ff93bce0SNick Fitzgerald     /// Get the null `(ref null nofunc)` (aka `nullfuncref`) reference.
86ff93bce0SNick Fitzgerald     #[inline]
null() -> Option<NoFunc>87ff93bce0SNick Fitzgerald     pub fn null() -> Option<NoFunc> {
88ff93bce0SNick Fitzgerald         None
89ff93bce0SNick Fitzgerald     }
90ff93bce0SNick Fitzgerald 
91ff93bce0SNick Fitzgerald     /// Get the null `(ref null nofunc)` (aka `nullfuncref`) reference as a
92ff93bce0SNick Fitzgerald     /// [`Ref`].
9322a3d9edSNick Fitzgerald     #[inline]
null_ref() -> Ref94ff93bce0SNick Fitzgerald     pub fn null_ref() -> Ref {
95ff93bce0SNick Fitzgerald         Ref::Func(None)
96ff93bce0SNick Fitzgerald     }
97ff93bce0SNick Fitzgerald 
98ff93bce0SNick Fitzgerald     /// Get the null `(ref null nofunc)` (aka `nullfuncref`) reference as a
99ff93bce0SNick Fitzgerald     /// [`Val`].
10022a3d9edSNick Fitzgerald     #[inline]
null_val() -> Val101ff93bce0SNick Fitzgerald     pub fn null_val() -> Val {
102ff93bce0SNick Fitzgerald         Val::FuncRef(None)
103ff93bce0SNick Fitzgerald     }
104ff93bce0SNick Fitzgerald }
105ff93bce0SNick Fitzgerald 
106d4242001SAdam Bratschi-Kaye /// A WebAssembly function which can be called.
107d4242001SAdam Bratschi-Kaye ///
1086d105f4dSAlex Crichton /// This type typically represents an exported function from a WebAssembly
1096d105f4dSAlex Crichton /// module instance. In this case a [`Func`] belongs to an [`Instance`] and is
1106d105f4dSAlex Crichton /// loaded from there. A [`Func`] may also represent a host function as well in
1116d105f4dSAlex Crichton /// some cases, too.
112d4242001SAdam Bratschi-Kaye ///
1136d105f4dSAlex Crichton /// Functions can be called in a few different ways, either synchronous or async
1146d105f4dSAlex Crichton /// and either typed or untyped (more on this below). Note that host functions
1156d105f4dSAlex Crichton /// are normally inserted directly into a [`Linker`](crate::Linker) rather than
1166d105f4dSAlex Crichton /// using this directly, but both options are available.
117d4242001SAdam Bratschi-Kaye ///
118d4242001SAdam Bratschi-Kaye /// # `Func` and `async`
119d4242001SAdam Bratschi-Kaye ///
120d4242001SAdam Bratschi-Kaye /// Functions from the perspective of WebAssembly are always synchronous. You
121d4242001SAdam Bratschi-Kaye /// might have an `async` function in Rust, however, which you'd like to make
122d4242001SAdam Bratschi-Kaye /// available from WebAssembly. Wasmtime supports asynchronously calling
123d4242001SAdam Bratschi-Kaye /// WebAssembly through native stack switching. You can get some more
124cc8d04f4SAlex Crichton /// information about [asynchronous configs](crate#async), but
125d4242001SAdam Bratschi-Kaye /// from the perspective of `Func` it's important to know that whether or not
126d4242001SAdam Bratschi-Kaye /// your [`Store`](crate::Store) is asynchronous will dictate whether you call
127d4242001SAdam Bratschi-Kaye /// functions through [`Func::call`] or [`Func::call_async`] (or the typed
128d4242001SAdam Bratschi-Kaye /// wrappers such as [`TypedFunc::call`] vs [`TypedFunc::call_async`]).
129d4242001SAdam Bratschi-Kaye ///
130d4242001SAdam Bratschi-Kaye /// # To `Func::call` or to `Func::typed().call()`
131d4242001SAdam Bratschi-Kaye ///
132d4242001SAdam Bratschi-Kaye /// There's a 2x2 matrix of methods to call [`Func`]. Invocations can either be
133d4242001SAdam Bratschi-Kaye /// asynchronous or synchronous. They can also be statically typed or not.
134d4242001SAdam Bratschi-Kaye /// Whether or not an invocation is asynchronous is indicated via the method
135d4242001SAdam Bratschi-Kaye /// being `async` and [`call_async`](Func::call_async) being the entry point.
136d4242001SAdam Bratschi-Kaye /// Otherwise for statically typed or not your options are:
137d4242001SAdam Bratschi-Kaye ///
138d4242001SAdam Bratschi-Kaye /// * Dynamically typed - if you don't statically know the signature of the
139d4242001SAdam Bratschi-Kaye ///   function that you're calling you'll be using [`Func::call`] or
140d4242001SAdam Bratschi-Kaye ///   [`Func::call_async`]. These functions take a variable-length slice of
141d4242001SAdam Bratschi-Kaye ///   "boxed" arguments in their [`Val`] representation. Additionally the
142d4242001SAdam Bratschi-Kaye ///   results are returned as an owned slice of [`Val`]. These methods are not
143d4242001SAdam Bratschi-Kaye ///   optimized due to the dynamic type checks that must occur, in addition to
144d4242001SAdam Bratschi-Kaye ///   some dynamic allocations for where to put all the arguments. While this
145d4242001SAdam Bratschi-Kaye ///   allows you to call all possible wasm function signatures, if you're
146d4242001SAdam Bratschi-Kaye ///   looking for a speedier alternative you can also use...
147d4242001SAdam Bratschi-Kaye ///
148d4242001SAdam Bratschi-Kaye /// * Statically typed - if you statically know the type signature of the wasm
149d4242001SAdam Bratschi-Kaye ///   function you're calling, then you'll want to use the [`Func::typed`]
150d4242001SAdam Bratschi-Kaye ///   method to acquire an instance of [`TypedFunc`]. This structure is static proof
151d4242001SAdam Bratschi-Kaye ///   that the underlying wasm function has the ascripted type, and type
152d4242001SAdam Bratschi-Kaye ///   validation is only done once up-front. The [`TypedFunc::call`] and
153d4242001SAdam Bratschi-Kaye ///   [`TypedFunc::call_async`] methods are much more efficient than [`Func::call`]
154d4242001SAdam Bratschi-Kaye ///   and [`Func::call_async`] because the type signature is statically known.
155d4242001SAdam Bratschi-Kaye ///   This eschews runtime checks as much as possible to get into wasm as fast
156d4242001SAdam Bratschi-Kaye ///   as possible.
157d4242001SAdam Bratschi-Kaye ///
158d4242001SAdam Bratschi-Kaye /// # Examples
159d4242001SAdam Bratschi-Kaye ///
160d4242001SAdam Bratschi-Kaye /// One way to get a `Func` is from an [`Instance`] after you've instantiated
161d4242001SAdam Bratschi-Kaye /// it:
162d4242001SAdam Bratschi-Kaye ///
163d4242001SAdam Bratschi-Kaye /// ```
164d4242001SAdam Bratschi-Kaye /// # use wasmtime::*;
16596e19700SNick Fitzgerald /// # fn main() -> Result<()> {
166d4242001SAdam Bratschi-Kaye /// let engine = Engine::default();
167d4242001SAdam Bratschi-Kaye /// let module = Module::new(&engine, r#"(module (func (export "foo")))"#)?;
168d4242001SAdam Bratschi-Kaye /// let mut store = Store::new(&engine, ());
169d4242001SAdam Bratschi-Kaye /// let instance = Instance::new(&mut store, &module, &[])?;
170d4242001SAdam Bratschi-Kaye /// let foo = instance.get_func(&mut store, "foo").expect("export wasn't a function");
171d4242001SAdam Bratschi-Kaye ///
172d4242001SAdam Bratschi-Kaye /// // Work with `foo` as a `Func` at this point, such as calling it
173d4242001SAdam Bratschi-Kaye /// // dynamically...
174d4242001SAdam Bratschi-Kaye /// match foo.call(&mut store, &[], &mut []) {
175d4242001SAdam Bratschi-Kaye ///     Ok(()) => { /* ... */ }
176d4242001SAdam Bratschi-Kaye ///     Err(trap) => {
177d4242001SAdam Bratschi-Kaye ///         panic!("execution of `foo` resulted in a wasm trap: {}", trap);
178d4242001SAdam Bratschi-Kaye ///     }
179d4242001SAdam Bratschi-Kaye /// }
180d4242001SAdam Bratschi-Kaye /// foo.call(&mut store, &[], &mut [])?;
181d4242001SAdam Bratschi-Kaye ///
182d4242001SAdam Bratschi-Kaye /// // ... or we can make a static assertion about its signature and call it.
183d4242001SAdam Bratschi-Kaye /// // Our first call here can fail if the signatures don't match, and then the
184d4242001SAdam Bratschi-Kaye /// // second call can fail if the function traps (like the `match` above).
185d4242001SAdam Bratschi-Kaye /// let foo = foo.typed::<(), ()>(&store)?;
186d4242001SAdam Bratschi-Kaye /// foo.call(&mut store, ())?;
187d4242001SAdam Bratschi-Kaye /// # Ok(())
188d4242001SAdam Bratschi-Kaye /// # }
189d4242001SAdam Bratschi-Kaye /// ```
190d4242001SAdam Bratschi-Kaye ///
191d4242001SAdam Bratschi-Kaye /// You can also use the [`wrap` function](Func::wrap) to create a
192d4242001SAdam Bratschi-Kaye /// `Func`
193d4242001SAdam Bratschi-Kaye ///
194d4242001SAdam Bratschi-Kaye /// ```
195d4242001SAdam Bratschi-Kaye /// # use wasmtime::*;
19696e19700SNick Fitzgerald /// # fn main() -> Result<()> {
197d4242001SAdam Bratschi-Kaye /// let mut store = Store::<()>::default();
198d4242001SAdam Bratschi-Kaye ///
199d4242001SAdam Bratschi-Kaye /// // Create a custom `Func` which can execute arbitrary code inside of the
200d4242001SAdam Bratschi-Kaye /// // closure.
201d4242001SAdam Bratschi-Kaye /// let add = Func::wrap(&mut store, |a: i32, b: i32| -> i32 { a + b });
202d4242001SAdam Bratschi-Kaye ///
203d4242001SAdam Bratschi-Kaye /// // Next we can hook that up to a wasm module which uses it.
204d4242001SAdam Bratschi-Kaye /// let module = Module::new(
205d4242001SAdam Bratschi-Kaye ///     store.engine(),
206d4242001SAdam Bratschi-Kaye ///     r#"
207d4242001SAdam Bratschi-Kaye ///         (module
208d4242001SAdam Bratschi-Kaye ///             (import "" "" (func $add (param i32 i32) (result i32)))
209d4242001SAdam Bratschi-Kaye ///             (func (export "call_add_twice") (result i32)
210d4242001SAdam Bratschi-Kaye ///                 i32.const 1
211d4242001SAdam Bratschi-Kaye ///                 i32.const 2
212d4242001SAdam Bratschi-Kaye ///                 call $add
213d4242001SAdam Bratschi-Kaye ///                 i32.const 3
214d4242001SAdam Bratschi-Kaye ///                 i32.const 4
215d4242001SAdam Bratschi-Kaye ///                 call $add
216d4242001SAdam Bratschi-Kaye ///                 i32.add))
217d4242001SAdam Bratschi-Kaye ///     "#,
218d4242001SAdam Bratschi-Kaye /// )?;
219d4242001SAdam Bratschi-Kaye /// let instance = Instance::new(&mut store, &module, &[add.into()])?;
220d4242001SAdam Bratschi-Kaye /// let call_add_twice = instance.get_typed_func::<(), i32>(&mut store, "call_add_twice")?;
221d4242001SAdam Bratschi-Kaye ///
222d4242001SAdam Bratschi-Kaye /// assert_eq!(call_add_twice.call(&mut store, ())?, 10);
223d4242001SAdam Bratschi-Kaye /// # Ok(())
224d4242001SAdam Bratschi-Kaye /// # }
225d4242001SAdam Bratschi-Kaye /// ```
226d4242001SAdam Bratschi-Kaye ///
227d4242001SAdam Bratschi-Kaye /// Or you could also create an entirely dynamic `Func`!
228d4242001SAdam Bratschi-Kaye ///
229d4242001SAdam Bratschi-Kaye /// ```
230d4242001SAdam Bratschi-Kaye /// # use wasmtime::*;
23196e19700SNick Fitzgerald /// # fn main() -> Result<()> {
232d4242001SAdam Bratschi-Kaye /// let mut store = Store::<()>::default();
233d4242001SAdam Bratschi-Kaye ///
234d4242001SAdam Bratschi-Kaye /// // Here we need to define the type signature of our `Double` function and
235d4242001SAdam Bratschi-Kaye /// // then wrap it up in a `Func`
236d4242001SAdam Bratschi-Kaye /// let double_type = wasmtime::FuncType::new(
2378652011fSNick Fitzgerald ///     store.engine(),
238d4242001SAdam Bratschi-Kaye ///     [wasmtime::ValType::I32].iter().cloned(),
239d4242001SAdam Bratschi-Kaye ///     [wasmtime::ValType::I32].iter().cloned(),
240d4242001SAdam Bratschi-Kaye /// );
241d4242001SAdam Bratschi-Kaye /// let double = Func::new(&mut store, double_type, |_, params, results| {
242d4242001SAdam Bratschi-Kaye ///     let mut value = params[0].unwrap_i32();
243d4242001SAdam Bratschi-Kaye ///     value *= 2;
244d4242001SAdam Bratschi-Kaye ///     results[0] = value.into();
245d4242001SAdam Bratschi-Kaye ///     Ok(())
246d4242001SAdam Bratschi-Kaye /// });
247d4242001SAdam Bratschi-Kaye ///
248d4242001SAdam Bratschi-Kaye /// let module = Module::new(
249d4242001SAdam Bratschi-Kaye ///     store.engine(),
250d4242001SAdam Bratschi-Kaye ///     r#"
251d4242001SAdam Bratschi-Kaye ///         (module
252d4242001SAdam Bratschi-Kaye ///             (import "" "" (func $double (param i32) (result i32)))
253d4242001SAdam Bratschi-Kaye ///             (func $start
254d4242001SAdam Bratschi-Kaye ///                 i32.const 1
255d4242001SAdam Bratschi-Kaye ///                 call $double
256d4242001SAdam Bratschi-Kaye ///                 drop)
257d4242001SAdam Bratschi-Kaye ///             (start $start))
258d4242001SAdam Bratschi-Kaye ///     "#,
259d4242001SAdam Bratschi-Kaye /// )?;
260d4242001SAdam Bratschi-Kaye /// let instance = Instance::new(&mut store, &module, &[double.into()])?;
261d4242001SAdam Bratschi-Kaye /// // .. work with `instance` if necessary
262d4242001SAdam Bratschi-Kaye /// # Ok(())
263d4242001SAdam Bratschi-Kaye /// # }
264d4242001SAdam Bratschi-Kaye /// ```
265d4242001SAdam Bratschi-Kaye #[derive(Copy, Clone, Debug)]
2664fcfe17aSAlex Crichton #[repr(C)] // here for the C API
2674fcfe17aSAlex Crichton pub struct Func {
2684fcfe17aSAlex Crichton     /// The store that the below pointer belongs to.
2694fcfe17aSAlex Crichton     ///
2704fcfe17aSAlex Crichton     /// It's only safe to look at the contents of the pointer below when the
2714fcfe17aSAlex Crichton     /// `StoreOpaque` matching this id is in-scope.
2724fcfe17aSAlex Crichton     store: StoreId,
273d4242001SAdam Bratschi-Kaye 
2744fcfe17aSAlex Crichton     /// The raw `VMFuncRef`, whose lifetime is bound to the store this func
2754fcfe17aSAlex Crichton     /// belongs to.
2764fcfe17aSAlex Crichton     ///
2774fcfe17aSAlex Crichton     /// Note that this field has an `unsafe_*` prefix to discourage use of it.
2784fcfe17aSAlex Crichton     /// This is only safe to read/use if `self.store` is validated to belong to
2794fcfe17aSAlex Crichton     /// an ambiently provided `StoreOpaque` or similar. Use the
2804fcfe17aSAlex Crichton     /// `self.func_ref()` method instead of this field to perform this check.
2814fcfe17aSAlex Crichton     unsafe_func_ref: SendSyncPtr<VMFuncRef>,
282d4242001SAdam Bratschi-Kaye }
283d4242001SAdam Bratschi-Kaye 
2844fcfe17aSAlex Crichton // Double-check that the C representation in `extern.h` matches our in-Rust
2854fcfe17aSAlex Crichton // representation here in terms of size/alignment/etc.
2864fcfe17aSAlex Crichton const _: () = {
2874fcfe17aSAlex Crichton     #[repr(C)]
2884fcfe17aSAlex Crichton     struct C(u64, *mut u8);
2894fcfe17aSAlex Crichton     assert!(core::mem::size_of::<C>() == core::mem::size_of::<Func>());
2904fcfe17aSAlex Crichton     assert!(core::mem::align_of::<C>() == core::mem::align_of::<Func>());
2914fcfe17aSAlex Crichton     assert!(core::mem::offset_of!(Func, store) == 0);
2924fcfe17aSAlex Crichton };
293d4242001SAdam Bratschi-Kaye 
294d4242001SAdam Bratschi-Kaye macro_rules! for_each_function_signature {
295d4242001SAdam Bratschi-Kaye     ($mac:ident) => {
296d4242001SAdam Bratschi-Kaye         $mac!(0);
297d4242001SAdam Bratschi-Kaye         $mac!(1 A1);
298d4242001SAdam Bratschi-Kaye         $mac!(2 A1 A2);
299d4242001SAdam Bratschi-Kaye         $mac!(3 A1 A2 A3);
300d4242001SAdam Bratschi-Kaye         $mac!(4 A1 A2 A3 A4);
301d4242001SAdam Bratschi-Kaye         $mac!(5 A1 A2 A3 A4 A5);
302d4242001SAdam Bratschi-Kaye         $mac!(6 A1 A2 A3 A4 A5 A6);
303d4242001SAdam Bratschi-Kaye         $mac!(7 A1 A2 A3 A4 A5 A6 A7);
304d4242001SAdam Bratschi-Kaye         $mac!(8 A1 A2 A3 A4 A5 A6 A7 A8);
305d4242001SAdam Bratschi-Kaye         $mac!(9 A1 A2 A3 A4 A5 A6 A7 A8 A9);
306d4242001SAdam Bratschi-Kaye         $mac!(10 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10);
307d4242001SAdam Bratschi-Kaye         $mac!(11 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11);
308d4242001SAdam Bratschi-Kaye         $mac!(12 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12);
309d4242001SAdam Bratschi-Kaye         $mac!(13 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13);
310d4242001SAdam Bratschi-Kaye         $mac!(14 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14);
311d4242001SAdam Bratschi-Kaye         $mac!(15 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 A15);
312d4242001SAdam Bratschi-Kaye         $mac!(16 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 A15 A16);
31358f82587SJanito Vaqueiro Ferreira Filho         $mac!(17 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 A15 A16 A17);
314d4242001SAdam Bratschi-Kaye     };
315d4242001SAdam Bratschi-Kaye }
316d4242001SAdam Bratschi-Kaye 
317d4242001SAdam Bratschi-Kaye mod typed;
31863d482c8SFrank Emrich use crate::runtime::vm::VMStackChain;
319d4242001SAdam Bratschi-Kaye pub use typed::*;
320d4242001SAdam Bratschi-Kaye 
321d4242001SAdam Bratschi-Kaye impl Func {
322d4242001SAdam Bratschi-Kaye     /// Creates a new `Func` with the given arguments, typically to create a
323d4242001SAdam Bratschi-Kaye     /// host-defined function to pass as an import to a module.
324d4242001SAdam Bratschi-Kaye     ///
325d4242001SAdam Bratschi-Kaye     /// * `store` - the store in which to create this [`Func`], which will own
326d4242001SAdam Bratschi-Kaye     ///   the return value.
327d4242001SAdam Bratschi-Kaye     ///
328d4242001SAdam Bratschi-Kaye     /// * `ty` - the signature of this function, used to indicate what the
329d4242001SAdam Bratschi-Kaye     ///   inputs and outputs are.
330d4242001SAdam Bratschi-Kaye     ///
331d4242001SAdam Bratschi-Kaye     /// * `func` - the native code invoked whenever this `Func` will be called.
332d4242001SAdam Bratschi-Kaye     ///   This closure is provided a [`Caller`] as its first argument to learn
333d4242001SAdam Bratschi-Kaye     ///   information about the caller, and then it's passed a list of
334d4242001SAdam Bratschi-Kaye     ///   parameters as a slice along with a mutable slice of where to write
335d4242001SAdam Bratschi-Kaye     ///   results.
336d4242001SAdam Bratschi-Kaye     ///
337d4242001SAdam Bratschi-Kaye     /// Note that the implementation of `func` must adhere to the `ty` signature
338d4242001SAdam Bratschi-Kaye     /// given, error or traps may occur if it does not respect the `ty`
339d4242001SAdam Bratschi-Kaye     /// signature. For example if the function type declares that it returns one
340d4242001SAdam Bratschi-Kaye     /// i32 but the `func` closures does not write anything into the results
341d4242001SAdam Bratschi-Kaye     /// slice then a trap may be generated.
342d4242001SAdam Bratschi-Kaye     ///
343d4242001SAdam Bratschi-Kaye     /// Additionally note that this is quite a dynamic function since signatures
344d4242001SAdam Bratschi-Kaye     /// are not statically known. For a more performant and ergonomic `Func`
345d4242001SAdam Bratschi-Kaye     /// it's recommended to use [`Func::wrap`] if you can because with
346d4242001SAdam Bratschi-Kaye     /// statically known signatures Wasmtime can optimize the implementation
347d4242001SAdam Bratschi-Kaye     /// much more.
348d4242001SAdam Bratschi-Kaye     ///
349d4242001SAdam Bratschi-Kaye     /// For more information about `Send + Sync + 'static` requirements on the
350d4242001SAdam Bratschi-Kaye     /// `func`, see [`Func::wrap`](#why-send--sync--static).
351d4242001SAdam Bratschi-Kaye     ///
352d4242001SAdam Bratschi-Kaye     /// # Errors
353d4242001SAdam Bratschi-Kaye     ///
354d4242001SAdam Bratschi-Kaye     /// The host-provided function here returns a
35596e19700SNick Fitzgerald     /// [`Result<()>`](crate::Result). If the function returns `Ok(())` then
356d4242001SAdam Bratschi-Kaye     /// that indicates that the host function completed successfully and wrote
357d4242001SAdam Bratschi-Kaye     /// the result into the `&mut [Val]` argument.
358d4242001SAdam Bratschi-Kaye     ///
359d4242001SAdam Bratschi-Kaye     /// If the function returns `Err(e)`, however, then this is equivalent to
360d4242001SAdam Bratschi-Kaye     /// the host function triggering a trap for wasm. WebAssembly execution is
361d4242001SAdam Bratschi-Kaye     /// immediately halted and the original caller of [`Func::call`], for
362d4242001SAdam Bratschi-Kaye     /// example, will receive the error returned here (possibly with
363d4242001SAdam Bratschi-Kaye     /// [`WasmBacktrace`](crate::WasmBacktrace) context information attached).
364d4242001SAdam Bratschi-Kaye     ///
365d4242001SAdam Bratschi-Kaye     /// For more information about errors in Wasmtime see the [`Trap`]
366d4242001SAdam Bratschi-Kaye     /// documentation.
367d4242001SAdam Bratschi-Kaye     ///
368d4242001SAdam Bratschi-Kaye     /// [`Trap`]: crate::Trap
369ff93bce0SNick Fitzgerald     ///
370ff93bce0SNick Fitzgerald     /// # Panics
371ff93bce0SNick Fitzgerald     ///
372ff93bce0SNick Fitzgerald     /// Panics if the given function type is not associated with this store's
373ff93bce0SNick Fitzgerald     /// engine.
new<T: 'static>( store: impl AsContextMut<Data = T>, ty: FuncType, func: impl Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()> + Send + Sync + 'static, ) -> Self374f81c0dc0SAlex Crichton     pub fn new<T: 'static>(
375*439de7fbSNick Fitzgerald         store: impl AsContextMut<Data = T>,
376d4242001SAdam Bratschi-Kaye         ty: FuncType,
377d4242001SAdam Bratschi-Kaye         func: impl Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()> + Send + Sync + 'static,
378d4242001SAdam Bratschi-Kaye     ) -> Self {
379*439de7fbSNick Fitzgerald         Self::try_new_(store, ty, func).panic_on_oom()
380*439de7fbSNick Fitzgerald     }
381*439de7fbSNick Fitzgerald 
382*439de7fbSNick Fitzgerald     /// Same as [`Func::new`] but returns an error instead of panicking on
383*439de7fbSNick Fitzgerald     /// allocation failure.
try_new<T: 'static>( store: impl AsContextMut<Data = T>, ty: FuncType, func: impl Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()> + Send + Sync + 'static, ) -> Result<Self>384*439de7fbSNick Fitzgerald     pub fn try_new<T: 'static>(
385*439de7fbSNick Fitzgerald         store: impl AsContextMut<Data = T>,
386*439de7fbSNick Fitzgerald         ty: FuncType,
387*439de7fbSNick Fitzgerald         func: impl Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()> + Send + Sync + 'static,
388*439de7fbSNick Fitzgerald     ) -> Result<Self> {
389*439de7fbSNick Fitzgerald         Ok(Self::try_new_(store, ty, func)?)
390*439de7fbSNick Fitzgerald     }
391*439de7fbSNick Fitzgerald 
try_new_<T: 'static>( mut store: impl AsContextMut<Data = T>, ty: FuncType, func: impl Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()> + Send + Sync + 'static, ) -> Result<Self, OutOfMemory>392*439de7fbSNick Fitzgerald     fn try_new_<T: 'static>(
393*439de7fbSNick Fitzgerald         mut store: impl AsContextMut<Data = T>,
394*439de7fbSNick Fitzgerald         ty: FuncType,
395*439de7fbSNick Fitzgerald         func: impl Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()> + Send + Sync + 'static,
396*439de7fbSNick Fitzgerald     ) -> Result<Self, OutOfMemory> {
39791bf5016SAlex Crichton         let store = store.as_context_mut().0;
398*439de7fbSNick Fitzgerald         let host = HostFunc::new(store.engine(), ty, func)?;
39991bf5016SAlex Crichton 
40091bf5016SAlex Crichton         // SAFETY: the `T` used by `func` matches the `T` of the store we're
40191bf5016SAlex Crichton         // inserting into via this function's type signature.
402*439de7fbSNick Fitzgerald         unsafe { host.into_func(store) }
403d4242001SAdam Bratschi-Kaye     }
404d4242001SAdam Bratschi-Kaye 
405d4242001SAdam Bratschi-Kaye     /// Creates a new [`Func`] with the given arguments, although has fewer
406d4242001SAdam Bratschi-Kaye     /// runtime checks than [`Func::new`].
407d4242001SAdam Bratschi-Kaye     ///
408d4242001SAdam Bratschi-Kaye     /// This function takes a callback of a different signature than
409d4242001SAdam Bratschi-Kaye     /// [`Func::new`], instead receiving a raw pointer with a list of [`ValRaw`]
410d4242001SAdam Bratschi-Kaye     /// structures. These values have no type information associated with them
411d4242001SAdam Bratschi-Kaye     /// so it's up to the caller to provide a function that will correctly
412d4242001SAdam Bratschi-Kaye     /// interpret the list of values as those coming from the `ty` specified.
413d4242001SAdam Bratschi-Kaye     ///
414d4242001SAdam Bratschi-Kaye     /// If you're calling this from Rust it's recommended to either instead use
415d4242001SAdam Bratschi-Kaye     /// [`Func::new`] or [`Func::wrap`]. The [`Func::wrap`] API, in particular,
416d4242001SAdam Bratschi-Kaye     /// is both safer and faster than this API.
417d4242001SAdam Bratschi-Kaye     ///
418d4242001SAdam Bratschi-Kaye     /// # Errors
419d4242001SAdam Bratschi-Kaye     ///
420d4242001SAdam Bratschi-Kaye     /// See [`Func::new`] for the behavior of returning an error from the host
421d4242001SAdam Bratschi-Kaye     /// function provided here.
422d4242001SAdam Bratschi-Kaye     ///
423d4242001SAdam Bratschi-Kaye     /// # Unsafety
424d4242001SAdam Bratschi-Kaye     ///
425d4242001SAdam Bratschi-Kaye     /// This function is not safe because it's not known at compile time that
426d4242001SAdam Bratschi-Kaye     /// the `func` provided correctly interprets the argument types provided to
427d4242001SAdam Bratschi-Kaye     /// it, or that the results it produces will be of the correct type.
428ff93bce0SNick Fitzgerald     ///
429ff93bce0SNick Fitzgerald     /// # Panics
430ff93bce0SNick Fitzgerald     ///
431ff93bce0SNick Fitzgerald     /// Panics if the given function type is not associated with this store's
432ff93bce0SNick Fitzgerald     /// engine.
new_unchecked<T: 'static>( mut store: impl AsContextMut<Data = T>, ty: FuncType, func: impl Fn(Caller<'_, T>, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync + 'static, ) -> Self433f81c0dc0SAlex Crichton     pub unsafe fn new_unchecked<T: 'static>(
434d4242001SAdam Bratschi-Kaye         mut store: impl AsContextMut<Data = T>,
435d4242001SAdam Bratschi-Kaye         ty: FuncType,
4368c349a3dSAlex Crichton         func: impl Fn(Caller<'_, T>, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync + 'static,
437d4242001SAdam Bratschi-Kaye     ) -> Self {
438d4242001SAdam Bratschi-Kaye         let store = store.as_context_mut().0;
4390f457fadSAlex Crichton 
4400f457fadSAlex Crichton         // SAFETY: the contract required by `new_unchecked` is the same as the
4410f457fadSAlex Crichton         // contract required by this function itself.
442c2112959SNick Fitzgerald         let host = unsafe { HostFunc::new_unchecked(store.engine(), ty, func).panic_on_oom() };
4430f457fadSAlex Crichton 
4440f457fadSAlex Crichton         // SAFETY: the `T` used by `func` matches the `T` of the store we're
4450f457fadSAlex Crichton         // inserting into via this function's type signature.
44666ef086dSNick Fitzgerald         unsafe { host.into_func(store).panic_on_oom() }
447d4242001SAdam Bratschi-Kaye     }
448d4242001SAdam Bratschi-Kaye 
449d4242001SAdam Bratschi-Kaye     /// Creates a new host-defined WebAssembly function which, when called,
450d4242001SAdam Bratschi-Kaye     /// will run the asynchronous computation defined by `func` to completion
451d4242001SAdam Bratschi-Kaye     /// and then return the result to WebAssembly.
452d4242001SAdam Bratschi-Kaye     ///
453d4242001SAdam Bratschi-Kaye     /// This function is the asynchronous analogue of [`Func::new`] and much of
454d4242001SAdam Bratschi-Kaye     /// that documentation applies to this as well. The key difference is that
455d4242001SAdam Bratschi-Kaye     /// `func` returns a future instead of simply a `Result`. Note that the
456d4242001SAdam Bratschi-Kaye     /// returned future can close over any of the arguments, but it cannot close
457d4242001SAdam Bratschi-Kaye     /// over the state of the closure itself. It's recommended to store any
458d4242001SAdam Bratschi-Kaye     /// necessary async state in the `T` of the [`Store<T>`](crate::Store) which
459d4242001SAdam Bratschi-Kaye     /// can be accessed through [`Caller::data`] or [`Caller::data_mut`].
460d4242001SAdam Bratschi-Kaye     ///
461d4242001SAdam Bratschi-Kaye     /// For more information on `Send + Sync + 'static`, see
462d4242001SAdam Bratschi-Kaye     /// [`Func::wrap`](#why-send--sync--static).
463d4242001SAdam Bratschi-Kaye     ///
464d4242001SAdam Bratschi-Kaye     /// # Panics
465d4242001SAdam Bratschi-Kaye     ///
466ff93bce0SNick Fitzgerald     /// Panics if the given function type is not associated with this store's
467ff93bce0SNick Fitzgerald     /// engine.
468ff93bce0SNick Fitzgerald     ///
469d4242001SAdam Bratschi-Kaye     /// # Errors
470d4242001SAdam Bratschi-Kaye     ///
471d4242001SAdam Bratschi-Kaye     /// See [`Func::new`] for the behavior of returning an error from the host
472d4242001SAdam Bratschi-Kaye     /// function provided here.
473d4242001SAdam Bratschi-Kaye     ///
474d4242001SAdam Bratschi-Kaye     /// # Examples
475d4242001SAdam Bratschi-Kaye     ///
476d4242001SAdam Bratschi-Kaye     /// ```
477d4242001SAdam Bratschi-Kaye     /// # use wasmtime::*;
47896e19700SNick Fitzgerald     /// # fn main() -> Result<()> {
479d4242001SAdam Bratschi-Kaye     /// // Simulate some application-specific state as well as asynchronous
480d4242001SAdam Bratschi-Kaye     /// // functions to query that state.
481d4242001SAdam Bratschi-Kaye     /// struct MyDatabase {
482d4242001SAdam Bratschi-Kaye     ///     // ...
483d4242001SAdam Bratschi-Kaye     /// }
484d4242001SAdam Bratschi-Kaye     ///
485d4242001SAdam Bratschi-Kaye     /// impl MyDatabase {
486d4242001SAdam Bratschi-Kaye     ///     async fn get_row_count(&self) -> u32 {
487d4242001SAdam Bratschi-Kaye     ///         // ...
488d4242001SAdam Bratschi-Kaye     /// #       100
489d4242001SAdam Bratschi-Kaye     ///     }
490d4242001SAdam Bratschi-Kaye     /// }
491d4242001SAdam Bratschi-Kaye     ///
492d4242001SAdam Bratschi-Kaye     /// let my_database = MyDatabase {
493d4242001SAdam Bratschi-Kaye     ///     // ...
494d4242001SAdam Bratschi-Kaye     /// };
495d4242001SAdam Bratschi-Kaye     ///
496d4242001SAdam Bratschi-Kaye     /// // Using `new_async` we can hook up into calling our async
497d4242001SAdam Bratschi-Kaye     /// // `get_row_count` function.
498cc8d04f4SAlex Crichton     /// let engine = Engine::default();
499d4242001SAdam Bratschi-Kaye     /// let mut store = Store::new(&engine, MyDatabase {
500d4242001SAdam Bratschi-Kaye     ///     // ...
501d4242001SAdam Bratschi-Kaye     /// });
502d4242001SAdam Bratschi-Kaye     /// let get_row_count_type = wasmtime::FuncType::new(
5038652011fSNick Fitzgerald     ///     &engine,
504d4242001SAdam Bratschi-Kaye     ///     None,
505d4242001SAdam Bratschi-Kaye     ///     Some(wasmtime::ValType::I32),
506d4242001SAdam Bratschi-Kaye     /// );
507d4242001SAdam Bratschi-Kaye     /// let get = Func::new_async(&mut store, get_row_count_type, |caller, _params, results| {
508d4242001SAdam Bratschi-Kaye     ///     Box::new(async move {
509d4242001SAdam Bratschi-Kaye     ///         let count = caller.data().get_row_count().await;
510d4242001SAdam Bratschi-Kaye     ///         results[0] = Val::I32(count as i32);
511d4242001SAdam Bratschi-Kaye     ///         Ok(())
512d4242001SAdam Bratschi-Kaye     ///     })
513d4242001SAdam Bratschi-Kaye     /// });
514d4242001SAdam Bratschi-Kaye     /// // ...
515d4242001SAdam Bratschi-Kaye     /// # Ok(())
516d4242001SAdam Bratschi-Kaye     /// # }
517d4242001SAdam Bratschi-Kaye     /// ```
5188e194be7SAlex Crichton     #[cfg(feature = "async")]
new_async<T, F>(mut store: impl AsContextMut<Data = T>, ty: FuncType, func: F) -> Func where F: for<'a> Fn( Caller<'a, T>, &'a [Val], &'a mut [Val], ) -> Box<dyn Future<Output = Result<()>> + Send + 'a> + Send + Sync + 'static, T: Send + 'static,51991bf5016SAlex Crichton     pub fn new_async<T, F>(mut store: impl AsContextMut<Data = T>, ty: FuncType, func: F) -> Func
520d4242001SAdam Bratschi-Kaye     where
521d4242001SAdam Bratschi-Kaye         F: for<'a> Fn(
522d4242001SAdam Bratschi-Kaye                 Caller<'a, T>,
523d4242001SAdam Bratschi-Kaye                 &'a [Val],
524d4242001SAdam Bratschi-Kaye                 &'a mut [Val],
525d4242001SAdam Bratschi-Kaye             ) -> Box<dyn Future<Output = Result<()>> + Send + 'a>
526d4242001SAdam Bratschi-Kaye             + Send
527d4242001SAdam Bratschi-Kaye             + Sync
528d4242001SAdam Bratschi-Kaye             + 'static,
5298c349a3dSAlex Crichton         T: Send + 'static,
530d4242001SAdam Bratschi-Kaye     {
53191bf5016SAlex Crichton         let store = store.as_context_mut().0;
532cc8d04f4SAlex Crichton 
533c2112959SNick Fitzgerald         let host = HostFunc::new_async(store.engine(), ty, func).panic_on_oom();
53491bf5016SAlex Crichton 
53591bf5016SAlex Crichton         // SAFETY: the `T` used by `func` matches the `T` of the store we're
53691bf5016SAlex Crichton         // inserting into via this function's type signature.
53766ef086dSNick Fitzgerald         unsafe { host.into_func(store).panic_on_oom() }
538d4242001SAdam Bratschi-Kaye     }
539d4242001SAdam Bratschi-Kaye 
5402b832281SAlex Crichton     /// Creates a new `Func` from a store and a funcref within that store.
5412b832281SAlex Crichton     ///
5422b832281SAlex Crichton     /// # Safety
5432b832281SAlex Crichton     ///
5442b832281SAlex Crichton     /// The safety of this function requires that `func_ref` is a valid function
5452b832281SAlex Crichton     /// pointer owned by `store`.
from_vm_func_ref(store: StoreId, func_ref: NonNull<VMFuncRef>) -> Func5462b832281SAlex Crichton     pub(crate) unsafe fn from_vm_func_ref(store: StoreId, func_ref: NonNull<VMFuncRef>) -> Func {
5470f457fadSAlex Crichton         // SAFETY: given the contract of this function it's safe to read the
5480f457fadSAlex Crichton         // `type_index` field.
5490f457fadSAlex Crichton         unsafe {
550d4242001SAdam Bratschi-Kaye             debug_assert!(func_ref.as_ref().type_index != VMSharedTypeIndex::default());
5510f457fadSAlex Crichton         }
5524fcfe17aSAlex Crichton         Func {
5532b832281SAlex Crichton             store,
5544fcfe17aSAlex Crichton             unsafe_func_ref: func_ref.into(),
5554fcfe17aSAlex Crichton         }
556d4242001SAdam Bratschi-Kaye     }
557d4242001SAdam Bratschi-Kaye 
558d4242001SAdam Bratschi-Kaye     /// Creates a new `Func` from the given Rust closure.
559d4242001SAdam Bratschi-Kaye     ///
560d4242001SAdam Bratschi-Kaye     /// This function will create a new `Func` which, when called, will
561d4242001SAdam Bratschi-Kaye     /// execute the given Rust closure. Unlike [`Func::new`] the target
562d4242001SAdam Bratschi-Kaye     /// function being called is known statically so the type signature can
563d4242001SAdam Bratschi-Kaye     /// be inferred. Rust types will map to WebAssembly types as follows:
564d4242001SAdam Bratschi-Kaye     ///
565d4242001SAdam Bratschi-Kaye     /// | Rust Argument Type                | WebAssembly Type                          |
56622a3d9edSNick Fitzgerald     /// |-----------------------------------|-------------------------------------------|
567d4242001SAdam Bratschi-Kaye     /// | `i32`                             | `i32`                                     |
568d4242001SAdam Bratschi-Kaye     /// | `u32`                             | `i32`                                     |
569d4242001SAdam Bratschi-Kaye     /// | `i64`                             | `i64`                                     |
570d4242001SAdam Bratschi-Kaye     /// | `u64`                             | `i64`                                     |
571d4242001SAdam Bratschi-Kaye     /// | `f32`                             | `f32`                                     |
572d4242001SAdam Bratschi-Kaye     /// | `f64`                             | `f64`                                     |
573ff93bce0SNick Fitzgerald     /// | `V128` on x86-64 and aarch64 only | `v128`                                    |
574ff93bce0SNick Fitzgerald     /// | `Option<Func>`                    | `funcref` aka `(ref null func)`           |
575ff93bce0SNick Fitzgerald     /// | `Func`                            | `(ref func)`                              |
576ff93bce0SNick Fitzgerald     /// | `Option<Nofunc>`                  | `nullfuncref` aka `(ref null nofunc)`     |
577ff93bce0SNick Fitzgerald     /// | `NoFunc`                          | `(ref nofunc)`                            |
578c16414fbSNick Fitzgerald     /// | `Option<Rooted<ExternRef>>`       | `externref` aka `(ref null extern)`       |
579c16414fbSNick Fitzgerald     /// | `Rooted<ExternRef>`               | `(ref extern)`                            |
58022a3d9edSNick Fitzgerald     /// | `Option<NoExtern>`                | `nullexternref` aka `(ref null noextern)` |
58122a3d9edSNick Fitzgerald     /// | `NoExtern`                        | `(ref noextern)`                          |
582c16414fbSNick Fitzgerald     /// | `Option<Rooted<AnyRef>>`          | `anyref` aka `(ref null any)`             |
583c16414fbSNick Fitzgerald     /// | `Rooted<AnyRef>`                  | `(ref any)`                               |
584c16414fbSNick Fitzgerald     /// | `Option<Rooted<EqRef>>`           | `eqref` aka `(ref null eq)`               |
585c16414fbSNick Fitzgerald     /// | `Rooted<EqRef>`                   | `(ref eq)`                                |
5860fa13013SNick Fitzgerald     /// | `Option<I31>`                     | `i31ref` aka `(ref null i31)`             |
5870fa13013SNick Fitzgerald     /// | `I31`                             | `(ref i31)`                               |
588c16414fbSNick Fitzgerald     /// | `Option<Rooted<StructRef>>`       | `(ref null struct)`                       |
589c16414fbSNick Fitzgerald     /// | `Rooted<StructRef>`               | `(ref struct)`                            |
590c16414fbSNick Fitzgerald     /// | `Option<Rooted<ArrayRef>>`        | `(ref null array)`                        |
591c16414fbSNick Fitzgerald     /// | `Rooted<ArrayRef>`                | `(ref array)`                             |
592939917dcSNick Fitzgerald     /// | `Option<NoneRef>`                 | `nullref` aka `(ref null none)`           |
593939917dcSNick Fitzgerald     /// | `NoneRef`                         | `(ref none)`                              |
594c16414fbSNick Fitzgerald     ///
5959826719aSChris Fallin     /// Note that anywhere a `Rooted<T>` appears, a `OwnedRooted<T>` may also
596c16414fbSNick Fitzgerald     /// be used.
597d4242001SAdam Bratschi-Kaye     ///
598d4242001SAdam Bratschi-Kaye     /// Any of the Rust types can be returned from the closure as well, in
599d4242001SAdam Bratschi-Kaye     /// addition to some extra types
600d4242001SAdam Bratschi-Kaye     ///
601d4242001SAdam Bratschi-Kaye     /// | Rust Return Type  | WebAssembly Return Type | Meaning               |
602d4242001SAdam Bratschi-Kaye     /// |-------------------|-------------------------|-----------------------|
603d4242001SAdam Bratschi-Kaye     /// | `()`              | nothing                 | no return value       |
604d4242001SAdam Bratschi-Kaye     /// | `T`               | `T`                     | a single return value |
605d4242001SAdam Bratschi-Kaye     /// | `(T1, T2, ...)`   | `T1 T2 ...`             | multiple returns      |
606d4242001SAdam Bratschi-Kaye     ///
607d4242001SAdam Bratschi-Kaye     /// Note that all return types can also be wrapped in `Result<_>` to
608d4242001SAdam Bratschi-Kaye     /// indicate that the host function can generate a trap as well as possibly
609d4242001SAdam Bratschi-Kaye     /// returning a value.
610d4242001SAdam Bratschi-Kaye     ///
611d4242001SAdam Bratschi-Kaye     /// Finally you can also optionally take [`Caller`] as the first argument of
612d4242001SAdam Bratschi-Kaye     /// your closure. If inserted then you're able to inspect the caller's
613d4242001SAdam Bratschi-Kaye     /// state, for example the [`Memory`](crate::Memory) it has exported so you
614d4242001SAdam Bratschi-Kaye     /// can read what pointers point to.
615d4242001SAdam Bratschi-Kaye     ///
616d4242001SAdam Bratschi-Kaye     /// Note that when using this API, the intention is to create as thin of a
617d4242001SAdam Bratschi-Kaye     /// layer as possible for when WebAssembly calls the function provided. With
618d4242001SAdam Bratschi-Kaye     /// sufficient inlining and optimization the WebAssembly will call straight
619d4242001SAdam Bratschi-Kaye     /// into `func` provided, with no extra fluff entailed.
620d4242001SAdam Bratschi-Kaye     ///
621d4242001SAdam Bratschi-Kaye     /// # Why `Send + Sync + 'static`?
622d4242001SAdam Bratschi-Kaye     ///
623d4242001SAdam Bratschi-Kaye     /// All host functions defined in a [`Store`](crate::Store) (including
624d4242001SAdam Bratschi-Kaye     /// those from [`Func::new`] and other constructors) require that the
625d4242001SAdam Bratschi-Kaye     /// `func` provided is `Send + Sync + 'static`. Additionally host functions
626d4242001SAdam Bratschi-Kaye     /// always are `Fn` as opposed to `FnMut` or `FnOnce`. This can at-a-glance
627d4242001SAdam Bratschi-Kaye     /// feel restrictive since the closure cannot close over as many types as
628d4242001SAdam Bratschi-Kaye     /// before. The reason for this, though, is to ensure that
629d4242001SAdam Bratschi-Kaye     /// [`Store<T>`](crate::Store) can implement both the `Send` and `Sync`
630d4242001SAdam Bratschi-Kaye     /// traits.
631d4242001SAdam Bratschi-Kaye     ///
632d4242001SAdam Bratschi-Kaye     /// Fear not, however, because this isn't as restrictive as it seems! Host
633d4242001SAdam Bratschi-Kaye     /// functions are provided a [`Caller<'_, T>`](crate::Caller) argument which
634d4242001SAdam Bratschi-Kaye     /// allows access to the host-defined data within the
635d4242001SAdam Bratschi-Kaye     /// [`Store`](crate::Store). The `T` type is not required to be any of
636d4242001SAdam Bratschi-Kaye     /// `Send`, `Sync`, or `'static`! This means that you can store whatever
637d4242001SAdam Bratschi-Kaye     /// you'd like in `T` and have it accessible by all host functions.
638d4242001SAdam Bratschi-Kaye     /// Additionally mutable access to `T` is allowed through
639d4242001SAdam Bratschi-Kaye     /// [`Caller::data_mut`].
640d4242001SAdam Bratschi-Kaye     ///
641d4242001SAdam Bratschi-Kaye     /// Most host-defined [`Func`] values provide closures that end up not
642d4242001SAdam Bratschi-Kaye     /// actually closing over any values. These zero-sized types will use the
643d4242001SAdam Bratschi-Kaye     /// context from [`Caller`] for host-defined information.
644d4242001SAdam Bratschi-Kaye     ///
645d4242001SAdam Bratschi-Kaye     /// # Errors
646d4242001SAdam Bratschi-Kaye     ///
647d4242001SAdam Bratschi-Kaye     /// The closure provided here to `wrap` can optionally return a
64896e19700SNick Fitzgerald     /// [`Result<T>`](crate::Result). Returning `Ok(t)` represents the host
649d4242001SAdam Bratschi-Kaye     /// function successfully completing with the `t` result. Returning
650d4242001SAdam Bratschi-Kaye     /// `Err(e)`, however, is equivalent to raising a custom wasm trap.
651d4242001SAdam Bratschi-Kaye     /// Execution of WebAssembly does not resume and the stack is unwound to the
652d4242001SAdam Bratschi-Kaye     /// original caller of the function where the error is returned.
653d4242001SAdam Bratschi-Kaye     ///
654d4242001SAdam Bratschi-Kaye     /// For more information about errors in Wasmtime see the [`Trap`]
655d4242001SAdam Bratschi-Kaye     /// documentation.
656d4242001SAdam Bratschi-Kaye     ///
657d4242001SAdam Bratschi-Kaye     /// [`Trap`]: crate::Trap
658d4242001SAdam Bratschi-Kaye     ///
659d4242001SAdam Bratschi-Kaye     /// # Examples
660d4242001SAdam Bratschi-Kaye     ///
661d4242001SAdam Bratschi-Kaye     /// First up we can see how simple wasm imports can be implemented, such
662d4242001SAdam Bratschi-Kaye     /// as a function that adds its two arguments and returns the result.
663d4242001SAdam Bratschi-Kaye     ///
664d4242001SAdam Bratschi-Kaye     /// ```
665d4242001SAdam Bratschi-Kaye     /// # use wasmtime::*;
66696e19700SNick Fitzgerald     /// # fn main() -> Result<()> {
667d4242001SAdam Bratschi-Kaye     /// # let mut store = Store::<()>::default();
668d4242001SAdam Bratschi-Kaye     /// let add = Func::wrap(&mut store, |a: i32, b: i32| a + b);
669d4242001SAdam Bratschi-Kaye     /// let module = Module::new(
670d4242001SAdam Bratschi-Kaye     ///     store.engine(),
671d4242001SAdam Bratschi-Kaye     ///     r#"
672d4242001SAdam Bratschi-Kaye     ///         (module
673d4242001SAdam Bratschi-Kaye     ///             (import "" "" (func $add (param i32 i32) (result i32)))
674d4242001SAdam Bratschi-Kaye     ///             (func (export "foo") (param i32 i32) (result i32)
675d4242001SAdam Bratschi-Kaye     ///                 local.get 0
676d4242001SAdam Bratschi-Kaye     ///                 local.get 1
677d4242001SAdam Bratschi-Kaye     ///                 call $add))
678d4242001SAdam Bratschi-Kaye     ///     "#,
679d4242001SAdam Bratschi-Kaye     /// )?;
680d4242001SAdam Bratschi-Kaye     /// let instance = Instance::new(&mut store, &module, &[add.into()])?;
681d4242001SAdam Bratschi-Kaye     /// let foo = instance.get_typed_func::<(i32, i32), i32>(&mut store, "foo")?;
682d4242001SAdam Bratschi-Kaye     /// assert_eq!(foo.call(&mut store, (1, 2))?, 3);
683d4242001SAdam Bratschi-Kaye     /// # Ok(())
684d4242001SAdam Bratschi-Kaye     /// # }
685d4242001SAdam Bratschi-Kaye     /// ```
686d4242001SAdam Bratschi-Kaye     ///
687d4242001SAdam Bratschi-Kaye     /// We can also do the same thing, but generate a trap if the addition
688d4242001SAdam Bratschi-Kaye     /// overflows:
689d4242001SAdam Bratschi-Kaye     ///
690d4242001SAdam Bratschi-Kaye     /// ```
691d4242001SAdam Bratschi-Kaye     /// # use wasmtime::*;
69296e19700SNick Fitzgerald     /// # fn main() -> Result<()> {
693d4242001SAdam Bratschi-Kaye     /// # let mut store = Store::<()>::default();
694d4242001SAdam Bratschi-Kaye     /// let add = Func::wrap(&mut store, |a: i32, b: i32| {
695d4242001SAdam Bratschi-Kaye     ///     match a.checked_add(b) {
696d4242001SAdam Bratschi-Kaye     ///         Some(i) => Ok(i),
69796e19700SNick Fitzgerald     ///         None => bail!("overflow"),
698d4242001SAdam Bratschi-Kaye     ///     }
699d4242001SAdam Bratschi-Kaye     /// });
700d4242001SAdam Bratschi-Kaye     /// let module = Module::new(
701d4242001SAdam Bratschi-Kaye     ///     store.engine(),
702d4242001SAdam Bratschi-Kaye     ///     r#"
703d4242001SAdam Bratschi-Kaye     ///         (module
704d4242001SAdam Bratschi-Kaye     ///             (import "" "" (func $add (param i32 i32) (result i32)))
705d4242001SAdam Bratschi-Kaye     ///             (func (export "foo") (param i32 i32) (result i32)
706d4242001SAdam Bratschi-Kaye     ///                 local.get 0
707d4242001SAdam Bratschi-Kaye     ///                 local.get 1
708d4242001SAdam Bratschi-Kaye     ///                 call $add))
709d4242001SAdam Bratschi-Kaye     ///     "#,
710d4242001SAdam Bratschi-Kaye     /// )?;
711d4242001SAdam Bratschi-Kaye     /// let instance = Instance::new(&mut store, &module, &[add.into()])?;
712d4242001SAdam Bratschi-Kaye     /// let foo = instance.get_typed_func::<(i32, i32), i32>(&mut store, "foo")?;
713d4242001SAdam Bratschi-Kaye     /// assert_eq!(foo.call(&mut store, (1, 2))?, 3);
714d4242001SAdam Bratschi-Kaye     /// assert!(foo.call(&mut store, (i32::max_value(), 1)).is_err());
715d4242001SAdam Bratschi-Kaye     /// # Ok(())
716d4242001SAdam Bratschi-Kaye     /// # }
717d4242001SAdam Bratschi-Kaye     /// ```
718d4242001SAdam Bratschi-Kaye     ///
719d4242001SAdam Bratschi-Kaye     /// And don't forget all the wasm types are supported!
720d4242001SAdam Bratschi-Kaye     ///
721d4242001SAdam Bratschi-Kaye     /// ```
722d4242001SAdam Bratschi-Kaye     /// # use wasmtime::*;
72396e19700SNick Fitzgerald     /// # fn main() -> Result<()> {
724d4242001SAdam Bratschi-Kaye     /// # let mut store = Store::<()>::default();
725d4242001SAdam Bratschi-Kaye     /// let debug = Func::wrap(&mut store, |a: i32, b: u32, c: f32, d: i64, e: u64, f: f64| {
726d4242001SAdam Bratschi-Kaye     ///
727d4242001SAdam Bratschi-Kaye     ///     println!("a={}", a);
728d4242001SAdam Bratschi-Kaye     ///     println!("b={}", b);
729d4242001SAdam Bratschi-Kaye     ///     println!("c={}", c);
730d4242001SAdam Bratschi-Kaye     ///     println!("d={}", d);
731d4242001SAdam Bratschi-Kaye     ///     println!("e={}", e);
732d4242001SAdam Bratschi-Kaye     ///     println!("f={}", f);
733d4242001SAdam Bratschi-Kaye     /// });
734d4242001SAdam Bratschi-Kaye     /// let module = Module::new(
735d4242001SAdam Bratschi-Kaye     ///     store.engine(),
736d4242001SAdam Bratschi-Kaye     ///     r#"
737d4242001SAdam Bratschi-Kaye     ///         (module
738d4242001SAdam Bratschi-Kaye     ///             (import "" "" (func $debug (param i32 i32 f32 i64 i64 f64)))
739d4242001SAdam Bratschi-Kaye     ///             (func (export "foo")
740d4242001SAdam Bratschi-Kaye     ///                 i32.const -1
741d4242001SAdam Bratschi-Kaye     ///                 i32.const 1
742d4242001SAdam Bratschi-Kaye     ///                 f32.const 2
743d4242001SAdam Bratschi-Kaye     ///                 i64.const -3
744d4242001SAdam Bratschi-Kaye     ///                 i64.const 3
745d4242001SAdam Bratschi-Kaye     ///                 f64.const 4
746d4242001SAdam Bratschi-Kaye     ///                 call $debug))
747d4242001SAdam Bratschi-Kaye     ///     "#,
748d4242001SAdam Bratschi-Kaye     /// )?;
749d4242001SAdam Bratschi-Kaye     /// let instance = Instance::new(&mut store, &module, &[debug.into()])?;
750d4242001SAdam Bratschi-Kaye     /// let foo = instance.get_typed_func::<(), ()>(&mut store, "foo")?;
751d4242001SAdam Bratschi-Kaye     /// foo.call(&mut store, ())?;
752d4242001SAdam Bratschi-Kaye     /// # Ok(())
753d4242001SAdam Bratschi-Kaye     /// # }
754d4242001SAdam Bratschi-Kaye     /// ```
755d4242001SAdam Bratschi-Kaye     ///
756d4242001SAdam Bratschi-Kaye     /// Finally if you want to get really fancy you can also implement
757d4242001SAdam Bratschi-Kaye     /// imports that read/write wasm module's memory
758d4242001SAdam Bratschi-Kaye     ///
759d4242001SAdam Bratschi-Kaye     /// ```
760d4242001SAdam Bratschi-Kaye     /// use std::str;
761d4242001SAdam Bratschi-Kaye     ///
762d4242001SAdam Bratschi-Kaye     /// # use wasmtime::*;
76396e19700SNick Fitzgerald     /// # fn main() -> Result<()> {
764d4242001SAdam Bratschi-Kaye     /// # let mut store = Store::default();
765d4242001SAdam Bratschi-Kaye     /// let log_str = Func::wrap(&mut store, |mut caller: Caller<'_, ()>, ptr: i32, len: i32| {
766d4242001SAdam Bratschi-Kaye     ///     let mem = match caller.get_export("memory") {
767d4242001SAdam Bratschi-Kaye     ///         Some(Extern::Memory(mem)) => mem,
76896e19700SNick Fitzgerald     ///         _ => bail!("failed to find host memory"),
769d4242001SAdam Bratschi-Kaye     ///     };
770d4242001SAdam Bratschi-Kaye     ///     let data = mem.data(&caller)
771d4242001SAdam Bratschi-Kaye     ///         .get(ptr as u32 as usize..)
772d4242001SAdam Bratschi-Kaye     ///         .and_then(|arr| arr.get(..len as u32 as usize));
773d4242001SAdam Bratschi-Kaye     ///     let string = match data {
774d4242001SAdam Bratschi-Kaye     ///         Some(data) => match str::from_utf8(data) {
775d4242001SAdam Bratschi-Kaye     ///             Ok(s) => s,
77696e19700SNick Fitzgerald     ///             Err(_) => bail!("invalid utf-8"),
777d4242001SAdam Bratschi-Kaye     ///         },
77896e19700SNick Fitzgerald     ///         None => bail!("pointer/length out of bounds"),
779d4242001SAdam Bratschi-Kaye     ///     };
780d4242001SAdam Bratschi-Kaye     ///     assert_eq!(string, "Hello, world!");
781d4242001SAdam Bratschi-Kaye     ///     println!("{}", string);
782d4242001SAdam Bratschi-Kaye     ///     Ok(())
783d4242001SAdam Bratschi-Kaye     /// });
784d4242001SAdam Bratschi-Kaye     /// let module = Module::new(
785d4242001SAdam Bratschi-Kaye     ///     store.engine(),
786d4242001SAdam Bratschi-Kaye     ///     r#"
787d4242001SAdam Bratschi-Kaye     ///         (module
788d4242001SAdam Bratschi-Kaye     ///             (import "" "" (func $log_str (param i32 i32)))
789d4242001SAdam Bratschi-Kaye     ///             (func (export "foo")
790d4242001SAdam Bratschi-Kaye     ///                 i32.const 4   ;; ptr
791d4242001SAdam Bratschi-Kaye     ///                 i32.const 13  ;; len
792d4242001SAdam Bratschi-Kaye     ///                 call $log_str)
793d4242001SAdam Bratschi-Kaye     ///             (memory (export "memory") 1)
794d4242001SAdam Bratschi-Kaye     ///             (data (i32.const 4) "Hello, world!"))
795d4242001SAdam Bratschi-Kaye     ///     "#,
796d4242001SAdam Bratschi-Kaye     /// )?;
797d4242001SAdam Bratschi-Kaye     /// let instance = Instance::new(&mut store, &module, &[log_str.into()])?;
798d4242001SAdam Bratschi-Kaye     /// let foo = instance.get_typed_func::<(), ()>(&mut store, "foo")?;
799d4242001SAdam Bratschi-Kaye     /// foo.call(&mut store, ())?;
800d4242001SAdam Bratschi-Kaye     /// # Ok(())
801d4242001SAdam Bratschi-Kaye     /// # }
802d4242001SAdam Bratschi-Kaye     /// ```
wrap<T, Params, Results>( store: impl AsContextMut<Data = T>, func: impl IntoFunc<T, Params, Results>, ) -> Func where T: 'static,803d4242001SAdam Bratschi-Kaye     pub fn wrap<T, Params, Results>(
804d2dee5ddSNick Fitzgerald         store: impl AsContextMut<Data = T>,
805d4242001SAdam Bratschi-Kaye         func: impl IntoFunc<T, Params, Results>,
806f81c0dc0SAlex Crichton     ) -> Func
807f81c0dc0SAlex Crichton     where
808f81c0dc0SAlex Crichton         T: 'static,
809f81c0dc0SAlex Crichton     {
810d2dee5ddSNick Fitzgerald         Self::try_wrap(store, func).expect(
811d2dee5ddSNick Fitzgerald             "allocation failure during `Func::wrap` (use `Func::try_wrap` to handle such errors)",
812d2dee5ddSNick Fitzgerald         )
813d2dee5ddSNick Fitzgerald     }
814d2dee5ddSNick Fitzgerald 
815d2dee5ddSNick Fitzgerald     /// Fallible version of [`Func::wrap`] that returns an error on
816d2dee5ddSNick Fitzgerald     /// out-of-memory instead of panicking.
try_wrap<T, Params, Results>( mut store: impl AsContextMut<Data = T>, func: impl IntoFunc<T, Params, Results>, ) -> Result<Func> where T: 'static,817d2dee5ddSNick Fitzgerald     pub fn try_wrap<T, Params, Results>(
818d2dee5ddSNick Fitzgerald         mut store: impl AsContextMut<Data = T>,
819d2dee5ddSNick Fitzgerald         func: impl IntoFunc<T, Params, Results>,
820d2dee5ddSNick Fitzgerald     ) -> Result<Func>
821d2dee5ddSNick Fitzgerald     where
822d2dee5ddSNick Fitzgerald         T: 'static,
823d2dee5ddSNick Fitzgerald     {
824d4242001SAdam Bratschi-Kaye         let store = store.as_context_mut().0;
8258c349a3dSAlex Crichton         let engine = store.engine();
826d2dee5ddSNick Fitzgerald         let host = func.into_func(engine)?;
8270f457fadSAlex Crichton 
8280f457fadSAlex Crichton         // SAFETY: The `T` the closure takes is the same as the `T` of the store
8290f457fadSAlex Crichton         // we're inserting into via the type signature above.
830d2dee5ddSNick Fitzgerald         Ok(unsafe { host.into_func(store)? })
831d4242001SAdam Bratschi-Kaye     }
832d4242001SAdam Bratschi-Kaye 
83305fe6282SShane Snover     /// Same as [`Func::wrap`], except the closure asynchronously produces the
83405fe6282SShane Snover     /// result and the arguments are passed within a tuple. For more information
83505fe6282SShane Snover     /// see the [`Func`] documentation.
83605fe6282SShane Snover     #[cfg(feature = "async")]
wrap_async<T, F, P, R>(mut store: impl AsContextMut<Data = T>, func: F) -> Func where F: for<'a> Fn(Caller<'a, T>, P) -> Box<dyn Future<Output = R> + Send + 'a> + Send + Sync + 'static, P: WasmTyList, R: WasmRet, T: Send + 'static,83791bf5016SAlex Crichton     pub fn wrap_async<T, F, P, R>(mut store: impl AsContextMut<Data = T>, func: F) -> Func
83805fe6282SShane Snover     where
83905fe6282SShane Snover         F: for<'a> Fn(Caller<'a, T>, P) -> Box<dyn Future<Output = R> + Send + 'a>
84005fe6282SShane Snover             + Send
84105fe6282SShane Snover             + Sync
84205fe6282SShane Snover             + 'static,
84305fe6282SShane Snover         P: WasmTyList,
84405fe6282SShane Snover         R: WasmRet,
8458c349a3dSAlex Crichton         T: Send + 'static,
84605fe6282SShane Snover     {
84791bf5016SAlex Crichton         let store = store.as_context_mut().0;
848c2112959SNick Fitzgerald         let host = HostFunc::wrap_async(store.engine(), func).panic_on_oom();
84991bf5016SAlex Crichton 
85091bf5016SAlex Crichton         // SAFETY: The `T` the closure takes is the same as the `T` of the store
85191bf5016SAlex Crichton         // we're inserting into via the type signature above.
85266ef086dSNick Fitzgerald         unsafe { host.into_func(store).panic_on_oom() }
85305fe6282SShane Snover     }
854d4242001SAdam Bratschi-Kaye 
855d4242001SAdam Bratschi-Kaye     /// Returns the underlying wasm type that this `Func` has.
856d4242001SAdam Bratschi-Kaye     ///
857d4242001SAdam Bratschi-Kaye     /// # Panics
858d4242001SAdam Bratschi-Kaye     ///
859d4242001SAdam Bratschi-Kaye     /// Panics if `store` does not own this function.
ty(&self, store: impl AsContext) -> FuncType860d4242001SAdam Bratschi-Kaye     pub fn ty(&self, store: impl AsContext) -> FuncType {
861d4242001SAdam Bratschi-Kaye         self.load_ty(&store.as_context().0)
862d4242001SAdam Bratschi-Kaye     }
863d4242001SAdam Bratschi-Kaye 
864d4242001SAdam Bratschi-Kaye     /// Forcibly loads the type of this function from the `Engine`.
865d4242001SAdam Bratschi-Kaye     ///
866d4242001SAdam Bratschi-Kaye     /// Note that this is a somewhat expensive method since it requires taking a
867d4242001SAdam Bratschi-Kaye     /// lock as well as cloning a type.
load_ty(&self, store: &StoreOpaque) -> FuncType868ff93bce0SNick Fitzgerald     pub(crate) fn load_ty(&self, store: &StoreOpaque) -> FuncType {
8694fcfe17aSAlex Crichton         FuncType::from_shared_type_index(store.engine(), self.type_index(store))
870d4242001SAdam Bratschi-Kaye     }
871d4242001SAdam Bratschi-Kaye 
872ff93bce0SNick Fitzgerald     /// Does this function match the given type?
873ff93bce0SNick Fitzgerald     ///
874ff93bce0SNick Fitzgerald     /// That is, is this function's type a subtype of the given type?
875f2e689cdSNick Fitzgerald     ///
876f2e689cdSNick Fitzgerald     /// # Panics
877f2e689cdSNick Fitzgerald     ///
878f2e689cdSNick Fitzgerald     /// Panics if this function is not associated with the given store or if the
879f2e689cdSNick Fitzgerald     /// function type is not associated with the store's engine.
matches_ty(&self, store: impl AsContext, func_ty: &FuncType) -> bool880ff93bce0SNick Fitzgerald     pub fn matches_ty(&self, store: impl AsContext, func_ty: &FuncType) -> bool {
881ff93bce0SNick Fitzgerald         self._matches_ty(store.as_context().0, func_ty)
882ff93bce0SNick Fitzgerald     }
883ff93bce0SNick Fitzgerald 
_matches_ty(&self, store: &StoreOpaque, func_ty: &FuncType) -> bool884ff93bce0SNick Fitzgerald     pub(crate) fn _matches_ty(&self, store: &StoreOpaque, func_ty: &FuncType) -> bool {
885ff93bce0SNick Fitzgerald         let actual_ty = self.load_ty(store);
886ff93bce0SNick Fitzgerald         actual_ty.matches(func_ty)
887ff93bce0SNick Fitzgerald     }
888ff93bce0SNick Fitzgerald 
ensure_matches_ty(&self, store: &StoreOpaque, func_ty: &FuncType) -> Result<()>889ff93bce0SNick Fitzgerald     pub(crate) fn ensure_matches_ty(&self, store: &StoreOpaque, func_ty: &FuncType) -> Result<()> {
890ff93bce0SNick Fitzgerald         if !self.comes_from_same_store(store) {
891ff93bce0SNick Fitzgerald             bail!("function used with wrong store");
892ff93bce0SNick Fitzgerald         }
893ff93bce0SNick Fitzgerald         if self._matches_ty(store, func_ty) {
894ff93bce0SNick Fitzgerald             Ok(())
895ff93bce0SNick Fitzgerald         } else {
896ff93bce0SNick Fitzgerald             let actual_ty = self.load_ty(store);
897ff93bce0SNick Fitzgerald             bail!("type mismatch: expected {func_ty}, found {actual_ty}")
898ff93bce0SNick Fitzgerald         }
899ff93bce0SNick Fitzgerald     }
900ff93bce0SNick Fitzgerald 
type_index(&self, data: &StoreOpaque) -> VMSharedTypeIndex9014fcfe17aSAlex Crichton     pub(crate) fn type_index(&self, data: &StoreOpaque) -> VMSharedTypeIndex {
9024fcfe17aSAlex Crichton         unsafe { self.vm_func_ref(data).as_ref().type_index }
903d4242001SAdam Bratschi-Kaye     }
904d4242001SAdam Bratschi-Kaye 
905d4242001SAdam Bratschi-Kaye     /// Invokes this function with the `params` given and writes returned values
906d4242001SAdam Bratschi-Kaye     /// to `results`.
907d4242001SAdam Bratschi-Kaye     ///
908d4242001SAdam Bratschi-Kaye     /// The `params` here must match the type signature of this `Func`, or an
909d4242001SAdam Bratschi-Kaye     /// error will occur. Additionally `results` must have the same
910d4242001SAdam Bratschi-Kaye     /// length as the number of results for this function. Calling this function
911d4242001SAdam Bratschi-Kaye     /// will synchronously execute the WebAssembly function referenced to get
912d4242001SAdam Bratschi-Kaye     /// the results.
913d4242001SAdam Bratschi-Kaye     ///
914d4242001SAdam Bratschi-Kaye     /// This function will return `Ok(())` if execution completed without a trap
915d4242001SAdam Bratschi-Kaye     /// or error of any kind. In this situation the results will be written to
916d4242001SAdam Bratschi-Kaye     /// the provided `results` array.
917d4242001SAdam Bratschi-Kaye     ///
918d4242001SAdam Bratschi-Kaye     /// # Errors
919d4242001SAdam Bratschi-Kaye     ///
920d4242001SAdam Bratschi-Kaye     /// Any error which occurs throughout the execution of the function will be
92196e19700SNick Fitzgerald     /// returned as `Err(e)`. The [`Error`](crate::Error) type can be inspected
922d4242001SAdam Bratschi-Kaye     /// for the precise error cause such as:
923d4242001SAdam Bratschi-Kaye     ///
924d4242001SAdam Bratschi-Kaye     /// * [`Trap`] - indicates that a wasm trap happened and execution was
925d4242001SAdam Bratschi-Kaye     ///   halted.
926d4242001SAdam Bratschi-Kaye     /// * [`WasmBacktrace`] - optionally included on errors for backtrace
927d4242001SAdam Bratschi-Kaye     ///   information of the trap/error.
928d4242001SAdam Bratschi-Kaye     /// * Other string-based errors to indicate issues such as type errors with
929d4242001SAdam Bratschi-Kaye     ///   `params`.
930d4242001SAdam Bratschi-Kaye     /// * Any host-originating error originally returned from a function defined
931d4242001SAdam Bratschi-Kaye     ///   via [`Func::new`], for example.
932cc8d04f4SAlex Crichton     /// * The `store` provided is configured to require `call_async` to be used
933cc8d04f4SAlex Crichton     ///   instead, such as with epochs or fuel.
934d4242001SAdam Bratschi-Kaye     ///
935d4242001SAdam Bratschi-Kaye     /// Errors typically indicate that execution of WebAssembly was halted
936d4242001SAdam Bratschi-Kaye     /// mid-way and did not complete after the error condition happened.
937d4242001SAdam Bratschi-Kaye     ///
938d4242001SAdam Bratschi-Kaye     /// [`Trap`]: crate::Trap
939d4242001SAdam Bratschi-Kaye     ///
940d4242001SAdam Bratschi-Kaye     /// # Panics
941d4242001SAdam Bratschi-Kaye     ///
942cc8d04f4SAlex Crichton     /// Panics if `store` does not own this function.
943d4242001SAdam Bratschi-Kaye     ///
944d4242001SAdam Bratschi-Kaye     /// [`WasmBacktrace`]: crate::WasmBacktrace
call( &self, mut store: impl AsContextMut, params: &[Val], results: &mut [Val], ) -> Result<()>945d4242001SAdam Bratschi-Kaye     pub fn call(
946d4242001SAdam Bratschi-Kaye         &self,
947d4242001SAdam Bratschi-Kaye         mut store: impl AsContextMut,
948d4242001SAdam Bratschi-Kaye         params: &[Val],
949d4242001SAdam Bratschi-Kaye         results: &mut [Val],
950d4242001SAdam Bratschi-Kaye     ) -> Result<()> {
9510fa13013SNick Fitzgerald         let mut store = store.as_context_mut();
952cc8d04f4SAlex Crichton         store.0.validate_sync_call()?;
953c22b3cb9SNick Fitzgerald 
95458e295eeSNick Fitzgerald         self.call_impl_check_args(&mut store, params, results)?;
955c22b3cb9SNick Fitzgerald 
9560fa13013SNick Fitzgerald         unsafe { self.call_impl_do_call(&mut store, params, results) }
957d4242001SAdam Bratschi-Kaye     }
958d4242001SAdam Bratschi-Kaye 
959d4242001SAdam Bratschi-Kaye     /// Invokes this function in an "unchecked" fashion, reading parameters and
960d4242001SAdam Bratschi-Kaye     /// writing results to `params_and_returns`.
961d4242001SAdam Bratschi-Kaye     ///
962d4242001SAdam Bratschi-Kaye     /// This function is the same as [`Func::call`] except that the arguments
963d4242001SAdam Bratschi-Kaye     /// and results both use a different representation. If possible it's
964d4242001SAdam Bratschi-Kaye     /// recommended to use [`Func::call`] if safety isn't necessary or to use
965d4242001SAdam Bratschi-Kaye     /// [`Func::typed`] in conjunction with [`TypedFunc::call`] since that's
966d4242001SAdam Bratschi-Kaye     /// both safer and faster than this method of invoking a function.
967d4242001SAdam Bratschi-Kaye     ///
968d4242001SAdam Bratschi-Kaye     /// Note that if this function takes `externref` arguments then it will
969d4242001SAdam Bratschi-Kaye     /// **not** automatically GC unlike the [`Func::call`] and
970d4242001SAdam Bratschi-Kaye     /// [`TypedFunc::call`] functions. This means that if this function is
971d4242001SAdam Bratschi-Kaye     /// invoked many times with new `ExternRef` values and no other GC happens
972d4242001SAdam Bratschi-Kaye     /// via any other means then no values will get collected.
973d4242001SAdam Bratschi-Kaye     ///
974d4242001SAdam Bratschi-Kaye     /// # Errors
975d4242001SAdam Bratschi-Kaye     ///
976d4242001SAdam Bratschi-Kaye     /// For more information about errors see the [`Func::call`] documentation.
977d4242001SAdam Bratschi-Kaye     ///
978d4242001SAdam Bratschi-Kaye     /// # Unsafety
979d4242001SAdam Bratschi-Kaye     ///
980d4242001SAdam Bratschi-Kaye     /// This function is unsafe because the `params_and_returns` argument is not
981d4242001SAdam Bratschi-Kaye     /// validated at all. It must uphold invariants such as:
982d4242001SAdam Bratschi-Kaye     ///
983d4242001SAdam Bratschi-Kaye     /// * It's a valid pointer to an array
984d4242001SAdam Bratschi-Kaye     /// * It has enough space to store all parameters
985d4242001SAdam Bratschi-Kaye     /// * It has enough space to store all results (not at the same time as
986d4242001SAdam Bratschi-Kaye     ///   parameters)
987d4242001SAdam Bratschi-Kaye     /// * Parameters are initially written to the array and have the correct
988d4242001SAdam Bratschi-Kaye     ///   types and such.
989d4242001SAdam Bratschi-Kaye     /// * Reference types like `externref` and `funcref` are valid at the
990d4242001SAdam Bratschi-Kaye     ///   time of this call and for the `store` specified.
991d4242001SAdam Bratschi-Kaye     ///
992d4242001SAdam Bratschi-Kaye     /// These invariants are all upheld for you with [`Func::call`] and
993d4242001SAdam Bratschi-Kaye     /// [`TypedFunc::call`].
call_unchecked( &self, mut store: impl AsContextMut, params_and_returns: *mut [ValRaw], ) -> Result<()>994d4242001SAdam Bratschi-Kaye     pub unsafe fn call_unchecked(
995d4242001SAdam Bratschi-Kaye         &self,
996d4242001SAdam Bratschi-Kaye         mut store: impl AsContextMut,
9978995bcc4SAlex Crichton         params_and_returns: *mut [ValRaw],
998d4242001SAdam Bratschi-Kaye     ) -> Result<()> {
999d4242001SAdam Bratschi-Kaye         let mut store = store.as_context_mut();
10004fcfe17aSAlex Crichton         let func_ref = self.vm_func_ref(store.0);
1001b86b9682SAlex Crichton         let params_and_returns = NonNull::new(params_and_returns).unwrap_or(NonNull::from(&mut []));
10020f457fadSAlex Crichton 
10030f457fadSAlex Crichton         // SAFETY: the safety of this function call is the same as the contract
10040f457fadSAlex Crichton         // of this function.
10050f457fadSAlex Crichton         unsafe { Self::call_unchecked_raw(&mut store, func_ref, params_and_returns) }
1006d4242001SAdam Bratschi-Kaye     }
1007d4242001SAdam Bratschi-Kaye 
call_unchecked_raw<T>( store: &mut StoreContextMut<'_, T>, func_ref: NonNull<VMFuncRef>, params_and_returns: NonNull<[ValRaw]>, ) -> Result<()>1008d4242001SAdam Bratschi-Kaye     pub(crate) unsafe fn call_unchecked_raw<T>(
1009d4242001SAdam Bratschi-Kaye         store: &mut StoreContextMut<'_, T>,
1010d4242001SAdam Bratschi-Kaye         func_ref: NonNull<VMFuncRef>,
1011b86b9682SAlex Crichton         params_and_returns: NonNull<[ValRaw]>,
1012d4242001SAdam Bratschi-Kaye     ) -> Result<()> {
10130f457fadSAlex Crichton         // SAFETY: the safety of this function call is the same as the contract
10140f457fadSAlex Crichton         // of this function.
10150f457fadSAlex Crichton         invoke_wasm_and_catch_traps(store, |caller, vm| unsafe {
1016078bc37bSAlex Crichton             VMFuncRef::array_call(func_ref, vm, caller, params_and_returns)
1017d4242001SAdam Bratschi-Kaye         })
1018d4242001SAdam Bratschi-Kaye     }
1019d4242001SAdam Bratschi-Kaye 
1020d4242001SAdam Bratschi-Kaye     /// Converts the raw representation of a `funcref` into an `Option<Func>`
1021d4242001SAdam Bratschi-Kaye     ///
1022d4242001SAdam Bratschi-Kaye     /// This is intended to be used in conjunction with [`Func::new_unchecked`],
1023686ea892SAlex Crichton     /// [`Func::call_unchecked`], and [`ValRaw`] with its `funcref` field. This
1024686ea892SAlex Crichton     /// is the dual of [`Func::to_raw`].
1025d4242001SAdam Bratschi-Kaye     ///
1026d4242001SAdam Bratschi-Kaye     /// # Unsafety
1027d4242001SAdam Bratschi-Kaye     ///
1028d4242001SAdam Bratschi-Kaye     /// This function is not safe because `raw` is not validated at all. The
1029d4242001SAdam Bratschi-Kaye     /// caller must guarantee that `raw` is owned by the `store` provided and is
1030d4242001SAdam Bratschi-Kaye     /// valid within the `store`.
from_raw(mut store: impl AsContextMut, raw: *mut c_void) -> Option<Func>1031d4242001SAdam Bratschi-Kaye     pub unsafe fn from_raw(mut store: impl AsContextMut, raw: *mut c_void) -> Option<Func> {
10320f457fadSAlex Crichton         // SAFETY: this function's own contract is that `raw` is owned by store
10330f457fadSAlex Crichton         // to make this safe.
10340f457fadSAlex Crichton         unsafe { Self::_from_raw(store.as_context_mut().0, raw) }
1035bd2ea901SNick Fitzgerald     }
1036bd2ea901SNick Fitzgerald 
10370f457fadSAlex Crichton     /// Same as `from_raw`, but with the internal `StoreOpaque` type.
_from_raw(store: &mut StoreOpaque, raw: *mut c_void) -> Option<Func>1038bd2ea901SNick Fitzgerald     pub(crate) unsafe fn _from_raw(store: &mut StoreOpaque, raw: *mut c_void) -> Option<Func> {
10390f457fadSAlex Crichton         // SAFETY: this function's own contract is that `raw` is owned by store
10400f457fadSAlex Crichton         // to make this safe.
10410f457fadSAlex Crichton         unsafe {
10422b832281SAlex Crichton             Some(Func::from_vm_func_ref(
10432b832281SAlex Crichton                 store.id(),
10442b832281SAlex Crichton                 NonNull::new(raw.cast())?,
10452b832281SAlex Crichton             ))
1046d4242001SAdam Bratschi-Kaye         }
10470f457fadSAlex Crichton     }
1048d4242001SAdam Bratschi-Kaye 
1049d4242001SAdam Bratschi-Kaye     /// Extracts the raw value of this `Func`, which is owned by `store`.
1050d4242001SAdam Bratschi-Kaye     ///
1051d4242001SAdam Bratschi-Kaye     /// This function returns a value that's suitable for writing into the
1052d4242001SAdam Bratschi-Kaye     /// `funcref` field of the [`ValRaw`] structure.
1053d4242001SAdam Bratschi-Kaye     ///
1054686ea892SAlex Crichton     /// # Safety
1055d4242001SAdam Bratschi-Kaye     ///
1056686ea892SAlex Crichton     /// The returned value is only valid for as long as the store is alive.
1057686ea892SAlex Crichton     /// This value is safe to pass to [`Func::from_raw`] so long as the same
1058686ea892SAlex Crichton     /// `store` is provided.
to_raw(&self, mut store: impl AsContextMut) -> *mut c_void1059686ea892SAlex Crichton     pub fn to_raw(&self, mut store: impl AsContextMut) -> *mut c_void {
1060d4242001SAdam Bratschi-Kaye         self.vm_func_ref(store.as_context_mut().0).as_ptr().cast()
1061d4242001SAdam Bratschi-Kaye     }
1062d4242001SAdam Bratschi-Kaye 
1063d4242001SAdam Bratschi-Kaye     /// Invokes this function with the `params` given, returning the results
1064d4242001SAdam Bratschi-Kaye     /// asynchronously.
1065d4242001SAdam Bratschi-Kaye     ///
1066d4242001SAdam Bratschi-Kaye     /// This function is the same as [`Func::call`] except that it is
1067cc8d04f4SAlex Crichton     /// asynchronous.
1068d4242001SAdam Bratschi-Kaye     ///
1069d4242001SAdam Bratschi-Kaye     /// It's important to note that the execution of WebAssembly will happen
1070d4242001SAdam Bratschi-Kaye     /// synchronously in the `poll` method of the future returned from this
1071d4242001SAdam Bratschi-Kaye     /// function. Wasmtime does not manage its own thread pool or similar to
1072d4242001SAdam Bratschi-Kaye     /// execute WebAssembly in. Future `poll` methods are generally expected to
1073d4242001SAdam Bratschi-Kaye     /// resolve quickly, so it's recommended that you run or poll this future
1074d4242001SAdam Bratschi-Kaye     /// in a "blocking context".
1075d4242001SAdam Bratschi-Kaye     ///
1076d4242001SAdam Bratschi-Kaye     /// For more information see the documentation on [asynchronous
1077cc8d04f4SAlex Crichton     /// configs](crate#async).
1078d4242001SAdam Bratschi-Kaye     ///
1079d4242001SAdam Bratschi-Kaye     /// # Errors
1080d4242001SAdam Bratschi-Kaye     ///
1081d4242001SAdam Bratschi-Kaye     /// For more information on errors see the [`Func::call`] documentation.
1082d4242001SAdam Bratschi-Kaye     ///
1083d4242001SAdam Bratschi-Kaye     /// # Panics
1084d4242001SAdam Bratschi-Kaye     ///
1085d4242001SAdam Bratschi-Kaye     /// Panics if this is called on a function in a synchronous store. This
1086d4242001SAdam Bratschi-Kaye     /// only works with functions defined within an asynchronous store. Also
1087d4242001SAdam Bratschi-Kaye     /// panics if `store` does not own this function.
1088d4242001SAdam Bratschi-Kaye     #[cfg(feature = "async")]
call_async( &self, mut store: impl AsContextMut<Data: Send>, params: &[Val], results: &mut [Val], ) -> Result<()>1089f81c0dc0SAlex Crichton     pub async fn call_async(
1090d4242001SAdam Bratschi-Kaye         &self,
1091f81c0dc0SAlex Crichton         mut store: impl AsContextMut<Data: Send>,
1092d4242001SAdam Bratschi-Kaye         params: &[Val],
1093d4242001SAdam Bratschi-Kaye         results: &mut [Val],
1094f81c0dc0SAlex Crichton     ) -> Result<()> {
1095d4242001SAdam Bratschi-Kaye         let mut store = store.as_context_mut();
1096c22b3cb9SNick Fitzgerald 
109758e295eeSNick Fitzgerald         self.call_impl_check_args(&mut store, params, results)?;
1098c22b3cb9SNick Fitzgerald 
1099d4242001SAdam Bratschi-Kaye         let result = store
11000fa13013SNick Fitzgerald             .on_fiber(|store| unsafe { self.call_impl_do_call(store, params, results) })
1101d4242001SAdam Bratschi-Kaye             .await??;
1102d4242001SAdam Bratschi-Kaye         Ok(result)
1103d4242001SAdam Bratschi-Kaye     }
1104d4242001SAdam Bratschi-Kaye 
11050fa13013SNick Fitzgerald     /// Perform dynamic checks that the arguments given to us match
11060fa13013SNick Fitzgerald     /// the signature of this function and are appropriate to pass to this
11070fa13013SNick Fitzgerald     /// function.
11080fa13013SNick Fitzgerald     ///
11090fa13013SNick Fitzgerald     /// This involves checking to make sure we have the right number and types
11100fa13013SNick Fitzgerald     /// of arguments as well as making sure everything is from the same `Store`.
11110fa13013SNick Fitzgerald     ///
11120fa13013SNick Fitzgerald     /// This must be called just before `call_impl_do_call`.
call_impl_check_args<T>( &self, store: &mut StoreContextMut<'_, T>, params: &[Val], results: &mut [Val], ) -> Result<()>11130fa13013SNick Fitzgerald     fn call_impl_check_args<T>(
1114d4242001SAdam Bratschi-Kaye         &self,
1115d4242001SAdam Bratschi-Kaye         store: &mut StoreContextMut<'_, T>,
1116d4242001SAdam Bratschi-Kaye         params: &[Val],
1117d4242001SAdam Bratschi-Kaye         results: &mut [Val],
111858e295eeSNick Fitzgerald     ) -> Result<()> {
11194fcfe17aSAlex Crichton         let ty = self.load_ty(store.0);
1120d4242001SAdam Bratschi-Kaye         if ty.params().len() != params.len() {
1121d4242001SAdam Bratschi-Kaye             bail!(
1122d4242001SAdam Bratschi-Kaye                 "expected {} arguments, got {}",
1123d4242001SAdam Bratschi-Kaye                 ty.params().len(),
1124d4242001SAdam Bratschi-Kaye                 params.len()
1125d4242001SAdam Bratschi-Kaye             );
1126d4242001SAdam Bratschi-Kaye         }
1127d4242001SAdam Bratschi-Kaye         if ty.results().len() != results.len() {
1128d4242001SAdam Bratschi-Kaye             bail!(
1129d4242001SAdam Bratschi-Kaye                 "expected {} results, got {}",
1130d4242001SAdam Bratschi-Kaye                 ty.results().len(),
1131d4242001SAdam Bratschi-Kaye                 results.len()
1132d4242001SAdam Bratschi-Kaye             );
1133d4242001SAdam Bratschi-Kaye         }
113463d482c8SFrank Emrich 
1135d4242001SAdam Bratschi-Kaye         for (ty, arg) in ty.params().zip(params) {
11364fcfe17aSAlex Crichton             arg.ensure_matches_ty(store.0, &ty)
1137ff93bce0SNick Fitzgerald                 .context("argument type mismatch")?;
11384fcfe17aSAlex Crichton             if !arg.comes_from_same_store(store.0) {
1139d4242001SAdam Bratschi-Kaye                 bail!("cross-`Store` values are not currently supported");
1140d4242001SAdam Bratschi-Kaye             }
1141d4242001SAdam Bratschi-Kaye         }
1142d4242001SAdam Bratschi-Kaye 
114358e295eeSNick Fitzgerald         Ok(())
11440fa13013SNick Fitzgerald     }
11450fa13013SNick Fitzgerald 
11460fa13013SNick Fitzgerald     /// Do the actual call into Wasm.
11470fa13013SNick Fitzgerald     ///
11480fa13013SNick Fitzgerald     /// # Safety
11490fa13013SNick Fitzgerald     ///
11500fa13013SNick Fitzgerald     /// You must have type checked the arguments by calling
11510fa13013SNick Fitzgerald     /// `call_impl_check_args` immediately before calling this function. It is
11520fa13013SNick Fitzgerald     /// only safe to call this function if that one did not return an error.
call_impl_do_call<T>( &self, store: &mut StoreContextMut<'_, T>, params: &[Val], results: &mut [Val], ) -> Result<()>11530fa13013SNick Fitzgerald     unsafe fn call_impl_do_call<T>(
11540fa13013SNick Fitzgerald         &self,
11550fa13013SNick Fitzgerald         store: &mut StoreContextMut<'_, T>,
11560fa13013SNick Fitzgerald         params: &[Val],
11570fa13013SNick Fitzgerald         results: &mut [Val],
11580fa13013SNick Fitzgerald     ) -> Result<()> {
1159d4242001SAdam Bratschi-Kaye         // Store the argument values into `values_vec`.
11604fcfe17aSAlex Crichton         let ty = self.load_ty(store.0);
11610fa13013SNick Fitzgerald         let values_vec_size = params.len().max(ty.results().len());
1162d4242001SAdam Bratschi-Kaye         let mut values_vec = store.0.take_wasm_val_raw_storage();
1163d4242001SAdam Bratschi-Kaye         debug_assert!(values_vec.is_empty());
1164*439de7fbSNick Fitzgerald         values_vec.resize_with(values_vec_size, || ValRaw::v128(0))?;
1165d4242001SAdam Bratschi-Kaye         for (arg, slot) in params.iter().cloned().zip(&mut values_vec) {
1166bd2ea901SNick Fitzgerald             *slot = arg.to_raw(&mut *store)?;
1167d4242001SAdam Bratschi-Kaye         }
1168d4242001SAdam Bratschi-Kaye 
1169d4242001SAdam Bratschi-Kaye         unsafe {
11708995bcc4SAlex Crichton             self.call_unchecked(
11718995bcc4SAlex Crichton                 &mut *store,
11728995bcc4SAlex Crichton                 core::ptr::slice_from_raw_parts_mut(values_vec.as_mut_ptr(), values_vec_size),
11738995bcc4SAlex Crichton             )?;
1174d4242001SAdam Bratschi-Kaye         }
1175d4242001SAdam Bratschi-Kaye 
1176d4242001SAdam Bratschi-Kaye         for ((i, slot), val) in results.iter_mut().enumerate().zip(&values_vec) {
11774fcfe17aSAlex Crichton             let ty = ty.results().nth(i).unwrap();
1178d4242001SAdam Bratschi-Kaye             *slot = unsafe { Val::from_raw(&mut *store, *val, ty) };
1179d4242001SAdam Bratschi-Kaye         }
1180d4242001SAdam Bratschi-Kaye         values_vec.truncate(0);
1181d4242001SAdam Bratschi-Kaye         store.0.save_wasm_val_raw_storage(values_vec);
1182d4242001SAdam Bratschi-Kaye         Ok(())
1183d4242001SAdam Bratschi-Kaye     }
1184d4242001SAdam Bratschi-Kaye 
1185d4242001SAdam Bratschi-Kaye     #[inline]
vm_func_ref(&self, store: &StoreOpaque) -> NonNull<VMFuncRef>11864fcfe17aSAlex Crichton     pub(crate) fn vm_func_ref(&self, store: &StoreOpaque) -> NonNull<VMFuncRef> {
11874fcfe17aSAlex Crichton         self.store.assert_belongs_to(store.id());
11884fcfe17aSAlex Crichton         self.unsafe_func_ref.as_non_null()
1189d4242001SAdam Bratschi-Kaye     }
1190d4242001SAdam Bratschi-Kaye 
vmimport(&self, store: &StoreOpaque) -> VMFunctionImport1191e012eedaSAlex Crichton     pub(crate) fn vmimport(&self, store: &StoreOpaque) -> VMFunctionImport {
1192d4242001SAdam Bratschi-Kaye         unsafe {
11934fcfe17aSAlex Crichton             let f = self.vm_func_ref(store);
1194d4242001SAdam Bratschi-Kaye             VMFunctionImport {
11954fcfe17aSAlex Crichton                 // Note that this is a load-bearing `unwrap` here, but is
11964fcfe17aSAlex Crichton                 // never expected to trip at runtime. The general problem is
11974fcfe17aSAlex Crichton                 // that host functions do not have a `wasm_call` function so
11984fcfe17aSAlex Crichton                 // the `VMFuncRef` type has an optional pointer there. This is
11994fcfe17aSAlex Crichton                 // only able to be filled out when a function is "paired" with
12004fcfe17aSAlex Crichton                 // a module where trampolines are present to fill out
12014fcfe17aSAlex Crichton                 // `wasm_call` pointers.
12024fcfe17aSAlex Crichton                 //
12034fcfe17aSAlex Crichton                 // This pairing of modules doesn't happen explicitly but is
12044fcfe17aSAlex Crichton                 // instead managed lazily throughout Wasmtime. Specifically the
12054fcfe17aSAlex Crichton                 // way this works is one of:
12064fcfe17aSAlex Crichton                 //
12074fcfe17aSAlex Crichton                 // * When a host function is created the store's list of
12084fcfe17aSAlex Crichton                 //   modules are searched for a wasm trampoline. If not found
12094fcfe17aSAlex Crichton                 //   the `wasm_call` field is left blank.
12104fcfe17aSAlex Crichton                 //
12114fcfe17aSAlex Crichton                 // * When a module instantiation happens, which uses this
12124fcfe17aSAlex Crichton                 //   function, the module will be used to fill any outstanding
12134fcfe17aSAlex Crichton                 //   holes that it has trampolines for.
12144fcfe17aSAlex Crichton                 //
12154fcfe17aSAlex Crichton                 // This means that by the time we get to this point any
12164fcfe17aSAlex Crichton                 // relevant holes should be filled out. Thus if this panic
12174fcfe17aSAlex Crichton                 // actually triggers then it's indicative of a missing `fill`
12184fcfe17aSAlex Crichton                 // call somewhere else.
12194fcfe17aSAlex Crichton                 wasm_call: f.as_ref().wasm_call.unwrap(),
1220d4242001SAdam Bratschi-Kaye                 array_call: f.as_ref().array_call,
1221d4242001SAdam Bratschi-Kaye                 vmctx: f.as_ref().vmctx,
1222d4242001SAdam Bratschi-Kaye             }
1223d4242001SAdam Bratschi-Kaye         }
1224d4242001SAdam Bratschi-Kaye     }
1225d4242001SAdam Bratschi-Kaye 
comes_from_same_store(&self, store: &StoreOpaque) -> bool1226d4242001SAdam Bratschi-Kaye     pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
12274fcfe17aSAlex Crichton         self.store == store.id()
1228d4242001SAdam Bratschi-Kaye     }
1229d4242001SAdam Bratschi-Kaye 
1230d4242001SAdam Bratschi-Kaye     /// Attempts to extract a typed object from this `Func` through which the
1231d4242001SAdam Bratschi-Kaye     /// function can be called.
1232d4242001SAdam Bratschi-Kaye     ///
1233d4242001SAdam Bratschi-Kaye     /// This function serves as an alternative to [`Func::call`] and
1234d4242001SAdam Bratschi-Kaye     /// [`Func::call_async`]. This method performs a static type check (using
1235d4242001SAdam Bratschi-Kaye     /// the `Params` and `Results` type parameters on the underlying wasm
1236d4242001SAdam Bratschi-Kaye     /// function. If the type check passes then a `TypedFunc` object is returned,
1237d4242001SAdam Bratschi-Kaye     /// otherwise an error is returned describing the typecheck failure.
1238d4242001SAdam Bratschi-Kaye     ///
1239d4242001SAdam Bratschi-Kaye     /// The purpose of this relative to [`Func::call`] is that it's much more
1240d4242001SAdam Bratschi-Kaye     /// efficient when used to invoke WebAssembly functions. With the types
1241d4242001SAdam Bratschi-Kaye     /// statically known far less setup/teardown is required when invoking
1242d4242001SAdam Bratschi-Kaye     /// WebAssembly. If speed is desired then this function is recommended to be
1243d4242001SAdam Bratschi-Kaye     /// used instead of [`Func::call`] (which is more general, hence its
1244d4242001SAdam Bratschi-Kaye     /// slowdown).
1245d4242001SAdam Bratschi-Kaye     ///
1246d4242001SAdam Bratschi-Kaye     /// The `Params` type parameter is used to describe the parameters of the
1247d4242001SAdam Bratschi-Kaye     /// WebAssembly function. This can either be a single type (like `i32`), or
1248d4242001SAdam Bratschi-Kaye     /// a tuple of types representing the list of parameters (like `(i32, f32,
1249d4242001SAdam Bratschi-Kaye     /// f64)`). Additionally you can use `()` to represent that the function has
1250d4242001SAdam Bratschi-Kaye     /// no parameters.
1251d4242001SAdam Bratschi-Kaye     ///
1252d4242001SAdam Bratschi-Kaye     /// The `Results` type parameter is used to describe the results of the
1253d4242001SAdam Bratschi-Kaye     /// function. This behaves the same way as `Params`, but just for the
1254d4242001SAdam Bratschi-Kaye     /// results of the function.
1255d4242001SAdam Bratschi-Kaye     ///
1256ff93bce0SNick Fitzgerald     /// # Translating Between WebAssembly and Rust Types
1257ff93bce0SNick Fitzgerald     ///
1258d4242001SAdam Bratschi-Kaye     /// Translation between Rust types and WebAssembly types looks like:
1259d4242001SAdam Bratschi-Kaye     ///
1260d4242001SAdam Bratschi-Kaye     /// | WebAssembly                               | Rust                                  |
126122a3d9edSNick Fitzgerald     /// |-------------------------------------------|---------------------------------------|
1262d4242001SAdam Bratschi-Kaye     /// | `i32`                                     | `i32` or `u32`                        |
1263d4242001SAdam Bratschi-Kaye     /// | `i64`                                     | `i64` or `u64`                        |
1264d4242001SAdam Bratschi-Kaye     /// | `f32`                                     | `f32`                                 |
1265d4242001SAdam Bratschi-Kaye     /// | `f64`                                     | `f64`                                 |
1266c16414fbSNick Fitzgerald     /// | `externref` aka `(ref null extern)`       | `Option<Rooted<ExternRef>>`           |
1267c16414fbSNick Fitzgerald     /// | `(ref extern)`                            | `Rooted<ExternRef>`                   |
126822a3d9edSNick Fitzgerald     /// | `nullexternref` aka `(ref null noextern)` | `Option<NoExtern>`                    |
1269c16414fbSNick Fitzgerald     /// | `(ref noextern)`                          | `NoExtern`                            |
1270c16414fbSNick Fitzgerald     /// | `anyref` aka `(ref null any)`             | `Option<Rooted<AnyRef>>`              |
1271c16414fbSNick Fitzgerald     /// | `(ref any)`                               | `Rooted<AnyRef>`                      |
1272c16414fbSNick Fitzgerald     /// | `eqref` aka `(ref null eq)`               | `Option<Rooted<EqRef>>`               |
1273c16414fbSNick Fitzgerald     /// | `(ref eq)`                                | `Rooted<EqRef>`                       |
12740fa13013SNick Fitzgerald     /// | `i31ref` aka `(ref null i31)`             | `Option<I31>`                         |
12750fa13013SNick Fitzgerald     /// | `(ref i31)`                               | `I31`                                 |
1276c16414fbSNick Fitzgerald     /// | `structref` aka `(ref null struct)`       | `Option<Rooted<StructRef>>`           |
1277c16414fbSNick Fitzgerald     /// | `(ref struct)`                            | `Rooted<StructRef>`                   |
1278c16414fbSNick Fitzgerald     /// | `arrayref` aka `(ref null array)`         | `Option<Rooted<ArrayRef>>`            |
1279c16414fbSNick Fitzgerald     /// | `(ref array)`                             | `Rooted<ArrayRef>`                    |
1280939917dcSNick Fitzgerald     /// | `nullref` aka `(ref null none)`           | `Option<NoneRef>`                     |
1281939917dcSNick Fitzgerald     /// | `(ref none)`                              | `NoneRef`                             |
1282ff93bce0SNick Fitzgerald     /// | `funcref` aka `(ref null func)`           | `Option<Func>`                        |
1283ff93bce0SNick Fitzgerald     /// | `(ref func)`                              | `Func`                                |
1284ff93bce0SNick Fitzgerald     /// | `(ref null <func type index>)`            | `Option<Func>`                        |
1285ff93bce0SNick Fitzgerald     /// | `(ref <func type index>)`                 | `Func`                                |
1286ff93bce0SNick Fitzgerald     /// | `nullfuncref` aka `(ref null nofunc)`     | `Option<NoFunc>`                      |
1287ff93bce0SNick Fitzgerald     /// | `(ref nofunc)`                            | `NoFunc`                              |
1288ff93bce0SNick Fitzgerald     /// | `v128`                                    | `V128` on `x86-64` and `aarch64` only |
1289d4242001SAdam Bratschi-Kaye     ///
1290c16414fbSNick Fitzgerald     /// (Note that this mapping is the same as that of [`Func::wrap`], and that
12919826719aSChris Fallin     /// anywhere a `Rooted<T>` appears, a `OwnedRooted<T>` may also appear).
1292d4242001SAdam Bratschi-Kaye     ///
1293d4242001SAdam Bratschi-Kaye     /// Note that once the [`TypedFunc`] return value is acquired you'll use either
1294d4242001SAdam Bratschi-Kaye     /// [`TypedFunc::call`] or [`TypedFunc::call_async`] as necessary to actually invoke
1295d4242001SAdam Bratschi-Kaye     /// the function. This method does not invoke any WebAssembly code, it
1296d4242001SAdam Bratschi-Kaye     /// simply performs a typecheck before returning the [`TypedFunc`] value.
1297d4242001SAdam Bratschi-Kaye     ///
1298d4242001SAdam Bratschi-Kaye     /// This method also has a convenience wrapper as
1299d4242001SAdam Bratschi-Kaye     /// [`Instance::get_typed_func`](crate::Instance::get_typed_func) to
1300d4242001SAdam Bratschi-Kaye     /// directly get a typed function value from an
1301d4242001SAdam Bratschi-Kaye     /// [`Instance`](crate::Instance).
1302d4242001SAdam Bratschi-Kaye     ///
1303ff93bce0SNick Fitzgerald     /// ## Subtyping
1304ff93bce0SNick Fitzgerald     ///
1305ff93bce0SNick Fitzgerald     /// For result types, you can always use a supertype of the WebAssembly
1306ff93bce0SNick Fitzgerald     /// function's actual declared result type. For example, if the WebAssembly
1307ff93bce0SNick Fitzgerald     /// function was declared with type `(func (result nullfuncref))` you could
1308ff93bce0SNick Fitzgerald     /// successfully call `f.typed::<(), Option<Func>>()` because `Option<Func>`
1309ff93bce0SNick Fitzgerald     /// corresponds to `funcref`, which is a supertype of `nullfuncref`.
1310ff93bce0SNick Fitzgerald     ///
1311ff93bce0SNick Fitzgerald     /// For parameter types, you can always use a subtype of the WebAssembly
1312ff93bce0SNick Fitzgerald     /// function's actual declared parameter type. For example, if the
1313ff93bce0SNick Fitzgerald     /// WebAssembly function was declared with type `(func (param (ref null
1314ff93bce0SNick Fitzgerald     /// func)))` you could successfully call `f.typed::<Func, ()>()` because
1315ff93bce0SNick Fitzgerald     /// `Func` corresponds to `(ref func)`, which is a subtype of `(ref null
1316ff93bce0SNick Fitzgerald     /// func)`.
1317ff93bce0SNick Fitzgerald     ///
1318ff93bce0SNick Fitzgerald     /// Additionally, for functions which take a reference to a concrete type as
1319ff93bce0SNick Fitzgerald     /// a parameter, you can also use the concrete type's supertype. Consider a
1320ff93bce0SNick Fitzgerald     /// WebAssembly function that takes a reference to a function with a
1321ff93bce0SNick Fitzgerald     /// concrete type: `(ref null <func type index>)`. In this scenario, there
1322ff93bce0SNick Fitzgerald     /// is no static `wasmtime::Foo` Rust type that corresponds to that
1323ff93bce0SNick Fitzgerald     /// particular Wasm-defined concrete reference type because Wasm modules are
1324ff93bce0SNick Fitzgerald     /// loaded dynamically at runtime. You *could* do `f.typed::<Option<NoFunc>,
1325ff93bce0SNick Fitzgerald     /// ()>()`, and while that is correctly typed and valid, it is often overly
1326ff93bce0SNick Fitzgerald     /// restrictive. The only value you could call the resulting typed function
1327ff93bce0SNick Fitzgerald     /// with is the null function reference, but we'd like to call it with
1328ff93bce0SNick Fitzgerald     /// non-null function references that happen to be of the correct
1329ff93bce0SNick Fitzgerald     /// type. Therefore, `f.typed<Option<Func>, ()>()` is also allowed in this
1330ff93bce0SNick Fitzgerald     /// case, even though `Option<Func>` represents `(ref null func)` which is
1331ff93bce0SNick Fitzgerald     /// the supertype, not subtype, of `(ref null <func type index>)`. This does
1332ff93bce0SNick Fitzgerald     /// imply some minimal dynamic type checks in this case, but it is supported
1333ff93bce0SNick Fitzgerald     /// for better ergonomics, to enable passing non-null references into the
1334ff93bce0SNick Fitzgerald     /// function.
1335ff93bce0SNick Fitzgerald     ///
1336d4242001SAdam Bratschi-Kaye     /// # Errors
1337d4242001SAdam Bratschi-Kaye     ///
1338d4242001SAdam Bratschi-Kaye     /// This function will return an error if `Params` or `Results` does not
1339d4242001SAdam Bratschi-Kaye     /// match the native type of this WebAssembly function.
1340d4242001SAdam Bratschi-Kaye     ///
1341d4242001SAdam Bratschi-Kaye     /// # Panics
1342d4242001SAdam Bratschi-Kaye     ///
1343d4242001SAdam Bratschi-Kaye     /// This method will panic if `store` does not own this function.
1344d4242001SAdam Bratschi-Kaye     ///
1345d4242001SAdam Bratschi-Kaye     /// # Examples
1346d4242001SAdam Bratschi-Kaye     ///
1347d4242001SAdam Bratschi-Kaye     /// An end-to-end example of calling a function which takes no parameters
1348d4242001SAdam Bratschi-Kaye     /// and has no results:
1349d4242001SAdam Bratschi-Kaye     ///
1350d4242001SAdam Bratschi-Kaye     /// ```
1351d4242001SAdam Bratschi-Kaye     /// # use wasmtime::*;
135296e19700SNick Fitzgerald     /// # fn main() -> Result<()> {
1353d4242001SAdam Bratschi-Kaye     /// let engine = Engine::default();
1354d4242001SAdam Bratschi-Kaye     /// let mut store = Store::new(&engine, ());
1355d4242001SAdam Bratschi-Kaye     /// let module = Module::new(&engine, r#"(module (func (export "foo")))"#)?;
1356d4242001SAdam Bratschi-Kaye     /// let instance = Instance::new(&mut store, &module, &[])?;
1357d4242001SAdam Bratschi-Kaye     /// let foo = instance.get_func(&mut store, "foo").expect("export wasn't a function");
1358d4242001SAdam Bratschi-Kaye     ///
1359d4242001SAdam Bratschi-Kaye     /// // Note that this call can fail due to the typecheck not passing, but
1360d4242001SAdam Bratschi-Kaye     /// // in our case we statically know the module so we know this should
1361d4242001SAdam Bratschi-Kaye     /// // pass.
1362d4242001SAdam Bratschi-Kaye     /// let typed = foo.typed::<(), ()>(&store)?;
1363d4242001SAdam Bratschi-Kaye     ///
1364d4242001SAdam Bratschi-Kaye     /// // Note that this can fail if the wasm traps at runtime.
1365d4242001SAdam Bratschi-Kaye     /// typed.call(&mut store, ())?;
1366d4242001SAdam Bratschi-Kaye     /// # Ok(())
1367d4242001SAdam Bratschi-Kaye     /// # }
1368d4242001SAdam Bratschi-Kaye     /// ```
1369d4242001SAdam Bratschi-Kaye     ///
1370d4242001SAdam Bratschi-Kaye     /// You can also pass in multiple parameters and get a result back
1371d4242001SAdam Bratschi-Kaye     ///
1372d4242001SAdam Bratschi-Kaye     /// ```
1373d4242001SAdam Bratschi-Kaye     /// # use wasmtime::*;
137496e19700SNick Fitzgerald     /// # fn foo(add: &Func, mut store: Store<()>) -> Result<()> {
1375d4242001SAdam Bratschi-Kaye     /// let typed = add.typed::<(i32, i64), f32>(&store)?;
1376d4242001SAdam Bratschi-Kaye     /// assert_eq!(typed.call(&mut store, (1, 2))?, 3.0);
1377d4242001SAdam Bratschi-Kaye     /// # Ok(())
1378d4242001SAdam Bratschi-Kaye     /// # }
1379d4242001SAdam Bratschi-Kaye     /// ```
1380d4242001SAdam Bratschi-Kaye     ///
1381d4242001SAdam Bratschi-Kaye     /// and similarly if a function has multiple results you can bind that too
1382d4242001SAdam Bratschi-Kaye     ///
1383d4242001SAdam Bratschi-Kaye     /// ```
1384d4242001SAdam Bratschi-Kaye     /// # use wasmtime::*;
138596e19700SNick Fitzgerald     /// # fn foo(add_with_overflow: &Func, mut store: Store<()>) -> Result<()> {
1386d4242001SAdam Bratschi-Kaye     /// let typed = add_with_overflow.typed::<(u32, u32), (u32, i32)>(&store)?;
1387d4242001SAdam Bratschi-Kaye     /// let (result, overflow) = typed.call(&mut store, (u32::max_value(), 2))?;
1388d4242001SAdam Bratschi-Kaye     /// assert_eq!(result, 1);
1389d4242001SAdam Bratschi-Kaye     /// assert_eq!(overflow, 1);
1390d4242001SAdam Bratschi-Kaye     /// # Ok(())
1391d4242001SAdam Bratschi-Kaye     /// # }
1392d4242001SAdam Bratschi-Kaye     /// ```
typed<Params, Results>( &self, store: impl AsContext, ) -> Result<TypedFunc<Params, Results>> where Params: WasmParams, Results: WasmResults,1393d4242001SAdam Bratschi-Kaye     pub fn typed<Params, Results>(
1394d4242001SAdam Bratschi-Kaye         &self,
1395d4242001SAdam Bratschi-Kaye         store: impl AsContext,
1396d4242001SAdam Bratschi-Kaye     ) -> Result<TypedFunc<Params, Results>>
1397d4242001SAdam Bratschi-Kaye     where
1398d4242001SAdam Bratschi-Kaye         Params: WasmParams,
1399d4242001SAdam Bratschi-Kaye         Results: WasmResults,
1400d4242001SAdam Bratschi-Kaye     {
1401d4242001SAdam Bratschi-Kaye         // Type-check that the params/results are all valid
1402ff93bce0SNick Fitzgerald         let store = store.as_context().0;
1403ff93bce0SNick Fitzgerald         let ty = self.load_ty(store);
1404ff93bce0SNick Fitzgerald         Params::typecheck(store.engine(), ty.params(), TypeCheckPosition::Param)
1405ff93bce0SNick Fitzgerald             .context("type mismatch with parameters")?;
1406ff93bce0SNick Fitzgerald         Results::typecheck(store.engine(), ty.results(), TypeCheckPosition::Result)
1407ff93bce0SNick Fitzgerald             .context("type mismatch with results")?;
1408d4242001SAdam Bratschi-Kaye 
1409d4242001SAdam Bratschi-Kaye         // and then we can construct the typed version of this function
1410d4242001SAdam Bratschi-Kaye         // (unsafely), which should be safe since we just did the type check above.
1411ff93bce0SNick Fitzgerald         unsafe { Ok(TypedFunc::_new_unchecked(store, *self)) }
1412d4242001SAdam Bratschi-Kaye     }
1413d4242001SAdam Bratschi-Kaye 
1414d4242001SAdam Bratschi-Kaye     /// Get a stable hash key for this function.
1415d4242001SAdam Bratschi-Kaye     ///
1416d4242001SAdam Bratschi-Kaye     /// Even if the same underlying function is added to the `StoreData`
1417d4242001SAdam Bratschi-Kaye     /// multiple times and becomes multiple `wasmtime::Func`s, this hash key
1418d4242001SAdam Bratschi-Kaye     /// will be consistent across all of these functions.
1419838ed2d0SAlex Crichton     #[cfg_attr(
1420838ed2d0SAlex Crichton         not(test),
1421838ed2d0SAlex Crichton         expect(dead_code, reason = "Not used yet, but added for consistency")
1422838ed2d0SAlex Crichton     )]
hash_key(&self, store: &mut StoreOpaque) -> impl core::hash::Hash + Eq + use<>1423de1ad347SAlex Crichton     pub(crate) fn hash_key(&self, store: &mut StoreOpaque) -> impl core::hash::Hash + Eq + use<> {
1424132a1a53SAlex Crichton         self.vm_func_ref(store).as_ptr().addr()
1425d4242001SAdam Bratschi-Kaye     }
1426d4242001SAdam Bratschi-Kaye }
1427d4242001SAdam Bratschi-Kaye 
1428d4242001SAdam Bratschi-Kaye /// Prepares for entrance into WebAssembly.
1429d4242001SAdam Bratschi-Kaye ///
1430d4242001SAdam Bratschi-Kaye /// This function will set up context such that `closure` is allowed to call a
1431d4242001SAdam Bratschi-Kaye /// raw trampoline or a raw WebAssembly function. This *must* be called to do
1432d4242001SAdam Bratschi-Kaye /// things like catch traps and set up GC properly.
1433d4242001SAdam Bratschi-Kaye ///
1434d4242001SAdam Bratschi-Kaye /// The `closure` provided receives a default "caller" `VMContext` parameter it
1435d4242001SAdam Bratschi-Kaye /// can pass to the called wasm function, if desired.
invoke_wasm_and_catch_traps<T>( store: &mut StoreContextMut<'_, T>, closure: impl FnMut(NonNull<VMContext>, Option<InterpreterRef<'_>>) -> bool, ) -> Result<()>1436d4242001SAdam Bratschi-Kaye pub(crate) fn invoke_wasm_and_catch_traps<T>(
1437d4242001SAdam Bratschi-Kaye     store: &mut StoreContextMut<'_, T>,
1438b86b9682SAlex Crichton     closure: impl FnMut(NonNull<VMContext>, Option<InterpreterRef<'_>>) -> bool,
1439d4242001SAdam Bratschi-Kaye ) -> Result<()> {
144063d482c8SFrank Emrich     // The `enter_wasm` call below will reset the store context's
144163d482c8SFrank Emrich     // `stack_chain` to a new `InitialStack`, pointing to the
144263d482c8SFrank Emrich     // stack-allocated `initial_stack_csi`.
144363d482c8SFrank Emrich     let mut initial_stack_csi = VMCommonStackInformation::running_default();
144463d482c8SFrank Emrich     // Stores some state of the runtime just before entering Wasm. Will be
144563d482c8SFrank Emrich     // restored upon exiting Wasm. Note that the `CallThreadState` that is
144663d482c8SFrank Emrich     // created by the `catch_traps` call below will store a pointer to this
144763d482c8SFrank Emrich     // stack-allocated `previous_runtime_state`.
1448192f2fcdSAlex Crichton     let mut previous_runtime_state = EntryStoreContext::enter_wasm(store, &mut initial_stack_csi);
1449d4242001SAdam Bratschi-Kaye 
1450d4242001SAdam Bratschi-Kaye     if let Err(trap) = store.0.call_hook(CallHook::CallingWasm) {
145120544ac6SFrank Emrich         // `previous_runtime_state` implicitly dropped here
1452d4242001SAdam Bratschi-Kaye         return Err(trap);
1453d4242001SAdam Bratschi-Kaye     }
1454b221fca7SJoel Dice     let result = crate::runtime::vm::catch_traps(store, &mut previous_runtime_state, closure);
1455b856261dSJoel Dice     #[cfg(feature = "component-model")]
1456b856261dSJoel Dice     if result.is_err() {
1457b856261dSJoel Dice         store.0.set_trapped();
1458b856261dSJoel Dice     }
145920544ac6SFrank Emrich     core::mem::drop(previous_runtime_state);
1460d4242001SAdam Bratschi-Kaye     store.0.call_hook(CallHook::ReturningFromWasm)?;
14612d25f862SChris Fallin     result
1462d4242001SAdam Bratschi-Kaye }
1463d4242001SAdam Bratschi-Kaye 
146420544ac6SFrank Emrich /// This type helps managing the state of the runtime when entering and exiting
146520544ac6SFrank Emrich /// Wasm. To this end, it contains a subset of the data in `VMStoreContext`.
146620544ac6SFrank Emrich /// Upon entering Wasm, it updates various runtime fields and their
146720544ac6SFrank Emrich /// original values saved in this struct. Upon exiting Wasm, the previous values
146820544ac6SFrank Emrich /// are restored.
146920544ac6SFrank Emrich pub(crate) struct EntryStoreContext {
147020544ac6SFrank Emrich     /// If set, contains value of `stack_limit` field to restore in
147163d482c8SFrank Emrich     /// `VMStoreContext` when exiting Wasm.
147220544ac6SFrank Emrich     pub stack_limit: Option<usize>,
147320544ac6SFrank Emrich     pub last_wasm_exit_pc: usize,
14742d25f862SChris Fallin     pub last_wasm_exit_trampoline_fp: usize,
147520544ac6SFrank Emrich     pub last_wasm_entry_fp: usize,
1476192f2fcdSAlex Crichton     pub last_wasm_entry_sp: usize,
1477192f2fcdSAlex Crichton     pub last_wasm_entry_trap_handler: usize,
147863d482c8SFrank Emrich     pub stack_chain: VMStackChain,
147920544ac6SFrank Emrich 
148020544ac6SFrank Emrich     /// We need a pointer to the runtime limits, so we can update them from
148120544ac6SFrank Emrich     /// `drop`/`exit_wasm`.
148220544ac6SFrank Emrich     vm_store_context: *const VMStoreContext,
148320544ac6SFrank Emrich }
148420544ac6SFrank Emrich 
148520544ac6SFrank Emrich impl EntryStoreContext {
148620544ac6SFrank Emrich     /// This function is called to update and save state when
1487d4242001SAdam Bratschi-Kaye     /// WebAssembly is entered within the `Store`.
1488d4242001SAdam Bratschi-Kaye     ///
148920544ac6SFrank Emrich     /// This updates various fields such as:
1490d4242001SAdam Bratschi-Kaye     ///
1491d4242001SAdam Bratschi-Kaye     /// * The stack limit. This is what ensures that we limit the stack space
1492d4242001SAdam Bratschi-Kaye     ///   allocated by WebAssembly code and it's relative to the initial stack
1493d4242001SAdam Bratschi-Kaye     ///   pointer that called into wasm.
1494d4242001SAdam Bratschi-Kaye     ///
149563d482c8SFrank Emrich     /// It also saves the different last_wasm_* values in the `VMStoreContext`.
enter_wasm<T>( store: &mut StoreContextMut<'_, T>, initial_stack_information: *mut VMCommonStackInformation, ) -> Self149663d482c8SFrank Emrich     pub fn enter_wasm<T>(
149763d482c8SFrank Emrich         store: &mut StoreContextMut<'_, T>,
149863d482c8SFrank Emrich         initial_stack_information: *mut VMCommonStackInformation,
149963d482c8SFrank Emrich     ) -> Self {
150020544ac6SFrank Emrich         let stack_limit;
150120544ac6SFrank Emrich 
1502d4242001SAdam Bratschi-Kaye         // If this is a recursive call, e.g. our stack limit is already set, then
1503d4242001SAdam Bratschi-Kaye         // we may be able to skip this function.
1504d4242001SAdam Bratschi-Kaye         //
1505d4242001SAdam Bratschi-Kaye         // For synchronous stores there's nothing else to do because all wasm calls
1506d4242001SAdam Bratschi-Kaye         // happen synchronously and on the same stack. This means that the previous
1507d4242001SAdam Bratschi-Kaye         // stack limit will suffice for the next recursive call.
1508d4242001SAdam Bratschi-Kaye         //
1509d4242001SAdam Bratschi-Kaye         // For asynchronous stores then each call happens on a separate native
1510d4242001SAdam Bratschi-Kaye         // stack. This means that the previous stack limit is no longer relevant
1511d4242001SAdam Bratschi-Kaye         // because we're on a separate stack.
1512c2732814SNick Fitzgerald         if unsafe { *store.0.vm_store_context().stack_limit.get() } != usize::MAX
1513cc8d04f4SAlex Crichton             && !store.0.can_block()
1514d4242001SAdam Bratschi-Kaye         {
151520544ac6SFrank Emrich             stack_limit = None;
1516d4242001SAdam Bratschi-Kaye         }
1517d4242001SAdam Bratschi-Kaye         // Ignore this stack pointer business on miri since we can't execute wasm
1518d4242001SAdam Bratschi-Kaye         // anyway and the concept of a stack pointer on miri is a bit nebulous
1519d4242001SAdam Bratschi-Kaye         // regardless.
152020544ac6SFrank Emrich         else if cfg!(miri) {
152120544ac6SFrank Emrich             stack_limit = None;
152220544ac6SFrank Emrich         } else {
15234afa86b8SAlex Crichton             // When Cranelift has support for the host then we might be running native
15244afa86b8SAlex Crichton             // compiled code meaning we need to read the actual stack pointer. If
15254afa86b8SAlex Crichton             // Cranelift can't be used though then we're guaranteed to be running pulley
1526df0a5bafSMaxim Evtush             // in which case this stack pointer isn't actually used as Pulley has custom
15274afa86b8SAlex Crichton             // mechanisms for stack overflow.
15284afa86b8SAlex Crichton             #[cfg(has_host_compiler_backend)]
152972004aadSNick Fitzgerald             let stack_pointer = crate::runtime::vm::get_stack_pointer();
15304afa86b8SAlex Crichton             #[cfg(not(has_host_compiler_backend))]
15314afa86b8SAlex Crichton             let stack_pointer = {
15324afa86b8SAlex Crichton                 use wasmtime_environ::TripleExt;
15334afa86b8SAlex Crichton                 debug_assert!(store.engine().target().is_pulley());
15344afa86b8SAlex Crichton                 usize::MAX
15354afa86b8SAlex Crichton             };
1536d4242001SAdam Bratschi-Kaye 
1537d4242001SAdam Bratschi-Kaye             // Determine the stack pointer where, after which, any wasm code will
1538d4242001SAdam Bratschi-Kaye             // immediately trap. This is checked on the entry to all wasm functions.
1539d4242001SAdam Bratschi-Kaye             //
1540d4242001SAdam Bratschi-Kaye             // Note that this isn't 100% precise. We are requested to give wasm
1541d4242001SAdam Bratschi-Kaye             // `max_wasm_stack` bytes, but what we're actually doing is giving wasm
1542d4242001SAdam Bratschi-Kaye             // probably a little less than `max_wasm_stack` because we're
1543d4242001SAdam Bratschi-Kaye             // calculating the limit relative to this function's approximate stack
1544d4242001SAdam Bratschi-Kaye             // pointer. Wasm will be executed on a frame beneath this one (or next
1545d4242001SAdam Bratschi-Kaye             // to it). In any case it's expected to be at most a few hundred bytes
1546d4242001SAdam Bratschi-Kaye             // of slop one way or another. When wasm is typically given a MB or so
1547d4242001SAdam Bratschi-Kaye             // (a million bytes) the slop shouldn't matter too much.
1548d4242001SAdam Bratschi-Kaye             //
1549d4242001SAdam Bratschi-Kaye             // After we've got the stack limit then we store it into the `stack_limit`
1550d4242001SAdam Bratschi-Kaye             // variable.
15512283e84fSAlex Crichton             //
15522283e84fSAlex Crichton             // Also note that `saturating_sub` is used here since if the user
15532283e84fSAlex Crichton             // said that the function gets nigh-infinite stack well then by
15542283e84fSAlex Crichton             // golly it'll get nigh-infinite stack in which case the limit is 0.
15552283e84fSAlex Crichton             let wasm_stack_limit =
15562283e84fSAlex Crichton                 stack_pointer.saturating_sub(store.engine().config().max_wasm_stack);
1557d4242001SAdam Bratschi-Kaye             let prev_stack = unsafe {
1558d4242001SAdam Bratschi-Kaye                 mem::replace(
1559c2732814SNick Fitzgerald                     &mut *store.0.vm_store_context().stack_limit.get(),
1560d4242001SAdam Bratschi-Kaye                     wasm_stack_limit,
1561d4242001SAdam Bratschi-Kaye                 )
1562d4242001SAdam Bratschi-Kaye             };
156320544ac6SFrank Emrich             stack_limit = Some(prev_stack);
1564d4242001SAdam Bratschi-Kaye         }
1565d4242001SAdam Bratschi-Kaye 
1566d4242001SAdam Bratschi-Kaye         unsafe {
156720544ac6SFrank Emrich             let vm_store_context = store.0.vm_store_context();
1568192f2fcdSAlex Crichton             let new_stack_chain = VMStackChain::InitialStack(initial_stack_information);
1569192f2fcdSAlex Crichton             *vm_store_context.stack_chain.get() = new_stack_chain;
157020544ac6SFrank Emrich 
157120544ac6SFrank Emrich             Self {
157220544ac6SFrank Emrich                 stack_limit,
1573192f2fcdSAlex Crichton                 last_wasm_exit_pc: *(*vm_store_context).last_wasm_exit_pc.get(),
1574192f2fcdSAlex Crichton                 last_wasm_exit_trampoline_fp: *(*vm_store_context)
1575192f2fcdSAlex Crichton                     .last_wasm_exit_trampoline_fp
1576192f2fcdSAlex Crichton                     .get(),
1577192f2fcdSAlex Crichton                 last_wasm_entry_fp: *(*vm_store_context).last_wasm_entry_fp.get(),
1578192f2fcdSAlex Crichton                 last_wasm_entry_sp: *(*vm_store_context).last_wasm_entry_sp.get(),
1579192f2fcdSAlex Crichton                 last_wasm_entry_trap_handler: *(*vm_store_context)
1580192f2fcdSAlex Crichton                     .last_wasm_entry_trap_handler
1581192f2fcdSAlex Crichton                     .get(),
1582192f2fcdSAlex Crichton                 stack_chain: (*(*vm_store_context).stack_chain.get()).clone(),
158320544ac6SFrank Emrich                 vm_store_context,
158420544ac6SFrank Emrich             }
158520544ac6SFrank Emrich         }
158620544ac6SFrank Emrich     }
158720544ac6SFrank Emrich 
158820544ac6SFrank Emrich     /// This function restores the values stored in this struct. We invoke this
158920544ac6SFrank Emrich     /// function through this type's `Drop` implementation. This ensures that we
159020544ac6SFrank Emrich     /// even restore the values if we unwind the stack (e.g., because we are
1591b221fca7SJoel Dice     /// panicking out of a Wasm execution).
1592cb484dd2SNick Fitzgerald     #[inline]
exit_wasm(&mut self)159320544ac6SFrank Emrich     fn exit_wasm(&mut self) {
159420544ac6SFrank Emrich         unsafe {
159520544ac6SFrank Emrich             if let Some(limit) = self.stack_limit {
159620544ac6SFrank Emrich                 *(&*self.vm_store_context).stack_limit.get() = limit;
159720544ac6SFrank Emrich             }
159820544ac6SFrank Emrich 
15992d25f862SChris Fallin             *(*self.vm_store_context).last_wasm_exit_trampoline_fp.get() =
16002d25f862SChris Fallin                 self.last_wasm_exit_trampoline_fp;
160120544ac6SFrank Emrich             *(*self.vm_store_context).last_wasm_exit_pc.get() = self.last_wasm_exit_pc;
160220544ac6SFrank Emrich             *(*self.vm_store_context).last_wasm_entry_fp.get() = self.last_wasm_entry_fp;
1603192f2fcdSAlex Crichton             *(*self.vm_store_context).last_wasm_entry_sp.get() = self.last_wasm_entry_sp;
1604192f2fcdSAlex Crichton             *(*self.vm_store_context).last_wasm_entry_trap_handler.get() =
1605192f2fcdSAlex Crichton                 self.last_wasm_entry_trap_handler;
160663d482c8SFrank Emrich             *(*self.vm_store_context).stack_chain.get() = self.stack_chain.clone();
160720544ac6SFrank Emrich         }
160820544ac6SFrank Emrich     }
160920544ac6SFrank Emrich }
161020544ac6SFrank Emrich 
161120544ac6SFrank Emrich impl Drop for EntryStoreContext {
1612cb484dd2SNick Fitzgerald     #[inline]
drop(&mut self)161320544ac6SFrank Emrich     fn drop(&mut self) {
161420544ac6SFrank Emrich         self.exit_wasm();
1615d4242001SAdam Bratschi-Kaye     }
1616d4242001SAdam Bratschi-Kaye }
1617d4242001SAdam Bratschi-Kaye 
1618d4242001SAdam Bratschi-Kaye /// A trait implemented for types which can be returned from closures passed to
1619d4242001SAdam Bratschi-Kaye /// [`Func::wrap`] and friends.
1620d4242001SAdam Bratschi-Kaye ///
1621d4242001SAdam Bratschi-Kaye /// This trait should not be implemented by user types. This trait may change at
1622d4242001SAdam Bratschi-Kaye /// any time internally. The types which implement this trait, however, are
1623d4242001SAdam Bratschi-Kaye /// stable over time.
1624d4242001SAdam Bratschi-Kaye ///
1625d4242001SAdam Bratschi-Kaye /// For more information see [`Func::wrap`]
1626d4242001SAdam Bratschi-Kaye pub unsafe trait WasmRet {
1627d4242001SAdam Bratschi-Kaye     // Same as `WasmTy::compatible_with_store`.
1628d4242001SAdam Bratschi-Kaye     #[doc(hidden)]
compatible_with_store(&self, store: &StoreOpaque) -> bool1629d4242001SAdam Bratschi-Kaye     fn compatible_with_store(&self, store: &StoreOpaque) -> bool;
1630d4242001SAdam Bratschi-Kaye 
16311d11b265SAlex Crichton     /// Stores this return value into the `ptr` specified using the rooted
16321d11b265SAlex Crichton     /// `store`.
16331d11b265SAlex Crichton     ///
16341d11b265SAlex Crichton     /// Traps are communicated through the `Result<_>` return value.
16351d11b265SAlex Crichton     ///
16361d11b265SAlex Crichton     /// # Unsafety
16371d11b265SAlex Crichton     ///
16381d11b265SAlex Crichton     /// This method is unsafe as `ptr` must have the correct length to store
16391d11b265SAlex Crichton     /// this result. This property is only checked in debug mode, not in release
16401d11b265SAlex Crichton     /// mode.
1641d4242001SAdam Bratschi-Kaye     #[doc(hidden)]
store( self, store: &mut AutoAssertNoGc<'_>, ptr: &mut [MaybeUninit<ValRaw>], ) -> Result<()>16421d11b265SAlex Crichton     unsafe fn store(
1643d4242001SAdam Bratschi-Kaye         self,
1644bd2ea901SNick Fitzgerald         store: &mut AutoAssertNoGc<'_>,
16451d11b265SAlex Crichton         ptr: &mut [MaybeUninit<ValRaw>],
16461d11b265SAlex Crichton     ) -> Result<()>;
1647d4242001SAdam Bratschi-Kaye 
1648d4242001SAdam Bratschi-Kaye     #[doc(hidden)]
func_type( engine: &Engine, params: impl Iterator<Item = ValType>, ) -> Result<FuncType, OutOfMemory>1649c2112959SNick Fitzgerald     fn func_type(
1650c2112959SNick Fitzgerald         engine: &Engine,
1651c2112959SNick Fitzgerald         params: impl Iterator<Item = ValType>,
1652c2112959SNick Fitzgerald     ) -> Result<FuncType, OutOfMemory>;
16533e0f4b66SAlex Crichton     #[doc(hidden)]
may_gc() -> bool16543e0f4b66SAlex Crichton     fn may_gc() -> bool;
1655d4242001SAdam Bratschi-Kaye 
1656d4242001SAdam Bratschi-Kaye     // Utilities used to convert an instance of this type to a `Result`
1657d4242001SAdam Bratschi-Kaye     // explicitly, used when wrapping async functions which always bottom-out
1658d4242001SAdam Bratschi-Kaye     // in a function that returns a trap because futures can be cancelled.
1659d4242001SAdam Bratschi-Kaye     #[doc(hidden)]
16601d11b265SAlex Crichton     type Fallible: WasmRet;
1661d4242001SAdam Bratschi-Kaye     #[doc(hidden)]
into_fallible(self) -> Self::Fallible1662d4242001SAdam Bratschi-Kaye     fn into_fallible(self) -> Self::Fallible;
1663d4242001SAdam Bratschi-Kaye     #[doc(hidden)]
fallible_from_error(error: Error) -> Self::Fallible1664d4242001SAdam Bratschi-Kaye     fn fallible_from_error(error: Error) -> Self::Fallible;
1665d4242001SAdam Bratschi-Kaye }
1666d4242001SAdam Bratschi-Kaye 
1667d4242001SAdam Bratschi-Kaye unsafe impl<T> WasmRet for T
1668d4242001SAdam Bratschi-Kaye where
1669d4242001SAdam Bratschi-Kaye     T: WasmTy,
1670d4242001SAdam Bratschi-Kaye {
1671d4242001SAdam Bratschi-Kaye     type Fallible = Result<T>;
1672d4242001SAdam Bratschi-Kaye 
compatible_with_store(&self, store: &StoreOpaque) -> bool1673d4242001SAdam Bratschi-Kaye     fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
1674d4242001SAdam Bratschi-Kaye         <Self as WasmTy>::compatible_with_store(self, store)
1675d4242001SAdam Bratschi-Kaye     }
1676d4242001SAdam Bratschi-Kaye 
store( self, store: &mut AutoAssertNoGc<'_>, ptr: &mut [MaybeUninit<ValRaw>], ) -> Result<()>16771d11b265SAlex Crichton     unsafe fn store(
1678bd2ea901SNick Fitzgerald         self,
1679bd2ea901SNick Fitzgerald         store: &mut AutoAssertNoGc<'_>,
16801d11b265SAlex Crichton         ptr: &mut [MaybeUninit<ValRaw>],
16811d11b265SAlex Crichton     ) -> Result<()> {
16821d11b265SAlex Crichton         debug_assert!(ptr.len() > 0);
16830f457fadSAlex Crichton         // SAFETY: the contract of this function/trait combo is such that `ptr`
16840f457fadSAlex Crichton         // is valid to store this type's value, thus this lookup should be safe.
16850f457fadSAlex Crichton         unsafe { <Self as WasmTy>::store(self, store, ptr.get_unchecked_mut(0)) }
1686d4242001SAdam Bratschi-Kaye     }
1687d4242001SAdam Bratschi-Kaye 
may_gc() -> bool16883e0f4b66SAlex Crichton     fn may_gc() -> bool {
16893e0f4b66SAlex Crichton         T::may_gc()
16903e0f4b66SAlex Crichton     }
16913e0f4b66SAlex Crichton 
func_type( engine: &Engine, params: impl Iterator<Item = ValType>, ) -> Result<FuncType, OutOfMemory>1692c2112959SNick Fitzgerald     fn func_type(
1693c2112959SNick Fitzgerald         engine: &Engine,
1694c2112959SNick Fitzgerald         params: impl Iterator<Item = ValType>,
1695c2112959SNick Fitzgerald     ) -> Result<FuncType, OutOfMemory> {
1696c2112959SNick Fitzgerald         FuncType::try_new(engine, params, Some(<Self as WasmTy>::valtype()))
1697d4242001SAdam Bratschi-Kaye     }
1698d4242001SAdam Bratschi-Kaye 
into_fallible(self) -> Result<T>1699d4242001SAdam Bratschi-Kaye     fn into_fallible(self) -> Result<T> {
1700d4242001SAdam Bratschi-Kaye         Ok(self)
1701d4242001SAdam Bratschi-Kaye     }
1702d4242001SAdam Bratschi-Kaye 
fallible_from_error(error: Error) -> Result<T>1703d4242001SAdam Bratschi-Kaye     fn fallible_from_error(error: Error) -> Result<T> {
1704d4242001SAdam Bratschi-Kaye         Err(error)
1705d4242001SAdam Bratschi-Kaye     }
1706d4242001SAdam Bratschi-Kaye }
1707d4242001SAdam Bratschi-Kaye 
1708d4242001SAdam Bratschi-Kaye unsafe impl<T> WasmRet for Result<T>
1709d4242001SAdam Bratschi-Kaye where
1710d4242001SAdam Bratschi-Kaye     T: WasmRet,
1711d4242001SAdam Bratschi-Kaye {
1712d4242001SAdam Bratschi-Kaye     type Fallible = Self;
1713d4242001SAdam Bratschi-Kaye 
compatible_with_store(&self, store: &StoreOpaque) -> bool1714d4242001SAdam Bratschi-Kaye     fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
1715d4242001SAdam Bratschi-Kaye         match self {
1716d4242001SAdam Bratschi-Kaye             Ok(x) => <T as WasmRet>::compatible_with_store(x, store),
1717d4242001SAdam Bratschi-Kaye             Err(_) => true,
1718d4242001SAdam Bratschi-Kaye         }
1719d4242001SAdam Bratschi-Kaye     }
1720d4242001SAdam Bratschi-Kaye 
store( self, store: &mut AutoAssertNoGc<'_>, ptr: &mut [MaybeUninit<ValRaw>], ) -> Result<()>17211d11b265SAlex Crichton     unsafe fn store(
1722d4242001SAdam Bratschi-Kaye         self,
1723bd2ea901SNick Fitzgerald         store: &mut AutoAssertNoGc<'_>,
17241d11b265SAlex Crichton         ptr: &mut [MaybeUninit<ValRaw>],
17251d11b265SAlex Crichton     ) -> Result<()> {
17260f457fadSAlex Crichton         // SAFETY: the safety of calling this function is the same as calling
17270f457fadSAlex Crichton         // the inner `store`.
17280f457fadSAlex Crichton         unsafe { self.and_then(|val| val.store(store, ptr)) }
1729d4242001SAdam Bratschi-Kaye     }
1730d4242001SAdam Bratschi-Kaye 
may_gc() -> bool17313e0f4b66SAlex Crichton     fn may_gc() -> bool {
17323e0f4b66SAlex Crichton         T::may_gc()
17333e0f4b66SAlex Crichton     }
17343e0f4b66SAlex Crichton 
func_type( engine: &Engine, params: impl Iterator<Item = ValType>, ) -> Result<FuncType, OutOfMemory>1735c2112959SNick Fitzgerald     fn func_type(
1736c2112959SNick Fitzgerald         engine: &Engine,
1737c2112959SNick Fitzgerald         params: impl Iterator<Item = ValType>,
1738c2112959SNick Fitzgerald     ) -> Result<FuncType, OutOfMemory> {
17398652011fSNick Fitzgerald         T::func_type(engine, params)
1740d4242001SAdam Bratschi-Kaye     }
1741d4242001SAdam Bratschi-Kaye 
into_fallible(self) -> Result<T>1742d4242001SAdam Bratschi-Kaye     fn into_fallible(self) -> Result<T> {
1743d4242001SAdam Bratschi-Kaye         self
1744d4242001SAdam Bratschi-Kaye     }
1745d4242001SAdam Bratschi-Kaye 
fallible_from_error(error: Error) -> Result<T>1746d4242001SAdam Bratschi-Kaye     fn fallible_from_error(error: Error) -> Result<T> {
1747d4242001SAdam Bratschi-Kaye         Err(error)
1748d4242001SAdam Bratschi-Kaye     }
1749d4242001SAdam Bratschi-Kaye }
1750d4242001SAdam Bratschi-Kaye 
1751d4242001SAdam Bratschi-Kaye macro_rules! impl_wasm_host_results {
1752d4242001SAdam Bratschi-Kaye     ($n:tt $($t:ident)*) => (
1753838ed2d0SAlex Crichton         #[allow(non_snake_case, reason = "macro-generated code")]
1754d4242001SAdam Bratschi-Kaye         unsafe impl<$($t),*> WasmRet for ($($t,)*)
1755d4242001SAdam Bratschi-Kaye         where
1756d4242001SAdam Bratschi-Kaye             $($t: WasmTy,)*
1757d4242001SAdam Bratschi-Kaye         {
1758d4242001SAdam Bratschi-Kaye             type Fallible = Result<Self>;
1759d4242001SAdam Bratschi-Kaye 
1760d4242001SAdam Bratschi-Kaye             #[inline]
1761d4242001SAdam Bratschi-Kaye             fn compatible_with_store(&self, _store: &StoreOpaque) -> bool {
1762d4242001SAdam Bratschi-Kaye                 let ($($t,)*) = self;
1763d4242001SAdam Bratschi-Kaye                 $( $t.compatible_with_store(_store) && )* true
1764d4242001SAdam Bratschi-Kaye             }
1765d4242001SAdam Bratschi-Kaye 
1766d4242001SAdam Bratschi-Kaye             #[inline]
17671d11b265SAlex Crichton             unsafe fn store(
1768bd2ea901SNick Fitzgerald                 self,
1769bd2ea901SNick Fitzgerald                 _store: &mut AutoAssertNoGc<'_>,
17701d11b265SAlex Crichton                 _ptr: &mut [MaybeUninit<ValRaw>],
17711d11b265SAlex Crichton             ) -> Result<()> {
1772d4242001SAdam Bratschi-Kaye                 let ($($t,)*) = self;
17731d11b265SAlex Crichton                 let mut _cur = 0;
17741d11b265SAlex Crichton                 $(
17751d11b265SAlex Crichton                     debug_assert!(_cur < _ptr.len());
17760f457fadSAlex Crichton                     // SAFETY: `store`'s unsafe contract is that `_ptr` is
17770f457fadSAlex Crichton                     // appropriately sized and additionally safe to call `store`
17780f457fadSAlex Crichton                     // for sub-types.
17790f457fadSAlex Crichton                     unsafe {
17801d11b265SAlex Crichton                         let val = _ptr.get_unchecked_mut(_cur);
17811d11b265SAlex Crichton                         _cur += 1;
17821d11b265SAlex Crichton                         WasmTy::store($t, _store, val)?;
17830f457fadSAlex Crichton                     }
17841d11b265SAlex Crichton                 )*
17851d11b265SAlex Crichton                 Ok(())
1786d4242001SAdam Bratschi-Kaye             }
1787d4242001SAdam Bratschi-Kaye 
17883e0f4b66SAlex Crichton             #[doc(hidden)]
17893e0f4b66SAlex Crichton             fn may_gc() -> bool {
17903e0f4b66SAlex Crichton                 $( $t::may_gc() || )* false
17913e0f4b66SAlex Crichton             }
17923e0f4b66SAlex Crichton 
1793c2112959SNick Fitzgerald             fn func_type(
1794c2112959SNick Fitzgerald                 engine: &Engine,
1795c2112959SNick Fitzgerald                 params: impl Iterator<Item = ValType>,
1796c2112959SNick Fitzgerald             ) -> Result<FuncType, OutOfMemory> {
1797c2112959SNick Fitzgerald                 FuncType::try_new(
17988652011fSNick Fitzgerald                     engine,
1799d4242001SAdam Bratschi-Kaye                     params,
1800d4242001SAdam Bratschi-Kaye                     IntoIterator::into_iter([$($t::valtype(),)*]),
1801d4242001SAdam Bratschi-Kaye                 )
1802d4242001SAdam Bratschi-Kaye             }
1803d4242001SAdam Bratschi-Kaye 
1804d4242001SAdam Bratschi-Kaye             #[inline]
1805d4242001SAdam Bratschi-Kaye             fn into_fallible(self) -> Result<Self> {
1806d4242001SAdam Bratschi-Kaye                 Ok(self)
1807d4242001SAdam Bratschi-Kaye             }
1808d4242001SAdam Bratschi-Kaye 
1809d4242001SAdam Bratschi-Kaye             #[inline]
1810d4242001SAdam Bratschi-Kaye             fn fallible_from_error(error: Error) -> Result<Self> {
1811d4242001SAdam Bratschi-Kaye                 Err(error)
1812d4242001SAdam Bratschi-Kaye             }
1813d4242001SAdam Bratschi-Kaye         }
1814d4242001SAdam Bratschi-Kaye     )
1815d4242001SAdam Bratschi-Kaye }
1816d4242001SAdam Bratschi-Kaye 
1817d4242001SAdam Bratschi-Kaye for_each_function_signature!(impl_wasm_host_results);
1818d4242001SAdam Bratschi-Kaye 
1819d4242001SAdam Bratschi-Kaye /// Internal trait implemented for all arguments that can be passed to
1820d4242001SAdam Bratschi-Kaye /// [`Func::wrap`] and [`Linker::func_wrap`](crate::Linker::func_wrap).
1821d4242001SAdam Bratschi-Kaye ///
1822d4242001SAdam Bratschi-Kaye /// This trait should not be implemented by external users, it's only intended
1823d4242001SAdam Bratschi-Kaye /// as an implementation detail of this crate.
1824d4242001SAdam Bratschi-Kaye pub trait IntoFunc<T, Params, Results>: Send + Sync + 'static {
1825d4242001SAdam Bratschi-Kaye     /// Convert this function into a `VM{Array,Native}CallHostFuncContext` and
1826d4242001SAdam Bratschi-Kaye     /// internal `VMFuncRef`.
1827d4242001SAdam Bratschi-Kaye     #[doc(hidden)]
into_func(self, engine: &Engine) -> Result<HostFunc, OutOfMemory>1828c2112959SNick Fitzgerald     fn into_func(self, engine: &Engine) -> Result<HostFunc, OutOfMemory>;
1829d4242001SAdam Bratschi-Kaye }
1830d4242001SAdam Bratschi-Kaye 
183105fe6282SShane Snover macro_rules! impl_into_func {
183205fe6282SShane Snover     ($num:tt $arg:ident) => {
18338c349a3dSAlex Crichton         // Implement for functions without a leading `Caller` parameter,
183405fe6282SShane Snover         // delegating to the implementation below which does have the leading
183505fe6282SShane Snover         // `Caller` parameter.
1836838ed2d0SAlex Crichton         #[expect(non_snake_case, reason = "macro-generated code")]
183705fe6282SShane Snover         impl<T, F, $arg, R> IntoFunc<T, $arg, R> for F
183805fe6282SShane Snover         where
183905fe6282SShane Snover             F: Fn($arg) -> R + Send + Sync + 'static,
184005fe6282SShane Snover             $arg: WasmTy,
184105fe6282SShane Snover             R: WasmRet,
1842f81c0dc0SAlex Crichton             T: 'static,
184305fe6282SShane Snover         {
1844c2112959SNick Fitzgerald             fn into_func(self, engine: &Engine) -> Result<HostFunc, OutOfMemory> {
184505fe6282SShane Snover                 let f = move |_: Caller<'_, T>, $arg: $arg| {
184605fe6282SShane Snover                     self($arg)
184705fe6282SShane Snover                 };
184805fe6282SShane Snover 
184905fe6282SShane Snover                 f.into_func(engine)
185005fe6282SShane Snover             }
185105fe6282SShane Snover         }
185205fe6282SShane Snover 
1853838ed2d0SAlex Crichton         #[expect(non_snake_case, reason = "macro-generated code")]
185405fe6282SShane Snover         impl<T, F, $arg, R> IntoFunc<T, (Caller<'_, T>, $arg), R> for F
185505fe6282SShane Snover         where
185605fe6282SShane Snover             F: Fn(Caller<'_, T>, $arg) -> R + Send + Sync + 'static,
185705fe6282SShane Snover             $arg: WasmTy,
185805fe6282SShane Snover             R: WasmRet,
1859f81c0dc0SAlex Crichton             T: 'static,
186005fe6282SShane Snover         {
1861c2112959SNick Fitzgerald             fn into_func(self, engine: &Engine) -> Result<HostFunc, OutOfMemory> {
18628c349a3dSAlex Crichton                 HostFunc::wrap(engine, move |caller: Caller<'_, T>, ($arg,)| {
186305fe6282SShane Snover                     self(caller, $arg)
186405fe6282SShane Snover                 })
186505fe6282SShane Snover             }
186605fe6282SShane Snover         }
186705fe6282SShane Snover     };
186805fe6282SShane Snover     ($num:tt $($args:ident)*) => {
18698c349a3dSAlex Crichton         // Implement for functions without a leading `Caller` parameter,
187005fe6282SShane Snover         // delegating to the implementation below which does have the leading
187105fe6282SShane Snover         // `Caller` parameter.
1872838ed2d0SAlex Crichton         #[allow(non_snake_case, reason = "macro-generated code")]
187305fe6282SShane Snover         impl<T, F, $($args,)* R> IntoFunc<T, ($($args,)*), R> for F
187405fe6282SShane Snover         where
187505fe6282SShane Snover             F: Fn($($args),*) -> R + Send + Sync + 'static,
187605fe6282SShane Snover             $($args: WasmTy,)*
187705fe6282SShane Snover             R: WasmRet,
1878f81c0dc0SAlex Crichton             T: 'static,
187905fe6282SShane Snover         {
1880c2112959SNick Fitzgerald             fn into_func(self, engine: &Engine) -> Result<HostFunc, OutOfMemory> {
188105fe6282SShane Snover                 let f = move |_: Caller<'_, T>, $($args:$args),*| {
188205fe6282SShane Snover                     self($($args),*)
188305fe6282SShane Snover                 };
188405fe6282SShane Snover 
188505fe6282SShane Snover                 f.into_func(engine)
188605fe6282SShane Snover             }
188705fe6282SShane Snover         }
188805fe6282SShane Snover 
1889838ed2d0SAlex Crichton         #[allow(non_snake_case, reason = "macro-generated code")]
189005fe6282SShane Snover         impl<T, F, $($args,)* R> IntoFunc<T, (Caller<'_, T>, $($args,)*), R> for F
189105fe6282SShane Snover         where
189205fe6282SShane Snover             F: Fn(Caller<'_, T>, $($args),*) -> R + Send + Sync + 'static,
189305fe6282SShane Snover             $($args: WasmTy,)*
189405fe6282SShane Snover             R: WasmRet,
1895f81c0dc0SAlex Crichton             T: 'static,
189605fe6282SShane Snover         {
1897c2112959SNick Fitzgerald             fn into_func(self, engine: &Engine) -> Result<HostFunc, OutOfMemory> {
18988c349a3dSAlex Crichton                 HostFunc::wrap(engine, move |caller: Caller<'_, T>, ( $( $args ),* )| {
189905fe6282SShane Snover                     self(caller, $( $args ),* )
190005fe6282SShane Snover                 })
190105fe6282SShane Snover             }
190205fe6282SShane Snover         }
190305fe6282SShane Snover     }
190405fe6282SShane Snover }
190505fe6282SShane Snover 
190605fe6282SShane Snover for_each_function_signature!(impl_into_func);
190705fe6282SShane Snover 
190805fe6282SShane Snover /// Trait implemented for various tuples made up of types which implement
1909bc4582c3SAlex Crichton /// [`WasmTy`] that can be passed to [`Func::wrap_async`].
191005fe6282SShane Snover pub unsafe trait WasmTyList {
191105fe6282SShane Snover     /// Get the value type that each Type in the list represents.
valtypes() -> impl Iterator<Item = ValType>191205fe6282SShane Snover     fn valtypes() -> impl Iterator<Item = ValType>;
191305fe6282SShane Snover 
191405fe6282SShane Snover     // Load a version of `Self` from the `values` provided.
191505fe6282SShane Snover     //
191605fe6282SShane Snover     // # Safety
191705fe6282SShane Snover     //
191805fe6282SShane Snover     // This function is unsafe as it's up to the caller to ensure that `values` are
191905fe6282SShane Snover     // valid for this given type.
192005fe6282SShane Snover     #[doc(hidden)]
load(store: &mut AutoAssertNoGc<'_>, values: &mut [MaybeUninit<ValRaw>]) -> Self192105fe6282SShane Snover     unsafe fn load(store: &mut AutoAssertNoGc<'_>, values: &mut [MaybeUninit<ValRaw>]) -> Self;
19223e0f4b66SAlex Crichton 
19233e0f4b66SAlex Crichton     #[doc(hidden)]
may_gc() -> bool19243e0f4b66SAlex Crichton     fn may_gc() -> bool;
192505fe6282SShane Snover }
192605fe6282SShane Snover 
192705fe6282SShane Snover macro_rules! impl_wasm_ty_list {
192861feceb9SAlex Crichton     ($num:tt $($args:ident)*) => (
1929838ed2d0SAlex Crichton         #[allow(non_snake_case, reason = "macro-generated code")]
193005fe6282SShane Snover         unsafe impl<$($args),*> WasmTyList for ($($args,)*)
193105fe6282SShane Snover         where
193205fe6282SShane Snover             $($args: WasmTy,)*
193305fe6282SShane Snover         {
193405fe6282SShane Snover             fn valtypes() -> impl Iterator<Item = ValType> {
193505fe6282SShane Snover                 IntoIterator::into_iter([$($args::valtype(),)*])
193605fe6282SShane Snover             }
193705fe6282SShane Snover 
193805fe6282SShane Snover             unsafe fn load(_store: &mut AutoAssertNoGc<'_>, _values: &mut [MaybeUninit<ValRaw>]) -> Self {
193905fe6282SShane Snover                 let mut _cur = 0;
194005fe6282SShane Snover                 ($({
194105fe6282SShane Snover                     debug_assert!(_cur < _values.len());
19420f457fadSAlex Crichton                     // SAFETY: this function's own contract means that `_values`
19430f457fadSAlex Crichton                     // is appropriately sized/typed for the internal loads.
19440f457fadSAlex Crichton                     unsafe {
194505fe6282SShane Snover                         let ptr = _values.get_unchecked(_cur).assume_init_ref();
194605fe6282SShane Snover                         _cur += 1;
194705fe6282SShane Snover                         $args::load(_store, ptr)
19480f457fadSAlex Crichton                     }
194905fe6282SShane Snover                 },)*)
195005fe6282SShane Snover             }
19513e0f4b66SAlex Crichton 
19523e0f4b66SAlex Crichton             fn may_gc() -> bool {
19533e0f4b66SAlex Crichton                 $( $args::may_gc() || )* false
19543e0f4b66SAlex Crichton             }
195505fe6282SShane Snover         }
195661feceb9SAlex Crichton     );
195705fe6282SShane Snover }
195805fe6282SShane Snover 
195905fe6282SShane Snover for_each_function_signature!(impl_wasm_ty_list);
196005fe6282SShane Snover 
1961d4242001SAdam Bratschi-Kaye /// A structure representing the caller's context when creating a function
1962d4242001SAdam Bratschi-Kaye /// via [`Func::wrap`].
1963d4242001SAdam Bratschi-Kaye ///
1964d4242001SAdam Bratschi-Kaye /// This structure can be taken as the first parameter of a closure passed to
1965d4242001SAdam Bratschi-Kaye /// [`Func::wrap`] or other constructors, and serves two purposes:
1966d4242001SAdam Bratschi-Kaye ///
1967d4242001SAdam Bratschi-Kaye /// * First consumers can use [`Caller<'_, T>`](crate::Caller) to get access to
1968d4242001SAdam Bratschi-Kaye ///   [`StoreContextMut<'_, T>`](crate::StoreContextMut) and/or get access to
1969d4242001SAdam Bratschi-Kaye ///   `T` itself. This means that the [`Caller`] type can serve as a proxy to
1970d4242001SAdam Bratschi-Kaye ///   the original [`Store`](crate::Store) itself and is used to satisfy
1971d4242001SAdam Bratschi-Kaye ///   [`AsContext`] and [`AsContextMut`] bounds.
1972d4242001SAdam Bratschi-Kaye ///
1973d4242001SAdam Bratschi-Kaye /// * Second a [`Caller`] can be used as the name implies, learning about the
1974d4242001SAdam Bratschi-Kaye ///   caller's context, namely it's exported memory and exported functions. This
1975d4242001SAdam Bratschi-Kaye ///   allows functions which take pointers as arguments to easily read the
1976d4242001SAdam Bratschi-Kaye ///   memory the pointers point into, or if a function is expected to call
1977d4242001SAdam Bratschi-Kaye ///   malloc in the wasm module to reserve space for the output you can do that.
1978d4242001SAdam Bratschi-Kaye ///
1979d4242001SAdam Bratschi-Kaye /// Host functions which want access to [`Store`](crate::Store)-level state are
1980d4242001SAdam Bratschi-Kaye /// recommended to use this type.
1981f81c0dc0SAlex Crichton pub struct Caller<'a, T: 'static> {
1982d4242001SAdam Bratschi-Kaye     pub(crate) store: StoreContextMut<'a, T>,
1983e012eedaSAlex Crichton     caller: Instance,
1984d4242001SAdam Bratschi-Kaye }
1985d4242001SAdam Bratschi-Kaye 
1986d4242001SAdam Bratschi-Kaye impl<T> Caller<'_, T> {
sub_caller(&mut self) -> Caller<'_, T>1987d4242001SAdam Bratschi-Kaye     fn sub_caller(&mut self) -> Caller<'_, T> {
1988d4242001SAdam Bratschi-Kaye         Caller {
1989d4242001SAdam Bratschi-Kaye             store: self.store.as_context_mut(),
1990d4242001SAdam Bratschi-Kaye             caller: self.caller,
1991d4242001SAdam Bratschi-Kaye         }
1992d4242001SAdam Bratschi-Kaye     }
1993d4242001SAdam Bratschi-Kaye 
1994d4242001SAdam Bratschi-Kaye     /// Looks up an export from the caller's module by the `name` given.
1995d4242001SAdam Bratschi-Kaye     ///
1996d4242001SAdam Bratschi-Kaye     /// This is a low-level function that's typically used to implement passing
1997d4242001SAdam Bratschi-Kaye     /// of pointers or indices between core Wasm instances, where the callee
1998d4242001SAdam Bratschi-Kaye     /// needs to consult the caller's exports to perform memory management and
1999d4242001SAdam Bratschi-Kaye     /// resolve the references.
2000d4242001SAdam Bratschi-Kaye     ///
2001d4242001SAdam Bratschi-Kaye     /// For comparison, in components, the component model handles translating
2002d4242001SAdam Bratschi-Kaye     /// arguments from one component instance to another and managing memory, so
2003d4242001SAdam Bratschi-Kaye     /// that callees don't need to be aware of their callers, which promotes
2004d4242001SAdam Bratschi-Kaye     /// virtualizability of APIs.
2005d4242001SAdam Bratschi-Kaye     ///
2006d4242001SAdam Bratschi-Kaye     /// # Return
2007d4242001SAdam Bratschi-Kaye     ///
2008d4242001SAdam Bratschi-Kaye     /// If an export with the `name` provided was found, then it is returned as an
2009d4242001SAdam Bratschi-Kaye     /// `Extern`. There are a number of situations, however, where the export may not
2010d4242001SAdam Bratschi-Kaye     /// be available:
2011d4242001SAdam Bratschi-Kaye     ///
2012d4242001SAdam Bratschi-Kaye     /// * The caller instance may not have an export named `name`
2013d4242001SAdam Bratschi-Kaye     /// * There may not be a caller available, for example if `Func` was called
2014d4242001SAdam Bratschi-Kaye     ///   directly from host code.
2015d4242001SAdam Bratschi-Kaye     ///
2016d4242001SAdam Bratschi-Kaye     /// It's recommended to take care when calling this API and gracefully
2017d4242001SAdam Bratschi-Kaye     /// handling a `None` return value.
get_export(&mut self, name: &str) -> Option<Extern>2018d4242001SAdam Bratschi-Kaye     pub fn get_export(&mut self, name: &str) -> Option<Extern> {
2019d4242001SAdam Bratschi-Kaye         // All instances created have a `host_state` with a pointer pointing
2020d4242001SAdam Bratschi-Kaye         // back to themselves. If this caller doesn't have that `host_state`
2021d4242001SAdam Bratschi-Kaye         // then it probably means it was a host-created object like `Func::new`
2022d4242001SAdam Bratschi-Kaye         // which doesn't have any exports we want to return anyway.
2023e012eedaSAlex Crichton         self.caller.get_export(&mut self.store, name)
2024d4242001SAdam Bratschi-Kaye     }
2025d4242001SAdam Bratschi-Kaye 
2026f305ef52SRichard Pringle     /// Looks up an exported [`Extern`] value by a [`ModuleExport`] value.
2027f305ef52SRichard Pringle     ///
2028bc4582c3SAlex Crichton     /// This is similar to [`Self::get_export`] but uses a [`ModuleExport`]
2029bc4582c3SAlex Crichton     /// value to avoid string lookups where possible. [`ModuleExport`]s can be
2030bc4582c3SAlex Crichton     /// obtained by calling [`Module::get_export_index`] on the [`Module`] that
2031bc4582c3SAlex Crichton     /// an instance was instantiated with.
2032f305ef52SRichard Pringle     ///
2033f305ef52SRichard Pringle     /// This method will search the module for an export with a matching entity index and return
2034f305ef52SRichard Pringle     /// the value, if found.
2035f305ef52SRichard Pringle     ///
2036f305ef52SRichard Pringle     /// Returns `None` if there was no export with a matching entity index.
2037bc4582c3SAlex Crichton     ///
2038bc4582c3SAlex Crichton     /// [`Module::get_export_index`]: crate::Module::get_export_index
2039bc4582c3SAlex Crichton     /// [`Module`]: crate::Module
2040bc4582c3SAlex Crichton     ///
2041f305ef52SRichard Pringle     /// # Panics
2042f305ef52SRichard Pringle     ///
2043f305ef52SRichard Pringle     /// Panics if `store` does not own this instance.
2044f305ef52SRichard Pringle     ///
2045f305ef52SRichard Pringle     /// # Usage
2046f305ef52SRichard Pringle     /// ```
2047f305ef52SRichard Pringle     /// use std::str;
2048f305ef52SRichard Pringle     ///
2049f305ef52SRichard Pringle     /// # use wasmtime::*;
205096e19700SNick Fitzgerald     /// # fn main() -> Result<()> {
2051f305ef52SRichard Pringle     /// # let mut store = Store::default();
2052f305ef52SRichard Pringle     ///
2053f305ef52SRichard Pringle     /// let module = Module::new(
2054f305ef52SRichard Pringle     ///     store.engine(),
2055f305ef52SRichard Pringle     ///     r#"
2056f305ef52SRichard Pringle     ///         (module
2057f305ef52SRichard Pringle     ///             (import "" "" (func $log_str (param i32 i32)))
2058f305ef52SRichard Pringle     ///             (func (export "foo")
2059f305ef52SRichard Pringle     ///                 i32.const 4   ;; ptr
2060f305ef52SRichard Pringle     ///                 i32.const 13  ;; len
2061f305ef52SRichard Pringle     ///                 call $log_str)
2062f305ef52SRichard Pringle     ///             (memory (export "memory") 1)
2063f305ef52SRichard Pringle     ///             (data (i32.const 4) "Hello, world!"))
2064f305ef52SRichard Pringle     ///     "#,
2065f305ef52SRichard Pringle     /// )?;
2066f305ef52SRichard Pringle     ///
2067f305ef52SRichard Pringle     /// let Some(module_export) = module.get_export_index("memory") else {
206896e19700SNick Fitzgerald     ///    bail!("failed to find `memory` export in module");
2069f305ef52SRichard Pringle     /// };
2070f305ef52SRichard Pringle     ///
2071f305ef52SRichard Pringle     /// let log_str = Func::wrap(&mut store, move |mut caller: Caller<'_, ()>, ptr: i32, len: i32| {
2072f305ef52SRichard Pringle     ///     let mem = match caller.get_module_export(&module_export) {
2073f305ef52SRichard Pringle     ///         Some(Extern::Memory(mem)) => mem,
207496e19700SNick Fitzgerald     ///         _ => bail!("failed to find host memory"),
2075f305ef52SRichard Pringle     ///     };
2076f305ef52SRichard Pringle     ///     let data = mem.data(&caller)
2077f305ef52SRichard Pringle     ///         .get(ptr as u32 as usize..)
2078f305ef52SRichard Pringle     ///         .and_then(|arr| arr.get(..len as u32 as usize));
2079f305ef52SRichard Pringle     ///     let string = match data {
2080f305ef52SRichard Pringle     ///         Some(data) => match str::from_utf8(data) {
2081f305ef52SRichard Pringle     ///             Ok(s) => s,
208296e19700SNick Fitzgerald     ///             Err(_) => bail!("invalid utf-8"),
2083f305ef52SRichard Pringle     ///         },
208496e19700SNick Fitzgerald     ///         None => bail!("pointer/length out of bounds"),
2085f305ef52SRichard Pringle     ///     };
2086f305ef52SRichard Pringle     ///     assert_eq!(string, "Hello, world!");
2087f305ef52SRichard Pringle     ///     println!("{}", string);
2088f305ef52SRichard Pringle     ///     Ok(())
2089f305ef52SRichard Pringle     /// });
2090f305ef52SRichard Pringle     /// let instance = Instance::new(&mut store, &module, &[log_str.into()])?;
2091f305ef52SRichard Pringle     /// let foo = instance.get_typed_func::<(), ()>(&mut store, "foo")?;
2092f305ef52SRichard Pringle     /// foo.call(&mut store, ())?;
2093f305ef52SRichard Pringle     /// # Ok(())
2094f305ef52SRichard Pringle     /// # }
2095f305ef52SRichard Pringle     /// ```
get_module_export(&mut self, export: &ModuleExport) -> Option<Extern>2096f305ef52SRichard Pringle     pub fn get_module_export(&mut self, export: &ModuleExport) -> Option<Extern> {
2097e012eedaSAlex Crichton         self.caller.get_module_export(&mut self.store, export)
2098f305ef52SRichard Pringle     }
2099f305ef52SRichard Pringle 
2100d4242001SAdam Bratschi-Kaye     /// Access the underlying data owned by this `Store`.
2101d4242001SAdam Bratschi-Kaye     ///
2102d4242001SAdam Bratschi-Kaye     /// Same as [`Store::data`](crate::Store::data)
data(&self) -> &T2103d4242001SAdam Bratschi-Kaye     pub fn data(&self) -> &T {
2104d4242001SAdam Bratschi-Kaye         self.store.data()
2105d4242001SAdam Bratschi-Kaye     }
2106d4242001SAdam Bratschi-Kaye 
2107d4242001SAdam Bratschi-Kaye     /// Access the underlying data owned by this `Store`.
2108d4242001SAdam Bratschi-Kaye     ///
2109d4242001SAdam Bratschi-Kaye     /// Same as [`Store::data_mut`](crate::Store::data_mut)
data_mut(&mut self) -> &mut T2110d4242001SAdam Bratschi-Kaye     pub fn data_mut(&mut self) -> &mut T {
2111d4242001SAdam Bratschi-Kaye         self.store.data_mut()
2112d4242001SAdam Bratschi-Kaye     }
2113d4242001SAdam Bratschi-Kaye 
2114d4242001SAdam Bratschi-Kaye     /// Returns the underlying [`Engine`] this store is connected to.
engine(&self) -> &Engine2115d4242001SAdam Bratschi-Kaye     pub fn engine(&self) -> &Engine {
2116d4242001SAdam Bratschi-Kaye         self.store.engine()
2117d4242001SAdam Bratschi-Kaye     }
2118d4242001SAdam Bratschi-Kaye 
21190fa13013SNick Fitzgerald     /// Perform garbage collection.
2120d4242001SAdam Bratschi-Kaye     ///
2121d4242001SAdam Bratschi-Kaye     /// Same as [`Store::gc`](crate::Store::gc).
2122dd0364d3SNick Fitzgerald     #[cfg(feature = "gc")]
gc(&mut self, why: Option<&crate::GcHeapOutOfMemory<()>>) -> Result<()>2123cc8d04f4SAlex Crichton     pub fn gc(&mut self, why: Option<&crate::GcHeapOutOfMemory<()>>) -> Result<()> {
2124cc8d04f4SAlex Crichton         self.store.gc(why)
2125d4242001SAdam Bratschi-Kaye     }
2126d4242001SAdam Bratschi-Kaye 
21270fa13013SNick Fitzgerald     /// Perform garbage collection asynchronously.
21280fa13013SNick Fitzgerald     ///
21290fa13013SNick Fitzgerald     /// Same as [`Store::gc_async`](crate::Store::gc_async).
21300fa13013SNick Fitzgerald     #[cfg(all(feature = "async", feature = "gc"))]
gc_async(&mut self, why: Option<&crate::GcHeapOutOfMemory<()>>) where T: Send + 'static,21311a88c70aSAlex Crichton     pub async fn gc_async(&mut self, why: Option<&crate::GcHeapOutOfMemory<()>>)
21320fa13013SNick Fitzgerald     where
2133f81c0dc0SAlex Crichton         T: Send + 'static,
21340fa13013SNick Fitzgerald     {
21351a88c70aSAlex Crichton         self.store.gc_async(why).await;
21360fa13013SNick Fitzgerald     }
21370fa13013SNick Fitzgerald 
2138d4242001SAdam Bratschi-Kaye     /// Returns the remaining fuel in the store.
2139d4242001SAdam Bratschi-Kaye     ///
2140d4242001SAdam Bratschi-Kaye     /// For more information see [`Store::get_fuel`](crate::Store::get_fuel)
get_fuel(&self) -> Result<u64>2141d4242001SAdam Bratschi-Kaye     pub fn get_fuel(&self) -> Result<u64> {
2142d4242001SAdam Bratschi-Kaye         self.store.get_fuel()
2143d4242001SAdam Bratschi-Kaye     }
2144d4242001SAdam Bratschi-Kaye 
2145d4242001SAdam Bratschi-Kaye     /// Set the amount of fuel in this store to be consumed when executing wasm code.
2146d4242001SAdam Bratschi-Kaye     ///
2147d4242001SAdam Bratschi-Kaye     /// For more information see [`Store::set_fuel`](crate::Store::set_fuel)
set_fuel(&mut self, fuel: u64) -> Result<()>2148d4242001SAdam Bratschi-Kaye     pub fn set_fuel(&mut self, fuel: u64) -> Result<()> {
2149d4242001SAdam Bratschi-Kaye         self.store.set_fuel(fuel)
2150d4242001SAdam Bratschi-Kaye     }
2151d4242001SAdam Bratschi-Kaye 
2152d4242001SAdam Bratschi-Kaye     /// Configures this `Store` to yield while executing futures every N units of fuel.
2153d4242001SAdam Bratschi-Kaye     ///
2154d4242001SAdam Bratschi-Kaye     /// For more information see
2155d4242001SAdam Bratschi-Kaye     /// [`Store::fuel_async_yield_interval`](crate::Store::fuel_async_yield_interval)
2156cc8d04f4SAlex Crichton     #[cfg(feature = "async")]
fuel_async_yield_interval(&mut self, interval: Option<u64>) -> Result<()>2157d4242001SAdam Bratschi-Kaye     pub fn fuel_async_yield_interval(&mut self, interval: Option<u64>) -> Result<()> {
2158d4242001SAdam Bratschi-Kaye         self.store.fuel_async_yield_interval(interval)
2159d4242001SAdam Bratschi-Kaye     }
2160d4242001SAdam Bratschi-Kaye }
2161d4242001SAdam Bratschi-Kaye 
2162f81c0dc0SAlex Crichton impl<T: 'static> AsContext for Caller<'_, T> {
2163d4242001SAdam Bratschi-Kaye     type Data = T;
as_context(&self) -> StoreContext<'_, T>2164d4242001SAdam Bratschi-Kaye     fn as_context(&self) -> StoreContext<'_, T> {
2165d4242001SAdam Bratschi-Kaye         self.store.as_context()
2166d4242001SAdam Bratschi-Kaye     }
2167d4242001SAdam Bratschi-Kaye }
2168d4242001SAdam Bratschi-Kaye 
2169f81c0dc0SAlex Crichton impl<T: 'static> AsContextMut for Caller<'_, T> {
as_context_mut(&mut self) -> StoreContextMut<'_, T>2170d4242001SAdam Bratschi-Kaye     fn as_context_mut(&mut self) -> StoreContextMut<'_, T> {
2171d4242001SAdam Bratschi-Kaye         self.store.as_context_mut()
2172d4242001SAdam Bratschi-Kaye     }
2173d4242001SAdam Bratschi-Kaye }
2174d4242001SAdam Bratschi-Kaye 
217591bf5016SAlex Crichton impl<'a, T: 'static> From<Caller<'a, T>> for StoreContextMut<'a, T> {
from(caller: Caller<'a, T>) -> Self217691bf5016SAlex Crichton     fn from(caller: Caller<'a, T>) -> Self {
217791bf5016SAlex Crichton         caller.store
217891bf5016SAlex Crichton     }
217991bf5016SAlex Crichton }
218091bf5016SAlex Crichton 
2181d4242001SAdam Bratschi-Kaye /// Representation of a host-defined function.
2182d4242001SAdam Bratschi-Kaye ///
2183d4242001SAdam Bratschi-Kaye /// This is used for `Func::new` but also for `Linker`-defined functions. For
2184d4242001SAdam Bratschi-Kaye /// `Func::new` this is stored within a `Store`, and for `Linker`-defined
2185d4242001SAdam Bratschi-Kaye /// functions they wrap this up in `Arc` to enable shared ownership of this
2186d4242001SAdam Bratschi-Kaye /// across many stores.
2187d4242001SAdam Bratschi-Kaye ///
2188d4242001SAdam Bratschi-Kaye /// Technically this structure needs a `<T>` type parameter to connect to the
2189d4242001SAdam Bratschi-Kaye /// `Store<T>` itself, but that's an unsafe contract of using this for now
2190d4242001SAdam Bratschi-Kaye /// rather than part of the struct type (to avoid `Func<T>` in the API).
21918c349a3dSAlex Crichton #[doc(hidden)]
21928c349a3dSAlex Crichton pub struct HostFunc {
21938c349a3dSAlex Crichton     ctx: StoreBox<VMArrayCallHostFuncContext>,
2194d4242001SAdam Bratschi-Kaye 
2195cc8d04f4SAlex Crichton     /// Whether or not this function was defined with an `async` host function,
21962811ee83SMikhail Katychev     /// meaning that it is only invocable when wasm is itself on a fiber to
2197cc8d04f4SAlex Crichton     /// support suspension on `Poll::Pending`.
2198cc8d04f4SAlex Crichton     ///
2199cc8d04f4SAlex Crichton     /// This is used to propagate to an `InstancePre` and then eventually into a
2200cc8d04f4SAlex Crichton     /// `Store` as to whether the store requires async entrypoints.
2201cc8d04f4SAlex Crichton     asyncness: Asyncness,
2202cc8d04f4SAlex Crichton 
2203d4242001SAdam Bratschi-Kaye     // Stored to unregister this function's signature with the engine when this
2204d4242001SAdam Bratschi-Kaye     // is dropped.
2205d4242001SAdam Bratschi-Kaye     engine: Engine,
2206d4242001SAdam Bratschi-Kaye }
2207d4242001SAdam Bratschi-Kaye 
22088c349a3dSAlex Crichton // State stored inside a `VMArrayCallHostFuncContext`.
22098c349a3dSAlex Crichton struct HostFuncState<F> {
22108c349a3dSAlex Crichton     // The actual host function.
22118c349a3dSAlex Crichton     func: F,
22128c349a3dSAlex Crichton 
22138c349a3dSAlex Crichton     // NB: We have to keep our `VMSharedTypeIndex` registered in the engine for
22148c349a3dSAlex Crichton     // as long as this function exists.
22158c349a3dSAlex Crichton     _ty: RegisteredType,
22168c349a3dSAlex Crichton }
22178c349a3dSAlex Crichton 
2218cb235ecfSNick Fitzgerald impl core::fmt::Debug for HostFunc {
fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result2219cb235ecfSNick Fitzgerald     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2220cb235ecfSNick Fitzgerald         f.debug_struct("HostFunc").finish_non_exhaustive()
2221cb235ecfSNick Fitzgerald     }
2222cb235ecfSNick Fitzgerald }
2223cb235ecfSNick Fitzgerald 
2224d4242001SAdam Bratschi-Kaye impl HostFunc {
2225bc4582c3SAlex Crichton     /// Requires that the signature in `ctx` is already registered
2226bc4582c3SAlex Crichton     /// within `Engine`, which is done by [`Self::vmctx_sync`] and
2227bc4582c3SAlex Crichton     /// [`Self::vmctx_async`].
22288c349a3dSAlex Crichton     ///
22298c349a3dSAlex Crichton     /// This is an internal private constructor for this type intended to only
22308c349a3dSAlex Crichton     /// be used by other constructors of this type below.
new_raw( engine: &Engine, ctx: StoreBox<VMArrayCallHostFuncContext>, asyncness: Asyncness, ) -> Self2231cc8d04f4SAlex Crichton     fn new_raw(
2232cc8d04f4SAlex Crichton         engine: &Engine,
2233cc8d04f4SAlex Crichton         ctx: StoreBox<VMArrayCallHostFuncContext>,
2234cc8d04f4SAlex Crichton         asyncness: Asyncness,
2235cc8d04f4SAlex Crichton     ) -> Self {
22368c349a3dSAlex Crichton         HostFunc {
22378c349a3dSAlex Crichton             ctx,
22388c349a3dSAlex Crichton             engine: engine.clone(),
2239cc8d04f4SAlex Crichton             asyncness,
22408c349a3dSAlex Crichton         }
22418c349a3dSAlex Crichton     }
22428c349a3dSAlex Crichton 
22438c349a3dSAlex Crichton     /// Constructor of a host function's `VMContext` for synchronous functions.
22448c349a3dSAlex Crichton     ///
22458c349a3dSAlex Crichton     /// This creates a `VMArrayCallHostFuncContext` which under the hood will
22468c349a3dSAlex Crichton     /// be viewed as `VMContext` in the eventually created `VMFuncRef`.
vmctx_sync<F, T>( engine: &Engine, ty: FuncType, func: F, ) -> Result<StoreBox<VMArrayCallHostFuncContext>, OutOfMemory> where F: Fn(Caller<'_, T>, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync + 'static, T: 'static,22478c349a3dSAlex Crichton     fn vmctx_sync<F, T>(
22488c349a3dSAlex Crichton         engine: &Engine,
22498c349a3dSAlex Crichton         ty: FuncType,
22508c349a3dSAlex Crichton         func: F,
2251c2112959SNick Fitzgerald     ) -> Result<StoreBox<VMArrayCallHostFuncContext>, OutOfMemory>
22528c349a3dSAlex Crichton     where
22538c349a3dSAlex Crichton         F: Fn(Caller<'_, T>, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync + 'static,
22548c349a3dSAlex Crichton         T: 'static,
22558c349a3dSAlex Crichton     {
22568c349a3dSAlex Crichton         assert!(ty.comes_from_same_engine(engine));
22578c349a3dSAlex Crichton 
22588c349a3dSAlex Crichton         unsafe {
22598c349a3dSAlex Crichton             VMArrayCallHostFuncContext::new(
22608c349a3dSAlex Crichton                 Self::array_call_trampoline::<T, F>,
22618c349a3dSAlex Crichton                 ty.type_index(),
2262c2112959SNick Fitzgerald                 try_new::<Box<_>>(HostFuncState {
22638c349a3dSAlex Crichton                     func,
22648c349a3dSAlex Crichton                     _ty: ty.into_registered_type(),
2265c2112959SNick Fitzgerald                 })?,
22668c349a3dSAlex Crichton             )
22678c349a3dSAlex Crichton         }
22688c349a3dSAlex Crichton     }
22698c349a3dSAlex Crichton 
22708c349a3dSAlex Crichton     /// Constructor of a host function's `VMContext` for asynchronous functions.
22718c349a3dSAlex Crichton     ///
22728c349a3dSAlex Crichton     /// This creates a `VMArrayCallHostFuncContext` which under the hood will
22738c349a3dSAlex Crichton     /// be viewed as `VMContext` in the eventually created `VMFuncRef`.
22748c349a3dSAlex Crichton     ///
22758c349a3dSAlex Crichton     /// Note that `ctx: U` is forwarded directly to `func`. This is subtly
22768c349a3dSAlex Crichton     /// different than closing over data in `F` because the future returned by
22778c349a3dSAlex Crichton     /// `F` can't refer to any data it closes over. The purpose of `U` is to
22788c349a3dSAlex Crichton     /// enable the returned future to be able to close over data generally
22798c349a3dSAlex Crichton     /// captured in the closures generated here.
22808c349a3dSAlex Crichton     #[cfg(feature = "async")]
vmctx_async<F, T, U>( engine: &Engine, ty: FuncType, ctx: U, func: F, ) -> Result<StoreBox<VMArrayCallHostFuncContext>, OutOfMemory> where F: for<'a> Fn( Caller<'a, T>, &'a mut [MaybeUninit<ValRaw>], &'a U, ) -> Box<dyn Future<Output = Result<()>> + Send + 'a> + Send + Sync + 'static, T: 'static, U: Send + Sync + 'static,22818c349a3dSAlex Crichton     fn vmctx_async<F, T, U>(
22828c349a3dSAlex Crichton         engine: &Engine,
22838c349a3dSAlex Crichton         ty: FuncType,
22848c349a3dSAlex Crichton         ctx: U,
22858c349a3dSAlex Crichton         func: F,
2286c2112959SNick Fitzgerald     ) -> Result<StoreBox<VMArrayCallHostFuncContext>, OutOfMemory>
22878c349a3dSAlex Crichton     where
22888c349a3dSAlex Crichton         F: for<'a> Fn(
22898c349a3dSAlex Crichton                 Caller<'a, T>,
22908c349a3dSAlex Crichton                 &'a mut [MaybeUninit<ValRaw>],
22918c349a3dSAlex Crichton                 &'a U,
22928c349a3dSAlex Crichton             ) -> Box<dyn Future<Output = Result<()>> + Send + 'a>
22938c349a3dSAlex Crichton             + Send
22948c349a3dSAlex Crichton             + Sync
22958c349a3dSAlex Crichton             + 'static,
22968c349a3dSAlex Crichton         T: 'static,
22978c349a3dSAlex Crichton         U: Send + Sync + 'static,
22988c349a3dSAlex Crichton     {
22998c349a3dSAlex Crichton         // Eventually we want to remove `with_blocking` + `block_on` from
23008c349a3dSAlex Crichton         // Wasmtime. For now this is the attempt to keep it as low-level as
23018c349a3dSAlex Crichton         // possible.
23028c349a3dSAlex Crichton         //
23038c349a3dSAlex Crichton         // Generally it's a lie to run async things on top of sync things and
23048c349a3dSAlex Crichton         // it's caused many headaches. For now it's the best that can be done.
23058c349a3dSAlex Crichton         Self::vmctx_sync(engine, ty, move |Caller { store, caller }, args| {
23068c349a3dSAlex Crichton             store.with_blocking(|store, cx| {
23078c349a3dSAlex Crichton                 cx.block_on(core::pin::Pin::from(func(
23088c349a3dSAlex Crichton                     Caller { store, caller },
23098c349a3dSAlex Crichton                     args,
23108c349a3dSAlex Crichton                     &ctx,
23118c349a3dSAlex Crichton                 )))
23128c349a3dSAlex Crichton             })?
23138c349a3dSAlex Crichton         })
23148c349a3dSAlex Crichton     }
23158c349a3dSAlex Crichton 
23168c349a3dSAlex Crichton     /// Entrypoint of WebAssembly back into the host.
23178c349a3dSAlex Crichton     ///
23188c349a3dSAlex Crichton     /// This is the standard wasmtime "array call signature" which then
23198c349a3dSAlex Crichton     /// delegates internally to the host. This assumes that `callee_vmctx` is a
23208c349a3dSAlex Crichton     /// `VMArrayCallHostFuncContext` which was built above with
23218c349a3dSAlex Crichton     /// `HostFuncState<F>` internally. This internal function is then used to
23228c349a3dSAlex Crichton     /// dispatch based on the arguments.
23238c349a3dSAlex Crichton     ///
23248c349a3dSAlex Crichton     /// Details handled by this wrapper are:
23258c349a3dSAlex Crichton     ///
23268c349a3dSAlex Crichton     /// * Host panics are handled (`enter_host_from_wasm`)
23278c349a3dSAlex Crichton     /// * `F` is loaded from `callee_vmctx`
23288c349a3dSAlex Crichton     /// * `Caller` is constructed to pass to `F`
23298c349a3dSAlex Crichton     /// * A GC LIFO scope is maintained around the execution of `F`.
23308c349a3dSAlex Crichton     /// * Call hooks for entering/leaving the host are maintained.
array_call_trampoline<T, F>( callee_vmctx: NonNull<VMOpaqueContext>, caller_vmctx: NonNull<VMContext>, args: NonNull<ValRaw>, args_len: usize, ) -> bool where F: Fn(Caller<'_, T>, &mut [MaybeUninit<ValRaw>]) -> Result<()> + 'static, T: 'static,23318c349a3dSAlex Crichton     unsafe extern "C" fn array_call_trampoline<T, F>(
23328c349a3dSAlex Crichton         callee_vmctx: NonNull<VMOpaqueContext>,
23338c349a3dSAlex Crichton         caller_vmctx: NonNull<VMContext>,
23348c349a3dSAlex Crichton         args: NonNull<ValRaw>,
23358c349a3dSAlex Crichton         args_len: usize,
23368c349a3dSAlex Crichton     ) -> bool
23378c349a3dSAlex Crichton     where
23388c349a3dSAlex Crichton         F: Fn(Caller<'_, T>, &mut [MaybeUninit<ValRaw>]) -> Result<()> + 'static,
23398c349a3dSAlex Crichton         T: 'static,
23408c349a3dSAlex Crichton     {
23418c349a3dSAlex Crichton         let run = |store: &mut dyn crate::vm::VMStore, instance: InstanceId| {
23428c349a3dSAlex Crichton             // SAFETY: correct usage of this trampoline requires correct
23438c349a3dSAlex Crichton             // ascription of `T`, so it's the caller's responsibility to line
23448c349a3dSAlex Crichton             // this up.
23458c349a3dSAlex Crichton             let mut store = unsafe { store.unchecked_context_mut() };
23468c349a3dSAlex Crichton 
23478c349a3dSAlex Crichton             // Handle the entry call hook, with a corresponding exit call hook
23488c349a3dSAlex Crichton             // below.
23498c349a3dSAlex Crichton             store.0.call_hook(CallHook::CallingHost)?;
23508c349a3dSAlex Crichton 
23518c349a3dSAlex Crichton             // SAFETY: this function itself requires that the `vmctx` is
23528c349a3dSAlex Crichton             // valid to use here.
23538c349a3dSAlex Crichton             let state = unsafe {
23548c349a3dSAlex Crichton                 let vmctx = VMArrayCallHostFuncContext::from_opaque(callee_vmctx);
23558c349a3dSAlex Crichton                 vmctx.as_ref().host_state()
23568c349a3dSAlex Crichton             };
23578c349a3dSAlex Crichton 
23588c349a3dSAlex Crichton             // Double-check ourselves in debug mode, but we control the
23598c349a3dSAlex Crichton             // `Any` here so an unsafe downcast should also work.
23608c349a3dSAlex Crichton             //
23618c349a3dSAlex Crichton             // SAFETY: this function is only usable with `F`.
23628c349a3dSAlex Crichton             let state = unsafe {
23638c349a3dSAlex Crichton                 debug_assert!(state.is::<HostFuncState<F>>());
23648c349a3dSAlex Crichton                 &*(state as *const _ as *const HostFuncState<F>)
23658c349a3dSAlex Crichton             };
23668c349a3dSAlex Crichton 
23678c349a3dSAlex Crichton             let (gc_lifo_scope, ret) = {
23688c349a3dSAlex Crichton                 let gc_lifo_scope = store.0.gc_roots().enter_lifo_scope();
23698c349a3dSAlex Crichton 
23708c349a3dSAlex Crichton                 let mut args = NonNull::slice_from_raw_parts(args.cast(), args_len);
23718c349a3dSAlex Crichton                 // SAFETY: it's a contract of this function itself that the values
23728c349a3dSAlex Crichton                 // provided are valid to view as a slice.
23738c349a3dSAlex Crichton                 let args = unsafe { args.as_mut() };
23748c349a3dSAlex Crichton 
23758c349a3dSAlex Crichton                 let ret = (state.func)(
23768c349a3dSAlex Crichton                     Caller {
23778c349a3dSAlex Crichton                         caller: Instance::from_wasmtime(instance, store.0),
23788c349a3dSAlex Crichton                         store: store.as_context_mut(),
23798c349a3dSAlex Crichton                     },
23808c349a3dSAlex Crichton                     args,
23818c349a3dSAlex Crichton                 );
23828c349a3dSAlex Crichton 
23838c349a3dSAlex Crichton                 (gc_lifo_scope, ret)
23848c349a3dSAlex Crichton             };
23858c349a3dSAlex Crichton 
23868c349a3dSAlex Crichton             store.0.exit_gc_lifo_scope(gc_lifo_scope);
23878c349a3dSAlex Crichton 
23888c349a3dSAlex Crichton             // Note that if this returns a trap then `ret` is discarded
23898c349a3dSAlex Crichton             // entirely.
23908c349a3dSAlex Crichton             store.0.call_hook(CallHook::ReturningFromHost)?;
23918c349a3dSAlex Crichton 
23928c349a3dSAlex Crichton             ret
23938c349a3dSAlex Crichton         };
23948c349a3dSAlex Crichton 
23958c349a3dSAlex Crichton         // SAFETY: this is an entrypoint of wasm which requires correct type
23968c349a3dSAlex Crichton         // ascription of `T` itself, meaning that this should be safe to call
23978c349a3dSAlex Crichton         // both `enter_host_from_wasm` as well as `unchecked_context_mut`.
23988c349a3dSAlex Crichton         unsafe { vm::Instance::enter_host_from_wasm(caller_vmctx, run) }
23998c349a3dSAlex Crichton     }
24008c349a3dSAlex Crichton     /// Analog of [`Func::new_unchecked`]
24018c349a3dSAlex Crichton     ///
24028c349a3dSAlex Crichton     /// # Panics
24038c349a3dSAlex Crichton     ///
24048c349a3dSAlex Crichton     /// Panics if the given function type is not associated with the given
24058c349a3dSAlex Crichton     /// engine.
24068c349a3dSAlex Crichton     ///
24078c349a3dSAlex Crichton     /// # Safety
24088c349a3dSAlex Crichton     ///
24098c349a3dSAlex Crichton     /// The `func` provided must operate according to the `ty` provided to
24108c349a3dSAlex Crichton     /// ensure it's reading the correctly-typed parameters and writing the
24118c349a3dSAlex Crichton     /// correctly-typed results.
new_unchecked<T>( engine: &Engine, ty: FuncType, func: impl Fn(Caller<'_, T>, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync + 'static, ) -> Result<Self, OutOfMemory> where T: 'static,24128c349a3dSAlex Crichton     pub unsafe fn new_unchecked<T>(
24138c349a3dSAlex Crichton         engine: &Engine,
24148c349a3dSAlex Crichton         ty: FuncType,
24158c349a3dSAlex Crichton         func: impl Fn(Caller<'_, T>, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync + 'static,
2416c2112959SNick Fitzgerald     ) -> Result<Self, OutOfMemory>
24178c349a3dSAlex Crichton     where
24188c349a3dSAlex Crichton         T: 'static,
24198c349a3dSAlex Crichton     {
2420c2112959SNick Fitzgerald         Ok(HostFunc::new_raw(
2421c2112959SNick Fitzgerald             engine,
2422c2112959SNick Fitzgerald             Self::vmctx_sync(engine, ty, func)?,
2423c2112959SNick Fitzgerald             Asyncness::No,
2424c2112959SNick Fitzgerald         ))
24258c349a3dSAlex Crichton     }
24268c349a3dSAlex Crichton 
2427d4242001SAdam Bratschi-Kaye     /// Analog of [`Func::new`]
2428ff93bce0SNick Fitzgerald     ///
2429ff93bce0SNick Fitzgerald     /// # Panics
2430ff93bce0SNick Fitzgerald     ///
2431ff93bce0SNick Fitzgerald     /// Panics if the given function type is not associated with the given
2432ff93bce0SNick Fitzgerald     /// engine.
new<T>( engine: &Engine, ty: FuncType, func: impl Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()> + Send + Sync + 'static, ) -> Result<Self, OutOfMemory> where T: 'static,2433d4242001SAdam Bratschi-Kaye     pub fn new<T>(
2434d4242001SAdam Bratschi-Kaye         engine: &Engine,
2435d4242001SAdam Bratschi-Kaye         ty: FuncType,
2436d4242001SAdam Bratschi-Kaye         func: impl Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()> + Send + Sync + 'static,
2437c2112959SNick Fitzgerald     ) -> Result<Self, OutOfMemory>
2438f81c0dc0SAlex Crichton     where
2439f81c0dc0SAlex Crichton         T: 'static,
2440f81c0dc0SAlex Crichton     {
24418c349a3dSAlex Crichton         // NB: this is "duplicated" below in `new_async`, so try to keep the
24428c349a3dSAlex Crichton         // two in sync.
2443c2112959SNick Fitzgerald         Ok(HostFunc::new_raw(
24448c349a3dSAlex Crichton             engine,
24458c349a3dSAlex Crichton             Self::vmctx_sync(engine, ty.clone(), move |mut caller, values| {
24468c349a3dSAlex Crichton                 // SAFETY: Wasmtime in general provides the guarantee that
24478c349a3dSAlex Crichton                 // `values` matches `ty`, so this should be safe.
24488c349a3dSAlex Crichton                 let mut vec = unsafe { Self::load_untyped_params(caller.store.0, &ty, values) };
24498c349a3dSAlex Crichton                 let (params, results) = vec.split_at_mut(ty.params().len());
24508c349a3dSAlex Crichton                 func(caller.sub_caller(), params, results)?;
24518c349a3dSAlex Crichton                 Self::store_untyped_results(caller.store, &ty, vec, values)
2452c2112959SNick Fitzgerald             })?,
2453cc8d04f4SAlex Crichton             Asyncness::No,
2454c2112959SNick Fitzgerald         ))
2455d4242001SAdam Bratschi-Kaye     }
2456d4242001SAdam Bratschi-Kaye 
245791bf5016SAlex Crichton     /// Analog of [`Func::new_async`]
245891bf5016SAlex Crichton     ///
245991bf5016SAlex Crichton     /// # Panics
246091bf5016SAlex Crichton     ///
246191bf5016SAlex Crichton     /// Panics if the given function type is not associated with the given
246291bf5016SAlex Crichton     /// engine.
246391bf5016SAlex Crichton     #[cfg(feature = "async")]
new_async<T, F>(engine: &Engine, ty: FuncType, func: F) -> Result<Self, OutOfMemory> where F: for<'a> Fn( Caller<'a, T>, &'a [Val], &'a mut [Val], ) -> Box<dyn Future<Output = Result<()>> + Send + 'a> + Send + Sync + 'static, T: Send + 'static,2464c2112959SNick Fitzgerald     pub fn new_async<T, F>(engine: &Engine, ty: FuncType, func: F) -> Result<Self, OutOfMemory>
246591bf5016SAlex Crichton     where
246691bf5016SAlex Crichton         F: for<'a> Fn(
246791bf5016SAlex Crichton                 Caller<'a, T>,
246891bf5016SAlex Crichton                 &'a [Val],
246991bf5016SAlex Crichton                 &'a mut [Val],
247091bf5016SAlex Crichton             ) -> Box<dyn Future<Output = Result<()>> + Send + 'a>
247191bf5016SAlex Crichton             + Send
247291bf5016SAlex Crichton             + Sync
247391bf5016SAlex Crichton             + 'static,
24748c349a3dSAlex Crichton         T: Send + 'static,
247591bf5016SAlex Crichton     {
24768c349a3dSAlex Crichton         // NB: this is "duplicated" above in `new`, so try to keep the two in
24778c349a3dSAlex Crichton         // sync.
2478c2112959SNick Fitzgerald         Ok(HostFunc::new_raw(
247991bf5016SAlex Crichton             engine,
24808c349a3dSAlex Crichton             Self::vmctx_async(
24818c349a3dSAlex Crichton                 engine,
24828c349a3dSAlex Crichton                 ty.clone(),
24838c349a3dSAlex Crichton                 (ty, func),
24848c349a3dSAlex Crichton                 move |mut caller, values, (ty, func)| {
24858c349a3dSAlex Crichton                     Box::new(async move {
24868c349a3dSAlex Crichton                         // SAFETY: Wasmtime in general provides the guarantee that
24878c349a3dSAlex Crichton                         // `values` matches `ty`, so this should be safe.
24888c349a3dSAlex Crichton                         let mut vec =
24898c349a3dSAlex Crichton                             unsafe { Self::load_untyped_params(caller.store.0, &ty, values) };
24908c349a3dSAlex Crichton                         let (params, results) = vec.split_at_mut(ty.params().len());
24918c349a3dSAlex Crichton                         core::pin::Pin::from(func(caller.sub_caller(), params, results)).await?;
24928c349a3dSAlex Crichton                         Self::store_untyped_results(caller.store, &ty, vec, values)
24938c349a3dSAlex Crichton                     })
249491bf5016SAlex Crichton                 },
2495c2112959SNick Fitzgerald             )?,
2496cc8d04f4SAlex Crichton             Asyncness::Yes,
2497c2112959SNick Fitzgerald         ))
249891bf5016SAlex Crichton     }
249991bf5016SAlex Crichton 
25008c349a3dSAlex Crichton     /// Loads the the parameters of `ty` from `params` into a vector.
2501ff93bce0SNick Fitzgerald     ///
25028c349a3dSAlex Crichton     /// This additionally pushes space onto the vector for all results to split
25038c349a3dSAlex Crichton     /// the vector into params/results halves.
25040f457fadSAlex Crichton     ///
25050f457fadSAlex Crichton     /// # Safety
25060f457fadSAlex Crichton     ///
25078c349a3dSAlex Crichton     /// Requires that `params` matches the parameters loaded by `P`.
load_untyped_params( store: &mut StoreOpaque, ty: &FuncType, params: &mut [MaybeUninit<ValRaw>], ) -> Vec<Val>25088c349a3dSAlex Crichton     unsafe fn load_untyped_params(
25098c349a3dSAlex Crichton         store: &mut StoreOpaque,
25108c349a3dSAlex Crichton         ty: &FuncType,
25118c349a3dSAlex Crichton         params: &mut [MaybeUninit<ValRaw>],
25128c349a3dSAlex Crichton     ) -> Vec<Val> {
25138c349a3dSAlex Crichton         let mut val_vec = store.take_hostcall_val_storage();
25148c349a3dSAlex Crichton         debug_assert!(val_vec.is_empty());
25158c349a3dSAlex Crichton         let nparams = ty.params().len();
25168c349a3dSAlex Crichton         val_vec.reserve(nparams + ty.results().len());
25178c349a3dSAlex Crichton         let mut store = AutoAssertNoGc::new(store);
25188c349a3dSAlex Crichton         for (i, ty) in ty.params().enumerate() {
25198c349a3dSAlex Crichton             val_vec.push(unsafe { Val::_from_raw(&mut store, params[i].assume_init(), &ty) })
25208c349a3dSAlex Crichton         }
25218c349a3dSAlex Crichton 
25228c349a3dSAlex Crichton         val_vec.extend((0..ty.results().len()).map(|_| Val::null_func_ref()));
25238c349a3dSAlex Crichton         val_vec
25248c349a3dSAlex Crichton     }
25258c349a3dSAlex Crichton 
25268c349a3dSAlex Crichton     /// Stores the results, at the end of `args_then_results` according to `ty`,
25278c349a3dSAlex Crichton     /// into `storage`.
store_untyped_results<T>( mut store: StoreContextMut<'_, T>, ty: &FuncType, mut args_then_results: Vec<Val>, storage: &mut [MaybeUninit<ValRaw>], ) -> Result<()>25288c349a3dSAlex Crichton     fn store_untyped_results<T>(
25298c349a3dSAlex Crichton         mut store: StoreContextMut<'_, T>,
25308c349a3dSAlex Crichton         ty: &FuncType,
25318c349a3dSAlex Crichton         mut args_then_results: Vec<Val>,
25328c349a3dSAlex Crichton         storage: &mut [MaybeUninit<ValRaw>],
25338c349a3dSAlex Crichton     ) -> Result<()> {
25348c349a3dSAlex Crichton         // Unlike our arguments we need to dynamically check that the return
25358c349a3dSAlex Crichton         // values produced are correct. There could be a bug in `func` that
25368c349a3dSAlex Crichton         // produces the wrong number, wrong types, or wrong stores of
25378c349a3dSAlex Crichton         // values, and we need to catch that here.
25388c349a3dSAlex Crichton         let results = &args_then_results[ty.params().len()..];
25398c349a3dSAlex Crichton         for (i, (ret, ty)) in results.iter().zip(ty.results()).enumerate() {
25408c349a3dSAlex Crichton             ret.ensure_matches_ty(store.0, &ty)
25418c349a3dSAlex Crichton                 .context("function attempted to return an incompatible value")?;
25428c349a3dSAlex Crichton             storage[i].write(ret.to_raw(store.as_context_mut())?);
25438c349a3dSAlex Crichton         }
25448c349a3dSAlex Crichton 
25458c349a3dSAlex Crichton         // Restore our `val_vec` back into the store so it's usable for the next
25468c349a3dSAlex Crichton         // hostcall to reuse our own storage.
25478c349a3dSAlex Crichton         args_then_results.truncate(0);
25488c349a3dSAlex Crichton         store.0.save_hostcall_val_storage(args_then_results);
25498c349a3dSAlex Crichton         Ok(())
2550d4242001SAdam Bratschi-Kaye     }
2551d4242001SAdam Bratschi-Kaye 
2552d4242001SAdam Bratschi-Kaye     /// Analog of [`Func::wrap`]
wrap<T, F, P, R>(engine: &Engine, func: F) -> Result<Self, OutOfMemory> where F: Fn(Caller<'_, T>, P) -> R + Send + Sync + 'static, P: WasmTyList, R: WasmRet, T: 'static,2553c2112959SNick Fitzgerald     pub fn wrap<T, F, P, R>(engine: &Engine, func: F) -> Result<Self, OutOfMemory>
2554f81c0dc0SAlex Crichton     where
25558c349a3dSAlex Crichton         F: Fn(Caller<'_, T>, P) -> R + Send + Sync + 'static,
25568c349a3dSAlex Crichton         P: WasmTyList,
25578c349a3dSAlex Crichton         R: WasmRet,
2558f81c0dc0SAlex Crichton         T: 'static,
2559f81c0dc0SAlex Crichton     {
25608c349a3dSAlex Crichton         // NB: this entire function is "duplicated" below in `wrap_async`, so
25618c349a3dSAlex Crichton         // try to keep the two in sync.
2562c2112959SNick Fitzgerald         let ty = R::func_type(engine, None::<ValType>.into_iter().chain(P::valtypes()))?;
25638c349a3dSAlex Crichton 
25648c349a3dSAlex Crichton         let ctx = Self::vmctx_sync(engine, ty, move |mut caller, args| {
25658c349a3dSAlex Crichton             // SAFETY: `args` matching `ty` is provided by `HostFunc` and
25668c349a3dSAlex Crichton             // wasmtime's ambient correctness.
25678c349a3dSAlex Crichton             let params = unsafe { Self::load_typed_params(caller.store.0, args) };
25688c349a3dSAlex Crichton             let ret = func(caller.sub_caller(), params).into_fallible();
25698c349a3dSAlex Crichton             // SAFETY: `args` matching `ty` is provided by `HostFunc` and
25708c349a3dSAlex Crichton             // wasmtime's ambient correctness.
25718c349a3dSAlex Crichton             unsafe { Self::store_typed_results(caller.store.0, ret, args) }
2572c2112959SNick Fitzgerald         })?;
2573c2112959SNick Fitzgerald         Ok(HostFunc::new_raw(engine, ctx, Asyncness::No))
2574d4242001SAdam Bratschi-Kaye     }
2575d4242001SAdam Bratschi-Kaye 
257691bf5016SAlex Crichton     /// Analog of [`Func::wrap_async`]
257791bf5016SAlex Crichton     #[cfg(feature = "async")]
wrap_async<T, F, P, R>(engine: &Engine, func: F) -> Result<Self, OutOfMemory> where F: for<'a> Fn(Caller<'a, T>, P) -> Box<dyn Future<Output = R> + Send + 'a> + Send + Sync + 'static, P: WasmTyList, R: WasmRet, T: Send + 'static,2578c2112959SNick Fitzgerald     pub fn wrap_async<T, F, P, R>(engine: &Engine, func: F) -> Result<Self, OutOfMemory>
257991bf5016SAlex Crichton     where
258091bf5016SAlex Crichton         F: for<'a> Fn(Caller<'a, T>, P) -> Box<dyn Future<Output = R> + Send + 'a>
258191bf5016SAlex Crichton             + Send
258291bf5016SAlex Crichton             + Sync
258391bf5016SAlex Crichton             + 'static,
258491bf5016SAlex Crichton         P: WasmTyList,
258591bf5016SAlex Crichton         R: WasmRet,
25868c349a3dSAlex Crichton         T: Send + 'static,
258791bf5016SAlex Crichton     {
25888c349a3dSAlex Crichton         // NB: this entire function is "duplicated" above in `wrap`, so try to
25898c349a3dSAlex Crichton         // keep the two in sync.
2590c2112959SNick Fitzgerald         let ty = R::func_type(engine, None::<ValType>.into_iter().chain(P::valtypes()))?;
25918c349a3dSAlex Crichton 
25928c349a3dSAlex Crichton         let ctx = Self::vmctx_async(engine, ty, func, move |mut caller, args, func| {
25938c349a3dSAlex Crichton             Box::new(async move {
25948c349a3dSAlex Crichton                 // SAFETY: `args` matching `ty` is provided by `HostFunc` and
25958c349a3dSAlex Crichton                 // wasmtime's ambient correctness.
25968c349a3dSAlex Crichton                 let params = unsafe { Self::load_typed_params(caller.store.0, args) };
25978c349a3dSAlex Crichton                 let ret = core::pin::Pin::from(func(caller.sub_caller(), params)).await;
25988c349a3dSAlex Crichton                 // SAFETY: `args` matching `ty` is provided by `HostFunc` and
25998c349a3dSAlex Crichton                 // wasmtime's ambient correctness.
26008c349a3dSAlex Crichton                 unsafe { Self::store_typed_results(caller.store.0, ret.into_fallible(), args) }
26018c349a3dSAlex Crichton             })
2602c2112959SNick Fitzgerald         })?;
2603c2112959SNick Fitzgerald         Ok(HostFunc::new_raw(engine, ctx, Asyncness::Yes))
260491bf5016SAlex Crichton     }
260591bf5016SAlex Crichton 
26068c349a3dSAlex Crichton     /// Loads the typed parameters from `params`
26078c349a3dSAlex Crichton     ///
26088c349a3dSAlex Crichton     /// # Safety
26098c349a3dSAlex Crichton     ///
26108c349a3dSAlex Crichton     /// Requires that `params` matches the parameters loaded by `P`.
load_typed_params<P>(store: &mut StoreOpaque, params: &mut [MaybeUninit<ValRaw>]) -> P where P: WasmTyList,26118c349a3dSAlex Crichton     unsafe fn load_typed_params<P>(store: &mut StoreOpaque, params: &mut [MaybeUninit<ValRaw>]) -> P
26128c349a3dSAlex Crichton     where
26138c349a3dSAlex Crichton         P: WasmTyList,
26148c349a3dSAlex Crichton     {
26158c349a3dSAlex Crichton         let mut store = if P::may_gc() {
26168c349a3dSAlex Crichton             AutoAssertNoGc::new(store)
26178c349a3dSAlex Crichton         } else {
26188c349a3dSAlex Crichton             unsafe { AutoAssertNoGc::disabled(store) }
26198c349a3dSAlex Crichton         };
26208c349a3dSAlex Crichton         // SAFETY: this function's own safety contract is the same as `P::load`.
26218c349a3dSAlex Crichton         unsafe { P::load(&mut store, params) }
2622d4242001SAdam Bratschi-Kaye     }
26238c349a3dSAlex Crichton 
26248c349a3dSAlex Crichton     /// Stores the results of `R` into the array provided.
26258c349a3dSAlex Crichton     ///
26268c349a3dSAlex Crichton     /// # Safety
26278c349a3dSAlex Crichton     ///
26288c349a3dSAlex Crichton     /// Requires that `ret` matches the result `storage` space. See `WasmRet`
26298c349a3dSAlex Crichton     /// for more safety info.
store_typed_results<R>( store: &mut StoreOpaque, ret: R, storage: &mut [MaybeUninit<ValRaw>], ) -> Result<()> where R: WasmRet,26308c349a3dSAlex Crichton     unsafe fn store_typed_results<R>(
26318c349a3dSAlex Crichton         store: &mut StoreOpaque,
26328c349a3dSAlex Crichton         ret: R,
26338c349a3dSAlex Crichton         storage: &mut [MaybeUninit<ValRaw>],
26348c349a3dSAlex Crichton     ) -> Result<()>
26358c349a3dSAlex Crichton     where
26368c349a3dSAlex Crichton         R: WasmRet,
26378c349a3dSAlex Crichton     {
26388c349a3dSAlex Crichton         ensure!(
26398c349a3dSAlex Crichton             ret.compatible_with_store(store),
26408c349a3dSAlex Crichton             "host function attempted to return cross-`Store` value to Wasm",
26418c349a3dSAlex Crichton         );
26428c349a3dSAlex Crichton 
26438c349a3dSAlex Crichton         let mut store = if R::may_gc() {
26448c349a3dSAlex Crichton             AutoAssertNoGc::new(store)
26458c349a3dSAlex Crichton         } else {
26468c349a3dSAlex Crichton             unsafe { AutoAssertNoGc::disabled(store) }
26478c349a3dSAlex Crichton         };
26488c349a3dSAlex Crichton         // SAFETY: this safety contract is the same as this own function's
26498c349a3dSAlex Crichton         // safety contract.
26508c349a3dSAlex Crichton         unsafe {
26518c349a3dSAlex Crichton             ret.store(&mut store, storage)?;
26528c349a3dSAlex Crichton         }
26538c349a3dSAlex Crichton         Ok(())
2654d4242001SAdam Bratschi-Kaye     }
2655d4242001SAdam Bratschi-Kaye 
2656d4242001SAdam Bratschi-Kaye     /// Inserts this `HostFunc` into a `Store`, returning the `Func` pointing to
2657d4242001SAdam Bratschi-Kaye     /// it.
2658d4242001SAdam Bratschi-Kaye     ///
2659d4242001SAdam Bratschi-Kaye     /// # Unsafety
2660d4242001SAdam Bratschi-Kaye     ///
2661d4242001SAdam Bratschi-Kaye     /// Can only be inserted into stores with a matching `T` relative to when
2662d4242001SAdam Bratschi-Kaye     /// this `HostFunc` was first created.
to_func(self: &Arc<Self>, store: &mut StoreOpaque) -> Result<Func, OutOfMemory>266366ef086dSNick Fitzgerald     pub unsafe fn to_func(self: &Arc<Self>, store: &mut StoreOpaque) -> Result<Func, OutOfMemory> {
2664d4242001SAdam Bratschi-Kaye         self.validate_store(store);
26654fcfe17aSAlex Crichton         let (funcrefs, modules) = store.func_refs_and_modules();
266666ef086dSNick Fitzgerald         let funcref = funcrefs.push_arc_host(self.clone(), modules)?;
26670f457fadSAlex Crichton         // SAFETY: this funcref was just pushed within the store, so it's safe
26680f457fadSAlex Crichton         // to say this store owns it.
266966ef086dSNick Fitzgerald         Ok(unsafe { Func::from_vm_func_ref(store.id(), funcref) })
2670d4242001SAdam Bratschi-Kaye     }
2671d4242001SAdam Bratschi-Kaye 
2672d4242001SAdam Bratschi-Kaye     /// Inserts this `HostFunc` into a `Store`, returning the `Func` pointing to
2673d4242001SAdam Bratschi-Kaye     /// it.
2674d4242001SAdam Bratschi-Kaye     ///
2675d4242001SAdam Bratschi-Kaye     /// This function is similar to, but not equivalent, to `HostFunc::to_func`.
2676d4242001SAdam Bratschi-Kaye     /// Notably this function requires that the `Arc<Self>` pointer is otherwise
2677d4242001SAdam Bratschi-Kaye     /// rooted within the `StoreOpaque` via another means. When in doubt use
2678d4242001SAdam Bratschi-Kaye     /// `to_func` above as it's safer.
2679d4242001SAdam Bratschi-Kaye     ///
2680d4242001SAdam Bratschi-Kaye     /// # Unsafety
2681d4242001SAdam Bratschi-Kaye     ///
2682d4242001SAdam Bratschi-Kaye     /// Can only be inserted into stores with a matching `T` relative to when
2683d4242001SAdam Bratschi-Kaye     /// this `HostFunc` was first created.
2684d4242001SAdam Bratschi-Kaye     ///
2685d4242001SAdam Bratschi-Kaye     /// Additionally the `&Arc<Self>` is not cloned in this function. Instead a
2686d4242001SAdam Bratschi-Kaye     /// raw pointer to `Self` is stored within the `Store` for this function.
2687d4242001SAdam Bratschi-Kaye     /// The caller must arrange for the `Arc<Self>` to be "rooted" in the store
2688d4242001SAdam Bratschi-Kaye     /// provided via another means, probably by pushing to
2689d4242001SAdam Bratschi-Kaye     /// `StoreOpaque::rooted_host_funcs`.
2690d4242001SAdam Bratschi-Kaye     ///
2691d4242001SAdam Bratschi-Kaye     /// Similarly, the caller must arrange for `rooted_func_ref` to be rooted in
26920f457fadSAlex Crichton     /// the same store and additionally be a valid pointer.
to_func_store_rooted( self: &Arc<Self>, store: &mut StoreOpaque, rooted_func_ref: Option<NonNull<VMFuncRef>>, ) -> Func2693d4242001SAdam Bratschi-Kaye     pub unsafe fn to_func_store_rooted(
2694d4242001SAdam Bratschi-Kaye         self: &Arc<Self>,
2695d4242001SAdam Bratschi-Kaye         store: &mut StoreOpaque,
2696d4242001SAdam Bratschi-Kaye         rooted_func_ref: Option<NonNull<VMFuncRef>>,
2697d4242001SAdam Bratschi-Kaye     ) -> Func {
2698d4242001SAdam Bratschi-Kaye         self.validate_store(store);
2699d4242001SAdam Bratschi-Kaye 
27004fcfe17aSAlex Crichton         match rooted_func_ref {
27014fcfe17aSAlex Crichton             Some(funcref) => {
27020f457fadSAlex Crichton                 // SAFETY: it's a contract of this function itself that
27030f457fadSAlex Crichton                 // `funcref` is safe to read.
27040f457fadSAlex Crichton                 unsafe {
27054fcfe17aSAlex Crichton                     debug_assert!(funcref.as_ref().wasm_call.is_some());
27060f457fadSAlex Crichton                 }
27070f457fadSAlex Crichton                 // SAFETY: it's a contract of this function that `funcref` is
27080f457fadSAlex Crichton                 // owned by `store`.
27090f457fadSAlex Crichton                 unsafe { Func::from_vm_func_ref(store.id(), funcref) }
2710d4242001SAdam Bratschi-Kaye             }
27114fcfe17aSAlex Crichton             None => {
27124fcfe17aSAlex Crichton                 debug_assert!(self.func_ref().wasm_call.is_some());
27130f457fadSAlex Crichton 
27140f457fadSAlex Crichton                 // SAFETY: it's an unsafe contract of this function that we are
27150f457fadSAlex Crichton                 // rooted within the store to say that the store owns a copy of
27160f457fadSAlex Crichton                 // this funcref.
27170f457fadSAlex Crichton                 unsafe { Func::from_vm_func_ref(store.id(), self.func_ref().into()) }
27184fcfe17aSAlex Crichton             }
27194fcfe17aSAlex Crichton         }
2720d4242001SAdam Bratschi-Kaye     }
2721d4242001SAdam Bratschi-Kaye 
2722d4242001SAdam Bratschi-Kaye     /// Same as [`HostFunc::to_func`], different ownership.
into_func(self, store: &mut StoreOpaque) -> Result<Func, OutOfMemory>272366ef086dSNick Fitzgerald     unsafe fn into_func(self, store: &mut StoreOpaque) -> Result<Func, OutOfMemory> {
2724d4242001SAdam Bratschi-Kaye         self.validate_store(store);
2725cc8d04f4SAlex Crichton 
2726cc8d04f4SAlex Crichton         // This function could be called by a guest at any time, and it requires
2727cc8d04f4SAlex Crichton         // fibers, so the store now required async entrypoints.
2728cc8d04f4SAlex Crichton         store.set_async_required(self.asyncness);
2729cc8d04f4SAlex Crichton 
27304fcfe17aSAlex Crichton         let (funcrefs, modules) = store.func_refs_and_modules();
2731d2dee5ddSNick Fitzgerald         let funcref = funcrefs.push_box_host(try_new::<Box<_>>(self)?, modules)?;
27320f457fadSAlex Crichton         // SAFETY: this funcref was just pushed within `store`, so it's safe to
27330f457fadSAlex Crichton         // say it's owned by the store's id.
273466ef086dSNick Fitzgerald         Ok(unsafe { Func::from_vm_func_ref(store.id(), funcref) })
2735d4242001SAdam Bratschi-Kaye     }
2736d4242001SAdam Bratschi-Kaye 
validate_store(&self, store: &mut StoreOpaque)2737d4242001SAdam Bratschi-Kaye     fn validate_store(&self, store: &mut StoreOpaque) {
2738d4242001SAdam Bratschi-Kaye         // This assert is required to ensure that we can indeed safely insert
2739d4242001SAdam Bratschi-Kaye         // `self` into the `store` provided, otherwise the type information we
2740d4242001SAdam Bratschi-Kaye         // have listed won't be correct. This is possible to hit with the public
2741d4242001SAdam Bratschi-Kaye         // API of Wasmtime, and should be documented in relevant functions.
2742d4242001SAdam Bratschi-Kaye         assert!(
2743d4242001SAdam Bratschi-Kaye             Engine::same(&self.engine, store.engine()),
2744d4242001SAdam Bratschi-Kaye             "cannot use a store with a different engine than a linker was created with",
2745d4242001SAdam Bratschi-Kaye         );
2746d4242001SAdam Bratschi-Kaye     }
2747d4242001SAdam Bratschi-Kaye 
sig_index(&self) -> VMSharedTypeIndex2748d4242001SAdam Bratschi-Kaye     pub(crate) fn sig_index(&self) -> VMSharedTypeIndex {
2749d4242001SAdam Bratschi-Kaye         self.func_ref().type_index
2750d4242001SAdam Bratschi-Kaye     }
2751d4242001SAdam Bratschi-Kaye 
func_ref(&self) -> &VMFuncRef2752d4242001SAdam Bratschi-Kaye     pub(crate) fn func_ref(&self) -> &VMFuncRef {
27538c349a3dSAlex Crichton         unsafe { self.ctx.get().as_ref().func_ref() }
2754d4242001SAdam Bratschi-Kaye     }
2755cc8d04f4SAlex Crichton 
asyncness(&self) -> Asyncness2756cc8d04f4SAlex Crichton     pub(crate) fn asyncness(&self) -> Asyncness {
2757cc8d04f4SAlex Crichton         self.asyncness
2758cc8d04f4SAlex Crichton     }
2759d4242001SAdam Bratschi-Kaye }
2760d4242001SAdam Bratschi-Kaye 
2761d4242001SAdam Bratschi-Kaye #[cfg(test)]
2762d4242001SAdam Bratschi-Kaye mod tests {
2763d4242001SAdam Bratschi-Kaye     use super::*;
27644fcfe17aSAlex Crichton     use crate::{Module, Store};
2765d4242001SAdam Bratschi-Kaye 
2766d4242001SAdam Bratschi-Kaye     #[test]
2767909cb23cSAlex Crichton     #[cfg_attr(miri, ignore)]
hash_key_is_stable_across_duplicate_store_data_entries() -> Result<()>2768d4242001SAdam Bratschi-Kaye     fn hash_key_is_stable_across_duplicate_store_data_entries() -> Result<()> {
2769d4242001SAdam Bratschi-Kaye         let mut store = Store::<()>::default();
2770d4242001SAdam Bratschi-Kaye         let module = Module::new(
2771d4242001SAdam Bratschi-Kaye             store.engine(),
2772d4242001SAdam Bratschi-Kaye             r#"
2773d4242001SAdam Bratschi-Kaye                 (module
2774d4242001SAdam Bratschi-Kaye                     (func (export "f")
2775d4242001SAdam Bratschi-Kaye                         nop
2776d4242001SAdam Bratschi-Kaye                     )
2777d4242001SAdam Bratschi-Kaye                 )
2778d4242001SAdam Bratschi-Kaye             "#,
2779d4242001SAdam Bratschi-Kaye         )?;
2780d4242001SAdam Bratschi-Kaye         let instance = Instance::new(&mut store, &module, &[])?;
2781d4242001SAdam Bratschi-Kaye 
2782d4242001SAdam Bratschi-Kaye         // Each time we `get_func`, we call `Func::from_wasmtime` which adds a
2783d4242001SAdam Bratschi-Kaye         // new entry to `StoreData`, so `f1` and `f2` will have different
2784d4242001SAdam Bratschi-Kaye         // indices into `StoreData`.
2785d4242001SAdam Bratschi-Kaye         let f1 = instance.get_func(&mut store, "f").unwrap();
2786d4242001SAdam Bratschi-Kaye         let f2 = instance.get_func(&mut store, "f").unwrap();
2787d4242001SAdam Bratschi-Kaye 
2788d4242001SAdam Bratschi-Kaye         // But their hash keys are the same.
2789d4242001SAdam Bratschi-Kaye         assert!(
2790d4242001SAdam Bratschi-Kaye             f1.hash_key(&mut store.as_context_mut().0)
2791d4242001SAdam Bratschi-Kaye                 == f2.hash_key(&mut store.as_context_mut().0)
2792d4242001SAdam Bratschi-Kaye         );
2793d4242001SAdam Bratschi-Kaye 
2794d4242001SAdam Bratschi-Kaye         // But the hash keys are different from different funcs.
2795d4242001SAdam Bratschi-Kaye         let instance2 = Instance::new(&mut store, &module, &[])?;
2796d4242001SAdam Bratschi-Kaye         let f3 = instance2.get_func(&mut store, "f").unwrap();
2797d4242001SAdam Bratschi-Kaye         assert!(
2798d4242001SAdam Bratschi-Kaye             f1.hash_key(&mut store.as_context_mut().0)
2799d4242001SAdam Bratschi-Kaye                 != f3.hash_key(&mut store.as_context_mut().0)
2800d4242001SAdam Bratschi-Kaye         );
2801d4242001SAdam Bratschi-Kaye 
2802d4242001SAdam Bratschi-Kaye         Ok(())
2803d4242001SAdam Bratschi-Kaye     }
2804d4242001SAdam Bratschi-Kaye }
2805