xref: /wasmtime-44.0.1/crates/c-api/src/func.rs (revision 08b7c877)
1 use crate::wasm_trap_t;
2 use crate::{
3     wasm_extern_t, wasm_functype_t, wasm_store_t, wasm_val_t, wasm_val_vec_t, wasmtime_error_t,
4     wasmtime_extern_t, wasmtime_val_t, wasmtime_val_union, CStoreContext, CStoreContextMut,
5 };
6 use std::ffi::c_void;
7 use std::mem::{self, MaybeUninit};
8 use std::panic::{self, AssertUnwindSafe};
9 use std::ptr;
10 use std::str;
11 use wasmtime::{AsContextMut, Caller, Extern, Func, Trap, Val, ValRaw};
12 
13 #[derive(Clone)]
14 #[repr(transparent)]
15 pub struct wasm_func_t {
16     ext: wasm_extern_t,
17 }
18 
19 wasmtime_c_api_macros::declare_ref!(wasm_func_t);
20 
21 pub type wasm_func_callback_t = extern "C" fn(
22     args: *const wasm_val_vec_t,
23     results: *mut wasm_val_vec_t,
24 ) -> Option<Box<wasm_trap_t>>;
25 
26 pub type wasm_func_callback_with_env_t = extern "C" fn(
27     env: *mut std::ffi::c_void,
28     args: *const wasm_val_vec_t,
29     results: *mut wasm_val_vec_t,
30 ) -> Option<Box<wasm_trap_t>>;
31 
32 impl wasm_func_t {
33     pub(crate) fn try_from(e: &wasm_extern_t) -> Option<&wasm_func_t> {
34         match &e.which {
35             Extern::Func(_) => Some(unsafe { &*(e as *const _ as *const _) }),
36             _ => None,
37         }
38     }
39 
40     pub(crate) fn func(&self) -> Func {
41         match self.ext.which {
42             Extern::Func(f) => f,
43             _ => unsafe { std::hint::unreachable_unchecked() },
44         }
45     }
46 }
47 
48 unsafe fn create_function(
49     store: &mut wasm_store_t,
50     ty: &wasm_functype_t,
51     func: impl Fn(*const wasm_val_vec_t, *mut wasm_val_vec_t) -> Option<Box<wasm_trap_t>>
52         + Send
53         + Sync
54         + 'static,
55 ) -> Box<wasm_func_t> {
56     let ty = ty.ty().ty.clone();
57     let func = Func::new(
58         store.store.context_mut(),
59         ty,
60         move |_caller, params, results| {
61             let params: wasm_val_vec_t = params
62                 .iter()
63                 .cloned()
64                 .map(|p| wasm_val_t::from_val(p))
65                 .collect::<Vec<_>>()
66                 .into();
67             let mut out_results: wasm_val_vec_t = vec![wasm_val_t::default(); results.len()].into();
68             let out = func(&params, &mut out_results);
69             if let Some(trap) = out {
70                 return Err(trap.trap.clone());
71             }
72 
73             let out_results = out_results.as_slice();
74             for i in 0..results.len() {
75                 results[i] = out_results[i].val();
76             }
77             Ok(())
78         },
79     );
80     Box::new(wasm_func_t {
81         ext: wasm_extern_t {
82             store: store.store.clone(),
83             which: func.into(),
84         },
85     })
86 }
87 
88 #[no_mangle]
89 pub unsafe extern "C" fn wasm_func_new(
90     store: &mut wasm_store_t,
91     ty: &wasm_functype_t,
92     callback: wasm_func_callback_t,
93 ) -> Box<wasm_func_t> {
94     create_function(store, ty, move |params, results| callback(params, results))
95 }
96 
97 #[no_mangle]
98 pub unsafe extern "C" fn wasm_func_new_with_env(
99     store: &mut wasm_store_t,
100     ty: &wasm_functype_t,
101     callback: wasm_func_callback_with_env_t,
102     data: *mut c_void,
103     finalizer: Option<extern "C" fn(arg1: *mut std::ffi::c_void)>,
104 ) -> Box<wasm_func_t> {
105     let finalizer = crate::ForeignData { data, finalizer };
106     create_function(store, ty, move |params, results| {
107         drop(&finalizer); // move entire finalizer into this closure
108         callback(finalizer.data, params, results)
109     })
110 }
111 
112 /// Places the `args` into `dst` and additionally reserves space in `dst` for `results_size`
113 /// returns. The params/results slices are then returned separately.
114 fn translate_args<'a>(
115     dst: &'a mut Vec<Val>,
116     args: impl ExactSizeIterator<Item = Val>,
117     results_size: usize,
118 ) -> (&'a [Val], &'a mut [Val]) {
119     debug_assert!(dst.is_empty());
120     let num_args = args.len();
121     dst.reserve(args.len() + results_size);
122     dst.extend(args);
123     dst.extend((0..results_size).map(|_| Val::null()));
124     let (a, b) = dst.split_at_mut(num_args);
125     (a, b)
126 }
127 
128 #[no_mangle]
129 pub unsafe extern "C" fn wasm_func_call(
130     func: &mut wasm_func_t,
131     args: *const wasm_val_vec_t,
132     results: *mut wasm_val_vec_t,
133 ) -> *mut wasm_trap_t {
134     let f = func.func();
135     let results = (*results).as_uninit_slice();
136     let args = (*args).as_slice();
137     let mut dst = Vec::new();
138     let (wt_params, wt_results) =
139         translate_args(&mut dst, args.iter().map(|i| i.val()), results.len());
140 
141     // We're calling arbitrary code here most of the time, and we in general
142     // want to try to insulate callers against bugs in wasmtime/wasi/etc if we
143     // can. As a result we catch panics here and transform them to traps to
144     // allow the caller to have any insulation possible against Rust panics.
145     let result = panic::catch_unwind(AssertUnwindSafe(|| {
146         f.call(func.ext.store.context_mut(), wt_params, wt_results)
147     }));
148     match result {
149         Ok(Ok(())) => {
150             for (slot, val) in results.iter_mut().zip(wt_results.iter().cloned()) {
151                 crate::initialize(slot, wasm_val_t::from_val(val));
152             }
153             ptr::null_mut()
154         }
155         Ok(Err(trap)) => match trap.downcast::<Trap>() {
156             Ok(trap) => Box::into_raw(Box::new(wasm_trap_t::new(trap))),
157             Err(err) => Box::into_raw(Box::new(wasm_trap_t::new(err.into()))),
158         },
159         Err(panic) => {
160             let trap = if let Some(msg) = panic.downcast_ref::<String>() {
161                 Trap::new(msg)
162             } else if let Some(msg) = panic.downcast_ref::<&'static str>() {
163                 Trap::new(*msg)
164             } else {
165                 Trap::new("rust panic happened")
166             };
167             let trap = Box::new(wasm_trap_t::new(trap));
168             Box::into_raw(trap)
169         }
170     }
171 }
172 
173 #[no_mangle]
174 pub unsafe extern "C" fn wasm_func_type(f: &wasm_func_t) -> Box<wasm_functype_t> {
175     Box::new(wasm_functype_t::new(f.func().ty(f.ext.store.context())))
176 }
177 
178 #[no_mangle]
179 pub unsafe extern "C" fn wasm_func_param_arity(f: &wasm_func_t) -> usize {
180     f.func().ty(f.ext.store.context()).params().len()
181 }
182 
183 #[no_mangle]
184 pub unsafe extern "C" fn wasm_func_result_arity(f: &wasm_func_t) -> usize {
185     f.func().ty(f.ext.store.context()).results().len()
186 }
187 
188 #[no_mangle]
189 pub extern "C" fn wasm_func_as_extern(f: &mut wasm_func_t) -> &mut wasm_extern_t {
190     &mut (*f).ext
191 }
192 
193 #[no_mangle]
194 pub extern "C" fn wasm_func_as_extern_const(f: &wasm_func_t) -> &wasm_extern_t {
195     &(*f).ext
196 }
197 
198 #[repr(C)]
199 pub struct wasmtime_caller_t<'a> {
200     caller: Caller<'a, crate::StoreData>,
201 }
202 
203 pub type wasmtime_func_callback_t = extern "C" fn(
204     *mut c_void,
205     *mut wasmtime_caller_t,
206     *const wasmtime_val_t,
207     usize,
208     *mut wasmtime_val_t,
209     usize,
210 ) -> Option<Box<wasm_trap_t>>;
211 
212 pub type wasmtime_func_unchecked_callback_t =
213     extern "C" fn(*mut c_void, *mut wasmtime_caller_t, *mut ValRaw) -> Option<Box<wasm_trap_t>>;
214 
215 #[no_mangle]
216 pub unsafe extern "C" fn wasmtime_func_new(
217     store: CStoreContextMut<'_>,
218     ty: &wasm_functype_t,
219     callback: wasmtime_func_callback_t,
220     data: *mut c_void,
221     finalizer: Option<extern "C" fn(*mut std::ffi::c_void)>,
222     func: &mut Func,
223 ) {
224     let ty = ty.ty().ty.clone();
225     let cb = c_callback_to_rust_fn(callback, data, finalizer);
226     let f = Func::new(store, ty, cb);
227     *func = f;
228 }
229 
230 pub(crate) unsafe fn c_callback_to_rust_fn(
231     callback: wasmtime_func_callback_t,
232     data: *mut c_void,
233     finalizer: Option<extern "C" fn(*mut std::ffi::c_void)>,
234 ) -> impl Fn(Caller<'_, crate::StoreData>, &[Val], &mut [Val]) -> Result<(), Trap> {
235     let foreign = crate::ForeignData { data, finalizer };
236     move |mut caller, params, results| {
237         drop(&foreign); // move entire foreign into this closure
238 
239         // Convert `params/results` to `wasmtime_val_t`. Use the previous
240         // storage in `hostcall_val_storage` to help avoid allocations all the
241         // time.
242         let mut vals = mem::take(&mut caller.data_mut().hostcall_val_storage);
243         debug_assert!(vals.is_empty());
244         vals.reserve(params.len() + results.len());
245         vals.extend(params.iter().cloned().map(|p| wasmtime_val_t::from_val(p)));
246         vals.extend((0..results.len()).map(|_| wasmtime_val_t {
247             kind: crate::WASMTIME_I32,
248             of: wasmtime_val_union { i32: 0 },
249         }));
250         let (params, out_results) = vals.split_at_mut(params.len());
251 
252         // Invoke the C function pointer, getting the results.
253         let mut caller = wasmtime_caller_t { caller };
254         let out = callback(
255             foreign.data,
256             &mut caller,
257             params.as_ptr(),
258             params.len(),
259             out_results.as_mut_ptr(),
260             out_results.len(),
261         );
262         if let Some(trap) = out {
263             return Err(trap.trap);
264         }
265 
266         // Translate the `wasmtime_val_t` results into the `results` space
267         for (i, result) in out_results.iter().enumerate() {
268             results[i] = result.to_val();
269         }
270 
271         // Move our `vals` storage back into the store now that we no longer
272         // need it. This'll get picked up by the next hostcall and reuse our
273         // same storage.
274         vals.truncate(0);
275         caller.caller.data_mut().hostcall_val_storage = vals;
276         Ok(())
277     }
278 }
279 
280 #[no_mangle]
281 pub unsafe extern "C" fn wasmtime_func_new_unchecked(
282     store: CStoreContextMut<'_>,
283     ty: &wasm_functype_t,
284     callback: wasmtime_func_unchecked_callback_t,
285     data: *mut c_void,
286     finalizer: Option<extern "C" fn(*mut std::ffi::c_void)>,
287     func: &mut Func,
288 ) {
289     let ty = ty.ty().ty.clone();
290     let cb = c_unchecked_callback_to_rust_fn(callback, data, finalizer);
291     *func = Func::new_unchecked(store, ty, cb);
292 }
293 
294 pub(crate) unsafe fn c_unchecked_callback_to_rust_fn(
295     callback: wasmtime_func_unchecked_callback_t,
296     data: *mut c_void,
297     finalizer: Option<extern "C" fn(*mut std::ffi::c_void)>,
298 ) -> impl Fn(Caller<'_, crate::StoreData>, *mut ValRaw) -> Result<(), Trap> {
299     let foreign = crate::ForeignData { data, finalizer };
300     move |caller, values| {
301         drop(&foreign); // move entire foreign into this closure
302         let mut caller = wasmtime_caller_t { caller };
303         match callback(foreign.data, &mut caller, values) {
304             None => Ok(()),
305             Some(trap) => Err(trap.trap),
306         }
307     }
308 }
309 
310 #[no_mangle]
311 pub unsafe extern "C" fn wasmtime_func_call(
312     mut store: CStoreContextMut<'_>,
313     func: &Func,
314     args: *const wasmtime_val_t,
315     nargs: usize,
316     results: *mut MaybeUninit<wasmtime_val_t>,
317     nresults: usize,
318     trap_ret: &mut *mut wasm_trap_t,
319 ) -> Option<Box<wasmtime_error_t>> {
320     let mut store = store.as_context_mut();
321     let mut params = mem::take(&mut store.data_mut().wasm_val_storage);
322     let (wt_params, wt_results) = translate_args(
323         &mut params,
324         crate::slice_from_raw_parts(args, nargs)
325             .iter()
326             .map(|i| i.to_val()),
327         nresults,
328     );
329 
330     // We're calling arbitrary code here most of the time, and we in general
331     // want to try to insulate callers against bugs in wasmtime/wasi/etc if we
332     // can. As a result we catch panics here and transform them to traps to
333     // allow the caller to have any insulation possible against Rust panics.
334     let result = panic::catch_unwind(AssertUnwindSafe(|| {
335         func.call(&mut store, wt_params, wt_results)
336     }));
337     match result {
338         Ok(Ok(())) => {
339             let results = crate::slice_from_raw_parts_mut(results, nresults);
340             for (slot, val) in results.iter_mut().zip(wt_results.iter()) {
341                 crate::initialize(slot, wasmtime_val_t::from_val(val.clone()));
342             }
343             params.truncate(0);
344             store.data_mut().wasm_val_storage = params;
345             None
346         }
347         Ok(Err(trap)) => match trap.downcast::<Trap>() {
348             Ok(trap) => {
349                 *trap_ret = Box::into_raw(Box::new(wasm_trap_t::new(trap)));
350                 None
351             }
352             Err(err) => Some(Box::new(wasmtime_error_t::from(err))),
353         },
354         Err(panic) => {
355             let trap = if let Some(msg) = panic.downcast_ref::<String>() {
356                 Trap::new(msg)
357             } else if let Some(msg) = panic.downcast_ref::<&'static str>() {
358                 Trap::new(*msg)
359             } else {
360                 Trap::new("rust panic happened")
361             };
362             *trap_ret = Box::into_raw(Box::new(wasm_trap_t::new(trap)));
363             None
364         }
365     }
366 }
367 
368 #[no_mangle]
369 pub unsafe extern "C" fn wasmtime_func_call_unchecked(
370     store: CStoreContextMut<'_>,
371     func: &Func,
372     args_and_results: *mut ValRaw,
373 ) -> *mut wasm_trap_t {
374     match func.call_unchecked(store, args_and_results) {
375         Ok(()) => ptr::null_mut(),
376         Err(trap) => Box::into_raw(Box::new(wasm_trap_t::new(trap))),
377     }
378 }
379 
380 #[no_mangle]
381 pub extern "C" fn wasmtime_func_type(
382     store: CStoreContext<'_>,
383     func: &Func,
384 ) -> Box<wasm_functype_t> {
385     Box::new(wasm_functype_t::new(func.ty(store)))
386 }
387 
388 #[no_mangle]
389 pub extern "C" fn wasmtime_caller_context<'a>(
390     caller: &'a mut wasmtime_caller_t,
391 ) -> CStoreContextMut<'a> {
392     caller.caller.as_context_mut()
393 }
394 
395 #[no_mangle]
396 pub unsafe extern "C" fn wasmtime_caller_export_get(
397     caller: &mut wasmtime_caller_t,
398     name: *const u8,
399     name_len: usize,
400     item: &mut MaybeUninit<wasmtime_extern_t>,
401 ) -> bool {
402     let name = match str::from_utf8(crate::slice_from_raw_parts(name, name_len)) {
403         Ok(name) => name,
404         Err(_) => return false,
405     };
406     let which = match caller.caller.get_export(name) {
407         Some(item) => item,
408         None => return false,
409     };
410     crate::initialize(item, which.into());
411     true
412 }
413 
414 #[no_mangle]
415 pub unsafe extern "C" fn wasmtime_func_from_raw(
416     store: CStoreContextMut<'_>,
417     raw: usize,
418     func: &mut Func,
419 ) {
420     *func = Func::from_raw(store, raw).unwrap();
421 }
422 
423 #[no_mangle]
424 pub unsafe extern "C" fn wasmtime_func_to_raw(store: CStoreContextMut<'_>, func: &Func) -> usize {
425     func.to_raw(store)
426 }
427