wasmi_c_api/
func.rs

1use crate::{
2    wasm_extern_t,
3    wasm_functype_t,
4    wasm_store_t,
5    wasm_trap_t,
6    wasm_val_t,
7    wasm_val_vec_t,
8};
9use alloc::{boxed::Box, string::String, vec, vec::Vec};
10use core::{any::Any, ffi::c_void, hint, iter, ptr, str};
11use wasmi::{Error, Extern, Func, Ref, Val};
12
13#[cfg(feature = "std")]
14use core::panic::AssertUnwindSafe;
15
16/// A Wasm function.
17///
18/// Wraps [`Func`].
19#[derive(Clone)]
20#[repr(transparent)]
21pub struct wasm_func_t {
22    inner: wasm_extern_t,
23}
24
25wasmi_c_api_macros::declare_ref!(wasm_func_t);
26
27/// A Wasm host function callback.
28pub type wasm_func_callback_t = extern "C" fn(
29    params: *const wasm_val_vec_t,
30    results: *mut wasm_val_vec_t,
31) -> Option<Box<wasm_trap_t>>;
32
33/// A Wasm host function callback with access to environmental data.
34pub type wasm_func_callback_with_env_t = extern "C" fn(
35    env: *mut c_void,
36    params: *const wasm_val_vec_t,
37    results: *mut wasm_val_vec_t,
38) -> Option<Box<wasm_trap_t>>;
39
40impl wasm_func_t {
41    pub(crate) fn try_from(e: &wasm_extern_t) -> Option<&wasm_func_t> {
42        match &e.which {
43            Extern::Func(_) => Some(unsafe { &*(e as *const _ as *const _) }),
44            _ => None,
45        }
46    }
47
48    pub(crate) fn try_from_mut(e: &mut wasm_extern_t) -> Option<&mut wasm_func_t> {
49        match &mut e.which {
50            Extern::Func(_) => Some(unsafe { &mut *(e as *mut _ as *mut _) }),
51            _ => None,
52        }
53    }
54
55    /// Returns the underlying [`Func`] of the [`wasm_func_t`].
56    pub(crate) fn func(&self) -> Func {
57        match self.inner.which {
58            Extern::Func(f) => f,
59            _ => unsafe { hint::unreachable_unchecked() },
60        }
61    }
62}
63
64/// Creates a [`wasm_func_t`] from the [`wasm_functype_t`] and C-like closure for the [`wasm_store_t`].
65///
66/// # Note
67///
68/// This is a convenience method that internally creates a trampoline Rust-like closure around
69/// that C-like closure to propagate the Wasm function call and do all marshalling that is required.
70///
71/// # Safety
72///
73/// It is the caller's responsibility not to alias the [`wasm_functype_t`]
74/// with its underlying, internal [`WasmStoreRef`](crate::WasmStoreRef).
75unsafe fn create_function(
76    store: &mut wasm_store_t,
77    ty: &wasm_functype_t,
78    func: impl Fn(*const wasm_val_vec_t, *mut wasm_val_vec_t) -> Option<Box<wasm_trap_t>>
79        + Send
80        + Sync
81        + 'static,
82) -> Box<wasm_func_t> {
83    let ty = ty.ty().ty.clone();
84    let func = Func::new(
85        store.inner.context_mut(),
86        ty,
87        move |_caller, params, results| {
88            let params: wasm_val_vec_t = params
89                .iter()
90                .cloned()
91                .map(wasm_val_t::from)
92                .collect::<Box<[_]>>()
93                .into();
94            let mut out_results: wasm_val_vec_t = vec![wasm_val_t::default(); results.len()].into();
95            if let Some(trap) = func(&params, &mut out_results) {
96                return Err(trap.error);
97            }
98            results
99                .iter_mut()
100                .zip(out_results.as_slice())
101                .for_each(|(result, out_results)| {
102                    *result = out_results.to_val();
103                });
104            Ok(())
105        },
106    );
107    Box::new(wasm_func_t {
108        inner: wasm_extern_t {
109            store: store.inner.clone(),
110            which: func.into(),
111        },
112    })
113}
114
115/// Creates a new [`wasm_func_t`] of type [`wasm_functype_t`] for the [`wasm_store_t`].
116///
117/// Calls the given [`wasm_func_callback_t`] when calling the returned [`wasm_func_t`].
118///
119/// Wraps [`Func::new`].
120///
121/// # Safety
122///
123/// It is the caller's responsibility not to alias the [`wasm_functype_t`]
124/// with its underlying, internal [`WasmStoreRef`](crate::WasmStoreRef).
125#[cfg_attr(not(feature = "prefix-symbols"), no_mangle)]
126#[cfg_attr(feature = "prefix-symbols", wasmi_c_api_macros::prefix_symbol)]
127pub unsafe extern "C" fn wasm_func_new(
128    store: &mut wasm_store_t,
129    ty: &wasm_functype_t,
130    callback: wasm_func_callback_t,
131) -> Box<wasm_func_t> {
132    #[allow(clippy::redundant_closure)] // TODO: remove once the `clippy` false-positive is fixed
133    create_function(store, ty, move |params, results| callback(params, results))
134}
135
136/// Creates a new [`wasm_func_t`] of type [`wasm_functype_t`] for the [`wasm_store_t`].
137///
138/// - Calls the given [`wasm_func_callback_t`] when calling the returned [`wasm_func_t`].
139/// - Unlike [`wasm_func_new`] this also allows to access environment data in the function closure.
140///
141/// Wraps [`Func::new`].
142///
143/// # Safety
144///
145/// It is the caller's responsibility not to alias the [`wasm_functype_t`]
146/// with its underlying, internal [`WasmStoreRef`](crate::WasmStoreRef).
147#[cfg_attr(not(feature = "prefix-symbols"), no_mangle)]
148#[cfg_attr(feature = "prefix-symbols", wasmi_c_api_macros::prefix_symbol)]
149pub unsafe extern "C" fn wasm_func_new_with_env(
150    store: &mut wasm_store_t,
151    ty: &wasm_functype_t,
152    callback: wasm_func_callback_with_env_t,
153    data: *mut c_void,
154    finalizer: Option<extern "C" fn(arg1: *mut c_void)>,
155) -> Box<wasm_func_t> {
156    let finalizer = crate::ForeignData { data, finalizer };
157    create_function(store, ty, move |params, results| {
158        let _ = &finalizer; // move entire finalizer into this closure
159        callback(finalizer.data, params, results)
160    })
161}
162
163/// Prepares `dst` to be populated with `params` and reserve space for `len_results`.
164///
165/// The parameters and results are returned as separate slices.
166fn prepare_params_and_results(
167    dst: &mut Vec<Val>,
168    params: impl ExactSizeIterator<Item = Val>,
169    len_results: usize,
170) -> (&[Val], &mut [Val]) {
171    debug_assert!(dst.is_empty());
172    let len_params = params.len();
173    dst.reserve(len_params + len_results);
174    dst.extend(params);
175    dst.extend(iter::repeat_n(Val::FuncRef(<Ref<Func>>::Null), len_results));
176    let (params, results) = dst.split_at_mut(len_params);
177    (params, results)
178}
179
180/// Calls the [`wasm_func_t`] with the given `params` and stores the result in `results`.
181///
182/// - Returns a [`wasm_trap_t`] if the Wasm function call failed or trapped.
183/// - Returns a `null` pointer if the Wasm function call succeeded.
184///
185/// Wraps [`Func::call`].
186///
187/// # Safety
188///
189/// It is the caller's responsibility not to alias the [`wasm_func_t`]
190/// with its underlying, internal [`WasmStoreRef`](crate::WasmStoreRef).
191#[cfg_attr(not(feature = "prefix-symbols"), no_mangle)]
192#[cfg_attr(feature = "prefix-symbols", wasmi_c_api_macros::prefix_symbol)]
193pub unsafe extern "C" fn wasm_func_call(
194    func: &mut wasm_func_t,
195    params: *const wasm_val_vec_t,
196    results: *mut wasm_val_vec_t,
197) -> *mut wasm_trap_t {
198    let f = func.func();
199    let results = (*results).as_uninit_slice();
200    let params = (*params).as_slice();
201    let mut dst = Vec::new();
202    let (wt_params, wt_results) =
203        prepare_params_and_results(&mut dst, params.iter().map(|i| i.to_val()), results.len());
204
205    let result = {
206        #[cfg(feature = "std")]
207        {
208            // We're calling arbitrary code here most of the time, and we in general
209            // want to try to insulate callers against bugs in wasmtime/wasi/etc if we
210            // can. As a result we catch panics here and transform them to traps to
211            // allow the caller to have any insulation possible against Rust panics.
212            std::panic::catch_unwind(AssertUnwindSafe(|| {
213                f.call(func.inner.store.context_mut(), wt_params, wt_results)
214            }))
215        }
216        #[cfg(not(feature = "std"))]
217        {
218            Ok(f.call(func.inner.store.context_mut(), wt_params, wt_results))
219        }
220    };
221    match result {
222        Ok(Ok(())) => {
223            for (slot, val) in results.iter_mut().zip(wt_results.iter().cloned()) {
224                crate::initialize(slot, wasm_val_t::from(val));
225            }
226            ptr::null_mut()
227        }
228        Ok(Err(err)) => Box::into_raw(Box::new(wasm_trap_t::new(err))),
229        Err(panic) => {
230            let err = error_from_panic(panic);
231            let trap = Box::new(wasm_trap_t::new(err));
232            Box::into_raw(trap)
233        }
234    }
235}
236
237/// Converts the panic data to a Wasmi [`Error`] as a best-effort basis.
238fn error_from_panic(panic: Box<dyn Any + Send>) -> Error {
239    if let Some(msg) = panic.downcast_ref::<String>() {
240        Error::new(msg.clone())
241    } else if let Some(msg) = panic.downcast_ref::<&'static str>() {
242        Error::new(*msg)
243    } else {
244        Error::new("panic happened on the Rust side")
245    }
246}
247
248/// Returns the [`wasm_functype_t`] of the [`wasm_func_t`].
249///
250/// Wraps [`Func::ty`].
251///
252/// # Safety
253///
254/// It is the caller's responsibility not to alias the [`wasm_func_t`]
255/// with its underlying, internal [`WasmStoreRef`](crate::WasmStoreRef).
256#[cfg_attr(not(feature = "prefix-symbols"), no_mangle)]
257#[cfg_attr(feature = "prefix-symbols", wasmi_c_api_macros::prefix_symbol)]
258pub unsafe extern "C" fn wasm_func_type(f: &wasm_func_t) -> Box<wasm_functype_t> {
259    Box::new(wasm_functype_t::new(f.func().ty(f.inner.store.context())))
260}
261
262/// Returns the number of parameter types of the [`wasm_func_t`].
263///
264/// Wraps [`Func::ty`], followed by [`FuncType::params`] and a call to `len`.
265///
266/// # Safety
267///
268/// It is the caller's responsibility not to alias the [`wasm_func_t`]
269/// with its underlying, internal [`WasmStoreRef`](crate::WasmStoreRef).
270///
271/// [`FuncType::params`]: wasmi::FuncType::params
272#[cfg_attr(not(feature = "prefix-symbols"), no_mangle)]
273#[cfg_attr(feature = "prefix-symbols", wasmi_c_api_macros::prefix_symbol)]
274pub unsafe extern "C" fn wasm_func_param_arity(f: &wasm_func_t) -> usize {
275    f.func().ty(f.inner.store.context()).params().len()
276}
277
278/// Returns the number of result types of the [`wasm_func_t`].
279///
280/// Wraps [`Func::ty`], followed by [`FuncType::results`] and a call to `len`.
281///
282/// # Safety
283///
284/// It is the caller's responsibility not to alias the [`wasm_func_t`]
285/// with its underlying, internal [`WasmStoreRef`](crate::WasmStoreRef).
286///
287/// [`FuncType::results`]: wasmi::FuncType::results
288#[cfg_attr(not(feature = "prefix-symbols"), no_mangle)]
289#[cfg_attr(feature = "prefix-symbols", wasmi_c_api_macros::prefix_symbol)]
290pub unsafe extern "C" fn wasm_func_result_arity(f: &wasm_func_t) -> usize {
291    f.func().ty(f.inner.store.context()).results().len()
292}
293
294/// Returns the [`wasm_func_t`] as mutable reference to [`wasm_extern_t`].
295#[cfg_attr(not(feature = "prefix-symbols"), no_mangle)]
296#[cfg_attr(feature = "prefix-symbols", wasmi_c_api_macros::prefix_symbol)]
297pub extern "C" fn wasm_func_as_extern(f: &mut wasm_func_t) -> &mut wasm_extern_t {
298    &mut f.inner
299}
300
301/// Returns the [`wasm_func_t`] as shared reference to [`wasm_extern_t`].
302#[cfg_attr(not(feature = "prefix-symbols"), no_mangle)]
303#[cfg_attr(feature = "prefix-symbols", wasmi_c_api_macros::prefix_symbol)]
304pub extern "C" fn wasm_func_as_extern_const(f: &wasm_func_t) -> &wasm_extern_t {
305    &f.inner
306}