wasmtime-c-api-impl 45.0.0

C API to expose the Wasmtime runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
#[cfg(feature = "gc")]
use crate::r#ref::ref_to_val;
#[cfg(feature = "gc")]
use crate::{
    WASM_EXTERNREF, WASM_FUNCREF, wasm_ref_t, wasmtime_anyref_t, wasmtime_exnref_t,
    wasmtime_externref_t,
};
use crate::{WASM_F32, WASM_F64, WASM_I32, WASM_I64, wasm_valkind_t};
use std::mem::{ManuallyDrop, MaybeUninit};
use std::ptr;
use wasmtime::{AsContextMut, Func, Val};
#[cfg(feature = "gc")]
use wasmtime::{Ref, RootScope};

#[repr(C)]
pub struct wasm_val_t {
    pub kind: wasm_valkind_t,
    pub of: wasm_val_union,
}

#[repr(C)]
#[derive(Copy, Clone)]
pub union wasm_val_union {
    pub i32: i32,
    pub i64: i64,
    pub u32: u32,
    pub u64: u64,
    pub f32: f32,
    pub f64: f64,
    #[cfg(feature = "gc")]
    pub ref_: *mut wasm_ref_t,
}

#[cfg(feature = "gc")]
impl Drop for wasm_val_t {
    fn drop(&mut self) {
        match self.kind {
            WASM_FUNCREF | WASM_EXTERNREF => unsafe {
                if !self.of.ref_.is_null() {
                    drop(Box::from_raw(self.of.ref_));
                }
            },
            _ => {}
        }
    }
}

impl Clone for wasm_val_t {
    fn clone(&self) -> Self {
        #[allow(
            unused_mut,
            reason = "needed for conditional mutation under cfg(feature = \"gc\")"
        )]
        let mut ret = wasm_val_t {
            kind: self.kind,
            of: self.of,
        };

        #[cfg(feature = "gc")]
        unsafe {
            match self.kind {
                WASM_FUNCREF | WASM_EXTERNREF if !self.of.ref_.is_null() => {
                    ret.of.ref_ = Box::into_raw(Box::new((*self.of.ref_).clone()));
                }
                _ => {}
            }
        }

        return ret;
    }
}

impl Default for wasm_val_t {
    fn default() -> Self {
        wasm_val_t {
            kind: WASM_I32,
            of: wasm_val_union { i32: 0 },
        }
    }
}

impl wasm_val_t {
    pub fn from_val(val: Val) -> wasm_val_t {
        match val {
            Val::I32(i) => wasm_val_t {
                kind: WASM_I32,
                of: wasm_val_union { i32: i },
            },
            Val::I64(i) => wasm_val_t {
                kind: WASM_I64,
                of: wasm_val_union { i64: i },
            },
            Val::F32(f) => wasm_val_t {
                kind: WASM_F32,
                of: wasm_val_union { u32: f },
            },
            Val::F64(f) => wasm_val_t {
                kind: WASM_F64,
                of: wasm_val_union { u64: f },
            },
            #[cfg(feature = "gc")]
            Val::FuncRef(f) => wasm_val_t {
                kind: WASM_FUNCREF,
                of: wasm_val_union {
                    ref_: f.map_or(ptr::null_mut(), |f| {
                        Box::into_raw(Box::new(wasm_ref_t {
                            r: Ref::Func(Some(f)),
                        }))
                    }),
                },
            },
            #[cfg(not(feature = "gc"))]
            Val::FuncRef(_) => crate::abort("creating a wasm_val_t from a funcref"),
            Val::AnyRef(_) => crate::abort("creating a wasm_val_t from an anyref"),
            Val::ExternRef(_) => crate::abort("creating a wasm_val_t from an externref"),
            Val::ExnRef(_) => crate::abort("creating a wasm_val_t from  an exnref"),
            Val::V128(_) => crate::abort("creating a wasm_val_t from a v128"),
            Val::ContRef(_) => crate::abort("creating a wasm_val_t from a contref"),
        }
    }

