A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Fix externref/anyref ownership in C/C++ API (#11799)
Alex Crichtonadff9d9d0f09
diff --git a/crates/c-api/include/wasmtime/error.hh b/crates/c-api/include/wasmtime/error.hhindex 7a7c83e267..2d89fc6bad 100644--- a/crates/c-api/include/wasmtime/error.hh+++ b/crates/c-api/include/wasmtime/error.hh@@ -102,6 +102,16 @@ public:/// \brief Returns the success, if present, aborts if this is an error.const T &&ok() const { return std::get<T>(std::move(data)); }+ /// \brief Returns the success, if present, aborts if this is an error.+ T &ok_ref() { return std::get<T>(data); }+ /// \brief Returns the success, if present, aborts if this is an error.+ const T &ok_ref() const { return std::get<T>(data); }++ /// \brief Returns the error, if present, aborts if this is not an error.+ E &err_ref() { return std::get<T>(data); }+ /// \brief Returns the error, if present, aborts if this is not an error.+ const E &err_ref() const { return std::get<T>(data); }+/// \brief Returns the success, if present, aborts if this is an error.T unwrap() {if (*this) {diff --git a/crates/c-api/include/wasmtime/func.hh b/crates/c-api/include/wasmtime/func.hhindex 29ef2b6323..4de28a153d 100644--- a/crates/c-api/include/wasmtime/func.hh+++ b/crates/c-api/include/wasmtime/func.hh@@ -86,10 +86,18 @@ NATIVE_WASM_TYPE(double, F64, f64)template <> struct WasmType<std::optional<ExternRef>> {static const bool valid = true;static const ValKind kind = ValKind::ExternRef;+ static void store(Store::Context cx, wasmtime_val_raw_t *p,+ std::optional<ExternRef> &&ref) {+ if (ref) {+ p->externref = ref->take_raw(cx);+ } else {+ p->externref = 0;+ }+ }static void store(Store::Context cx, wasmtime_val_raw_t *p,const std::optional<ExternRef> &ref) {if (ref) {- p->externref = wasmtime_externref_to_raw(cx.raw_context(), ref->raw());+ p->externref = ref->borrow_raw(cx);} else {p->externref = 0;}@@ -129,6 +137,9 @@ template <typename T> struct WasmTypeList {static bool matches(ValType::ListRef types) {return WasmTypeList<std::tuple<T>>::matches(types);}+ static void store(Store::Context cx, wasmtime_val_raw_t *storage, T &&t) {+ WasmType<T>::store(cx, storage, t);+ }static void store(Store::Context cx, wasmtime_val_raw_t *storage,const T &t) {WasmType<T>::store(cx, storage, t);@@ -169,6 +180,15 @@ template <typename... T> struct WasmTypeList<std::tuple<T...>> {size_t n = 0;return ((WasmType<T>::kind == types.begin()[n++].kind()) && ...);}+ static void store(Store::Context cx, wasmtime_val_raw_t *storage,+ std::tuple<T...> &&t) {+ size_t n = 0;+ std::apply(+ [&](auto &...val) {+ (WasmType<T>::store(cx, &storage[n++], val), ...); // NOLINT+ },+ t);+ }static void store(Store::Context cx, wasmtime_val_raw_t *storage,const std::tuple<T...> &t) {size_t n = 0;@@ -589,7 +609,7 @@ public:* Note that this function still may return a `Trap` indicating that calling* the WebAssembly function failed.*/- TrapResult<Results> call(Store::Context cx, Params params) const {+ TrapResult<Results> call(Store::Context cx, const Params ¶ms) const {std::array<wasmtime_val_raw_t, std::max(WasmTypeList<Params>::size,WasmTypeList<Results>::size)>storage;diff --git a/crates/c-api/include/wasmtime/store.hh b/crates/c-api/include/wasmtime/store.hhindex 0d4a5fbfd9..00ae9b865b 100644--- a/crates/c-api/include/wasmtime/store.hh+++ b/crates/c-api/include/wasmtime/store.hh@@ -191,6 +191,10 @@ public:/// Explicit function to acquire a `Context` from this store.Context context() { return this; }++ /// Runs a garbage collection pass in the referenced store to collect loose+ /// GC-managed objects, if any are available.+ void gc() { context().gc(); }};} // namespace wasmtimediff --git a/crates/c-api/include/wasmtime/val.h b/crates/c-api/include/wasmtime/val.hindex 4c1af27a5c..9d7e2aea94 100644--- a/crates/c-api/include/wasmtime/val.h+++ b/crates/c-api/include/wasmtime/val.h@@ -74,8 +74,7 @@ static inline bool wasmtime_anyref_is_null(const wasmtime_anyref_t *ref) {** The returned reference is stored in `out`.*/-WASM_API_EXTERN void wasmtime_anyref_clone(wasmtime_context_t *context,- const wasmtime_anyref_t *anyref,+WASM_API_EXTERN void wasmtime_anyref_clone(const wasmtime_anyref_t *anyref,wasmtime_anyref_t *out);/**@@ -91,8 +90,7 @@ WASM_API_EXTERN void wasmtime_anyref_clone(wasmtime_context_t *context,* Note that null or i32 anyref values do not need to be unrooted but are still* valid to pass to this function.*/-WASM_API_EXTERN void wasmtime_anyref_unroot(wasmtime_context_t *context,- wasmtime_anyref_t *ref);+WASM_API_EXTERN void wasmtime_anyref_unroot(wasmtime_anyref_t *ref);/*** \brief Converts a raw `anyref` value coming from #wasmtime_val_raw_t into@@ -250,8 +248,7 @@ WASM_API_EXTERN void *wasmtime_externref_data(wasmtime_context_t *context,* eventually be unrooted with #wasmtime_externref_unroot in the future to* enable GC'ing it.*/-WASM_API_EXTERN void wasmtime_externref_clone(wasmtime_context_t *context,- const wasmtime_externref_t *ref,+WASM_API_EXTERN void wasmtime_externref_clone(const wasmtime_externref_t *ref,wasmtime_externref_t *out);/**@@ -265,8 +262,7 @@ WASM_API_EXTERN void wasmtime_externref_clone(wasmtime_context_t *context,* Note that null externref values do not need to be unrooted but are still* valid to pass to this function.*/-WASM_API_EXTERN void wasmtime_externref_unroot(wasmtime_context_t *context,- wasmtime_externref_t *ref);+WASM_API_EXTERN void wasmtime_externref_unroot(wasmtime_externref_t *ref);/*** \brief Converts a raw `externref` value coming from #wasmtime_val_raw_t into@@ -475,8 +471,7 @@ typedef struct wasmtime_val {* This method does not need to be called for integers, floats, v128, or* funcref values.*/-WASM_API_EXTERN void wasmtime_val_unroot(wasmtime_context_t *context,- wasmtime_val_t *val);+WASM_API_EXTERN void wasmtime_val_unroot(wasmtime_val_t *val);/*** \brief Clones the value pointed to by `src` into the `dst` provided.@@ -485,8 +480,7 @@ WASM_API_EXTERN void wasmtime_val_unroot(wasmtime_context_t *context,* newly rooted inside of `dst`. When using this API the `dst` should be* later unrooted with #wasmtime_val_unroot if it contains GC values.*/-WASM_API_EXTERN void wasmtime_val_clone(wasmtime_context_t *context,- const wasmtime_val_t *src,+WASM_API_EXTERN void wasmtime_val_clone(const wasmtime_val_t *src,wasmtime_val_t *dst);#ifdef __cplusplusdiff --git a/crates/c-api/include/wasmtime/val.hh b/crates/c-api/include/wasmtime/val.hhindex 1f029f23e2..6e0b692e95 100644--- a/crates/c-api/include/wasmtime/val.hh+++ b/crates/c-api/include/wasmtime/val.hh@@ -38,13 +38,41 @@ public:/// Creates a new `ExternRef` directly from its C-API representation.explicit ExternRef(wasmtime_externref_t val) : val(val) {}+ /// Copy constructor to clone `other`.+ ExternRef(const ExternRef &other) {+ wasmtime_externref_clone(&other.val, &val);+ }++ /// Copy assignment to clone from `other`.+ ExternRef &operator=(const ExternRef &other) {+ wasmtime_externref_unroot(&val);+ wasmtime_externref_clone(&other.val, &val);+ return *this;+ }++ /// Move constructor to move the contents of `other`.+ ExternRef(ExternRef &&other) {+ val = other.val;+ wasmtime_externref_set_null(&other.val);+ }++ /// Move assignment to move the contents of `other`.+ ExternRef &operator=(ExternRef &&other) {+ wasmtime_externref_unroot(&val);+ val = other.val;+ wasmtime_externref_set_null(&other.val);+ return *this;+ }++ ~ExternRef() { wasmtime_externref_unroot(&val); }+/// Creates a new `externref` value from the provided argument.////// Note that `val` should be safe to send across threads and should own any/// memory that it points to. Also note that `ExternRef` is similar to a/// `std::shared_ptr` in that there can be many references to the same value.- template <typename T> explicit ExternRef(Store::Context cx, T val) {- void *ptr = std::make_unique<std::any>(std::move(val)).release();+ explicit ExternRef(Store::Context cx, std::any val) {+ void *ptr = std::make_unique<std::any>(val).release();bool ok = wasmtime_externref_new(cx.ptr, ptr, finalizer, &this->val);if (!ok) {fprintf(stderr, "failed to allocate a new externref");@@ -52,26 +80,23 @@ public:}}- /// Creates a new `ExternRef` which is separately rooted from this one.- ExternRef clone(Store::Context cx) {- wasmtime_externref_t other;- wasmtime_externref_clone(cx.ptr, &val, &other);- return ExternRef(other);- }-/// Returns the underlying host data associated with this `ExternRef`.std::any &data(Store::Context cx) {return *static_cast<std::any *>(wasmtime_externref_data(cx.ptr, &val));}- /// Unroots this value from the context provided, enabling a future GC to- /// collect the internal object if there are no more references.- void unroot(Store::Context cx) { wasmtime_externref_unroot(cx.ptr, &val); }+ /// Consumes ownership of the underlying `wasmtime_externref_t` and returns+ /// the result of `wasmtime_externref_to_raw`.+ uint32_t take_raw(Store::Context cx) {+ uint32_t ret = wasmtime_externref_to_raw(cx.raw_context(), &val);+ wasmtime_externref_set_null(&val);+ return ret;+ }- /// Returns the raw underlying C API value.- ///- /// This class still retains ownership of the pointer.- const wasmtime_externref_t *raw() const { return &val; }+ /// Returns `wasmtime_externref_to_raw`.+ uint32_t borrow_raw(Store::Context cx) const {+ return wasmtime_externref_to_raw(cx.raw_context(), &val);+ }};/**@@ -86,6 +111,32 @@ public:/// Creates a new `AnyRef` directly from its C-API representation.explicit AnyRef(wasmtime_anyref_t val) : val(val) {}+ /// Copy constructor to clone `other`.+ AnyRef(const AnyRef &other) { wasmtime_anyref_clone(&other.val, &val); }++ /// Copy assignment to clone from `other`.+ AnyRef &operator=(const AnyRef &other) {+ wasmtime_anyref_unroot(&val);+ wasmtime_anyref_clone(&other.val, &val);+ return *this;+ }++ /// Move constructor to move the contents of `other`.+ AnyRef(AnyRef &&other) {+ val = other.val;+ wasmtime_anyref_set_null(&other.val);+ }++ /// Move assignment to move the contents of `other`.+ AnyRef &operator=(AnyRef &&other) {+ wasmtime_anyref_unroot(&val);+ val = other.val;+ wasmtime_anyref_set_null(&other.val);+ return *this;+ }++ ~AnyRef() { wasmtime_anyref_unroot(&val); }+/// Creates a new `AnyRef` which is an `i31` with the given `value`,/// truncated if the upper bit is set.static AnyRef i31(Store::Context cx, uint32_t value) {@@ -94,21 +145,18 @@ public:return AnyRef(other);}- /// Creates a new `AnyRef` which is separately rooted from this one.- AnyRef clone(Store::Context cx) {- wasmtime_anyref_t other;- wasmtime_anyref_clone(cx.ptr, &val, &other);- return AnyRef(other);+ /// Consumes ownership of the underlying `wasmtime_anyref_t` and returns the+ /// result of `wasmtime_anyref_to_raw`.+ uint32_t take_raw(Store::Context cx) {+ uint32_t ret = wasmtime_anyref_to_raw(cx.raw_context(), &val);+ wasmtime_anyref_set_null(&val);+ return ret;}- /// Unroots this value from the context provided, enabling a future GC to- /// collect the internal object if there are no more references.- void unroot(Store::Context cx) { wasmtime_anyref_unroot(cx.ptr, &val); }-- /// Returns the raw underlying C API value.- ///- /// This class still retains ownership of the pointer.- const wasmtime_anyref_t *raw() const { return &val; }+ /// Returns `wasmtime_anyref_to_raw`.+ uint32_t borrow_raw(Store::Context cx) const {+ return wasmtime_anyref_to_raw(cx.raw_context(), &val);+ }/// \brief If this is an `i31`, get the value zero-extended.std::optional<uint32_t> u31(Store::Context cx) const {@@ -201,6 +249,7 @@ public:val.kind = WASMTIME_EXTERNREF;if (ptr) {val.of.externref = ptr->val;+ wasmtime_externref_set_null(&ptr->val);} else {wasmtime_externref_set_null(&val.of.externref);}@@ -210,6 +259,7 @@ public:val.kind = WASMTIME_ANYREF;if (ptr) {val.of.anyref = ptr->val;+ wasmtime_anyref_set_null(&ptr->val);} else {wasmtime_anyref_set_null(&val.of.anyref);}@@ -221,6 +271,35 @@ public:/// any`.Val(AnyRef ptr);+ /// Copy constructor to clone `other`.+ Val(const Val &other) { wasmtime_val_clone(&other.val, &val); }++ /// Copy assignment to clone from `other`.+ Val &operator=(const Val &other) {+ wasmtime_val_unroot(&val);+ wasmtime_val_clone(&other.val, &val);+ return *this;+ }++ /// Move constructor to move the contents of `other`.+ Val(Val &&other) {+ val = other.val;+ other.val.kind = WASMTIME_I32;+ other.val.of.i32 = 0;+ }++ /// Move assignment to move the contents of `other`.+ Val &operator=(Val &&other) {+ wasmtime_val_unroot(&val);+ val = other.val;+ other.val.kind = WASMTIME_I32;+ other.val.of.i32 = 0;+ return *this;+ }++ /// Unroots the values in `val`, if any.+ ~Val() { wasmtime_val_unroot(&val); }+/// Returns the kind of value that this value has.ValKind kind() const {switch (val.kind) {@@ -294,7 +373,7 @@ public:////// Note that `externref` is a nullable reference, hence the `optional` return/// value.- std::optional<ExternRef> externref(Store::Context cx) const {+ std::optional<ExternRef> externref() const {if (val.kind != WASMTIME_EXTERNREF) {std::abort();}@@ -302,7 +381,7 @@ public:return std::nullopt;}wasmtime_externref_t other;- wasmtime_externref_clone(cx.ptr, &val.of.externref, &other);+ wasmtime_externref_clone(&val.of.externref, &other);return ExternRef(other);}@@ -311,7 +390,7 @@ public:////// Note that `anyref` is a nullable reference, hence the `optional` return/// value.- std::optional<AnyRef> anyref(Store::Context cx) const {+ std::optional<AnyRef> anyref() const {if (val.kind != WASMTIME_ANYREF) {std::abort();}@@ -319,7 +398,7 @@ public:return std::nullopt;}wasmtime_anyref_t other;- wasmtime_anyref_clone(cx.ptr, &val.of.anyref, &other);+ wasmtime_anyref_clone(&val.of.anyref, &other);return AnyRef(other);}@@ -329,9 +408,6 @@ public:/// Note that `funcref` is a nullable reference, hence the `optional` return/// value.std::optional<Func> funcref() const;-- /// Unroots any GC references this `Val` points to within the `cx` provided.- void unroot(Store::Context cx) { wasmtime_val_unroot(cx.ptr, &val); }};} // namespace wasmtimediff --git a/crates/c-api/src/ref.rs b/crates/c-api/src/ref.rsindex e3a5b52d65..b890f03c74 100644--- a/crates/c-api/src/ref.rs+++ b/crates/c-api/src/ref.rs@@ -1,5 +1,6 @@use crate::{WasmtimeStoreContextMut, abort};-use std::{mem::MaybeUninit, num::NonZeroU64, os::raw::c_void, ptr};+use std::mem::{ManuallyDrop, MaybeUninit};+use std::{num::NonZeroU64, os::raw::c_void, ptr};use wasmtime::{AnyRef, ExternRef, I31, OwnedRooted, Ref, RootScope, Val};/// `*mut wasm_ref_t` is a reference type (`externref` or `funcref`), as seen by@@ -207,7 +208,11 @@ macro_rules! ref_wrapper {))}- pub unsafe fn from_wasmtime(self) -> Option<OwnedRooted<$wasmtime>> {+ pub unsafe fn into_wasmtime(self) -> Option<OwnedRooted<$wasmtime>> {+ ManuallyDrop::new(self).to_owned()+ }++ unsafe fn to_owned(&self) -> Option<OwnedRooted<$wasmtime>> {let store_id = NonZeroU64::new(self.store_id)?;Some(OwnedRooted::from_owned_raw_parts_for_c_api(store_id, self.a, self.b, self.c,@@ -215,6 +220,14 @@ macro_rules! ref_wrapper {}}+ impl Drop for $c {+ fn drop(&mut self) {+ unsafe {+ let _ = self.to_owned();+ }+ }+ }+impl From<Option<OwnedRooted<$wasmtime>>> for $c {fn from(rooted: Option<OwnedRooted<$wasmtime>>) -> $c {let mut ret = $c {@@ -248,7 +261,6 @@ ref_wrapper!(ExternRef => wasmtime_externref_t);#[unsafe(no_mangle)]pub unsafe extern "C" fn wasmtime_anyref_clone(- _cx: WasmtimeStoreContextMut<'_>,anyref: Option<&wasmtime_anyref_t>,out: &mut MaybeUninit<wasmtime_anyref_t>,) {@@ -257,12 +269,11 @@ pub unsafe extern "C" fn wasmtime_anyref_clone(}#[unsafe(no_mangle)]-pub unsafe extern "C" fn wasmtime_anyref_unroot(- _cx: WasmtimeStoreContextMut<'_>,- val: Option<&mut MaybeUninit<wasmtime_anyref_t>>,-) {- if let Some(val) = val.and_then(|v| v.assume_init_read().from_wasmtime()) {- drop(val);+pub unsafe extern "C" fn wasmtime_anyref_unroot(val: Option<&mut ManuallyDrop<wasmtime_anyref_t>>) {+ if let Some(val) = val {+ unsafe {+ ManuallyDrop::drop(val);+ }}}@@ -371,7 +382,6 @@ pub unsafe extern "C" fn wasmtime_externref_data(#[unsafe(no_mangle)]pub unsafe extern "C" fn wasmtime_externref_clone(- _cx: WasmtimeStoreContextMut<'_>,externref: Option<&wasmtime_externref_t>,out: &mut MaybeUninit<wasmtime_externref_t>,) {@@ -381,11 +391,12 @@ pub unsafe extern "C" fn wasmtime_externref_clone(#[unsafe(no_mangle)]pub unsafe extern "C" fn wasmtime_externref_unroot(- _cx: WasmtimeStoreContextMut<'_>,- val: Option<&mut MaybeUninit<wasmtime_externref_t>>,+ val: Option<&mut ManuallyDrop<wasmtime_externref_t>>,) {- if let Some(val) = val.and_then(|v| v.assume_init_read().from_wasmtime()) {- drop(val);+ if let Some(val) = val {+ unsafe {+ ManuallyDrop::drop(val);+ }}}diff --git a/crates/c-api/src/val.rs b/crates/c-api/src/val.rsindex 44823c70f1..8da29cc8d7 100644--- a/crates/c-api/src/val.rs+++ b/crates/c-api/src/val.rs@@ -1,7 +1,7 @@use crate::r#ref::ref_to_val;use crate::{- WASM_I32, WasmtimeStoreContextMut, from_valtype, into_valtype, wasm_ref_t, wasm_valkind_t,- wasmtime_anyref_t, wasmtime_externref_t, wasmtime_valkind_t,+ WASM_I32, from_valtype, into_valtype, wasm_ref_t, wasm_valkind_t, wasmtime_anyref_t,+ wasmtime_externref_t, wasmtime_valkind_t,};use std::mem::{ManuallyDrop, MaybeUninit};use std::ptr;@@ -158,6 +158,22 @@ const _: () = {assert!(std::mem::align_of::<wasmtime_val_union>() == std::mem::align_of::<u64>());};+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);+ }+ _ => {}+ }+ }+ }+}+// The raw pointers are actually optional boxes.unsafe impl Send for wasmtime_val_unionwhere@@ -298,33 +314,31 @@ impl wasmtime_val_t {}#[unsafe(no_mangle)]-pub unsafe extern "C" fn wasmtime_val_unroot(- _cx: WasmtimeStoreContextMut<'_>,- val: &mut MaybeUninit<wasmtime_val_t>,-) {- let val = val.assume_init_read();- match val.kind {- crate::WASMTIME_ANYREF => {- if let Some(val) = ManuallyDrop::into_inner(val.of.anyref).as_wasmtime() {- drop(val);- }- }- crate::WASMTIME_EXTERNREF => {- if let Some(val) = ManuallyDrop::into_inner(val.of.externref).as_wasmtime() {- drop(val);- }- }- _ => {}- }+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(- cx: WasmtimeStoreContextMut<'_>,src: &wasmtime_val_t,dst: &mut MaybeUninit<wasmtime_val_t>,) {- let mut scope = RootScope::new(cx);- let val = src.to_val(&mut scope);- crate::initialize(dst, wasmtime_val_t::from_val(&mut scope, val))+ let of = match src.kind {+ crate::WASMTIME_ANYREF => wasmtime_val_union {+ anyref: ManuallyDrop::new(src.of.anyref.as_wasmtime().into()),+ },+ crate::WASMTIME_EXTERNREF => wasmtime_val_union {+ externref: ManuallyDrop::new(src.of.externref.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 },+ crate::WASMTIME_FUNCREF => wasmtime_val_union {+ funcref: src.of.funcref,+ },+ _ => unreachable!(),+ };+ dst.write(wasmtime_val_t { kind: src.kind, of });}diff --git a/crates/c-api/tests/component/call_func.cc b/crates/c-api/tests/component/call_func.ccindex 89201b2c47..011fd6aa82 100644--- a/crates/c-api/tests/component/call_func.cc+++ b/crates/c-api/tests/component/call_func.cc@@ -78,6 +78,7 @@ TEST(component, call_func) {wasmtime_component_export_index_delete(f);wasmtime_component_linker_delete(linker);+ wasmtime_component_delete(component);wasmtime_store_delete(store);wasm_engine_delete(engine);diff --git a/crates/c-api/tests/component/define_module.cc b/crates/c-api/tests/component/define_module.ccindex d23d9a2acd..537e305d55 100644--- a/crates/c-api/tests/component/define_module.cc+++ b/crates/c-api/tests/component/define_module.cc@@ -36,6 +36,7 @@ TEST(component, define_module) {err = wasmtime_module_new(engine, reinterpret_cast<const uint8_t *>(wasm.data), wasm.size, &module);CHECK_ERR(err);+ wasm_byte_vec_delete(&wasm);const auto store = wasmtime_store_new(engine, nullptr, nullptr);const auto context = wasmtime_store_context(store);@@ -70,6 +71,8 @@ TEST(component, define_module) {CHECK_ERR(err);wasmtime_component_linker_delete(linker);+ wasmtime_component_delete(component);+ wasmtime_module_delete(module);wasmtime_store_delete(store);wasm_engine_delete(engine);diff --git a/crates/c-api/tests/component/instantiate.cc b/crates/c-api/tests/component/instantiate.ccindex 7267a27042..a08ef577bd 100644--- a/crates/c-api/tests/component/instantiate.cc+++ b/crates/c-api/tests/component/instantiate.cc@@ -38,6 +38,7 @@ TEST(component, instantiate) {CHECK_ERR(error);wasmtime_component_linker_delete(linker);+ wasmtime_component_delete(component);wasmtime_store_delete(store);wasm_engine_delete(engine);diff --git a/crates/c-api/tests/component/lookup_func.cc b/crates/c-api/tests/component/lookup_func.ccindex 4448be0259..b3990cd838 100644--- a/crates/c-api/tests/component/lookup_func.cc+++ b/crates/c-api/tests/component/lookup_func.cc@@ -60,6 +60,7 @@ TEST(component, lookup_func) {wasmtime_component_export_index_delete(f);wasmtime_component_linker_delete(linker);+ wasmtime_component_delete(component);wasmtime_store_delete(store);wasm_engine_delete(engine);diff --git a/crates/c-api/tests/func.cc b/crates/c-api/tests/func.ccindex 4df9601ea7..8d7bd4ba95 100644--- a/crates/c-api/tests/func.cc+++ b/crates/c-api/tests/func.cc@@ -88,10 +88,9 @@ TEST(TypedFunc, Call) {{ValKind::ExternRef, ValKind::ExternRef});Func f(store, ty, [](auto caller, auto params, auto results) {caller.context().gc();- EXPECT_TRUE(params[0].externref(caller));- EXPECT_EQ(std::any_cast<int>(params[0].externref(caller)->data(caller)),- 100);- EXPECT_FALSE(params[1].externref(caller));+ EXPECT_TRUE(params[0].externref());+ EXPECT_EQ(std::any_cast<int>(params[0].externref()->data(caller)), 100);+ EXPECT_FALSE(params[1].externref());results[0] = ExternRef(caller, int(3));results[1] = std::optional<ExternRef>(std::nullopt);caller.context().gc();diff --git a/crates/c-api/tests/simple.cc b/crates/c-api/tests/simple.ccindex 3fa4ff1a7d..c222f4a527 100644--- a/crates/c-api/tests/simple.cc+++ b/crates/c-api/tests/simple.cc@@ -63,7 +63,6 @@ TEST(ExternRef, Smoke) {ExternRef b(store, 3);EXPECT_STREQ(std::any_cast<const char *>(a.data(store)), "foo");EXPECT_EQ(std::any_cast<int>(b.data(store)), 3);- a.unroot(store);a = b;}diff --git a/crates/c-api/tests/val.cc b/crates/c-api/tests/val.ccindex 01d7d7fb7e..7d18166ab4 100644--- a/crates/c-api/tests/val.cc+++ b/crates/c-api/tests/val.cc@@ -36,29 +36,29 @@ TEST(Val, Smoke) {Store store(engine);val = std::optional<ExternRef>(std::nullopt);EXPECT_EQ(val.kind(), ValKind::ExternRef);- EXPECT_EQ(val.externref(store), std::nullopt);+ EXPECT_EQ(val.externref(), std::nullopt);val = std::optional<ExternRef>(ExternRef(store, 5));EXPECT_EQ(val.kind(), ValKind::ExternRef);- EXPECT_EQ(std::any_cast<int>(val.externref(store)->data(store)), 5);+ EXPECT_EQ(std::any_cast<int>(val.externref()->data(store)), 5);val = ExternRef(store, 5);EXPECT_EQ(val.kind(), ValKind::ExternRef);- EXPECT_EQ(std::any_cast<int>(val.externref(store)->data(store)), 5);+ EXPECT_EQ(std::any_cast<int>(val.externref()->data(store)), 5);val = std::optional<AnyRef>(std::nullopt);EXPECT_EQ(val.kind(), ValKind::AnyRef);- EXPECT_EQ(val.anyref(store), std::nullopt);+ EXPECT_EQ(val.anyref(), std::nullopt);val = std::optional<AnyRef>(AnyRef::i31(store, 5));EXPECT_EQ(val.kind(), ValKind::AnyRef);- EXPECT_EQ(val.anyref(store)->i31(store), 5);- EXPECT_EQ(val.anyref(store)->u31(store), 5);+ EXPECT_EQ(val.anyref()->i31(store), 5);+ EXPECT_EQ(val.anyref()->u31(store), 5);val = AnyRef::i31(store, -5);EXPECT_EQ(val.kind(), ValKind::AnyRef);- EXPECT_EQ(val.anyref(store)->i31(store), -5);- EXPECT_EQ(val.anyref(store)->u31(store), 0x7ffffffb);+ EXPECT_EQ(val.anyref()->i31(store), -5);+ EXPECT_EQ(val.anyref()->u31(store), 0x7ffffffb);val = std::optional<Func>(std::nullopt);EXPECT_EQ(val.kind(), ValKind::FuncRef);@@ -75,3 +75,82 @@ TEST(Val, Smoke) {val = func;EXPECT_EQ(val.kind(), ValKind::FuncRef);}++class SetOnDrop {+ std::shared_ptr<std::atomic<bool>> flag_;++public:+ SetOnDrop() : flag_(std::make_shared<std::atomic<bool>>(false)) {}+ SetOnDrop(const SetOnDrop &) = delete;+ SetOnDrop(SetOnDrop &&obj) : flag_(obj.flag_) { obj.flag_.reset(); }+ ~SetOnDrop() {+ if (flag_)+ flag_->store(true);+ }++ const std::shared_ptr<std::atomic<bool>> &flag() { return this->flag_; }+};++TEST(Val, DropsExternRef) {+ std::shared_ptr<std::atomic<bool>> flag;+ Engine engine;+ Store store(engine);++ // smoke test for `SetOnDrop` itself+ {+ SetOnDrop guard;+ flag = guard.flag();+ EXPECT_FALSE(flag->load());+ }+ EXPECT_TRUE(flag->load());++ // Test that if an `ExternRef` is created and dropped it doesn't leak.+ {+ SetOnDrop guard;+ flag = guard.flag();+ ExternRef r(store, std::make_shared<SetOnDrop>(std::move(guard)));+ EXPECT_FALSE(flag->load());+ store.gc();+ EXPECT_FALSE(flag->load());+ }+ EXPECT_FALSE(flag->load());+ store.gc();+ EXPECT_TRUE(flag->load());++ // Test that if a `Val(ExternRef)` is created and dropped it doesn't leak.+ {+ SetOnDrop guard;+ flag = guard.flag();+ ExternRef r(store, std::make_shared<SetOnDrop>(std::move(guard)));+ Val v(r);+ EXPECT_FALSE(flag->load());+ store.gc();+ EXPECT_FALSE(flag->load());+ }+ EXPECT_FALSE(flag->load());+ store.gc();+ EXPECT_TRUE(flag->load());++ // Similar to above testing a variety of APIs.+ {+ SetOnDrop guard;+ flag = guard.flag();+ ExternRef r(store, std::make_shared<SetOnDrop>(std::move(guard)));+ ExternRef r2 = r;+ ExternRef r3(r2);+ r3 = r2;+ r = std::move(r2);++ Val v(r3);+ Val v2 = v;+ Val v3(v2);+ v3 = v2;+ v = std::move(v2);++ store.gc();+ EXPECT_FALSE(flag->load());+ }+ EXPECT_FALSE(flag->load());+ store.gc();+ EXPECT_TRUE(flag->load());+}diff --git a/crates/c-api/tests/wasip2.cc b/crates/c-api/tests/wasip2.ccindex 0dc3fee427..c5a61307f4 100644--- a/crates/c-api/tests/wasip2.cc+++ b/crates/c-api/tests/wasip2.cc@@ -40,6 +40,7 @@ TEST(wasip2, smoke) {CHECK_ERR(err);wasmtime_component_linker_delete(linker);+ wasmtime_component_delete(component);wasmtime_store_delete(store);wasm_engine_delete(engine);diff --git a/examples/anyref.c b/examples/anyref.cindex 4cd782f8b4..e1897e6dfc 100644--- a/examples/anyref.c+++ b/examples/anyref.c@@ -117,7 +117,7 @@ int main() {is_i31 = wasmtime_anyref_i31_get_u(context, &elem.of.anyref, &i31val);assert(is_i31);assert(i31val == 1234);- wasmtime_val_unroot(context, &elem);+ wasmtime_val_unroot(&elem);printf("Touching `anyref` global...\n");@@ -141,7 +141,7 @@ int main() {is_i31 = wasmtime_anyref_i31_get_u(context, &global_val.of.anyref, &i31val);assert(is_i31);assert(i31val == 1234);- wasmtime_val_unroot(context, &global_val);+ wasmtime_val_unroot(&global_val);printf("Passing `anyref` into func...\n");@@ -179,8 +179,8 @@ int main() {is_i31 = wasmtime_anyref_i31_get_u(context, &results[0].of.anyref, &i31val);assert(is_i31);assert(i31val == 42);- wasmtime_val_unroot(context, &results[0]);- wasmtime_val_unroot(context, &anyref_val);+ wasmtime_val_unroot(&results[0]);+ wasmtime_val_unroot(&anyref_val);// We can GC any now-unused references to our anyref that the store is// holding.diff --git a/examples/anyref.cc b/examples/anyref.ccindex 112b267593..80cf96961a 100644--- a/examples/anyref.cc+++ b/examples/anyref.cc@@ -47,7 +47,7 @@ int main() {auto cx = store.context();AnyRef i31 = AnyRef::i31(cx, 1234);Val anyref_val(i31);- auto opt_any = anyref_val.anyref(cx);+ auto opt_any = anyref_val.anyref();if (!opt_any || !opt_any->u31(cx) || *opt_any->u31(cx) != 1234) {std::cerr << "> Error creating i31 anyref\n";return 1;@@ -61,7 +61,7 @@ int main() {std::cerr << "> Error getting table element\n";return 1;}- auto elem_any = elem_opt->anyref(cx);+ auto elem_any = elem_opt->anyref();if (!elem_any || !elem_any->u31(cx) || *elem_any->u31(cx) != 1234) {std::cerr << "> Error verifying table element\n";return 1;@@ -71,7 +71,7 @@ int main() {Global global = std::get<Global>(*instance.get(store, "global"));global.set(store, anyref_val).unwrap();Val global_val = global.get(store);- auto global_any = global_val.anyref(cx);+ auto global_any = global_val.anyref();if (!global_any || !global_any->u31(cx) || *global_any->u31(cx) != 1234) {std::cerr << "> Error verifying global value\n";return 1;@@ -88,7 +88,7 @@ int main() {std::cerr << "> Unexpected number of results\n";return 1;}- auto ret_any = results[0].anyref(cx);+ auto ret_any = results[0].anyref();if (!ret_any || !ret_any->u31(cx) || *ret_any->u31(cx) != 42) {std::cerr << "> Error verifying returned anyref\n";return 1;diff --git a/examples/externref.c b/examples/externref.cindex 61f570fc27..64f90c4ed0 100644--- a/examples/externref.c+++ b/examples/externref.c@@ -112,7 +112,7 @@ int main() {assert(elem.kind == WASMTIME_EXTERNREF);assert(strcmp((char *)wasmtime_externref_data(context, &elem.of.externref),"Hello, World!") == 0);- wasmtime_val_unroot(context, &elem);+ wasmtime_val_unroot(&elem);}printf("Touching `externref` global...\n");@@ -136,7 +136,7 @@ int main() {assert(strcmp((char *)wasmtime_externref_data(context,&global_val.of.externref),"Hello, World!") == 0);- wasmtime_val_unroot(context, &global_val);+ wasmtime_val_unroot(&global_val);}printf("Calling `externref` func...\n");@@ -161,9 +161,9 @@ int main() {assert(strcmp((char *)wasmtime_externref_data(context,&results[0].of.externref),"Hello, World!") == 0);- wasmtime_val_unroot(context, &results[0]);+ wasmtime_val_unroot(&results[0]);}- wasmtime_val_unroot(context, &externref_val);+ wasmtime_val_unroot(&externref_val);// We can GC any now-unused references to our externref that the store is// holding.diff --git a/examples/externref.cc b/examples/externref.ccindex c11e8c921e..4925852001 100644--- a/examples/externref.cc+++ b/examples/externref.cc@@ -31,21 +31,21 @@ int main() {std::cout << "Touching `externref` table..\n";Table table = std::get<Table>(*instance.get(store, "table"));table.set(store, 3, externref).unwrap();- ExternRef val = *table.get(store, 3)->externref(store);+ ExternRef val = *table.get(store, 3)->externref();std::cout << "externref data: " << std::any_cast<std::string>(val.data(store))<< "\n";std::cout << "Touching `externref` global..\n";Global global = std::get<Global>(*instance.get(store, "global"));global.set(store, externref).unwrap();- val = *global.get(store).externref(store);+ val = *global.get(store).externref();std::cout << "externref data: " << std::any_cast<std::string>(val.data(store))<< "\n";std::cout << "Calling `externref` func..\n";Func func = std::get<Func>(*instance.get(store, "func"));auto results = func.call(store, {externref}).unwrap();- val = *results[0].externref(store);+ val = *results[0].externref();std::cout << "externref data: " << std::any_cast<std::string>(val.data(store))<< "\n";diff --git a/examples/fib-debug/main.c b/examples/fib-debug/main.cindex 0d901caffa..945713b20a 100644--- a/examples/fib-debug/main.c+++ b/examples/fib-debug/main.c@@ -45,7 +45,7 @@ extern struct jit_descriptor __jit_debug_descriptor;static void exit_with_error(const char *message, wasmtime_error_t *error,wasm_trap_t *trap);-int main(int argc, const char *argv[]) {+int main() {// Configuring engine to support generating of DWARF info.// lldb can be used to attach to the program and observe// original fib-wasm.c source code and variables.diff --git a/examples/fuel.c b/examples/fuel.cindex 877690a8db..1d7ad9c451 100644--- a/examples/fuel.c+++ b/examples/fuel.c@@ -94,7 +94,10 @@ int main() {wasmtime_trap_code_t code;assert(wasmtime_trap_code(trap, &code));assert(code == WASMTIME_TRAP_CODE_OUT_OF_FUEL);+ wasm_trap_delete(trap);}+ if (error != NULL)+ wasmtime_error_delete(error);printf("Exhausted fuel computing fib(%d)\n", n);break;}diff --git a/examples/hello.c b/examples/hello.cindex fe5912d46c..cc71630a04 100644--- a/examples/hello.c+++ b/examples/hello.c@@ -19,6 +19,12 @@ static void exit_with_error(const char *message, wasmtime_error_t *error,static wasm_trap_t *hello_callback(void *env, wasmtime_caller_t *caller,const wasmtime_val_t *args, size_t nargs,wasmtime_val_t *results, size_t nresults) {+ (void)env;+ (void)caller;+ (void)args;+ (void)nargs;+ (void)results;+ (void)nresults;printf("Calling back...\n");printf("> Hello World!\n");return NULL;@@ -77,6 +83,7 @@ int main() {wasm_functype_t *hello_ty = wasm_functype_new_0_0();wasmtime_func_t hello;wasmtime_func_new(context, hello_ty, hello_callback, NULL, NULL, &hello);+ wasm_functype_delete(hello_ty);// With our callback function we can now instantiate the compiled module,// giving us an instance we can then execute exports from. Note thatdiff --git a/examples/interrupt.c b/examples/interrupt.cindex 671890040e..021970453d 100644--- a/examples/interrupt.c+++ b/examples/interrupt.c@@ -107,6 +107,7 @@ int main() {assert(error == NULL);assert(trap != NULL);printf("Got a trap!...\n");+ wasm_trap_delete(trap);wasmtime_store_delete(store);wasm_engine_delete(engine);diff --git a/examples/linking.c b/examples/linking.cindex 68faa27d82..c3fa3a6ac2 100644--- a/examples/linking.c+++ b/examples/linking.c@@ -18,8 +18,7 @@ mkdir build && cd build && cmake .. && cmake --build . --target wasmtime-linkingstatic void exit_with_error(const char *message, wasmtime_error_t *error,wasm_trap_t *trap);-static void read_wat_file(wasm_engine_t *engine, wasm_byte_vec_t *bytes,- const char *file);+static void read_wat_file(wasm_byte_vec_t *bytes, const char *file);int main() {// Set up our context@@ -30,8 +29,8 @@ int main() {wasmtime_context_t *context = wasmtime_store_context(store);wasm_byte_vec_t linking1_wasm, linking2_wasm;- read_wat_file(engine, &linking1_wasm, "examples/linking1.wat");- read_wat_file(engine, &linking2_wasm, "examples/linking2.wat");+ read_wat_file(&linking1_wasm, "examples/linking1.wat");+ read_wat_file(&linking2_wasm, "examples/linking2.wat");// Compile our two moduleswasmtime_error_t *error;@@ -106,8 +105,7 @@ int main() {return 0;}-static void read_wat_file(wasm_engine_t *engine, wasm_byte_vec_t *bytes,- const char *filename) {+static void read_wat_file(wasm_byte_vec_t *bytes, const char *filename) {wasm_byte_vec_t wat;// Load our input file to parse it nextFILE *file = fopen(filename, "r");diff --git a/examples/memory.c b/examples/memory.cindex fd897bbe99..e99e57268a 100644--- a/examples/memory.c+++ b/examples/memory.c@@ -118,7 +118,7 @@ void check_trap2(wasmtime_context_t *store, wasmtime_func_t *func, int32_t arg1,check_trap(store, func, args, 2, 0);}-int main(int argc, const char *argv[]) {+int main() {// Initialize.printf("Initializing...\n");wasm_engine_t *engine = wasm_engine_new();diff --git a/examples/multi.c b/examples/multi.cindex ccd55197e6..61fce9a71e 100644--- a/examples/multi.c+++ b/examples/multi.c@@ -25,6 +25,11 @@ static void exit_with_error(const char *message, wasmtime_error_t *error,wasm_trap_t *callback(void *env, wasmtime_caller_t *caller,const wasmtime_val_t *args, size_t nargs,wasmtime_val_t *results, size_t nresults) {+ (void)env;+ (void)caller;+ (void)nargs;+ (void)nresults;+printf("Calling back...\n");printf("> %" PRIu32 " %" PRIu64 "\n", args[0].of.i32, args[1].of.i64);printf("\n");@@ -38,6 +43,11 @@ wasm_trap_t *callback(void *env, wasmtime_caller_t *caller,wasm_trap_t *closure_callback(void *env, wasmtime_caller_t *caller,const wasmtime_val_t *args, size_t nargs,wasmtime_val_t *results, size_t nresults) {+ (void)caller;+ (void)args;+ (void)nargs;+ (void)nresults;+int i = *(int *)env;printf("Calling back closure...\n");printf("> %d\n", i);@@ -47,7 +57,7 @@ wasm_trap_t *closure_callback(void *env, wasmtime_caller_t *caller,return NULL;}-int main(int argc, const char *argv[]) {+int main() {// Initialize.printf("Initializing...\n");wasm_engine_t *engine = wasm_engine_new();diff --git a/examples/serialize.c b/examples/serialize.cindex 586fb4f2c0..650100013e 100644--- a/examples/serialize.c+++ b/examples/serialize.c@@ -20,6 +20,12 @@ static void exit_with_error(const char *message, wasmtime_error_t *error,static wasm_trap_t *hello_callback(void *env, wasmtime_caller_t *caller,const wasmtime_val_t *args, size_t nargs,wasmtime_val_t *results, size_t nresults) {+ (void)env;+ (void)caller;+ (void)args;+ (void)nargs;+ (void)results;+ (void)nresults;printf("Calling back...\n");printf("> Hello World!\n");return NULL;@@ -102,6 +108,7 @@ int deserialize(wasm_byte_vec_t *buffer) {wasm_functype_t *hello_ty = wasm_functype_new_0_0();wasmtime_func_t hello;wasmtime_func_new(context, hello_ty, hello_callback, NULL, NULL, &hello);+ wasm_functype_delete(hello_ty);// With our callback function we can now instantiate the compiled module,// giving us an instance we can then execute exports from. Note thatdiff --git a/examples/threads.c b/examples/threads.cindex 75cf2fc378..fd0ed83815 100644--- a/examples/threads.c+++ b/examples/threads.c@@ -43,6 +43,8 @@ uint64_t get_thread_id() {// A function to be called from Wasm code.own wasm_trap_t *callback(const wasm_val_vec_t *args, wasm_val_vec_t *results) {+ (void)args;+ (void)results;printf("> Thread %lu running\n", (uint64_t)get_thread_id());return NULL;}@@ -117,7 +119,7 @@ void *run(void *args_abs) {return NULL;}-int main(int argc, const char *argv[]) {+int main() {// Initialize.wasm_engine_t *engine = wasm_engine_new();diff --git a/examples/wasip1/main.c b/examples/wasip1/main.cindex 0e1ccf4ec8..a57b346633 100644--- a/examples/wasip1/main.c+++ b/examples/wasip1/main.c@@ -99,6 +99,7 @@ int main() {exit_with_error("error calling default export", error, trap);// Clean up after ourselves at this point+ wasmtime_linker_delete(linker);wasmtime_module_delete(module);wasmtime_store_delete(store);wasm_engine_delete(engine);