A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Add `eqref` support to the C and C++ APIs (#12914)
Nick Fitzgeralda46300a7a373
diff --git a/crates/c-api/include/wasmtime.h b/crates/c-api/include/wasmtime.hindex 3150cc055b..3883d0c439 100644--- a/crates/c-api/include/wasmtime.h+++ b/crates/c-api/include/wasmtime.h@@ -205,6 +205,7 @@#include <wasmtime/tag.h>#include <wasmtime/trap.h>#include <wasmtime/val.h>+#include <wasmtime/gc.h>#include <wasmtime/async.h>#include <wasmtime/component.h>#include <wasmtime/wat.h>diff --git a/crates/c-api/include/wasmtime.hh b/crates/c-api/include/wasmtime.hhindex 3d7ccf15c1..4a6df6d887 100644--- a/crates/c-api/include/wasmtime.hh+++ b/crates/c-api/include/wasmtime.hh@@ -41,6 +41,7 @@#include <wasmtime/exn.hh>#include <wasmtime/extern.hh>#include <wasmtime/func.hh>+#include <wasmtime/gc.hh>#include <wasmtime/global.hh>#include <wasmtime/instance.hh>#include <wasmtime/linker.hh>diff --git a/crates/c-api/include/wasmtime/gc.h b/crates/c-api/include/wasmtime/gc.hnew file mode 100644index 0000000000..eac86508e1--- /dev/null+++ b/crates/c-api/include/wasmtime/gc.h@@ -0,0 +1,133 @@+/**+ * \file wasmtime/gc.h+ *+ * APIs for interacting with WebAssembly GC types in Wasmtime.+ *+ * This header provides types and functions for GC reference types beyond+ * the basic `anyref` and `externref` in val.h: `eqref`, `structref`,+ * and `arrayref`.+ */++#ifndef WASMTIME_GC_H+#define WASMTIME_GC_H++#include <wasmtime/val.h>++#ifdef __cplusplus+extern "C" {+#endif++/**+ * \typedef wasmtime_eqref_t+ * \brief Convenience alias for #wasmtime_eqref+ *+ * \struct wasmtime_eqref+ * \brief A WebAssembly `eqref` value.+ *+ * This structure represents a reference to a GC object that can be tested for+ * equality. The subtypes of `eqref` include `structref`, `arrayref`, and+ * `i31ref`.+ *+ * This type has the same representation and ownership semantics as+ * #wasmtime_anyref_t. Values must be explicitly unrooted via+ * #wasmtime_eqref_unroot to enable garbage collection.+ */+typedef struct wasmtime_eqref {+ /// Internal metadata tracking within the store, embedders should not+ /// configure or modify these fields.+ uint64_t store_id;+ /// Internal to Wasmtime.+ uint32_t __private1;+ /// Internal to Wasmtime.+ uint32_t __private2;+ /// Internal to Wasmtime.+ void *__private3;+} wasmtime_eqref_t;++/// \brief Initialize the `ref` to a null `eqref` value.+static inline void wasmtime_eqref_set_null(wasmtime_eqref_t *ref) {+ ref->store_id = 0;+}++/// \brief Returns whether the provided `ref` is a null `eqref` value.+static inline bool wasmtime_eqref_is_null(const wasmtime_eqref_t *ref) {+ return ref->store_id == 0;+}++/**+ * \brief Clone an `eqref`, creating a new root.+ *+ * The cloned reference is stored in `out`.+ */+WASM_API_EXTERN void wasmtime_eqref_clone(const wasmtime_eqref_t *eqref,+ wasmtime_eqref_t *out);++/**+ * \brief Unroot an `eqref` to allow garbage collection.+ *+ * After calling this, `ref` is left in an undefined state and should not be+ * used again.+ */+WASM_API_EXTERN void wasmtime_eqref_unroot(wasmtime_eqref_t *ref);++/**+ * \brief Upcast an `eqref` to an `anyref`.+ *+ * The original `eqref` is not consumed; `out` receives a new cloned root+ * pointing to the same GC object as `anyref`.+ */+WASM_API_EXTERN void wasmtime_eqref_to_anyref(const wasmtime_eqref_t *eqref,+ wasmtime_anyref_t *out);++/**+ * \brief Create a new `i31ref` value.+ *+ * Creates a new `i31ref` value (which is a subtype of `eqref`) and returns a+ * pointer to it.+ *+ * If `i31val` does not fit in 31 bits, it is wrapped.+ */+WASM_API_EXTERN void wasmtime_eqref_from_i31(wasmtime_context_t *context,+ uint32_t i31val,+ wasmtime_eqref_t *out);++/**+ * \brief Test whether this `eqref` is an `i31ref`.+ *+ * Returns `true` if the given `eqref` is an `i31ref`, `false` otherwise.+ * Returns `false` for null references.+ */+WASM_API_EXTERN bool wasmtime_eqref_is_i31(wasmtime_context_t *context,+ const wasmtime_eqref_t *eqref);++/**+ * \brief Get the `eqref`'s underlying `i31ref` value, zero extended.+ *+ * If the given `eqref` is an instance of `i31ref`, then its value is zero+ * extended to 32 bits, written to `dst`, and `true` is returned.+ *+ * If the given `eqref` is not an instance of `i31ref`, then `false` is+ * returned and `dst` is left unmodified.+ */+WASM_API_EXTERN bool wasmtime_eqref_i31_get_u(wasmtime_context_t *context,+ const wasmtime_eqref_t *eqref,+ uint32_t *dst);++/**+ * \brief Get the `eqref`'s underlying `i31ref` value, sign extended.+ *+ * If the given `eqref` is an instance of `i31ref`, then its value is sign+ * extended to 32 bits, written to `dst`, and `true` is returned.+ *+ * If the given `eqref` is not an instance of `i31ref`, then `false` is+ * returned and `dst` is left unmodified.+ */+WASM_API_EXTERN bool wasmtime_eqref_i31_get_s(wasmtime_context_t *context,+ const wasmtime_eqref_t *eqref,+ int32_t *dst);++#ifdef __cplusplus+} // extern "C"+#endif++#endif // WASMTIME_GC_Hdiff --git a/crates/c-api/include/wasmtime/gc.hh b/crates/c-api/include/wasmtime/gc.hhnew file mode 100644index 0000000000..e404f471ad--- /dev/null+++ b/crates/c-api/include/wasmtime/gc.hh@@ -0,0 +1,100 @@+/**+ * \file wasmtime/gc.hh+ *+ * C++ API for WebAssembly GC types: eqref, structref, and arrayref.+ */++#ifndef WASMTIME_GC_HH+#define WASMTIME_GC_HH++#include <wasmtime/gc.h>+#include <wasmtime/val.hh>++namespace wasmtime {++/**+ * \brief Representation of a WebAssembly `eqref` value.+ *+ * An `eqref` is a reference to a GC object that supports equality testing.+ * Subtypes include `structref`, `arrayref`, and `i31ref`.+ *+ * Like all GC references, `EqRef` values are rooted in a `Store` and must be+ * unrooted (by destruction or move) to allow garbage collection.+ */+class EqRef {+ friend class Val;+ friend class AnyRef;++ wasmtime_eqref_t val;++public:+ /// Creates a new `EqRef` from its C-API representation.+ explicit EqRef(wasmtime_eqref_t val) : val(val) {}++ /// Copy constructor.+ EqRef(const EqRef &other) { wasmtime_eqref_clone(&other.val, &val); }++ /// Copy assignment.+ EqRef &operator=(const EqRef &other) {+ wasmtime_eqref_unroot(&val);+ wasmtime_eqref_clone(&other.val, &val);+ return *this;+ }++ /// Move constructor.+ EqRef(EqRef &&other) {+ val = other.val;+ wasmtime_eqref_set_null(&other.val);+ }++ /// Move assignment.+ EqRef &operator=(EqRef &&other) {+ wasmtime_eqref_unroot(&val);+ val = other.val;+ wasmtime_eqref_set_null(&other.val);+ return *this;+ }++ ~EqRef() { wasmtime_eqref_unroot(&val); }++ /// Create an `eqref` from an i31 value.+ static EqRef from_i31(Store::Context cx, uint32_t val) {+ wasmtime_eqref_t out;+ wasmtime_eqref_from_i31(cx.capi(), val, &out);+ return EqRef(out);+ }++ /// Returns `true` if this eqref is an i31ref.+ bool is_i31(Store::Context cx) const {+ return wasmtime_eqref_is_i31(cx.capi(), &val);+ }++ /// Get the i31 value as an unsigned 32-bit integer.+ /// Returns `std::nullopt` if this eqref is not an i31ref.+ std::optional<uint32_t> i31_get_u(Store::Context cx) const {+ uint32_t dst;+ if (wasmtime_eqref_i31_get_u(cx.capi(), &val, &dst))+ return dst;+ return std::nullopt;+ }++ /// Get the i31 value as a signed 32-bit integer.+ /// Returns `std::nullopt` if this eqref is not an i31ref.+ std::optional<int32_t> i31_get_s(Store::Context cx) const {+ int32_t dst;+ if (wasmtime_eqref_i31_get_s(cx.capi(), &val, &dst))+ return dst;+ return std::nullopt;+ }++ /// Upcast this `eqref` to an `anyref`.+ AnyRef to_anyref() const {+ wasmtime_anyref_t out;+ wasmtime_eqref_to_anyref(&val, &out);+ return AnyRef(out);+ }+};++} // namespace wasmtime++#endif // WASMTIME_GC_HHdiff --git a/crates/c-api/include/wasmtime/store.hh b/crates/c-api/include/wasmtime/store.hhindex bffd7fc632..4cad54b39e 100644--- a/crates/c-api/include/wasmtime/store.hh+++ b/crates/c-api/include/wasmtime/store.hh@@ -75,6 +75,7 @@ public:friend class Linker;friend class ExternRef;friend class AnyRef;+ friend class EqRef;friend class Val;friend class Store;friend class Tag;diff --git a/crates/c-api/include/wasmtime/val.h b/crates/c-api/include/wasmtime/val.hindex e1de440ff5..bb4cfa993c 100644--- a/crates/c-api/include/wasmtime/val.h+++ b/crates/c-api/include/wasmtime/val.h@@ -15,6 +15,10 @@extern "C" {#endif+struct wasmtime_eqref;+/// Convenience alias for #wasmtime_eqref+typedef struct wasmtime_eqref wasmtime_eqref_t;+/*** \typedef wasmtime_anyref_t* \brief Convenience alias for #wasmtime_anyref@@ -77,6 +81,19 @@ static inline bool wasmtime_anyref_is_null(const wasmtime_anyref_t *ref) {WASM_API_EXTERN void wasmtime_anyref_clone(const wasmtime_anyref_t *anyref,wasmtime_anyref_t *out);+/**+ * \brief Downcast an `anyref` to an `eqyref`.+ *+ * Returns `true` if the downcast succeeded, and `out` is initialized. Returns+ * `false` if the downcast failed, and `out` is left uninitialized.+ *+ * The original `anyref` is not consumed; `out` receives a new cloned root+ * pointing to the same GC object as `anyref`.+ */+WASM_API_EXTERN bool wasmtime_anyref_to_eqref(wasmtime_context_t *context,+ const wasmtime_anyref_t *anyref,+ wasmtime_eqref_t *out);+/*** \brief Unroots the `ref` provided within the `context`.*@@ -128,6 +145,15 @@ WASM_API_EXTERN void wasmtime_anyref_from_i31(wasmtime_context_t *context,uint32_t i31val,wasmtime_anyref_t *out);+/**+ * \brief Test whether an `anyref` is an `i31ref`.+ *+ * Returns `true` if the given `anyref` is an `i31ref`, `false` otherwise.+ * Returns `false` for null references.+ */+WASM_API_EXTERN bool wasmtime_anyref_is_i31(wasmtime_context_t *context,+ const wasmtime_anyref_t *anyref);+/*** \brief Get the `anyref`'s underlying `i31ref` value, zero extended, if any.*diff --git a/crates/c-api/include/wasmtime/val.hh b/crates/c-api/include/wasmtime/val.hhindex bca399085b..b93e10af5e 100644--- a/crates/c-api/include/wasmtime/val.hh+++ b/crates/c-api/include/wasmtime/val.hh@@ -6,6 +6,7 @@#define WASMTIME_VAL_HH#include <optional>+#include <wasmtime/gc.h>#include <wasmtime/store.hh>#include <wasmtime/types/val.hh>#include <wasmtime/val.h>@@ -99,6 +100,8 @@ public:}};+class EqRef;+/*** \brief Representation of a WebAssembly `anyref` value.*/@@ -173,6 +176,11 @@ public:return ret;return std::nullopt;}++ /// \brief Returns `true` if this anyref is an i31ref.+ bool is_i31(Store::Context cx) const {+ return wasmtime_anyref_is_i31(cx.ptr, &val);+ }};/// \brief Container for the `v128` WebAssembly type.diff --git a/crates/c-api/src/ref.rs b/crates/c-api/src/ref.rsindex a6dea92071..d72631b462 100644--- a/crates/c-api/src/ref.rs+++ b/crates/c-api/src/ref.rs@@ -1,7 +1,7 @@use crate::{WasmtimeStoreContextMut, abort};use std::mem::{ManuallyDrop, MaybeUninit};use std::{num::NonZeroU64, os::raw::c_void, ptr};-use wasmtime::{AnyRef, ExnRef, ExternRef, I31, OwnedRooted, Ref, RootScope, Val};+use wasmtime::{AnyRef, EqRef, ExnRef, ExternRef, I31, OwnedRooted, Ref, RootScope, Val};/// `*mut wasm_ref_t` is a reference type (`externref` or `funcref`), as seen by/// the C API. Because we do not have a uniform representation for `funcref`s@@ -247,6 +247,12 @@ macro_rules! ref_wrapper {}}+ impl From<OwnedRooted<$wasmtime>> for $c {+ fn from(rooted: OwnedRooted<$wasmtime>) -> $c {+ Self::from(Some(rooted))+ }+ }+// SAFETY: The `*const ()` comes from (and is converted back// into) an `Arc<()>`, and is only accessed as such, so this// type is both Send and Sync. These constraints are necessary@@ -258,6 +264,7 @@ macro_rules! ref_wrapper {ref_wrapper!(AnyRef => wasmtime_anyref_t);ref_wrapper!(ExternRef => wasmtime_externref_t);+ref_wrapper!(EqRef => wasmtime_eqref_t);ref_wrapper!(ExnRef => wasmtime_exnref_t);#[unsafe(no_mangle)]@@ -312,6 +319,17 @@ pub extern "C" fn wasmtime_anyref_from_i31(crate::initialize(out, Some(anyref).into())}+#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_anyref_is_i31(+ cx: WasmtimeStoreContextMut<'_>,+ anyref: Option<&wasmtime_anyref_t>,+) -> bool {+ match anyref.and_then(|a| a.as_wasmtime()) {+ Some(anyref) => anyref.is_i31(&cx).expect("OwnedRooted always in scope"),+ None => false,+ }+}+#[unsafe(no_mangle)]pub unsafe extern "C" fn wasmtime_anyref_i31_get_u(cx: WasmtimeStoreContextMut<'_>,@@ -440,3 +458,85 @@ pub unsafe extern "C" fn wasmtime_exnref_unroot(val: Option<&mut ManuallyDrop<wa}}}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_eqref_clone(+ eqref: Option<&wasmtime_eqref_t>,+ out: &mut MaybeUninit<wasmtime_eqref_t>,+) {+ let eqref = eqref.and_then(|e| e.as_wasmtime());+ crate::initialize(out, eqref.into());+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_eqref_unroot(val: Option<&mut ManuallyDrop<wasmtime_eqref_t>>) {+ if let Some(val) = val {+ unsafe {+ ManuallyDrop::drop(val);+ }+ }+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_eqref_to_anyref(+ eqref: Option<&wasmtime_eqref_t>,+ out: &mut MaybeUninit<wasmtime_anyref_t>,+) {+ let anyref = eqref.and_then(|e| e.as_wasmtime()).map(|e| e.to_anyref());+ crate::initialize(out, anyref.into());+}++#[unsafe(no_mangle)]+pub extern "C" fn wasmtime_eqref_from_i31(+ cx: WasmtimeStoreContextMut<'_>,+ val: u32,+ out: &mut MaybeUninit<wasmtime_eqref_t>,+) {+ let mut scope = RootScope::new(cx);+ let eqref = EqRef::from_i31(&mut scope, I31::wrapping_u32(val));+ let eqref = eqref.to_owned_rooted(&mut scope).expect("in scope");+ crate::initialize(out, Some(eqref).into())+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_eqref_is_i31(+ cx: WasmtimeStoreContextMut<'_>,+ eqref: Option<&wasmtime_eqref_t>,+) -> bool {+ match eqref.and_then(|e| e.as_wasmtime()) {+ Some(eqref) => eqref.is_i31(&cx).expect("OwnedRooted always in scope"),+ None => false,+ }+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_eqref_i31_get_u(+ cx: WasmtimeStoreContextMut<'_>,+ eqref: Option<&wasmtime_eqref_t>,+ dst: &mut MaybeUninit<u32>,+) -> bool {+ let mut scope = RootScope::new(cx);+ if let Some(eqref) = eqref.and_then(|e| e.as_wasmtime()) {+ if let Some(val) = eqref.as_i31(&mut scope).expect("in scope") {+ crate::initialize(dst, val.get_u32());+ return true;+ }+ }+ false+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_eqref_i31_get_s(+ cx: WasmtimeStoreContextMut<'_>,+ eqref: Option<&wasmtime_eqref_t>,+ dst: &mut MaybeUninit<i32>,+) -> bool {+ let mut scope = RootScope::new(cx);+ if let Some(eqref) = eqref.and_then(|e| e.as_wasmtime()) {+ if let Some(val) = eqref.as_i31(&mut scope).expect("in scope") {+ crate::initialize(dst, val.get_i32());+ return true;+ }+ }+ false+}diff --git a/crates/c-api/tests/CMakeLists.txt b/crates/c-api/tests/CMakeLists.txtindex 81fa7b004b..6e8a6b0b70 100644--- a/crates/c-api/tests/CMakeLists.txt+++ b/crates/c-api/tests/CMakeLists.txt@@ -49,6 +49,7 @@ add_capi_test(tests FILESwasi.ccstore.ccval.cc+ gc.cctable.ccglobal.ccmemory.ccdiff --git a/crates/c-api/tests/gc.cc b/crates/c-api/tests/gc.ccnew file mode 100644index 0000000000..aa5b4233ee--- /dev/null+++ b/crates/c-api/tests/gc.cc@@ -0,0 +1,92 @@+#include <wasmtime/gc.hh>++#include <gtest/gtest.h>+#include <wasmtime.hh>++using namespace wasmtime;++TEST(EqRef, CopyAndMove) {+ Config config;+ config.wasm_gc(true);+ Engine engine(std::move(config));+ Store store(engine);++ auto cx = store.context();++ // Create an i31 eqref.+ EqRef eq = EqRef::from_i31(cx, 42);+ EXPECT_TRUE(eq.is_i31(cx));++ // Copy constructor+ EqRef eq2(eq);++ // Move constructor+ EqRef eq3(std::move(eq2));++ // Copy assignment+ EqRef eq4 = eq3;++ // Move assignment+ EqRef eq5 = std::move(eq4);++ // Upcast to anyref and check value+ AnyRef upcast = eq.to_anyref();+ auto val = upcast.u31(cx);+ ASSERT_TRUE(val.has_value());+ EXPECT_EQ(*val, 42u);+}++TEST(EqRef, NullEqRef) {+ wasmtime_eqref_t raw;+ wasmtime_eqref_set_null(&raw);+ EXPECT_TRUE(wasmtime_eqref_is_null(&raw));++ // Upcast null eqref to anyref via C API+ wasmtime_anyref_t out;+ wasmtime_eqref_to_anyref(&raw, &out);+ EXPECT_TRUE(wasmtime_anyref_is_null(&out));+}++TEST(I31Ref, CreateAndRead) {+ Config config;+ config.wasm_gc(true);+ Engine engine(std::move(config));+ Store store(engine);+ auto cx = store.context();++ // Create an i31 eqref+ EqRef eq = EqRef::from_i31(cx, 42);+ EXPECT_TRUE(eq.is_i31(cx));++ // Read unsigned+ auto u = eq.i31_get_u(cx);+ ASSERT_TRUE(u.has_value());+ EXPECT_EQ(*u, 42u);++ // Read signed (positive value)+ auto s = eq.i31_get_s(cx);+ ASSERT_TRUE(s.has_value());+ EXPECT_EQ(*s, 42);++ // Upcast to anyref and check is_i31+ AnyRef any = eq.to_anyref();+ EXPECT_TRUE(any.is_i31(cx));+}++TEST(I31Ref, SignedValues) {+ Config config;+ config.wasm_gc(true);+ Engine engine(std::move(config));+ Store store(engine);+ auto cx = store.context();++ // i31 wraps to 31 bits. 0x7FFFFFFF (all 31 bits set) should give -1 signed.+ EqRef eq = EqRef::from_i31(cx, 0x7FFFFFFF);+ auto u = eq.i31_get_u(cx);+ ASSERT_TRUE(u.has_value());+ EXPECT_EQ(*u, 0x7FFFFFFFu);++ auto s = eq.i31_get_s(cx);+ ASSERT_TRUE(s.has_value());+ EXPECT_EQ(*s, -1);+}diff --git a/crates/wasmtime/src/runtime/gc/enabled/anyref.rs b/crates/wasmtime/src/runtime/gc/enabled/anyref.rsindex 561cb6fbef..497e595397 100644--- a/crates/wasmtime/src/runtime/gc/enabled/anyref.rs+++ b/crates/wasmtime/src/runtime/gc/enabled/anyref.rs@@ -453,13 +453,16 @@ impl AnyRef {/// # Panics////// Panics if this reference is associated with a different store.- pub fn as_eqref(&self, store: impl AsContext) -> Result<Option<Rooted<EqRef>>> {- self._as_eqref(store.as_context().0)+ pub fn as_eqref(&self, mut store: impl AsContextMut) -> Result<Option<Rooted<EqRef>>> {+ self._as_eqref(store.as_context_mut().0)}- pub(crate) fn _as_eqref(&self, store: &StoreOpaque) -> Result<Option<Rooted<EqRef>>> {+ pub(crate) fn _as_eqref(&self, store: &mut StoreOpaque) -> Result<Option<Rooted<EqRef>>> {if self._is_eqref(store)? {- Ok(Some(Rooted::from_gc_root_index(self.inner)))+ let gc_ref = self.inner.try_gc_ref(store)?.unchecked_copy();+ let gc_ref = store.clone_gc_ref(&gc_ref);+ let mut store = AutoAssertNoGc::new(store);+ Ok(Some(Rooted::new(&mut store, gc_ref)))} else {Ok(None)}@@ -476,11 +479,11 @@ impl AnyRef {////// Panics if this reference is associated with a different store, or if/// this `anyref` is not an `eqref`.- pub fn unwrap_eqref(&self, store: impl AsContext) -> Result<Rooted<EqRef>> {- self._unwrap_eqref(store.as_context().0)+ pub fn unwrap_eqref(&self, mut store: impl AsContextMut) -> Result<Rooted<EqRef>> {+ self._unwrap_eqref(store.as_context_mut().0)}- pub(crate) fn _unwrap_eqref(&self, store: &StoreOpaque) -> Result<Rooted<EqRef>> {+ pub(crate) fn _unwrap_eqref(&self, store: &mut StoreOpaque) -> Result<Rooted<EqRef>> {Ok(self._as_eqref(store)?.expect("AnyRef::unwrap_eqref on non-eqref"))