    pub fn val(&self) -> Val {
        match self.kind {
            WASM_I32 => Val::from(unsafe { self.of.i32 }),
            WASM_I64 => Val::from(unsafe { self.of.i64 }),
            WASM_F32 => Val::from(unsafe { self.of.f32 }),
            WASM_F64 => Val::from(unsafe { self.of.f64 }),
            #[cfg(feature = "gc")]
            WASM_FUNCREF => unsafe {
                if self.of.ref_.is_null() {
                    Val::FuncRef(None)
                } else {
                    ref_to_val(&*self.of.ref_)
                }
            },
            _ => crate::abort("unsupported val discriminant"),
        }
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn wasm_val_copy(out: &mut MaybeUninit<wasm_val_t>, source: &wasm_val_t) {
    crate::initialize(out, source.clone());
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn wasm_val_delete(val: *mut wasm_val_t) {
    ptr::drop_in_place(val);
}

#[repr(C)]
pub struct wasmtime_val_t {
    pub kind: wasmtime_valkind_t,
    pub of: wasmtime_val_union,
}

pub type wasmtime_valkind_t = u8;
pub const WASMTIME_I32: wasmtime_valkind_t = 0;
pub const WASMTIME_I64: wasmtime_valkind_t = 1;
pub const WASMTIME_F32: wasmtime_valkind_t = 2;
pub const WASMTIME_F64: wasmtime_valkind_t = 3;
pub const WASMTIME_V128: wasmtime_valkind_t = 4;
pub const WASMTIME_FUNCREF: wasmtime_valkind_t = 5;
pub const WASMTIME_EXTERNREF: wasmtime_valkind_t = 6;
pub const WASMTIME_ANYREF: wasmtime_valkind_t = 7;
pub const WASMTIME_EXNREF: wasmtime_valkind_t = 8;

#[repr(C)]
pub union wasmtime_val_union {
    pub i32: i32,
    pub i64: i64,
    pub f32: u32,
    pub f64: u64,
    #[cfg(feature = "gc")]
    pub anyref: ManuallyDrop<wasmtime_anyref_t>,
    #[cfg(feature = "gc")]
    pub externref: ManuallyDrop<wasmtime_externref_t>,
    #[cfg(feature = "gc")]
    pub exnref: ManuallyDrop<wasmtime_exnref_t>,
    #[cfg(feature = "gc")]
    pub funcref: wasmtime_func_t,
    pub v128: [u8; 16],
}

const _: () = {
    // This is forced to 24 or 20 bytes by `anyref` and `externref`.
    assert!(std::mem::size_of::<wasmtime_val_union>() <= 24);
    assert!(std::mem::align_of::<wasmtime_val_union>() == std::mem::align_of::<u64>());
};

#[cfg(feature = "gc")]
impl Drop for wasmtime_val_t {
    fn drop(&mut self) {
        unsafe {
            match self.kind {
                crate::WASMTIME_ANYREF => {
                    let _ = ManuallyDrop::take(&mut self.of.anyref);
                }
                crate::WASMTIME_EXTERNREF => {
                    let _ = ManuallyDrop::take(&mut self.of.externref);
                }
                crate::WASMTIME_EXNREF => {
                    let _ = ManuallyDrop::take(&mut self.of.exnref);
                }
                _ => {}
            }
        }
    }
}

// The raw pointers are actually optional boxes.
#[cfg(feature = "gc")]
unsafe impl Send for wasmtime_val_union
where
    Option<Box<wasmtime_anyref_t>>: Send,
    Option<Box<wasmtime_externref_t>>: Send,
    Option<Box<wasmtime_exnref_t>>: Send,
{
}
#[cfg(feature = "gc")]
unsafe impl Sync for wasmtime_val_union
where
    Option<Box<wasmtime_anyref_t>>: Sync,
    Option<Box<wasmtime_externref_t>>: Sync,
    Option<Box<wasmtime_exnref_t>>: Sync,
{
}

#[repr(C)]
#[derive(Clone, Copy)]
pub union wasmtime_func_t {
    store_id: u64,
    func: Func,
}

impl wasmtime_func_t {
    #[cfg(feature = "gc")]
    unsafe fn as_wasmtime(&self) -> Option<Func> {
        if self.store_id == 0 {
            None
        } else {
            Some(self.func)
        }
    }
}

impl From<Option<Func>> for wasmtime_func_t {
    fn from(func: Option<Func>) -> wasmtime_func_t {
        match func {
            Some(func) => wasmtime_func_t { func },
            None => wasmtime_func_t { store_id: 0 },
        }
    }
}

impl wasmtime_val_t {
    /// Creates a new `wasmtime_val_t` from a `wasmtime::Val`.
    ///
    /// Note that this requires a `RootScope` to be present to serve as proof
    /// that `val` is not require to be rooted in the store itself which would
    /// prevent GC. Callers should prefer this API where possible, creating a
    /// temporary `RootScope` when needed.
    #[cfg(feature = "gc")]
    pub fn from_val(cx: &mut RootScope<impl AsContextMut>, val: Val) -> wasmtime_val_t {
        Self::from_val_unscoped(cx, val)
    }

    /// Creates a new `wasmtime_val_t` from a `wasmtime::Val` (non-gc version).
    ///
    /// When gc feature is disabled, this does not require a `RootScope`.
    #[cfg(not(feature = "gc"))]
    pub fn from_val(cx: impl AsContextMut, val: Val) -> wasmtime_val_t {
        Self::from_val_unscoped(cx, val)
    }

    /// Equivalent of [`wasmtime_val_t::from_val`] except that a `RootScope`
    /// is not required.
    ///
    /// This method should only be used when a `RootScope` is known to be
    /// elsewhere on the stack. For example this is used when we call back out
    /// to the embedder. In such a situation we know we previously entered with
    /// some other call so the root scope is on the stack there.
    pub fn from_val_unscoped(cx: impl AsContextMut, val: Val) -> wasmtime_val_t {
        #[cfg(not(feature = "gc"))]
        let _ = cx;
        match val {
            Val::I32(i) => wasmtime_val_t {
                kind: crate::WASMTIME_I32,
                of: wasmtime_val_union { i32: i },
            },
            Val::I64(i) => wasmtime_val_t {
                kind: crate::WASMTIME_I64,
                of: wasmtime_val_union { i64: i },
            },
            Val::F32(i) => wasmtime_val_t {
                kind: crate::WASMTIME_F32,
                of: wasmtime_val_union { f32: i },
            },
            Val::F64(i) => wasmtime_val_t {
                kind: crate::WASMTIME_F64,
                of: wasmtime_val_union { f64: i },
            },
            #[cfg(feature = "gc")]
            Val::AnyRef(a) => wasmtime_val_t {
                kind: crate::WASMTIME_ANYREF,
                of: wasmtime_val_union {
                    anyref: ManuallyDrop::new(a.and_then(|a| a.to_owned_rooted(cx).ok()).into()),
                },
            },
            #[cfg(feature = "gc")]
            Val::ExternRef(e) => wasmtime_val_t {
                kind: crate::WASMTIME_EXTERNREF,
                of: wasmtime_val_union {
                    externref: ManuallyDrop::new(e.and_then(|e| e.to_owned_rooted(cx).ok()).into()),
                },
            },
            #[cfg(feature = "gc")]
            Val::FuncRef(func) => wasmtime_val_t {
                kind: crate::WASMTIME_FUNCREF,
                of: wasmtime_val_union {
                    funcref: func.into(),
                },
            },
            #[cfg(feature = "gc")]
            Val::ExnRef(e) => wasmtime_val_t {
                kind: crate::WASMTIME_EXNREF,
                of: wasmtime_val_union {
                    exnref: ManuallyDrop::new(e.and_then(|e| e.to_owned_rooted(cx).ok()).into()),
                },
            },
            #[cfg(not(feature = "gc"))]
            Val::AnyRef(_) | Val::ExternRef(_) | Val::FuncRef(_) | Val::ExnRef(_) => {
                crate::abort("reference types require gc feature")
            }
            Val::V128(val) => wasmtime_val_t {
                kind: crate::WASMTIME_V128,
                of: wasmtime_val_union {
                    v128: val.as_u128().to_le_bytes(),
                },
            },
            Val::ContRef(_) => crate::abort("contrefs not yet supported in C API (#10248)"),
        }
    }

    /// Convert this `wasmtime_val_t` into a `wasmtime::Val`.
    ///
    /// See [`wasmtime_val_t::from_val`] for notes on the `RootScope`
    /// requirement here. Note that this is particularly meaningful for this
    /// API as the `Val` returned may contain a `Rooted<T>` which requires a
    /// `RootScope` if we don't want the value to live for the entire lifetime
    /// of the `Store`.
    #[cfg(feature = "gc")]
    pub unsafe fn to_val(&self, cx: &mut RootScope<impl AsContextMut>) -> Val {
        self.to_val_unscoped(cx)
    }

    /// Convert this `wasmtime_val_t` into a `wasmtime::Val` (non-gc version).
    ///
    /// When gc feature is disabled, this does not require a `RootScope`.
    #[cfg(not(feature = "gc"))]
    pub unsafe fn to_val(&self, cx: impl AsContextMut) -> Val {
        self.to_val_unscoped(cx)
    }

    /// Equivalent of `to_val` except doesn't require a `RootScope`.
    ///
    /// See notes on [`wasmtime_val_t::from_val_unscoped`] for notes on when to
    /// use this.
    pub unsafe fn to_val_unscoped(&self, cx: impl AsContextMut) -> Val {
        #[cfg(not(feature = "gc"))]
        let _ = cx;
        match self.kind {
            crate::WASMTIME_I32 => Val::I32(self.of.i32),
            crate::WASMTIME_I64 => Val::I64(self.of.i64),
            crate::WASMTIME_F32 => Val::F32(self.of.f32),
            crate::WASMTIME_F64 => Val::F64(self.of.f64),
            crate::WASMTIME_V128 => Val::V128(u128::from_le_bytes(self.of.v128).into()),
            #[cfg(feature = "gc")]
            crate::WASMTIME_ANYREF => {
                Val::AnyRef(self.of.anyref.as_wasmtime().map(|a| a.to_rooted(cx)))
            }
            #[cfg(feature = "gc")]
            crate::WASMTIME_EXTERNREF => {
                Val::ExternRef(self.of.externref.as_wasmtime().map(|e| e.to_rooted(cx)))
            }
            #[cfg(feature = "gc")]
            crate::WASMTIME_FUNCREF => Val::FuncRef(self.of.funcref.as_wasmtime()),
            #[cfg(feature = "gc")]
            crate::WASMTIME_EXNREF => {
                Val::ExnRef(self.of.exnref.as_wasmtime().map(|e| e.to_rooted(cx)))
            }
            other => panic!("unknown wasmtime_valkind_t: {other}"),
        }
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn wasmtime_val_unroot(val: &mut ManuallyDrop<wasmtime_val_t>) {
    ManuallyDrop::drop(val);
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn wasmtime_val_clone(
    src: &wasmtime_val_t,
    dst: &mut MaybeUninit<wasmtime_val_t>,
) {
    let of = match src.kind {
        #[cfg(feature = "gc")]
        crate::WASMTIME_ANYREF => wasmtime_val_union {
            anyref: ManuallyDrop::new(src.of.anyref.as_wasmtime().into()),
        },
        #[cfg(feature = "gc")]
        crate::WASMTIME_EXTERNREF => wasmtime_val_union {
            externref: ManuallyDrop::new(src.of.externref.as_wasmtime().into()),
        },
        #[cfg(feature = "gc")]
        crate::WASMTIME_EXNREF => wasmtime_val_union {
            exnref: ManuallyDrop::new(src.of.exnref.as_wasmtime().into()),
        },
        crate::WASMTIME_I32 => wasmtime_val_union { i32: src.of.i32 },
        crate::WASMTIME_I64 => wasmtime_val_union { i64: src.of.i64 },
        crate::WASMTIME_F32 => wasmtime_val_union { f32: src.of.f32 },
        crate::WASMTIME_F64 => wasmtime_val_union { f64: src.of.f64 },
        crate::WASMTIME_V128 => wasmtime_val_union { v128: src.of.v128 },
        #[cfg(feature = "gc")]
        crate::WASMTIME_FUNCREF => wasmtime_val_union {
            funcref: src.of.funcref,
        },
        _ => unreachable!(),
    };
    dst.write(wasmtime_val_t { kind: src.kind, of });
}