wasmtime_c_api/
val.rs

1use crate::r#ref::ref_to_val;
2use crate::{
3    WASM_I32, WasmtimeStoreContextMut, from_valtype, into_valtype, wasm_ref_t, wasm_valkind_t,
4    wasmtime_anyref_t, wasmtime_externref_t, wasmtime_valkind_t,
5};
6use std::mem::{ManuallyDrop, MaybeUninit};
7use std::ptr;
8use wasmtime::{AsContextMut, Func, HeapType, Ref, RootScope, Val, ValType};
9
10#[repr(C)]
11pub struct wasm_val_t {
12    pub kind: wasm_valkind_t,
13    pub of: wasm_val_union,
14}
15
16#[repr(C)]
17#[derive(Copy, Clone)]
18pub union wasm_val_union {
19    pub i32: i32,
20    pub i64: i64,
21    pub u32: u32,
22    pub u64: u64,
23    pub f32: f32,
24    pub f64: f64,
25    pub ref_: *mut wasm_ref_t,
26}
27
28impl Drop for wasm_val_t {
29    fn drop(&mut self) {
30        match into_valtype(self.kind) {
31            ValType::Ref(_) => unsafe {
32                if !self.of.ref_.is_null() {
33                    drop(Box::from_raw(self.of.ref_));
34                }
35            },
36            _ => {}
37        }
38    }
39}
40
41impl Clone for wasm_val_t {
42    fn clone(&self) -> Self {
43        let mut ret = wasm_val_t {
44            kind: self.kind,
45            of: self.of,
46        };
47        unsafe {
48            match into_valtype(self.kind) {
49                ValType::Ref(_) if !self.of.ref_.is_null() => {
50                    ret.of.ref_ = Box::into_raw(Box::new((*self.of.ref_).clone()));
51                }
52                _ => {}
53            }
54        }
55        return ret;
56    }
57}
58
59impl Default for wasm_val_t {
60    fn default() -> Self {
61        wasm_val_t {
62            kind: WASM_I32,
63            of: wasm_val_union { i32: 0 },
64        }
65    }
66}
67
68impl wasm_val_t {
69    pub fn from_val(val: Val) -> wasm_val_t {
70        match val {
71            Val::I32(i) => wasm_val_t {
72                kind: from_valtype(&ValType::I32),
73                of: wasm_val_union { i32: i },
74            },
75            Val::I64(i) => wasm_val_t {
76                kind: from_valtype(&ValType::I64),
77                of: wasm_val_union { i64: i },
78            },
79            Val::F32(f) => wasm_val_t {
80                kind: from_valtype(&ValType::F32),
81                of: wasm_val_union { u32: f },
82            },
83            Val::F64(f) => wasm_val_t {
84                kind: from_valtype(&ValType::F64),
85                of: wasm_val_union { u64: f },
86            },
87            Val::FuncRef(f) => wasm_val_t {
88                kind: from_valtype(&ValType::FUNCREF),
89                of: wasm_val_union {
90                    ref_: f.map_or(ptr::null_mut(), |f| {
91                        Box::into_raw(Box::new(wasm_ref_t {
92                            r: Ref::Func(Some(f)),
93                        }))
94                    }),
95                },
96            },
97            Val::AnyRef(_) => crate::abort("creating a wasm_val_t from an anyref"),
98            Val::ExternRef(_) => crate::abort("creating a wasm_val_t from an externref"),
99            Val::ExnRef(_) => crate::abort("creating a wasm_val_t from  an exnref"),
100            Val::V128(_) => crate::abort("creating a wasm_val_t from a v128"),
101        }
102    }
103
104    pub fn val(&self) -> Val {
105        match into_valtype(self.kind) {
106            ValType::I32 => Val::from(unsafe { self.of.i32 }),
107            ValType::I64 => Val::from(unsafe { self.of.i64 }),
108            ValType::F32 => Val::from(unsafe { self.of.f32 }),
109            ValType::F64 => Val::from(unsafe { self.of.f64 }),
110            ValType::Ref(r) => match r.heap_type() {
111                HeapType::Func => unsafe {
112                    if self.of.ref_.is_null() {
113                        assert!(r.is_nullable());
114                        Val::FuncRef(None)
115                    } else {
116                        ref_to_val(&*self.of.ref_)
117                    }
118                },
119                _ => unreachable!("wasm_val_t cannot contain non-function reference values"),
120            },
121            ValType::V128 => unimplemented!("wasm_val_t: v128"),
122        }
123    }
124}
125
126#[unsafe(no_mangle)]
127pub unsafe extern "C" fn wasm_val_copy(out: &mut MaybeUninit<wasm_val_t>, source: &wasm_val_t) {
128    crate::initialize(out, source.clone());
129}
130
131#[unsafe(no_mangle)]
132pub unsafe extern "C" fn wasm_val_delete(val: *mut wasm_val_t) {
133    ptr::drop_in_place(val);
134}
135
136#[repr(C)]
137pub struct wasmtime_val_t {
138    pub kind: wasmtime_valkind_t,
139    pub of: wasmtime_val_union,
140}
141
142#[repr(C)]
143pub union wasmtime_val_union {
144    pub i32: i32,
145    pub i64: i64,
146    pub f32: u32,
147    pub f64: u64,
148    pub anyref: ManuallyDrop<wasmtime_anyref_t>,
149    pub externref: ManuallyDrop<wasmtime_externref_t>,
150    pub funcref: wasmtime_func_t,
151    pub v128: [u8; 16],
152}
153
154const _: () = {
155    assert!(std::mem::size_of::<wasmtime_val_union>() == 16);
156    assert!(std::mem::align_of::<wasmtime_val_union>() == std::mem::align_of::<u64>());
157};
158
159// The raw pointers are actually optional boxes.
160unsafe impl Send for wasmtime_val_union
161where
162    Option<Box<wasmtime_anyref_t>>: Send,
163    Option<Box<wasmtime_externref_t>>: Send,
164{
165}
166unsafe impl Sync for wasmtime_val_union
167where
168    Option<Box<wasmtime_anyref_t>>: Sync,
169    Option<Box<wasmtime_externref_t>>: Sync,
170{
171}
172
173#[repr(C)]
174#[derive(Clone, Copy)]
175pub union wasmtime_func_t {
176    store_id: u64,
177    func: Func,
178}
179
180impl wasmtime_func_t {
181    unsafe fn as_wasmtime(&self) -> Option<Func> {
182        if self.store_id == 0 {
183            None
184        } else {
185            Some(self.func)
186        }
187    }
188}
189
190impl From<Option<Func>> for wasmtime_func_t {
191    fn from(func: Option<Func>) -> wasmtime_func_t {
192        match func {
193            Some(func) => wasmtime_func_t { func },
194            None => wasmtime_func_t { store_id: 0 },
195        }
196    }
197}
198
199impl wasmtime_val_t {
200    /// Creates a new `wasmtime_val_t` from a `wasmtime::Val`.
201    ///
202    /// Note that this requires a `RootScope` to be present to serve as proof
203    /// that `val` is not require to be rooted in the store itself which would
204    /// prevent GC. Callers should prefer this API where possible, creating a
205    /// temporary `RootScope` when needed.
206    pub fn from_val(cx: &mut RootScope<impl AsContextMut>, val: Val) -> wasmtime_val_t {
207        Self::from_val_unscoped(cx, val)
208    }
209
210    /// Equivalent of [`wasmtime_val_t::from_val`] except that a `RootScope`
211    /// is not required.
212    ///
213    /// This method should only be used when a `RootScope` is known to be
214    /// elsewhere on the stack. For example this is used when we call back out
215    /// to the embedder. In such a situation we know we previously entered with
216    /// some other call so the root scope is on the stack there.
217    pub fn from_val_unscoped(cx: impl AsContextMut, val: Val) -> wasmtime_val_t {
218        match val {
219            Val::I32(i) => wasmtime_val_t {
220                kind: crate::WASMTIME_I32,
221                of: wasmtime_val_union { i32: i },
222            },
223            Val::I64(i) => wasmtime_val_t {
224                kind: crate::WASMTIME_I64,
225                of: wasmtime_val_union { i64: i },
226            },
227            Val::F32(i) => wasmtime_val_t {
228                kind: crate::WASMTIME_F32,
229                of: wasmtime_val_union { f32: i },
230            },
231            Val::F64(i) => wasmtime_val_t {
232                kind: crate::WASMTIME_F64,
233                of: wasmtime_val_union { f64: i },
234            },
235            Val::AnyRef(a) => wasmtime_val_t {
236                kind: crate::WASMTIME_ANYREF,
237                of: wasmtime_val_union {
238                    anyref: ManuallyDrop::new(a.and_then(|a| a.to_manually_rooted(cx).ok()).into()),
239                },
240            },
241            Val::ExternRef(e) => wasmtime_val_t {
242                kind: crate::WASMTIME_EXTERNREF,
243                of: wasmtime_val_union {
244                    externref: ManuallyDrop::new(
245                        e.and_then(|e| e.to_manually_rooted(cx).ok()).into(),
246                    ),
247                },
248            },
249            Val::FuncRef(func) => wasmtime_val_t {
250                kind: crate::WASMTIME_FUNCREF,
251                of: wasmtime_val_union {
252                    funcref: func.into(),
253                },
254            },
255            Val::ExnRef(_) => crate::abort("exnrefs not yet supported in C API"),
256            Val::V128(val) => wasmtime_val_t {
257                kind: crate::WASMTIME_V128,
258                of: wasmtime_val_union {
259                    v128: val.as_u128().to_le_bytes(),
260                },
261            },
262        }
263    }
264
265    /// Convert this `wasmtime_val_t` into a `wasmtime::Val`.
266    ///
267    /// See [`wasmtime_val_t::from_val`] for notes on the `RootScope`
268    /// requirement here. Note that this is particularly meaningful for this
269    /// API as the `Val` returned may contain a `Rooted<T>` which requires a
270    /// `RootScope` if we don't want the value to live for the entire lifetime
271    /// of the `Store`.
272    pub unsafe fn to_val(&self, cx: &mut RootScope<impl AsContextMut>) -> Val {
273        self.to_val_unscoped(cx)
274    }
275
276    /// Equivalent of `to_val` except doesn't require a `RootScope`.
277    ///
278    /// See notes on [`wasmtime_val_t::from_val_unscoped`] for notes on when to
279    /// use this.
280    pub unsafe fn to_val_unscoped(&self, cx: impl AsContextMut) -> Val {
281        match self.kind {
282            crate::WASMTIME_I32 => Val::I32(self.of.i32),
283            crate::WASMTIME_I64 => Val::I64(self.of.i64),
284            crate::WASMTIME_F32 => Val::F32(self.of.f32),
285            crate::WASMTIME_F64 => Val::F64(self.of.f64),
286            crate::WASMTIME_V128 => Val::V128(u128::from_le_bytes(self.of.v128).into()),
287            crate::WASMTIME_ANYREF => {
288                Val::AnyRef(self.of.anyref.as_wasmtime().map(|a| a.to_rooted(cx)))
289            }
290            crate::WASMTIME_EXTERNREF => {
291                Val::ExternRef(self.of.externref.as_wasmtime().map(|e| e.to_rooted(cx)))
292            }
293            crate::WASMTIME_FUNCREF => Val::FuncRef(self.of.funcref.as_wasmtime()),
294            other => panic!("unknown wasmtime_valkind_t: {other}"),
295        }
296    }
297}
298
299#[unsafe(no_mangle)]
300pub unsafe extern "C" fn wasmtime_val_unroot(
301    cx: WasmtimeStoreContextMut<'_>,
302    val: &mut MaybeUninit<wasmtime_val_t>,
303) {
304    let val = val.assume_init_read();
305    match val.kind {
306        crate::WASMTIME_ANYREF => {
307            if let Some(val) = ManuallyDrop::into_inner(val.of.anyref).as_wasmtime() {
308                val.unroot(cx);
309            }
310        }
311        crate::WASMTIME_EXTERNREF => {
312            if let Some(val) = ManuallyDrop::into_inner(val.of.externref).as_wasmtime() {
313                val.unroot(cx);
314            }
315        }
316        _ => {}
317    }
318}
319
320#[unsafe(no_mangle)]
321pub unsafe extern "C" fn wasmtime_val_clone(
322    cx: WasmtimeStoreContextMut<'_>,
323    src: &wasmtime_val_t,
324    dst: &mut MaybeUninit<wasmtime_val_t>,
325) {
326    let mut scope = RootScope::new(cx);
327    let val = src.to_val(&mut scope);
328    crate::initialize(dst, wasmtime_val_t::from_val(&mut scope, val))
329}