Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Refactor reference types in the C/C++ API (#13154)

Alex Crichton06432bd47d6b
diff --git a/crates/c-api/include/wasmtime.h b/crates/c-api/include/wasmtime.h
index 0e0a969a08..7665c33141 100644
--- a/crates/c-api/include/wasmtime.h
+++ b/crates/c-api/include/wasmtime.h
@@ -196,11 +196,17 @@
#include <wasmtime/conf.h>
// clang-format off
// IWYU pragma: begin_exports
+#include <wasmtime/anyref.h>
+#include <wasmtime/arrayref.h>
+#include <wasmtime/async.h>
+#include <wasmtime/component.h>
#include <wasmtime/config.h>
#include <wasmtime/engine.h>
+#include <wasmtime/eqref.h>
#include <wasmtime/error.h>
-#include <wasmtime/exn.h>
+#include <wasmtime/exnref.h>
#include <wasmtime/extern.h>
+#include <wasmtime/externref.h>
#include <wasmtime/func.h>
#include <wasmtime/global.h>
#include <wasmtime/instance.h>
@@ -210,13 +216,13 @@
#include <wasmtime/profiling.h>
#include <wasmtime/sharedmemory.h>
#include <wasmtime/store.h>
+#include <wasmtime/structref.h>
#include <wasmtime/table.h>
#include <wasmtime/tag.h>
#include <wasmtime/trap.h>
+#include <wasmtime/types/arrayref.h>
+#include <wasmtime/types/structref.h>
#include <wasmtime/val.h>
-#include <wasmtime/gc.h>
-#include <wasmtime/async.h>
-#include <wasmtime/component.h>
#include <wasmtime/wat.h>
// IWYU pragma: end_exports
// clang-format on
diff --git a/crates/c-api/include/wasmtime.hh b/crates/c-api/include/wasmtime.hh
index 4a6df6d887..89dc5ac842 100644
--- a/crates/c-api/include/wasmtime.hh
+++ b/crates/c-api/include/wasmtime.hh
@@ -35,19 +35,23 @@
#ifndef WASMTIME_HH
#define WASMTIME_HH
+#include <wasmtime/anyref.hh>
+#include <wasmtime/arrayref.hh>
#include <wasmtime/config.hh>
#include <wasmtime/engine.hh>
+#include <wasmtime/eqref.hh>
#include <wasmtime/error.hh>
-#include <wasmtime/exn.hh>
+#include <wasmtime/exnref.hh>
#include <wasmtime/extern.hh>
+#include <wasmtime/externref.hh>
#include <wasmtime/func.hh>
-#include <wasmtime/gc.hh>
#include <wasmtime/global.hh>
#include <wasmtime/instance.hh>
#include <wasmtime/linker.hh>
#include <wasmtime/memory.hh>
#include <wasmtime/module.hh>
#include <wasmtime/store.hh>
+#include <wasmtime/structref.hh>
#include <wasmtime/table.hh>
#include <wasmtime/tag.hh>
#include <wasmtime/trap.hh>
diff --git a/crates/c-api/include/wasmtime/_anyref_class.hh b/crates/c-api/include/wasmtime/_anyref_class.hh
new file mode 100644
index 0000000000..c5a5163d8c
--- /dev/null
+++ b/crates/c-api/include/wasmtime/_anyref_class.hh
@@ -0,0 +1,76 @@
+#ifndef WASMTIME_ANYREF_CLASS_HH
+#define WASMTIME_ANYREF_CLASS_HH
+
+#include <wasmtime/conf.h>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <wasmtime/_store_class.hh>
+#include <wasmtime/anyref.h>
+#include <wasmtime/helpers.hh>
+
+namespace wasmtime {
+
+class ArrayRef;
+class EqRef;
+class StructRef;
+
+/**
+ * \brief Representation of a WebAssembly `anyref` value.
+ */
+class AnyRef {
+ WASMTIME_TOP_REF_WRAPPER(AnyRef, wasmtime_anyref);
+
+ /// 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) {
+ wasmtime_anyref_t other;
+ wasmtime_anyref_from_i31(cx.capi(), value, &other);
+ return AnyRef(other);
+ }
+
+ /// \brief If this is an `i31`, get the value zero-extended.
+ std::optional<uint32_t> u31(Store::Context cx) const {
+ uint32_t ret = 0;
+ if (wasmtime_anyref_i31_get_u(cx.capi(), &raw, &ret))
+ return ret;
+ return std::nullopt;
+ }
+
+ /// \brief If this is an `i31`, get the value sign-extended.
+ std::optional<int32_t> i31(Store::Context cx) const {
+ int32_t ret = 0;
+ if (wasmtime_anyref_i31_get_s(cx.capi(), &raw, &ret))
+ 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.capi(), &raw);
+ }
+
+ /// \brief Returns `true` if this anyref is an eqref.
+ inline bool is_eqref(Store::Context cx) const;
+
+ /// \brief Returns `true` if this anyref is a structref.
+ inline bool is_struct(Store::Context cx) const;
+
+ /// \brief Returns `true` if this anyref is an arrayref.
+ inline bool is_array(Store::Context cx) const;
+
+ /// \brief Downcast to eqref. Returns null eqref if not an eqref.
+ inline std::optional<EqRef> as_eqref(Store::Context cx) const;
+
+ /// \brief Downcast to structref. Returns null structref if not a structref.
+ inline std::optional<StructRef> as_struct(Store::Context cx) const;
+
+ /// \brief Downcast to arrayref. Returns null arrayref if not an arrayref.
+ inline std::optional<ArrayRef> as_array(Store::Context cx) const;
+};
+
+} // namespace wasmtime
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_ANYREF_CLASS_HH
diff --git a/crates/c-api/include/wasmtime/_arrayref_class.hh b/crates/c-api/include/wasmtime/_arrayref_class.hh
new file mode 100644
index 0000000000..ad5fc2558e
--- /dev/null
+++ b/crates/c-api/include/wasmtime/_arrayref_class.hh
@@ -0,0 +1,78 @@
+#ifndef WASMTIME_ARRAYREF_CLASS_HH
+#define WASMTIME_ARRAYREF_CLASS_HH
+
+#include <wasmtime/conf.h>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <wasmtime/_store_class.hh>
+#include <wasmtime/arrayref.h>
+#include <wasmtime/types/arrayref.hh>
+
+namespace wasmtime {
+
+class Val;
+class AnyRef;
+class EqRef;
+
+/**
+ * \brief Pre-allocated array layout for fast allocation of array instances.
+ *
+ * Created from a ArrayType and a store context. Reusable for allocating
+ * many array instances of the same type.
+ */
+class ArrayRefPre {
+ friend class ArrayRef;
+ WASMTIME_OWN_WRAPPER(ArrayRefPre, wasmtime_array_ref_pre)
+
+public:
+ /// Create a new array pre-allocator.
+ static ArrayRefPre create(Store::Context cx, const ArrayType &ty) {
+ auto *raw = wasmtime_array_ref_pre_new(cx.capi(), ty.capi());
+ ArrayRefPre pre(raw);
+ return pre;
+ }
+};
+
+/**
+ * \brief Representation of a WebAssembly `arrayref` value.
+ *
+ * An `arrayref` is a reference to a GC array instance. It is a subtype
+ * of `eqref` and `anyref`.
+ */
+class ArrayRef {
+ WASMTIME_REF_WRAPPER(ArrayRef, wasmtime_arrayref)
+
+public:
+ /// Allocate a new array with all elements set to the same value.
+ static Result<ArrayRef> create(Store::Context cx, const ArrayRefPre &pre,
+ const Val &elem, uint32_t len);
+
+ /// Get the length of the array.
+ Result<uint32_t> len(Store::Context cx) const {
+ uint32_t out;
+ auto *err = wasmtime_arrayref_len(cx.capi(), &raw, &out);
+ if (err)
+ return Result<uint32_t>(Error(err));
+ return Result<uint32_t>(out);
+ }
+
+ /// Read an element from the array.
+ Result<Val> get(Store::Context cx, uint32_t index) const;
+
+ /// Set an element of the array.
+ Result<std::monostate> set(Store::Context cx, uint32_t index,
+ const Val &value) const;
+
+ /// Upcast to anyref.
+ AnyRef to_anyref() const;
+
+ /// Upcast to eqref.
+ EqRef to_eqref() const;
+};
+
+} // namespace wasmtime
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_ARRAYREF_CLASS_HH
diff --git a/crates/c-api/include/wasmtime/_eqref_class.hh b/crates/c-api/include/wasmtime/_eqref_class.hh
new file mode 100644
index 0000000000..6665dbee15
--- /dev/null
+++ b/crates/c-api/include/wasmtime/_eqref_class.hh
@@ -0,0 +1,89 @@
+#ifndef WASMTIME_EQREF_CLASS_HH
+#define WASMTIME_EQREF_CLASS_HH
+
+#include <wasmtime/conf.h>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <wasmtime/_store_class.hh>
+#include <wasmtime/eqref.h>
+#include <wasmtime/helpers.hh>
+
+namespace wasmtime {
+
+class AnyRef;
+class StructRef;
+class ArrayRef;
+
+/**
+ * \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 {
+ WASMTIME_REF_WRAPPER(EqRef, wasmtime_eqref);
+
+public:
+ /// 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(), &raw);
+ }
+
+ /// 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(), &raw, &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(), &raw, &dst))
+ return dst;
+ return std::nullopt;
+ }
+
+ /// Returns `true` if this eqref is a structref.
+ bool is_struct(Store::Context cx) const {
+ return wasmtime_eqref_is_struct(cx.capi(), &raw);
+ }
+
+ /// Returns `true` if this eqref is an arrayref.
+ bool is_array(Store::Context cx) const {
+ return wasmtime_eqref_is_array(cx.capi(), &raw);
+ }
+
+ /// Upcast this `eqref` to an `anyref`.
+ AnyRef to_anyref() const;
+
+ /// Downcast this `eqref` into a `structref`.
+ //
+ // as_struct() defined after StructRef below.
+ StructRef as_struct(Store::Context cx) const;
+
+ /// Downcast this `eqref` into an `arrayref`.
+ //
+ // as_array() defined after ArrayRef below.
+ ArrayRef as_array(Store::Context cx) const;
+};
+
+} // namespace wasmtime
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_EQREF_CLASS_HH
diff --git a/crates/c-api/include/wasmtime/_exnref_class.hh b/crates/c-api/include/wasmtime/_exnref_class.hh
new file mode 100644
index 0000000000..ad94c75094
--- /dev/null
+++ b/crates/c-api/include/wasmtime/_exnref_class.hh
@@ -0,0 +1,64 @@
+#ifndef WASMTIME_EXNREF_CLASS_HH
+#define WASMTIME_EXNREF_CLASS_HH
+
+#include <wasmtime/conf.h>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <vector>
+#include <wasmtime/_store_class.hh>
+#include <wasmtime/error.hh>
+#include <wasmtime/exnref.h>
+#include <wasmtime/helpers.hh>
+#include <wasmtime/tag.hh>
+
+namespace wasmtime {
+
+class Val;
+
+/**
+ * \brief A WebAssembly exception object.
+ *
+ * Exception objects carry a tag and a set of field values. They are
+ * allocated on the GC heap within a store.
+ *
+ * This type owns its underlying `wasmtime_exnref_t` handle. When it goes out
+ * of scope the handle is freed.
+ */
+class ExnRef {
+ WASMTIME_TOP_REF_WRAPPER(ExnRef, wasmtime_exnref);
+
+ /**
+ * \brief Create a new exception object.
+ *
+ * \param cx the store in which to allocate the exception
+ * \param tag the tag to associate with this exception
+ * \param fields the field values matching the tag's payload signature
+ */
+ static Result<ExnRef> create(Store::Context cx, const Tag &tag,
+ const std::vector<Val> &fields);
+
+ /// Returns the tag associated with this exception.
+ Result<Tag> tag(Store::Context cx) const {
+ wasmtime_tag_t tag;
+ auto *error = wasmtime_exnref_tag(cx.capi(), &raw, &tag);
+ if (error != nullptr) {
+ return Error(error);
+ }
+ return Tag(tag);
+ }
+
+ /// Returns the number of fields in this exception.
+ size_t field_count(Store::Context cx) const {
+ return wasmtime_exnref_field_count(cx.capi(), &raw);
+ }
+
+ /// Reads a field value by index.
+ Result<Val> field(Store::Context cx, size_t index) const;
+};
+
+} // namespace wasmtime
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_EXNREF_CLASS_HH
diff --git a/crates/c-api/include/wasmtime/_externref_class.hh b/crates/c-api/include/wasmtime/_externref_class.hh
new file mode 100644
index 0000000000..0f8674403e
--- /dev/null
+++ b/crates/c-api/include/wasmtime/_externref_class.hh
@@ -0,0 +1,60 @@
+#ifndef WASMTIME_EXTERNREF_CLASS_HH
+#define WASMTIME_EXTERNREF_CLASS_HH
+
+#include <wasmtime/conf.h>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <wasmtime/_store_class.hh>
+#include <wasmtime/externref.h>
+#include <wasmtime/helpers.hh>
+
+namespace wasmtime {
+
+/**
+ * \brief Representation of a WebAssembly `externref` value.
+ *
+ * This class represents an value that cannot be forged by WebAssembly itself.
+ * All `ExternRef` values are guaranteed to be created by the host and its
+ * embedding. It's suitable to place private data structures in here which
+ * WebAssembly will not have access to, only other host functions will have
+ * access to them.
+ *
+ * Note that `ExternRef` values are rooted within a `Store` and must be manually
+ * unrooted via the `unroot` function. If this is not used then values will
+ * never be candidates for garbage collection.
+ */
+class ExternRef {
+ WASMTIME_TOP_REF_WRAPPER(ExternRef, wasmtime_externref);
+
+private:
+ static void finalizer(void *ptr) {
+ std::unique_ptr<std::any> _ptr(static_cast<std::any *>(ptr));
+ }
+
+public:
+ /// 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.
+ explicit ExternRef(Store::Context cx, std::any val) {
+ void *ptr = std::make_unique<std::any>(val).release();
+ bool ok = wasmtime_externref_new(cx.capi(), ptr, finalizer, &this->raw);
+ if (!ok) {
+ fprintf(stderr, "failed to allocate a new externref");
+ abort();
+ }
+ }
+
+ /// Returns the underlying host data associated with this `ExternRef`.
+ std::any &data(Store::Context cx) {
+ return *static_cast<std::any *>(wasmtime_externref_data(cx.capi(), &raw));
+ }
+};
+
+} // namespace wasmtime
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_EXTERNREF_CLASS_HH
diff --git a/crates/c-api/include/wasmtime/_func_class.hh b/crates/c-api/include/wasmtime/_func_class.hh
new file mode 100644
index 0000000000..6b7bbc3151
--- /dev/null
+++ b/crates/c-api/include/wasmtime/_func_class.hh
@@ -0,0 +1,366 @@
+#ifndef WASMTIME_FUNC_CLASS_HH
+#define WASMTIME_FUNC_CLASS_HH
+
+#include <array>
+#include <wasmtime/_store_class.hh>
+#include <wasmtime/error.hh>
+#include <wasmtime/extern_declare.hh>
+#include <wasmtime/func.h>
+#include <wasmtime/span.hh>
+#include <wasmtime/trap.hh>
+#include <wasmtime/types/func.hh>
+#include <wasmtime/types/val.hh>
+
+namespace wasmtime {
+
+class Val;
+
+/**
+ * \brief Structure provided to host functions to lookup caller information or
+ * acquire a `Store::Context`.
+ *
+ * This structure is passed to all host functions created with `Func`. It can be
+ * used to create a `Store::Context`.
+ */
+class Caller {
+ friend class Func;
+ friend class Store;
+ wasmtime_caller_t *ptr;
+ Caller(wasmtime_caller_t *ptr) : ptr(ptr) {}
+
+public:
+ /// Attempts to load an exported item from the calling instance.
+ ///
+ /// For more information see the Rust documentation -
+ /// https://docs.wasmtime.dev/api/wasmtime/struct.Caller.html#method.get_export
+ std::optional<Extern> get_export(std::string_view name);
+
+ /// Explicitly acquire a `Store::Context` from this `Caller`.
+ Store::Context context() { return this; }
+};
+
+namespace detail {
+
+/// A "trait" for native types that correspond to WebAssembly types for use with
+/// `Func::wrap` and `TypedFunc::call`
+template <typename T> struct WasmType {
+ static const bool valid = false;
+};
+
+/// A "trait" for a list of types and operations on them, used for `Func::wrap`
+/// and `TypedFunc::call`
+///
+/// The base case is a single type which is a list of one element.
+template <typename T> struct WasmTypeList {
+ static const bool valid = WasmType<T>::valid;
+ static const size_t size = 1;
+ 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);
+ }
+ static T load(Store::Context cx, wasmtime_val_raw_t *storage) {
+ return WasmType<T>::load(cx, storage);
+ }
+ static std::vector<ValType> types() { return {WasmType<T>::kind}; }
+};
+
+/// A "trait" for what can be returned from closures specified to `Func::wrap`.
+///
+/// The base case here is a bare return value like `int32_t`.
+template <typename R> struct WasmHostRet {
+ using Results = WasmTypeList<R>;
+
+ template <typename F, typename... A>
+ static std::optional<Trap> invoke(F f, Caller cx, wasmtime_val_raw_t *raw,
+ A... args) {
+ auto ret = f(args...);
+ Results::store(cx, raw, ret);
+ return std::nullopt;
+ }
+};
+
+template <typename F, typename = void> struct WasmHostFunc;
+
+} // namespace detail
+
+using namespace detail;
+
+// forward-declaration for `Func::typed` below.
+template <typename Params, typename Results> class TypedFunc;
+
+/**
+ * \brief Representation of a WebAssembly function.
+ *
+ * This class represents a WebAssembly function, either created through
+ * instantiating a module or a host function.
+ *
+ * Note that this type does not itself own any resources. It points to resources
+ * owned within a `Store` and the `Store` must be passed in as the first
+ * argument to the functions defined on `Func`. Note that if the wrong `Store`
+ * is passed in then the process will be aborted.
+ */
+class Func {
+ friend class Val;
+ friend class Instance;
+ friend class Linker;
+ template <typename Params, typename Results> friend class TypedFunc;
+
+ wasmtime_func_t func;
+
+ template <typename F>
+ static wasm_trap_t *raw_callback(void *env, wasmtime_caller_t *caller,
+ const wasmtime_val_t *args, size_t nargs,
+ wasmtime_val_t *results, size_t nresults);
+
+ template <typename F>
+ static wasm_trap_t *
+ raw_callback_unchecked(void *env, wasmtime_caller_t *caller,
+ wasmtime_val_raw_t *args_and_results,
+ size_t nargs_and_results) {
+ (void)nargs_and_results;
+ using HostFunc = WasmHostFunc<F>;
+ Caller cx(caller);
+ F *func = reinterpret_cast<F *>(env); // NOLINT
+ auto trap = HostFunc::invoke(*func, cx, args_and_results);
+ if (trap) {
+ return trap->capi_release();
+ }
+ return nullptr;
+ }
+
+ template <typename F> static void raw_finalize(void *env) {
+ std::unique_ptr<F> ptr(reinterpret_cast<F *>(env)); // NOLINT
+ }
+
+public:
+ /// Creates a new function from the raw underlying C API representation.
+ Func(wasmtime_func_t func) : func(func) {}
+
+ /**
+ * \brief Creates a new host-defined function.
+ *
+ * This constructor is used to create a host function within the store
+ * provided. This is how WebAssembly can call into the host and make use of
+ * external functionality.
+ *
+ * > **Note**: host functions created this way are more flexible but not
+ * > as fast to call as those created by `Func::wrap`.
+ *
+ * \param cx the store to create the function within
+ * \param ty the type of the function that will be created
+ * \param f the host callback to be executed when this function is called.
+ *
+ * The parameter `f` is expected to be a lambda (or a lambda lookalike) which
+ * takes three parameters:
+ *
+ * * The first parameter is a `Caller` to get recursive access to the store
+ * and other caller state.
+ * * The second parameter is a `Span<const Val>` which is the list of
+ * parameters to the function. These parameters are guaranteed to be of the
+ * types specified by `ty` when constructing this function.
+ * * The last argument is `Span<Val>` which is where to write the return
+ * values of the function. The function must produce the types of values
+ * specified by `ty` or otherwise a trap will be raised.
+ *
+ * The parameter `f` is expected to return `Result<std::monostate, Trap>`.
+ * This allows `f` to raise a trap if desired, or otherwise return no trap and
+ * finish successfully. If a trap is raised then the results pointer does not
+ * need to be written to.
+ */
+ template <typename F,
+ std::enable_if_t<
+ std::is_invocable_r_v<Result<std::monostate, Trap>, F, Caller,
+ Span<const Val>, Span<Val>>,
+ bool> = true>
+ Func(Store::Context cx, const FuncType &ty, F f) : func({}) {
+ wasmtime_func_new(cx.ptr, ty.ptr.get(), raw_callback<F>,
+ std::make_unique<F>(f).release(), raw_finalize<F>, &func);
+ }
+
+ /**
+ * \brief Creates a new host function from the provided callback `f`,
+ * inferring the WebAssembly function type from the host signature.
+ *
+ * This function is akin to the `Func` constructor except that the WebAssembly
+ * type does not need to be specified and additionally the signature of `f`
+ * is different. The main goal of this function is to enable WebAssembly to
+ * call the function `f` as-fast-as-possible without having to validate any
+ * types or such.
+ *
+ * The function `f` can optionally take a `Caller` as its first parameter,
+ * but otherwise its arguments are translated to WebAssembly types:
+ *
+ * * `int32_t`, `uint32_t` - `i32`
+ * * `int64_t`, `uint64_t` - `i64`
+ * * `float` - `f32`
+ * * `double` - `f64`
+ * * `std::optional<Func>` - `funcref`
+ * * `std::optional<ExternRef>` - `externref`
+ * * `wasmtime::V128` - `v128`
+ *
+ * The function may only take these arguments and if it takes any other kinds
+ * of arguments then it will fail to compile.
+ *
+ * The function may return a few different flavors of return values:
+ *
+ * * `void` - interpreted as returning nothing
+ * * Any type above - interpreted as a singular return value.
+ * * `std::tuple<T...>` where `T` is one of the valid argument types -
+ * interpreted as returning multiple values.
+ * * `Result<T, Trap>` where `T` is another valid return type - interpreted as
+ * a function that returns `T` to wasm but is optionally allowed to also
+ * raise a trap.
+ *
+ * It's recommended, if possible, to use this function over the `Func`
+ * constructor since this is generally easier to work with and also enables
+ * a faster path for WebAssembly to call this function.
+ */
+ template <typename F,
+ std::enable_if_t<WasmHostFunc<F>::Params::valid, bool> = true,
+ std::enable_if_t<WasmHostFunc<F>::Results::valid, bool> = true>
+ static Func wrap(Store::Context cx, F f) {
+ using HostFunc = WasmHostFunc<F>;
+ auto params = HostFunc::Params::types();
+ auto results = HostFunc::Results::types();
+ auto ty = FuncType::from_iters(params, results);
+ wasmtime_func_t func;
+ wasmtime_func_new_unchecked(cx.ptr, ty.ptr.get(), raw_callback_unchecked<F>,
+ std::make_unique<F>(f).release(),
+ raw_finalize<F>, &func);
+ return func;
+ }
+
+ /**
+ * \brief Invoke a WebAssembly function.
+ *
+ * This function will execute this WebAssembly function. This function muts be
+ * defined within the `cx`'s store provided. The `params` argument is the list
+ * of parameters that are passed to the wasm function, and the types of the
+ * values within `params` must match the type signature of this function.
+ *
+ * This may return one of three values:
+ *
+ * * First the function could succeed, returning a vector of values
+ * representing the results of the function.
+ * * Otherwise a `Trap` might be generated by the WebAssembly function.
+ * * Finally an `Error` could be returned indicating that `params` were not of
+ * the right type.
+ *
+ * > **Note**: for optimized calls into WebAssembly where the function
+ * > signature is statically known it's recommended to use `Func::typed` and
+ * > `TypedFunc::call`.
+ */
+ template <typename I>
+ TrapResult<std::vector<Val>> call(Store::Context cx, const I &begin,
+ const I &end) const;
+
+ /**
+ * \brief Helper function for `call(Store::Context cx, const I &begin, const I
+ * &end)`
+ *
+ * \see call(Store::Context cx, const I &begin, const I &end)
+ */
+ TrapResult<std::vector<Val>> call(Store::Context cx,
+ const std::vector<Val> &params) const;
+
+ /**
+ * \brief Helper function for `call(Store::Context cx, const I &begin, const I
+ * &end)`
+ *
+ * \see call(Store::Context cx, const I &begin, const I &end)
+ */
+ TrapResult<std::vector<Val>>
+ call(Store::Context cx, const std::initializer_list<Val> &params) const;
+
+ /// Returns the type of this function.
+ FuncType type(Store::Context cx) const {
+ return wasmtime_func_type(cx.ptr, &func);
+ }
+
+ /**
+ * \brief Statically checks this function against the provided types.
+ *
+ * This function will check whether it takes the statically known `Params`
+ * and returns the statically known `Results`. If the type check succeeds then
+ * a `TypedFunc` is returned which enables a faster method of invoking
+ * WebAssembly functions.
+ *
+ * The `Params` and `Results` specified as template parameters here are the
+ * parameters and results of the wasm function. They can either be a bare
+ * type which means that the wasm takes/returns one value, or they can be a
+ * `std::tuple<T...>` of types to represent multiple arguments or multiple
+ * returns.
+ *
+ * The valid types for this function are those mentioned as the arguments
+ * for `Func::wrap`.
+ */
+ template <typename Params, typename Results,
+ std::enable_if_t<WasmTypeList<Params>::valid, bool> = true,
+ std::enable_if_t<WasmTypeList<Results>::valid, bool> = true>
+ Result<TypedFunc<Params, Results>, Trap> typed(Store::Context cx) const {
+ auto ty = this->type(cx);
+ if (!WasmTypeList<Params>::matches(ty->params()) ||
+ !WasmTypeList<Results>::matches(ty->results())) {
+ return Trap("static type for this function does not match actual type");
+ }
+ TypedFunc<Params, Results> ret(*this);
+ return ret;
+ }
+
+ /// Returns the raw underlying C API function this is using.
+ const wasmtime_func_t &capi() const { return func; }
+};
+
+/**
+ * \brief A version of a WebAssembly `Func` where the type signature of the
+ * function is statically known.
+ */
+template <typename Params, typename Results> class TypedFunc {
+ friend class Func;
+ Func f;
+ TypedFunc(Func func) : f(func) {}
+
+public:
+ /**
+ * \brief Calls this function with the provided parameters.
+ *
+ * This function is akin to `Func::call` except that since static type
+ * information is available it statically takes its parameters and statically
+ * returns its results.
+ *
+ * Note that this function still may return a `Trap` indicating that calling
+ * the WebAssembly function failed.
+ */
+ TrapResult<Results> call(Store::Context cx, const Params &params) const {
+ std::array<wasmtime_val_raw_t, std::max(WasmTypeList<Params>::size,
+ WasmTypeList<Results>::size)>
+ storage;
+ wasmtime_val_raw_t *ptr = storage.data();
+ if (ptr == nullptr)
+ ptr = reinterpret_cast<wasmtime_val_raw_t *>(alignof(wasmtime_val_raw_t));
+ WasmTypeList<Params>::store(cx, ptr, params);
+ wasm_trap_t *trap = nullptr;
+ auto *error = wasmtime_func_call_unchecked(cx.capi(), &f.func, ptr,
+ storage.size(), &trap);
+ if (error != nullptr) {
+ return TrapError(Error(error));
+ }
+ if (trap != nullptr) {
+ return TrapError(Trap(trap));
+ }
+ return WasmTypeList<Results>::load(cx, ptr);
+ }
+
+ /// Returns the underlying un-typed `Func` for this function.
+ const Func &func() const { return f; }
+};
+
+} // namespace wasmtime
+
+#endif // WASMTIME_FUNC_CLASS_HH
diff --git a/crates/c-api/include/wasmtime/_store_class.hh b/crates/c-api/include/wasmtime/_store_class.hh
new file mode 100644
index 0000000000..199271353b
--- /dev/null
+++ b/crates/c-api/include/wasmtime/_store_class.hh
@@ -0,0 +1,281 @@
+#ifndef WASMTIME_STORE_CLASS_HH
+#define WASMTIME_STORE_CLASS_HH
+
+#include <any>
+#include <memory>
+#include <optional>
+#include <wasmtime/conf.h>
+#include <wasmtime/engine.hh>
+#include <wasmtime/error.hh>
+#include <wasmtime/helpers.hh>
+#include <wasmtime/store.h>
+#include <wasmtime/wasi.hh>
+
+namespace wasmtime {
+
+class Caller;
+class Tag;
+class ExnRef;
+class Trap;
+
+/// \brief An enum for the behavior before extending the epoch deadline.
+enum class DeadlineKind {
+ /// Directly continue to updating the deadline and executing WebAssembly.
+ Continue = WASMTIME_UPDATE_DEADLINE_CONTINUE,
+ /// Yield control (via async support) then update the deadline.
+ Yield = WASMTIME_UPDATE_DEADLINE_YIELD,
+};
+
+/**
+ * \brief Owner of all WebAssembly objects
+ *
+ * A `Store` owns all WebAssembly objects such as instances, globals, functions,
+ * memories, etc. A `Store` is one of the main central points about working with
+ * WebAssembly since it's an argument to almost all APIs. The `Store` serves as
+ * a form of "context" to give meaning to the pointers of `Func` and friends.
+ *
+ * A `Store` can be sent between threads but it cannot generally be shared
+ * concurrently between threads. Memory associated with WebAssembly instances
+ * will be deallocated when the `Store` is deallocated.
+ */
+class Store {
+ WASMTIME_OWN_WRAPPER(Store, wasmtime_store);
+
+private:
+ static void finalizer(void *ptr) {
+ std::unique_ptr<std::any> _ptr(static_cast<std::any *>(ptr));
+ }
+
+public:
+ /// Creates a new `Store` within the provided `Engine`.
+ explicit Store(Engine &engine)
+ : ptr(wasmtime_store_new(engine.capi(), nullptr, finalizer)) {}
+
+ /**
+ * \brief An interior pointer into a `Store`.
+ *
+ * A `Context` object is created from either a `Store` or a `Caller`. It is an
+ * interior pointer into a `Store` and cannot be used outside the lifetime of
+ * the original object it was created from.
+ *
+ * This object is an argument to most APIs in Wasmtime but typically doesn't
+ * need to be constructed explicitly since it can be created from a `Store&`
+ * or a `Caller&`.
+ */
+ class Context {
+ friend class Global;
+ friend class Table;
+ friend class Memory;
+ friend class Func;
+ friend class Instance;
+ friend class Linker;
+ friend class Val;
+ friend class Store;
+ friend class Tag;
+ wasmtime_context_t *ptr;
+
+ public:
+ /// Creates a context from the raw C API pointer.
+ explicit Context(wasmtime_context_t *ptr) : ptr(ptr) {}
+
+ /// Creates a context referencing the provided `Store`.
+ Context(Store &store) : Context(wasmtime_store_context(store.ptr.get())) {}
+ /// Creates a context referencing the provided `Store`.
+ Context(Store *store) : Context(*store) {}
+ /// Creates a context referencing the provided `Caller`.
+ Context(Caller &caller);
+ /// Creates a context referencing the provided `Caller`.
+ Context(Caller *caller);
+
+#ifdef WASMTIME_FEATURE_GC
+ /// Runs a garbage collection pass in the referenced store to collect loose
+ /// `externref` values, if any are available.
+ Result<std::monostate> gc() {
+ auto *error = wasmtime_context_gc(ptr);
+ if (error != nullptr) {
+ return Error(error);
+ }
+ return std::monostate();
+ }
+#endif
+
+ /// Injects fuel to be consumed within this store.
+ ///
+ /// Stores start with 0 fuel and if `Config::consume_fuel` is enabled then
+ /// this is required if you want to let WebAssembly actually execute.
+ ///
+ /// Returns an error if fuel consumption isn't enabled.
+ Result<std::monostate> set_fuel(uint64_t fuel) {
+ auto *error = wasmtime_context_set_fuel(ptr, fuel);
+ if (error != nullptr) {
+ return Error(error);
+ }
+ return std::monostate();
+ }
+
+ /// Returns the amount of fuel consumed so far by executing WebAssembly.
+ ///
+ /// Returns `std::nullopt` if fuel consumption is not enabled.
+ Result<uint64_t> get_fuel() const {
+ uint64_t fuel = 0;
+ auto *error = wasmtime_context_get_fuel(ptr, &fuel);
+ if (error != nullptr) {
+ return Error(error);
+ }
+ return fuel;
+ }
+
+ /// Set user specified data associated with this store.
+ void set_data(std::any data) const {
+ finalizer(static_cast<std::any *>(wasmtime_context_get_data(ptr)));
+ wasmtime_context_set_data(
+ ptr, std::make_unique<std::any>(std::move(data)).release());
+ }
+
+ /// Get user specified data associated with this store.
+ std::any &get_data() const {
+ return *static_cast<std::any *>(wasmtime_context_get_data(ptr));
+ }
+
+#ifdef WASMTIME_FEATURE_WASI
+ /// Configures the WASI state used by this store.
+ ///
+ /// This will only have an effect if used in conjunction with
+ /// `Linker::define_wasi` because otherwise no host functions will use the
+ /// WASI state.
+ Result<std::monostate> set_wasi(WasiConfig config) {
+ auto *error = wasmtime_context_set_wasi(ptr, config.capi_release());
+ if (error != nullptr) {
+ return Error(error);
+ }
+ return std::monostate();
+ }
+#endif // WASMTIME_FEATURE_WASI
+
+ /// Configures this store's epoch deadline to be the specified number of
+ /// ticks beyond the engine's current epoch.
+ ///
+ /// By default the deadline is the current engine's epoch, immediately
+ /// interrupting code if epoch interruption is enabled. This must be called
+ /// to extend the deadline to allow interruption.
+ void set_epoch_deadline(uint64_t ticks_beyond_current) {
+ wasmtime_context_set_epoch_deadline(ptr, ticks_beyond_current);
+ }
+
+#ifdef WASMTIME_FEATURE_GC
+ /// \brief Sets the pending exception on the store and returns a Trap.
+ ///
+ /// This transfers ownership of `exn`. After this call, `exn` is consumed.
+ /// Returns a Trap that the host callback MUST return to propagate the
+ /// exception through Wasm catch blocks.
+ inline Trap throw_exception(ExnRef exn);
+
+ /// \brief Takes the pending exception from the store, if any.
+ ///
+ /// Returns the exception if one was pending, or std::nullopt.
+ inline std::optional<ExnRef> take_exception();
+
+ /// \brief Tests whether there is a pending exception on the store.
+ inline bool has_exception();
+#endif // WASMTIME_FEATURE_GC
+
+ /// \brief Returns the underlying C API pointer.
+ const wasmtime_context_t *capi() const { return ptr; }
+
+ /// \brief Returns the underlying C API pointer.
+ wasmtime_context_t *capi() { return ptr; }
+ };
+
+ /// \brief Provides limits for a store. Used by hosts to limit resource
+ /// consumption of instances. Use negative value to keep the default value
+ /// for the limit.
+ ///
+ /// \param memory_size the maximum number of bytes a linear memory can grow
+ /// to. Growing a linear memory beyond this limit will fail. By default,
+ /// linear memory will not be limited.
+ ///
+ /// \param table_elements the maximum number of elements in a table.
+ /// Growing a table beyond this limit will fail. By default, table elements
+ /// will not be limited.
+ ///
+ /// \param instances the maximum number of instances that can be created
+ /// for a Store. Module instantiation will fail if this limit is exceeded.
+ /// This value defaults to 10,000.
+ ///
+ /// \param tables the maximum number of tables that can be created for a
+ /// Store. Module instantiation will fail if this limit is exceeded. This
+ /// value defaults to 10,000.
+ ///
+ /// \param memories the maximum number of linear
+ /// memories that can be created for a Store. Instantiation will fail with an
+ /// error if this limit is exceeded. This value defaults to 10,000.
+ ///
+ /// Use any negative value for the parameters that should be kept on
+ /// the default values.
+ ///
+ /// Note that the limits are only used to limit the creation/growth of
+ /// resources in the future, this does not retroactively attempt to apply
+ /// limits to the store.
+ void limiter(int64_t memory_size, int64_t table_elements, int64_t instances,
+ int64_t tables, int64_t memories) {
+ wasmtime_store_limiter(ptr.get(), memory_size, table_elements, instances,
+ tables, memories);
+ }
+
+ /// \brief Configures epoch deadline callback to C function.
+ ///
+ /// This function configures a store-local callback function that will be
+ /// called when the running WebAssembly function has exceeded its epoch
+ /// deadline. That function can:
+ /// - return an error to terminate the function
+ /// - set the delta argument and return DeadlineKind::Continue to update the
+ /// epoch deadline delta and resume function execution.
+ /// - set the delta argument, update the epoch deadline, and return
+ /// DeadlineKind::Yield to yield (via async support) and resume function
+ /// execution.
+ template <typename F,
+ std::enable_if_t<std::is_invocable_r_v<Result<DeadlineKind>, F,
+ Context, uint64_t &>,
+ bool> = true>
+ void epoch_deadline_callback(F &&f) {
+ wasmtime_store_epoch_deadline_callback(
+ ptr.get(), raw_epoch_callback<std::remove_reference_t<F>>,
+ std::make_unique<std::remove_reference_t<F>>(std::forward<F>(f))
+ .release(),
+ raw_epoch_finalizer<std::remove_reference_t<F>>);
+ }
+
+ /// Explicit function to acquire a `Context` from this store.
+ Context context() { return this; }
+
+#ifdef WASMTIME_FEATURE_GC
+ /// Runs a garbage collection pass in the referenced store to collect loose
+ /// GC-managed objects, if any are available.
+ Result<std::monostate> gc() { return context().gc(); }
+#endif
+
+private:
+ template <typename F>
+ static wasmtime_error_t *
+ raw_epoch_callback(wasmtime_context_t *context, void *data,
+ uint64_t *epoch_deadline_delta,
+ wasmtime_update_deadline_kind_t *update_kind) {
+ auto &callback = *static_cast<F *>(data);
+ Context ctx(context);
+ auto result = callback(ctx, *epoch_deadline_delta);
+
+ if (!result) {
+ return result.err().capi_release();
+ }
+ *update_kind = static_cast<wasmtime_update_deadline_kind_t>(result.ok());
+ return nullptr;
+ }
+
+ template <typename F> static void raw_epoch_finalizer(void *data) {
+ std::unique_ptr<F> _ptr(static_cast<F *>(data));
+ }
+};
+
+} // namespace wasmtime
+
+#endif // WASMTIME_STORE_CLASS_HH
diff --git a/crates/c-api/include/wasmtime/_structref_class.hh b/crates/c-api/include/wasmtime/_structref_class.hh
new file mode 100644
index 0000000000..628237000b
--- /dev/null
+++ b/crates/c-api/include/wasmtime/_structref_class.hh
@@ -0,0 +1,65 @@
+#ifndef WASMTIME_STRUCTREF_CLASS_HH
+#define WASMTIME_STRUCTREF_CLASS_HH
+
+#include <wasmtime/conf.h>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <wasmtime/_anyref_class.hh>
+#include <wasmtime/_eqref_class.hh>
+#include <wasmtime/_store_class.hh>
+#include <wasmtime/helpers.hh>
+#include <wasmtime/structref.h>
+#include <wasmtime/types/structref.hh>
+
+namespace wasmtime {
+
+class Val;
+
+/**
+ * \brief Pre-allocated struct layout for fast allocation of struct instances.
+ *
+ * Created from a StructType and a store context. Reusable for allocating
+ * many struct instances of the same type.
+ */
+class StructRefPre {
+ WASMTIME_OWN_WRAPPER(StructRefPre, wasmtime_struct_ref_pre)
+
+ /// Create a new struct pre-allocator.
+ static StructRefPre create(Store::Context cx, const StructType &ty) {
+ return StructRefPre(wasmtime_struct_ref_pre_new(cx.capi(), ty.capi()));
+ }
+};
+
+/**
+ * \brief Representation of a WebAssembly `structref` value.
+ *
+ * A `structref` is a reference to a GC struct instance. It is a subtype
+ * of `eqref` and `anyref`.
+ */
+class StructRef {
+ WASMTIME_REF_WRAPPER(StructRef, wasmtime_structref);
+
+ /// Allocate a new struct instance.
+ static Result<StructRef> create(Store::Context cx, const StructRefPre &pre,
+ const std::vector<Val> &fields);
+
+ /// Read a field from the struct.
+ Result<Val> field(Store::Context cx, size_t index) const;
+
+ /// Set a field of the struct.
+ Result<std::monostate> set_field(Store::Context cx, size_t index,
+ const Val &value) const;
+
+ /// Upcast to anyref.
+ AnyRef to_anyref() const;
+
+ /// Upcast to eqref.
+ EqRef to_eqref() const;
+};
+
+} // namespace wasmtime
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_STRUCTREF_CLASS_HH
diff --git a/crates/c-api/include/wasmtime/_val_class.hh b/crates/c-api/include/wasmtime/_val_class.hh
new file mode 100644
index 0000000000..e275b172e9
--- /dev/null
+++ b/crates/c-api/include/wasmtime/_val_class.hh
@@ -0,0 +1,237 @@
+#ifndef WASMTIME_VAL_CLASS_HH
+#define WASMTIME_VAL_CLASS_HH
+
+#include <optional>
+#include <wasmtime/_anyref_class.hh>
+#include <wasmtime/_arrayref_class.hh>
+#include <wasmtime/_eqref_class.hh>
+#include <wasmtime/_externref_class.hh>
+#include <wasmtime/_func_class.hh>
+#include <wasmtime/_store_class.hh>
+#include <wasmtime/_structref_class.hh>
+#include <wasmtime/types/val.hh>
+#include <wasmtime/val.h>
+
+namespace wasmtime {
+
+/// \brief Container for the `v128` WebAssembly type.
+struct V128 {
+ /// \brief The little-endian bytes of the `v128` value.
+ wasmtime_v128 v128;
+
+ /// \brief Creates a new zero-value `v128`.
+ V128() : v128{} { memset(&v128[0], 0, sizeof(wasmtime_v128)); }
+
+ /// \brief Creates a new `V128` from its C API representation.
+ V128(const wasmtime_v128 &v) : v128{} {
+ memcpy(&v128[0], &v[0], sizeof(wasmtime_v128));
+ }
+};
+
+/**
+ * \brief Representation of a generic WebAssembly value.
+ *
+ * This is roughly equivalent to a tagged union of all possible WebAssembly
+ * values. This is later used as an argument with functions, globals, tables,
+ * etc.
+ *
+ * Note that a `Val` can represent owned GC pointers. In this case the `unroot`
+ * method must be used to ensure that they can later be garbage-collected.
+ */
+class Val {
+ friend class Global;
+ friend class Table;
+ friend class Func;
+
+ wasmtime_val_t val;
+
+ Val() : val{} {
+ val.kind = WASMTIME_I32;
+ val.of.i32 = 0;
+ }
+
+public:
+ /// Creates a new value from the raw C API representation.
+ Val(wasmtime_val_t val) : val(val) {}
+
+ /// Creates a new `i32` WebAssembly value.
+ Val(int32_t i32) : val{} {
+ val.kind = WASMTIME_I32;
+ val.of.i32 = i32;
+ }
+ /// Creates a new `i64` WebAssembly value.
+ Val(int64_t i64) : val{} {
+ val.kind = WASMTIME_I64;
+ val.of.i64 = i64;
+ }
+ /// Creates a new `f32` WebAssembly value.
+ Val(float f32) : val{} {
+ val.kind = WASMTIME_F32;
+ val.of.f32 = f32;
+ }
+ /// Creates a new `f64` WebAssembly value.
+ Val(double f64) : val{} {
+ val.kind = WASMTIME_F64;
+ val.of.f64 = f64;
+ }
+ /// Creates a new `v128` WebAssembly value.
+ Val(const V128 &v128) : val{} {
+ val.kind = WASMTIME_V128;
+ memcpy(&val.of.v128[0], &v128.v128[0], sizeof(wasmtime_v128));
+ }
+ /// Creates a new `funcref` WebAssembly value.
+ Val(std::optional<Func> func);
+ /// Creates a new `funcref` WebAssembly value which is not `ref.null func`.
+ Val(Func func);
+#ifdef WASMTIME_FEATURE_GC
+ /// Creates a new `externref` value.
+ Val(std::optional<ExternRef> ptr);
+ /// Creates a new `anyref` value.
+ Val(std::optional<AnyRef> ptr);
+ /// Creates a new `externref` WebAssembly value which is not `ref.null
+ /// extern`.
+ Val(ExternRef ptr);
+ /// Creates a new `anyref` WebAssembly value which is not `ref.null
+ /// any`.
+ Val(AnyRef ptr);
+#endif
+
+ /// 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) {
+ case WASMTIME_I32:
+ return ValKind::I32;
+ case WASMTIME_I64:
+ return ValKind::I64;
+ case WASMTIME_F32:
+ return ValKind::F32;
+ case WASMTIME_F64:
+ return ValKind::F64;
+ case WASMTIME_FUNCREF:
+ return ValKind::FuncRef;
+ case WASMTIME_EXTERNREF:
+ return ValKind::ExternRef;
+ case WASMTIME_ANYREF:
+ return ValKind::AnyRef;
+ case WASMTIME_EXNREF:
+ return ValKind::ExnRef;
+ case WASMTIME_V128:
+ return ValKind::V128;
+ }
+ std::abort();
+ }
+
+ /// Returns the underlying `i32`, requires `kind() == KindI32` or aborts the
+ /// process.
+ int32_t i32() const {
+ if (val.kind != WASMTIME_I32) {
+ std::abort();
+ }
+ return val.of.i32;
+ }
+
+ /// Returns the underlying `i64`, requires `kind() == KindI64` or aborts the
+ /// process.
+ int64_t i64() const {
+ if (val.kind != WASMTIME_I64) {
+ std::abort();
+ }
+ return val.of.i64;
+ }
+
+ /// Returns the underlying `f32`, requires `kind() == KindF32` or aborts the
+ /// process.
+ float f32() const {
+ if (val.kind != WASMTIME_F32) {
+ std::abort();
+ }
+ return val.of.f32;
+ }
+
+ /// Returns the underlying `f64`, requires `kind() == KindF64` or aborts the
+ /// process.
+ double f64() const {
+ if (val.kind != WASMTIME_F64) {
+ std::abort();
+ }
+ return val.of.f64;
+ }
+
+ /// Returns the underlying `v128`, requires `kind() == KindV128` or aborts
+ /// the process.
+ V128 v128() const {
+ if (val.kind != WASMTIME_V128) {
+ std::abort();
+ }
+ return val.of.v128;
+ }
+
+#ifdef WASMTIME_FEATURE_GC
+ /// Returns the underlying `externref`, requires `kind() == KindExternRef` or
+ /// aborts the process.
+ ///
+ /// Note that `externref` is a nullable reference, hence the `optional` return
+ /// value.
+ std::optional<ExternRef> externref() const;
+
+ /// Returns the underlying `anyref`, requires `kind() == KindAnyRef` or
+ /// aborts the process.
+ ///
+ /// Note that `anyref` is a nullable reference, hence the `optional` return
+ /// value.
+ std::optional<AnyRef> anyref() const;
+#endif
+
+ /// Returns the underlying `funcref`, requires `kind() == KindFuncRef` or
+ /// aborts the process.
+ ///
+ /// Note that `funcref` is a nullable reference, hence the `optional` return
+ /// value.
+ std::optional<Func> funcref() const;
+
+ /// Raw C-API representation.
+ using Raw = wasmtime_val_t;
+
+ /**
+ * \brief Returns the underlying C API pointer.
+ */
+ const Raw *capi() const { return &val; }
+
+ /**
+ * \brief Returns the underlying C API pointer.
+ */
+ Raw *capi() { return &val; }
+};
+
+} // namespace wasmtime
+
+#endif // WASMTIME_VAL_CLASS_HH
diff --git a/crates/c-api/include/wasmtime/anyref.h b/crates/c-api/include/wasmtime/anyref.h
new file mode 100644
index 0000000000..896db368e9
--- /dev/null
+++ b/crates/c-api/include/wasmtime/anyref.h
@@ -0,0 +1,189 @@
+/**
+ * \file wasmtime/anyref.h
+ *
+ * APIs for interacting with WebAssembly GC `anyref` type in Wasmtime.
+ */
+
+#ifndef WASMTIME_ANYREF_H
+#define WASMTIME_ANYREF_H
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <wasmtime/val.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/// \brief Helper function to initialize the `ref` provided to a null anyref
+/// value.
+static inline void wasmtime_anyref_set_null(wasmtime_anyref_t *ref) {
+ ref->store_id = 0;
+}
+
+/// \brief Helper function to return whether the provided `ref` points to a null
+/// `anyref` value.
+///
+/// Note that `ref` itself should not be null as null is represented internally
+/// within a #wasmtime_anyref_t value.
+static inline bool wasmtime_anyref_is_null(const wasmtime_anyref_t *ref) {
+ return ref->store_id == 0;
+}
+
+/**
+ * \brief Creates a new reference pointing to the same data that `anyref`
+ * points to (depending on the configured collector this might increase a
+ * reference count or create a new GC root).
+ *
+ * The returned reference is stored in `out`.
+ */
+WASM_API_EXTERN void wasmtime_anyref_clone(const wasmtime_anyref_t *anyref,
+ wasmtime_anyref_t *out);
+
+/**
+ * \brief Unroots the `ref` provided within the `context`.
+ *
+ * This API is required to enable the `ref` value provided to be
+ * garbage-collected. This API itself does not necessarily garbage-collect the
+ * value, but it's possible to collect it in the future after this.
+ *
+ * This may modify `ref` and the contents of `ref` are left in an undefined
+ * state after this API is called and it should no longer be used.
+ *
+ * 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_anyref_t *ref);
+
+/**
+ * \brief Converts a raw `anyref` value coming from #wasmtime_val_raw_t into
+ * a #wasmtime_anyref_t.
+ *
+ * The provided `out` pointer is filled in with a reference converted from
+ * `raw`.
+ */
+WASM_API_EXTERN void wasmtime_anyref_from_raw(wasmtime_context_t *context,
+ uint32_t raw,
+ wasmtime_anyref_t *out);
+
+/**
+ * \brief Converts a #wasmtime_anyref_t to a raw value suitable for storing
+ * into a #wasmtime_val_raw_t.
+ *
+ * Note that the returned underlying value is not tracked by Wasmtime's garbage
+ * collector until it enters WebAssembly. This means that a GC may release the
+ * context's reference to the raw value, making the raw value invalid within the
+ * context of the store. Do not perform a GC between calling this function and
+ * passing it to WebAssembly.
+ */
+WASM_API_EXTERN uint32_t wasmtime_anyref_to_raw(wasmtime_context_t *context,
+ const wasmtime_anyref_t *ref);
+
+/**
+ * \brief Create a new `i31ref` value.
+ *
+ * Creates a new `i31ref` value (which is a subtype of `anyref`) and returns a
+ * pointer to it.
+ *
+ * If `i31val` does not fit in 31 bits, it is wrapped.
+ */
+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.
+ *
+ * If the given `anyref` is an instance of `i31ref`, then its value is zero
+ * extended to 32 bits, written to `dst`, and `true` is returned.
+ *
+ * If the given `anyref` is not an instance of `i31ref`, then `false` is
+ * returned and `dst` is left unmodified.
+ */
+WASM_API_EXTERN bool wasmtime_anyref_i31_get_u(wasmtime_context_t *context,
+ const wasmtime_anyref_t *anyref,
+ uint32_t *dst);
+
+/**
+ * \brief Get the `anyref`'s underlying `i31ref` value, sign extended, if any.
+ *
+ * If the given `anyref` is an instance of `i31ref`, then its value is sign
+ * extended to 32 bits, written to `dst`, and `true` is returned.
+ *
+ * If the given `anyref` is not an instance of `i31ref`, then `false` is
+ * returned and `dst` is left unmodified.
+ */
+WASM_API_EXTERN bool wasmtime_anyref_i31_get_s(wasmtime_context_t *context,
+ const wasmtime_anyref_t *anyref,
+ int32_t *dst);
+
+/**
+ * \brief Test whether an `anyref` is an `eqref`.
+ *
+ * Returns `false` for null references.
+ */
+WASM_API_EXTERN bool wasmtime_anyref_is_eqref(wasmtime_context_t *context,
+ const wasmtime_anyref_t *anyref);
+
+/**
+ * \brief Downcast an `anyref` to an `eqref`.
+ *
+ * If the given `anyref` is an `eqref`, a new root is stored in `out` and
+ * `true` is returned. Otherwise `false` is returned and `out` is set to null.
+ */
+WASM_API_EXTERN bool wasmtime_anyref_as_eqref(wasmtime_context_t *context,
+ const wasmtime_anyref_t *anyref,
+ wasmtime_eqref_t *out);
+
+/**
+ * \brief Test whether an `anyref` is a `structref`.
+ *
+ * Returns `false` for null references.
+ */
+WASM_API_EXTERN bool wasmtime_anyref_is_struct(wasmtime_context_t *context,
+ const wasmtime_anyref_t *anyref);
+
+/**
+ * \brief Downcast an `anyref` to a `structref`.
+ *
+ * If the given `anyref` is a `structref`, a new root is stored in `out` and
+ * `true` is returned. Otherwise `false` is returned and `out` is set to null.
+ */
+WASM_API_EXTERN bool wasmtime_anyref_as_struct(wasmtime_context_t *context,
+ const wasmtime_anyref_t *anyref,
+ wasmtime_structref_t *out);
+
+/**
+ * \brief Test whether an `anyref` is an `arrayref`.
+ *
+ * Returns `false` for null references.
+ */
+WASM_API_EXTERN bool wasmtime_anyref_is_array(wasmtime_context_t *context,
+ const wasmtime_anyref_t *anyref);
+
+/**
+ * \brief Downcast an `anyref` to an `arrayref`.
+ *
+ * If the given `anyref` is an `arrayref`, a new root is stored in `out` and
+ * `true` is returned. Otherwise `false` is returned and `out` is set to null.
+ */
+WASM_API_EXTERN bool wasmtime_anyref_as_array(wasmtime_context_t *context,
+ const wasmtime_anyref_t *anyref,
+ wasmtime_arrayref_t *out);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_ANYREF_H
diff --git a/crates/c-api/include/wasmtime/anyref.hh b/crates/c-api/include/wasmtime/anyref.hh
new file mode 100644
index 0000000000..265b2a2414
--- /dev/null
+++ b/crates/c-api/include/wasmtime/anyref.hh
@@ -0,0 +1,51 @@
+/**
+ * \file wasmtime/anyref.hh
+ */
+
+#ifndef WASMTIME_ANYREF_HH
+#define WASMTIME_ANYREF_HH
+
+#include <wasmtime/_anyref_class.hh>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <wasmtime/_arrayref_class.hh>
+#include <wasmtime/_eqref_class.hh>
+#include <wasmtime/_structref_class.hh>
+
+namespace wasmtime {
+
+// AnyRef downcast method definitions (declared in val.hh)
+inline bool AnyRef::is_eqref(Store::Context cx) const {
+ return wasmtime_anyref_is_eqref(cx.capi(), &raw);
+}
+inline bool AnyRef::is_struct(Store::Context cx) const {
+ return wasmtime_anyref_is_struct(cx.capi(), &raw);
+}
+inline bool AnyRef::is_array(Store::Context cx) const {
+ return wasmtime_anyref_is_array(cx.capi(), &raw);
+}
+inline std::optional<EqRef> AnyRef::as_eqref(Store::Context cx) const {
+ wasmtime_eqref_t out;
+ if (wasmtime_anyref_as_eqref(cx.capi(), &raw, &out))
+ return EqRef(out);
+ return std::nullopt;
+}
+inline std::optional<StructRef> AnyRef::as_struct(Store::Context cx) const {
+ wasmtime_structref_t out;
+ if (wasmtime_anyref_as_struct(cx.capi(), &raw, &out))
+ return StructRef(out);
+ return std::nullopt;
+}
+inline std::optional<ArrayRef> AnyRef::as_array(Store::Context cx) const {
+ wasmtime_arrayref_t out;
+ if (wasmtime_anyref_as_array(cx.capi(), &raw, &out))
+ return ArrayRef(out);
+ return std::nullopt;
+}
+
+} // namespace wasmtime
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_ANYREF_HH
diff --git a/crates/c-api/include/wasmtime/arrayref.h b/crates/c-api/include/wasmtime/arrayref.h
new file mode 100644
index 0000000000..3f404ae0ff
--- /dev/null
+++ b/crates/c-api/include/wasmtime/arrayref.h
@@ -0,0 +1,151 @@
+/**
+ * \file wasmtime/arrayref.h
+ *
+ * APIs for interacting with WebAssembly `arrayref` type in Wasmtime.
+ */
+
+#ifndef WASMTIME_ARRAYREF_H
+#define WASMTIME_ARRAYREF_H
+
+#include <wasmtime/conf.h>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <wasmtime/types/arrayref.h>
+#include <wasmtime/val.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief An opaque pre-allocated array layout for fast allocation.
+ *
+ * Created from a #wasmtime_array_type_t and a store context. Reusable for
+ * allocating many array instances of the same type.
+ *
+ * Owned. Must be deleted with #wasmtime_array_ref_pre_delete.
+ */
+typedef struct wasmtime_array_ref_pre wasmtime_array_ref_pre_t;
+
+/**
+ * \brief Create a new array pre-allocator.
+ *
+ * \param context The store context.
+ * \param ty The array type (not consumed; caller retains ownership).
+ *
+ * \return Returns a new array ref pre-allocator.
+ */
+WASM_API_EXTERN wasmtime_array_ref_pre_t *
+wasmtime_array_ref_pre_new(wasmtime_context_t *context,
+ const wasmtime_array_type_t *ty);
+
+/**
+ * \brief Delete an array pre-allocator.
+ */
+WASM_API_EXTERN void
+wasmtime_array_ref_pre_delete(wasmtime_array_ref_pre_t *pre);
+
+/// \brief Initialize the `ref` to a null `arrayref` value.
+static inline void wasmtime_arrayref_set_null(wasmtime_arrayref_t *ref) {
+ ref->store_id = 0;
+}
+
+/// \brief Returns whether the provided `ref` is a null `arrayref` value.
+static inline bool wasmtime_arrayref_is_null(const wasmtime_arrayref_t *ref) {
+ return ref->store_id == 0;
+}
+
+/**
+ * \brief Allocate a new array instance.
+ *
+ * All elements are initialized to the same value.
+ *
+ * \param context The store context.
+ * \param pre The array pre-allocator.
+ * \param elem The initial element value.
+ * \param len The number of elements.
+ * \param out Receives the new arrayref on success.
+ *
+ * \return NULL on success, or a #wasmtime_error_t on failure.
+ */
+WASM_API_EXTERN wasmtime_error_t *wasmtime_arrayref_new(
+ wasmtime_context_t *context, const wasmtime_array_ref_pre_t *pre,
+ const wasmtime_val_t *elem, uint32_t len, wasmtime_arrayref_t *out);
+
+/**
+ * \brief Clone an `arrayref`, creating a new root.
+ */
+WASM_API_EXTERN void
+wasmtime_arrayref_clone(const wasmtime_arrayref_t *arrayref,
+ wasmtime_arrayref_t *out);
+
+/**
+ * \brief Unroot an `arrayref` to allow garbage collection.
+ */
+WASM_API_EXTERN void wasmtime_arrayref_unroot(wasmtime_arrayref_t *ref);
+
+/**
+ * \brief Upcast an `arrayref` to an `anyref`.
+ */
+WASM_API_EXTERN void
+wasmtime_arrayref_to_anyref(const wasmtime_arrayref_t *arrayref,
+ wasmtime_anyref_t *out);
+
+/**
+ * \brief Upcast an `arrayref` to an `eqref`.
+ */
+WASM_API_EXTERN void
+wasmtime_arrayref_to_eqref(const wasmtime_arrayref_t *arrayref,
+ wasmtime_eqref_t *out);
+
+/**
+ * \brief Get the length of an array.
+ *
+ * \param context The store context.
+ * \param arrayref The array (not consumed).
+ * \param out Receives the length on success.
+ *
+ * \return NULL on success, or a #wasmtime_error_t on failure.
+ */
+WASM_API_EXTERN wasmtime_error_t *
+wasmtime_arrayref_len(wasmtime_context_t *context,
+ const wasmtime_arrayref_t *arrayref, uint32_t *out);
+
+/**
+ * \brief Read an element from an array.
+ *
+ * \param context The store context.
+ * \param arrayref The array (not consumed).
+ * \param index The element index.
+ * \param out Receives the element value on success.
+ *
+ * \return NULL on success, or a #wasmtime_error_t on failure.
+ */
+WASM_API_EXTERN wasmtime_error_t *
+wasmtime_arrayref_get(wasmtime_context_t *context,
+ const wasmtime_arrayref_t *arrayref, uint32_t index,
+ wasmtime_val_t *out);
+
+/**
+ * \brief Set an element of an array.
+ *
+ * \param context The store context.
+ * \param arrayref The array (not consumed).
+ * \param index The element index.
+ * \param val The value to write.
+ *
+ * \return NULL on success, or a #wasmtime_error_t on failure.
+ */
+WASM_API_EXTERN wasmtime_error_t *
+wasmtime_arrayref_set(wasmtime_context_t *context,
+ const wasmtime_arrayref_t *arrayref, uint32_t index,
+ const wasmtime_val_t *val);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_ARRAYREF_H
diff --git a/crates/c-api/include/wasmtime/arrayref.hh b/crates/c-api/include/wasmtime/arrayref.hh
new file mode 100644
index 0000000000..718c10733d
--- /dev/null
+++ b/crates/c-api/include/wasmtime/arrayref.hh
@@ -0,0 +1,63 @@
+/**
+ * \file wasmtime/arrayref.hh
+ */
+
+#ifndef WASMTIME_ARRAYREF_HH
+#define WASMTIME_ARRAYREF_HH
+
+#include <wasmtime/_arrayref_class.hh>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <wasmtime/_anyref_class.hh>
+#include <wasmtime/_eqref_class.hh>
+#include <wasmtime/_val_class.hh>
+
+namespace wasmtime {
+
+inline Result<ArrayRef> ArrayRef::create(Store::Context cx,
+ const ArrayRefPre &pre,
+ const Val &elem, uint32_t len) {
+ wasmtime_arrayref_t out;
+ auto *err =
+ wasmtime_arrayref_new(cx.capi(), pre.capi(), elem.capi(), len, &out);
+ if (err)
+ return Result<ArrayRef>(Error(err));
+ return Result<ArrayRef>(ArrayRef(out));
+}
+
+inline Result<Val> ArrayRef::get(Store::Context cx, uint32_t index) const {
+ wasmtime_val_t out;
+ auto *err = wasmtime_arrayref_get(cx.capi(), &raw, index, &out);
+ if (err)
+ return Result<Val>(Error(err));
+ return Result<Val>(Val(out));
+}
+
+inline Result<std::monostate> ArrayRef::set(Store::Context cx, uint32_t index,
+ const Val &value) const {
+ auto *err = wasmtime_arrayref_set(cx.capi(), &raw, index, value.capi());
+ if (err)
+ return Result<std::monostate>(Error(err));
+ return Result<std::monostate>(std::monostate{});
+}
+
+/// Upcast to anyref.
+inline AnyRef ArrayRef::to_anyref() const {
+ wasmtime_anyref_t out;
+ wasmtime_arrayref_to_anyref(&raw, &out);
+ return AnyRef(out);
+}
+
+/// Upcast to eqref.
+inline EqRef ArrayRef::to_eqref() const {
+ wasmtime_eqref_t out;
+ wasmtime_arrayref_to_eqref(&raw, &out);
+ return EqRef(out);
+}
+
+} // namespace wasmtime
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_ARRAYREF_HH
diff --git a/crates/c-api/include/wasmtime/eqref.h b/crates/c-api/include/wasmtime/eqref.h
new file mode 100644
index 0000000000..1f1a8e3173
--- /dev/null
+++ b/crates/c-api/include/wasmtime/eqref.h
@@ -0,0 +1,146 @@
+/**
+ * \file wasmtime/eqref.h
+ *
+ * APIs for interacting with WebAssembly `eqref` type in Wasmtime.
+ */
+
+#ifndef WASMTIME_EQREF_H
+#define WASMTIME_EQREF_H
+
+#include <wasmtime/conf.h>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <wasmtime/val.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/// \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);
+
+/**
+ * \brief Test whether an `eqref` is an `arrayref`.
+ *
+ * Returns `false` for null references.
+ */
+WASM_API_EXTERN bool wasmtime_eqref_is_array(wasmtime_context_t *context,
+ const wasmtime_eqref_t *eqref);
+
+/**
+ * \brief Downcast an `eqref` to an `arrayref`.
+ *
+ * If the given `eqref` is an `arrayref`, a new root for it is stored in `out`
+ * and `true` is returned. Otherwise `false` is returned and `out` is set to
+ * null.
+ */
+WASM_API_EXTERN bool wasmtime_eqref_as_array(wasmtime_context_t *context,
+ const wasmtime_eqref_t *eqref,
+ wasmtime_arrayref_t *out);
+
+/**
+ * \brief Test whether an `eqref` is a `structref`.
+ *
+ * Returns `false` for null references.
+ */
+WASM_API_EXTERN bool wasmtime_eqref_is_struct(wasmtime_context_t *context,
+ const wasmtime_eqref_t *eqref);
+
+/**
+ * \brief Downcast an `eqref` to a `structref`.
+ *
+ * If the given `eqref` is a `structref`, a new root for it is stored in `out`
+ * and `true` is returned. Otherwise `false` is returned and `out` is set to
+ * null.
+ */
+WASM_API_EXTERN bool wasmtime_eqref_as_struct(wasmtime_context_t *context,
+ const wasmtime_eqref_t *eqref,
+ wasmtime_structref_t *out);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_EQREF_H
diff --git a/crates/c-api/include/wasmtime/eqref.hh b/crates/c-api/include/wasmtime/eqref.hh
new file mode 100644
index 0000000000..5ac8e9fe7f
--- /dev/null
+++ b/crates/c-api/include/wasmtime/eqref.hh
@@ -0,0 +1,40 @@
+/**
+ * \file wasmtime/eqref.hh
+ */
+
+#ifndef WASMTIME_EQREF_HH
+#define WASMTIME_EQREF_HH
+
+#include <wasmtime/_eqref_class.hh>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <wasmtime/_anyref_class.hh>
+#include <wasmtime/_arrayref_class.hh>
+#include <wasmtime/_structref_class.hh>
+
+namespace wasmtime {
+
+inline StructRef EqRef::as_struct(Store::Context cx) const {
+ wasmtime_structref_t out;
+ wasmtime_eqref_as_struct(cx.capi(), &raw, &out);
+ return StructRef(out);
+}
+
+inline ArrayRef EqRef::as_array(Store::Context cx) const {
+ wasmtime_arrayref_t out;
+ wasmtime_eqref_as_array(cx.capi(), &raw, &out);
+ return ArrayRef(out);
+}
+
+inline AnyRef EqRef::to_anyref() const {
+ wasmtime_anyref_t out;
+ wasmtime_eqref_to_anyref(&raw, &out);
+ return AnyRef(out);
+}
+
+} // namespace wasmtime
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_EQREF_HH
diff --git a/crates/c-api/include/wasmtime/exn.h b/crates/c-api/include/wasmtime/exn.h
deleted file mode 100644
index effc5d383c..0000000000
--- a/crates/c-api/include/wasmtime/exn.h
+++ /dev/null
@@ -1,166 +0,0 @@
-/**
- * \file wasmtime/exn.h
- *
- * \brief Wasmtime APIs for WebAssembly exception objects.
- *
- * Exception objects carry a tag and a set of field values. They are
- * allocated on the GC heap within a store.
- *
- * ## Throwing from host functions
- *
- * To throw an exception from a host function implemented via the C API:
- *
- * 1. Create an exception object with #wasmtime_exn_new.
- * 2. Set it as the pending exception with #wasmtime_context_set_exception.
- * 3. Return a trap from the host callback (e.g. via `wasmtime_trap_new`).
- *
- * The runtime will propagate the exception through WebAssembly
- * `try_table`/`catch` blocks.
- *
- * ## Catching exceptions from Wasm
- *
- * When a call to a WebAssembly function (e.g. via #wasmtime_func_call)
- * returns a trap, check for a pending exception:
- *
- * 1. Call #wasmtime_context_has_exception or #wasmtime_context_take_exception.
- * 2. If present, examine the exception's tag and fields.
- */
-
-#ifndef WASMTIME_EXN_H
-#define WASMTIME_EXN_H
-
-#include <wasmtime/conf.h>
-
-#ifdef WASMTIME_FEATURE_GC
-
-#include <wasm.h>
-#include <wasmtime/error.h>
-#include <wasmtime/store.h>
-#include <wasmtime/tag.h>
-#include <wasmtime/val.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * \typedef wasmtime_exn_t
- * \brief An opaque type representing a WebAssembly exception object.
- *
- * Exception objects are allocated on the GC heap and referenced through
- * this handle. The handle is owned by the caller and must be freed
- * with #wasmtime_exn_delete.
- */
-typedef struct wasmtime_exn wasmtime_exn_t;
-
-/**
- * \brief Deletes a #wasmtime_exn_t.
- */
-WASM_API_EXTERN void wasmtime_exn_delete(wasmtime_exn_t *exn);
-
-/**
- * \brief Creates a new exception object.
- *
- * \param store the store context
- * \param tag the tag to associate with this exception
- * \param fields pointer to an array of field values matching the tag's
- * payload signature
- * \param nfields the number of elements in `fields`
- * \param exn_ret on success, set to the newly allocated exception.
- * The caller owns the returned pointer and must free it with
- * #wasmtime_exn_delete.
- *
- * \return NULL on success, or an error on failure.
- */
-WASM_API_EXTERN wasmtime_error_t *wasmtime_exn_new(wasmtime_context_t *store,
- const wasmtime_tag_t *tag,
- const wasmtime_val_t *fields,
- size_t nfields,
- wasmtime_exn_t **exn_ret);
-
-/**
- * \brief Returns the tag associated with this exception.
- *
- * \param store the store context
- * \param exn the exception to query
- * \param tag_ret on success, filled with the exception's tag
- *
- * \return NULL on success, or an error on failure.
- */
-WASM_API_EXTERN wasmtime_error_t *wasmtime_exn_tag(wasmtime_context_t *store,
- const wasmtime_exn_t *exn,
- wasmtime_tag_t *tag_ret);
-
-/**
- * \brief Returns the number of fields in this exception.
- *
- * \param store the store context
- * \param exn the exception to query
- */
-WASM_API_EXTERN size_t wasmtime_exn_field_count(wasmtime_context_t *store,
- const wasmtime_exn_t *exn);
-
-/**
- * \brief Reads a field value from this exception by index.
- *
- * \param store the store context
- * \param exn the exception to query
- * \param index the field index (0-based)
- * \param val_ret on success, filled with the field value
- * (caller-owned on return).
- *
- * \return NULL on success, or an error if the index is out of bounds.
- */
-WASM_API_EXTERN wasmtime_error_t *wasmtime_exn_field(wasmtime_context_t *store,
- const wasmtime_exn_t *exn,
- size_t index,
- wasmtime_val_t *val_ret);
-
-/**
- * \brief Sets the pending exception on the store and returns a trap.
- *
- * This transfers ownership of `exn` to the store. After this call,
- * the caller must not use or free `exn`.
- *
- * Returns a `wasm_trap_t` that the host callback MUST return to signal
- * to the Wasm runtime that an exception was thrown. The caller owns
- * the returned trap.
- *
- * \param store the store context
- * \param exn the exception to throw (ownership transferred)
- * \return a trap to return from the host callback (caller-owned)
- */
-WASM_API_EXTERN wasm_trap_t *
-wasmtime_context_set_exception(wasmtime_context_t *store, wasmtime_exn_t *exn);
-
-/**
- * \brief Takes the pending exception from the store, if any.
- *
- * If there is a pending exception, removes it from the store and
- * returns it. The caller owns the returned pointer and must free it
- * with #wasmtime_exn_delete.
- *
- * \param store the store context
- * \param exn_ret on success, set to the exception (caller-owned)
- *
- * \return true if there was a pending exception, false otherwise.
- */
-WASM_API_EXTERN bool wasmtime_context_take_exception(wasmtime_context_t *store,
- wasmtime_exn_t **exn_ret);
-
-/**
- * \brief Tests whether there is a pending exception on the store.
- *
- * \param store the store context
- *
- * \return true if a pending exception is set, false otherwise.
- */
-WASM_API_EXTERN bool wasmtime_context_has_exception(wasmtime_context_t *store);
-
-#ifdef __cplusplus
-} // extern "C"
-#endif
-
-#endif // WASMTIME_FEATURE_GC
-
-#endif // WASMTIME_EXN_H
diff --git a/crates/c-api/include/wasmtime/exn.hh b/crates/c-api/include/wasmtime/exn.hh
deleted file mode 100644
index 12ea8f3075..0000000000
--- a/crates/c-api/include/wasmtime/exn.hh
+++ /dev/null
@@ -1,122 +0,0 @@
-/**
- * \file wasmtime/exn.hh
- */
-
-#ifndef WASMTIME_EXN_HH
-#define WASMTIME_EXN_HH
-
-#include <wasmtime/conf.h>
-
-#ifdef WASMTIME_FEATURE_GC
-
-#include <vector>
-#include <wasmtime/error.hh>
-#include <wasmtime/exn.h>
-#include <wasmtime/store.hh>
-#include <wasmtime/tag.hh>
-#include <wasmtime/val.hh>
-
-namespace wasmtime {
-
-/**
- * \brief A WebAssembly exception object.
- *
- * Exception objects carry a tag and a set of field values. They are
- * allocated on the GC heap within a store.
- *
- * This type owns its underlying `wasmtime_exn_t` handle. When it goes out
- * of scope the handle is freed.
- */
-class Exn {
- struct deleter {
- void operator()(wasmtime_exn_t *p) const { wasmtime_exn_delete(p); }
- };
-
- std::unique_ptr<wasmtime_exn_t, deleter> ptr;
-
-public:
- /// Takes ownership of a raw `wasmtime_exn_t` pointer.
- explicit Exn(wasmtime_exn_t *raw) : ptr(raw) {}
-
- /// Constructs a new exception.
- Exn(Exn &&other) = default;
- /// Moves an exception.
- Exn &operator=(Exn &&other) = default;
- Exn(const Exn &) = delete;
- Exn &operator=(const Exn &) = delete;
- /// Destroys an exception.
- ~Exn() = default;
-
- /**
- * \brief Create a new exception object.
- *
- * \param cx the store in which to allocate the exception
- * \param tag the tag to associate with this exception
- * \param fields the field values matching the tag's payload signature
- */
- static Result<Exn> create(Store::Context cx, const Tag &tag,
- const std::vector<Val> &fields) {
- wasmtime_exn_t *exn = nullptr;
- auto *error = wasmtime_exn_new(
- cx.capi(), &tag.capi(),
- reinterpret_cast<const wasmtime_val_t *>(fields.data()), fields.size(),
- &exn);
- if (error != nullptr) {
- return Error(error);
- }
- return Exn(exn);
- }
-
- /// Returns the tag associated with this exception.
- Result<Tag> tag(Store::Context cx) const {
- wasmtime_tag_t tag;
- auto *error = wasmtime_exn_tag(cx.capi(), ptr.get(), &tag);
- if (error != nullptr) {
- return Error(error);
- }
- return Tag(tag);
- }
-
- /// Returns the number of fields in this exception.
- size_t field_count(Store::Context cx) const {
- return wasmtime_exn_field_count(cx.capi(), ptr.get());
- }
-
- /// Reads a field value by index.
- Result<Val> field(Store::Context cx, size_t index) const {
- wasmtime_val_t val;
- auto *error = wasmtime_exn_field(cx.capi(), ptr.get(), index, &val);
- if (error != nullptr) {
- return Error(error);
- }
- return Val(val);
- }
-
- /// Returns the raw underlying C API pointer (non-owning).
- wasmtime_exn_t *capi() const { return ptr.get(); }
-
- /// Releases ownership of the underlying C API pointer.
- wasmtime_exn_t *release() { return ptr.release(); }
-};
-
-inline Trap Store::Context::throw_exception(Exn exn) {
- return Trap(wasmtime_context_set_exception(capi(), exn.release()));
-}
-
-inline std::optional<Exn> Store::Context::take_exception() {
- wasmtime_exn_t *exn = nullptr;
- if (wasmtime_context_take_exception(capi(), &exn)) {
- return Exn(exn);
- }
- return std::nullopt;
-}
-
-inline bool Store::Context::has_exception() {
- return wasmtime_context_has_exception(capi());
-}
-
-} // namespace wasmtime
-
-#endif // WASMTIME_FEATURE_GC
-
-#endif // WASMTIME_EXN_HH
diff --git a/crates/c-api/include/wasmtime/exnref.h b/crates/c-api/include/wasmtime/exnref.h
new file mode 100644
index 0000000000..eaf6140754
--- /dev/null
+++ b/crates/c-api/include/wasmtime/exnref.h
@@ -0,0 +1,173 @@
+/**
+ * \file wasmtime/exnref.h
+ *
+ * APIs for interacting with WebAssembly `exnref` type in Wasmtime.
+ */
+
+#ifndef WASMTIME_EXNREF_H
+#define WASMTIME_EXNREF_H
+
+#include <wasmtime/conf.h>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <wasmtime/val.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief Creates a new exception object.
+ *
+ * \param store the store context
+ * \param tag the tag to associate with this exception
+ * \param fields pointer to an array of field values matching the tag's
+ * payload signature
+ * \param nfields the number of elements in `fields`
+ * \param exn_ret on success, set to the newly allocated exception.
+ * The caller owns the returned pointer and must free it with
+ * #wasmtime_exnref_unroot.
+ *
+ * \return NULL on success, or an error on failure.
+ */
+WASM_API_EXTERN wasmtime_error_t *
+wasmtime_exnref_new(wasmtime_context_t *store, const wasmtime_tag_t *tag,
+ const wasmtime_val_t *fields, size_t nfields,
+ wasmtime_exnref_t *exn_ret);
+
+/// \brief Helper function to initialize the `ref` provided to a null exnref
+/// value.
+static inline void wasmtime_exnref_set_null(wasmtime_exnref_t *ref) {
+ ref->store_id = 0;
+}
+
+/// \brief Helper function to return whether the provided `ref` points to a null
+/// `exnref` value.
+static inline bool wasmtime_exnref_is_null(const wasmtime_exnref_t *ref) {
+ return ref->store_id == 0;
+}
+
+/**
+ * \brief Creates a new reference pointing to the same exception that `ref`
+ * points to.
+ *
+ * The returned reference is stored in `out`.
+ */
+WASM_API_EXTERN void wasmtime_exnref_clone(const wasmtime_exnref_t *ref,
+ wasmtime_exnref_t *out);
+
+/**
+ * \brief Unroots the `ref` provided, enabling future garbage collection.
+ *
+ * After this call, `ref` is left in an undefined state and should not be used.
+ */
+WASM_API_EXTERN void wasmtime_exnref_unroot(wasmtime_exnref_t *ref);
+
+/**
+ * \brief Converts a raw `exnref` value coming from #wasmtime_val_raw_t into
+ * a #wasmtime_exnref_t.
+ *
+ * The `out` reference is filled in with the non-raw version of this exnref.
+ * It must eventually be unrooted with #wasmtime_exnref_unroot.
+ */
+WASM_API_EXTERN void wasmtime_exnref_from_raw(wasmtime_context_t *context,
+ uint32_t raw,
+ wasmtime_exnref_t *out);
+
+/**
+ * \brief Converts a #wasmtime_exnref_t to a raw value suitable for storing
+ * into a #wasmtime_val_raw_t.
+ *
+ * Note that the returned underlying value is not tracked by Wasmtime's garbage
+ * collector until it enters WebAssembly. This means that a GC may release the
+ * context's reference to the raw value, making the raw value invalid within the
+ * context of the store. Do not perform a GC between calling this function and
+ * passing it to WebAssembly.
+ */
+WASM_API_EXTERN uint32_t wasmtime_exnref_to_raw(wasmtime_context_t *context,
+ const wasmtime_exnref_t *ref);
+
+/**
+ * \brief Returns the tag associated with this exception.
+ *
+ * \param store the store context
+ * \param exn the exception to query
+ * \param tag_ret on success, filled with the exception's tag
+ *
+ * \return NULL on success, or an error on failure.
+ */
+WASM_API_EXTERN wasmtime_error_t *
+wasmtime_exnref_tag(wasmtime_context_t *store, const wasmtime_exnref_t *exn,
+ wasmtime_tag_t *tag_ret);
+
+/**
+ * \brief Returns the number of fields in this exception.
+ *
+ * \param store the store context
+ * \param exn the exception to query
+ */
+WASM_API_EXTERN size_t wasmtime_exnref_field_count(
+ wasmtime_context_t *store, const wasmtime_exnref_t *exn);
+
+/**
+ * \brief Reads a field value from this exception by index.
+ *
+ * \param store the store context
+ * \param exn the exception to query
+ * \param index the field index (0-based)
+ * \param val_ret on success, filled with the field value
+ * (caller-owned on return).
+ *
+ * \return NULL on success, or an error if the index is out of bounds.
+ */
+WASM_API_EXTERN wasmtime_error_t *
+wasmtime_exnref_field(wasmtime_context_t *store, const wasmtime_exnref_t *exn,
+ size_t index, wasmtime_val_t *val_ret);
+
+/**
+ * \brief Sets the pending exception on the store and returns a trap.
+ *
+ * Returns a `wasm_trap_t` that the host callback MUST return to signal
+ * to the Wasm runtime that an exception was thrown. The caller owns
+ * the returned trap.
+ *
+ * \param store the store context
+ * \param exn the exception to throw
+ * \return a trap to return from the host callback (caller-owned)
+ */
+WASM_API_EXTERN wasm_trap_t *
+wasmtime_context_set_exception(wasmtime_context_t *store,
+ const wasmtime_exnref_t *exn);
+
+/**
+ * \brief Takes the pending exception from the store, if any.
+ *
+ * If there is a pending exception, removes it from the store and
+ * returns it. The caller owns the returned pointer and must free it
+ * with #wasmtime_exnref_unroot.
+ *
+ * \param store the store context
+ * \param exn_ret on success, set to the exception (caller-owned)
+ *
+ * \return true if there was a pending exception, false otherwise.
+ */
+WASM_API_EXTERN bool
+wasmtime_context_take_exception(wasmtime_context_t *store,
+ wasmtime_exnref_t *exn_ret);
+
+/**
+ * \brief Tests whether there is a pending exception on the store.
+ *
+ * \param store the store context
+ *
+ * \return true if a pending exception is set, false otherwise.
+ */
+WASM_API_EXTERN bool wasmtime_context_has_exception(wasmtime_context_t *store);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // WASMTIME_FEATURE_GC
+#endif // WASMTIME_EXNREF_H
diff --git a/crates/c-api/include/wasmtime/exnref.hh b/crates/c-api/include/wasmtime/exnref.hh
new file mode 100644
index 0000000000..16137477ca
--- /dev/null
+++ b/crates/c-api/include/wasmtime/exnref.hh
@@ -0,0 +1,43 @@
+/**
+ * \file wasmtime/exnref.hh
+ */
+
+#ifndef WASMTIME_EXNREF_HH
+#define WASMTIME_EXNREF_HH
+
+#include <wasmtime/_exnref_class.hh>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <wasmtime/_val_class.hh>
+
+namespace wasmtime {
+
+inline Result<ExnRef> ExnRef::create(Store::Context cx, const Tag &tag,
+ const std::vector<Val> &fields) {
+ wasmtime_exnref_t exn;
+ auto *error = wasmtime_exnref_new(
+ cx.capi(), &tag.capi(),
+ reinterpret_cast<const wasmtime_val_t *>(fields.data()), fields.size(),
+ &exn);
+ if (error != nullptr) {
+ return Error(error);
+ }
+ return ExnRef(exn);
+}
+
+/// Reads a field value by index.
+inline Result<Val> ExnRef::field(Store::Context cx, size_t index) const {
+ wasmtime_val_t val;
+ auto *error = wasmtime_exnref_field(cx.capi(), &raw, index, &val);
+ if (error != nullptr) {
+ return Error(error);
+ }
+ return Val(val);
+}
+
+} // namespace wasmtime
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_EXNREF_HH
diff --git a/crates/c-api/include/wasmtime/extern.hh b/crates/c-api/include/wasmtime/extern.hh
index 05407facdd..aa2a4c231b 100644
--- a/crates/c-api/include/wasmtime/extern.hh
+++ b/crates/c-api/include/wasmtime/extern.hh
@@ -5,9 +5,9 @@
#ifndef WASMTIME_EXTERN_HH
#define WASMTIME_EXTERN_HH
+#include <wasmtime/_func_class.hh>
#include <wasmtime/extern.h>
#include <wasmtime/extern_declare.hh>
-#include <wasmtime/func.hh>
#include <wasmtime/global.hh>
#include <wasmtime/memory.hh>
#include <wasmtime/table.hh>
diff --git a/crates/c-api/include/wasmtime/externref.h b/crates/c-api/include/wasmtime/externref.h
new file mode 100644
index 0000000000..a036d05884
--- /dev/null
+++ b/crates/c-api/include/wasmtime/externref.h
@@ -0,0 +1,126 @@
+/**
+ * \file wasmtime/externref.h
+ *
+ * APIs for interacting with WebAssembly `externref` types in Wasmtime.
+ */
+
+#ifndef WASMTIME_EXTERNREF_H
+#define WASMTIME_EXTERNREF_H
+
+#include <wasmtime/conf.h>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <wasmtime/val.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/// \brief Helper function to initialize the `ref` provided to a null externref
+/// value.
+static inline void wasmtime_externref_set_null(wasmtime_externref_t *ref) {
+ ref->store_id = 0;
+}
+
+/// \brief Helper function to return whether the provided `ref` points to a null
+/// `externref` value.
+///
+/// Note that `ref` itself should not be null as null is represented internally
+/// within a #wasmtime_externref_t value.
+static inline bool wasmtime_externref_is_null(const wasmtime_externref_t *ref) {
+ return ref->store_id == 0;
+}
+
+/**
+ * \brief Create a new `externref` value.
+ *
+ * Creates a new `externref` value wrapping the provided data, returning whether
+ * it was created or not.
+ *
+ * \param context the store context to allocate this externref within
+ * \param data the host-specific data to wrap
+ * \param finalizer an optional finalizer for `data`
+ * \param out where to store the created value.
+ *
+ * When the reference is reclaimed, the wrapped data is cleaned up with the
+ * provided `finalizer`.
+ *
+ * If `true` is returned then `out` has been filled in and must be unrooted
+ * in the future with #wasmtime_externref_unroot. If `false` is returned then
+ * the host wasn't able to create more GC values at this time. Performing a GC
+ * may free up enough space to try again.
+ *
+ * If you do not unroot the value, *even if you free the corresponding
+ * Store*, there will be some memory leaked, because GC roots use a
+ * separate allocation to track liveness.
+ */
+WASM_API_EXTERN bool wasmtime_externref_new(wasmtime_context_t *context,
+ void *data,
+ void (*finalizer)(void *),
+ wasmtime_externref_t *out);
+
+/**
+ * \brief Get an `externref`'s wrapped data
+ *
+ * Returns the original `data` passed to #wasmtime_externref_new. It is required
+ * that `data` is not `NULL`.
+ */
+WASM_API_EXTERN void *wasmtime_externref_data(wasmtime_context_t *context,
+ const wasmtime_externref_t *data);
+
+/**
+ * \brief Creates a new reference pointing to the same data that `ref` points
+ * to (depending on the configured collector this might increase a reference
+ * count or create a new GC root).
+ *
+ * The `out` parameter stores the cloned reference. This reference must
+ * eventually be unrooted with #wasmtime_externref_unroot in the future to
+ * enable GC'ing it.
+ */
+WASM_API_EXTERN void wasmtime_externref_clone(const wasmtime_externref_t *ref,
+ wasmtime_externref_t *out);
+
+/**
+ * \brief Unroots the pointer `ref` from the `context` provided.
+ *
+ * This function will enable future garbage collection of the value pointed to
+ * by `ref` once there are no more references. The `ref` value may be mutated in
+ * place by this function and its contents are undefined after this function
+ * returns. It should not be used until after re-initializing it.
+ *
+ * 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_externref_t *ref);
+
+/**
+ * \brief Converts a raw `externref` value coming from #wasmtime_val_raw_t into
+ * a #wasmtime_externref_t.
+ *
+ * The `out` reference is filled in with the non-raw version of this externref.
+ * It must eventually be unrooted with #wasmtime_externref_unroot.
+ */
+WASM_API_EXTERN void wasmtime_externref_from_raw(wasmtime_context_t *context,
+ uint32_t raw,
+ wasmtime_externref_t *out);
+
+/**
+ * \brief Converts a #wasmtime_externref_t to a raw value suitable for storing
+ * into a #wasmtime_val_raw_t.
+ *
+ * Note that the returned underlying value is not tracked by Wasmtime's garbage
+ * collector until it enters WebAssembly. This means that a GC may release the
+ * context's reference to the raw value, making the raw value invalid within the
+ * context of the store. Do not perform a GC between calling this function and
+ * passing it to WebAssembly.
+ */
+WASM_API_EXTERN uint32_t wasmtime_externref_to_raw(
+ wasmtime_context_t *context, const wasmtime_externref_t *ref);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // WASMTIME_FEATURE_GC
+#endif // WASMTIME_EXTERNREF_H
diff --git a/crates/c-api/include/wasmtime/externref.hh b/crates/c-api/include/wasmtime/externref.hh
new file mode 100644
index 0000000000..cd79c1b1a1
--- /dev/null
+++ b/crates/c-api/include/wasmtime/externref.hh
@@ -0,0 +1,53 @@
+/**
+ * \file wasmtime/externref.hh
+ */
+
+#ifndef WASMTIME_EXTERNREF_HH
+#define WASMTIME_EXTERNREF_HH
+
+#include <wasmtime/_externref_class.hh>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <wasmtime/_func_class.hh>
+
+namespace wasmtime {
+
+/// Type information for `externref`, represented on the host as an optional
+/// `ExternRef`.
+template <> struct detail::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 = ref->borrow_raw(cx);
+ } else {
+ p->externref = 0;
+ }
+ }
+
+ static std::optional<ExternRef> load(Store::Context cx,
+ wasmtime_val_raw_t *p) {
+ if (p->externref == 0) {
+ return std::nullopt;
+ }
+ wasmtime_externref_t val;
+ wasmtime_externref_from_raw(cx.capi(), p->externref, &val);
+ return ExternRef(val);
+ }
+};
+
+} // namespace wasmtime
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_EXTERNREF_HH
diff --git a/crates/c-api/include/wasmtime/func.hh b/crates/c-api/include/wasmtime/func.hh
index 5425609451..184aa7763e 100644
--- a/crates/c-api/include/wasmtime/func.hh
+++ b/crates/c-api/include/wasmtime/func.hh
@@ -5,55 +5,13 @@
#ifndef WASMTIME_FUNC_HH
#define WASMTIME_FUNC_HH
-#include <array>
-#include <wasmtime/error.hh>
-#include <wasmtime/extern_declare.hh>
-#include <wasmtime/func.h>
-#include <wasmtime/span.hh>
-#include <wasmtime/store.hh>
-#include <wasmtime/trap.hh>
-#include <wasmtime/types/func.hh>
-#include <wasmtime/types/val.hh>
-#include <wasmtime/val.hh>
+#include <wasmtime/_func_class.hh>
+#include <wasmtime/_val_class.hh>
namespace wasmtime {
-/**
- * \brief Structure provided to host functions to lookup caller information or
- * acquire a `Store::Context`.
- *
- * This structure is passed to all host functions created with `Func`. It can be
- * used to create a `Store::Context`.
- */
-class Caller {
- friend class Func;
- friend class Store;
- wasmtime_caller_t *ptr;
- Caller(wasmtime_caller_t *ptr) : ptr(ptr) {}
-
-public:
- /// Attempts to load an exported item from the calling instance.
- ///
- /// For more information see the Rust documentation -
- /// https://docs.wasmtime.dev/api/wasmtime/struct.Caller.html#method.get_export
- std::optional<Extern> get_export(std::string_view name);
-
- /// Explicitly acquire a `Store::Context` from this `Caller`.
- Store::Context context() { return this; }
-};
-
-inline Store::Context::Context(Caller &caller)
- : Context(wasmtime_caller_context(caller.ptr)) {}
-inline Store::Context::Context(Caller *caller) : Context(*caller) {}
-
namespace detail {
-/// A "trait" for native types that correspond to WebAssembly types for use with
-/// `Func::wrap` and `TypedFunc::call`
-template <typename T> struct WasmType {
- static const bool valid = false;
-};
-
/// Helper macro to define `WasmType` definitions for primitive types like
/// int32_t and such.
// NOLINTNEXTLINE
@@ -81,78 +39,6 @@ NATIVE_WASM_TYPE(double, F64, f64)
#undef NATIVE_WASM_TYPE
-#ifdef WASMTIME_FEATURE_GC
-/// Type information for `externref`, represented on the host as an optional
-/// `ExternRef`.
-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 = ref->borrow_raw(cx);
- } else {
- p->externref = 0;
- }
- }
-
- static std::optional<ExternRef> load(Store::Context cx,
- wasmtime_val_raw_t *p) {
- if (p->externref == 0) {
- return std::nullopt;
- }
- wasmtime_externref_t val;
- wasmtime_externref_from_raw(cx.capi(), p->externref, &val);
- return ExternRef(val);
- }
-};
-#endif // WASMTIME_FEATURE_GC
-
-/// Type information for the `V128` host value used as a wasm value.
-template <> struct WasmType<V128> {
- static const bool valid = true;
- static const ValKind kind = ValKind::V128;
- static void store(Store::Context cx, wasmtime_val_raw_t *p, const V128 &t) {
- (void)cx;
- memcpy(&p->v128[0], &t.v128[0], sizeof(wasmtime_v128));
- }
- static V128 load(Store::Context cx, wasmtime_val_raw_t *p) {
- (void)cx;
- return p->v128;
- }
-};
-
-/// A "trait" for a list of types and operations on them, used for `Func::wrap`
-/// and `TypedFunc::call`
-///
-/// The base case is a single type which is a list of one element.
-template <typename T> struct WasmTypeList {
- static const bool valid = WasmType<T>::valid;
- static const size_t size = 1;
- 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);
- }
- static T load(Store::Context cx, wasmtime_val_raw_t *storage) {
- return WasmType<T>::load(cx, storage);
- }
- static std::vector<ValType> types() { return {WasmType<T>::kind}; }
-};
-
/// std::monostate translates to an empty list of types.
template <> struct WasmTypeList<std::monostate> {
static const bool valid = true;
@@ -208,21 +94,6 @@ template <typename... T> struct WasmTypeList<std::tuple<T...>> {
static std::vector<ValType> types() { return {WasmType<T>::kind...}; }
};
-/// A "trait" for what can be returned from closures specified to `Func::wrap`.
-///
-/// The base case here is a bare return value like `int32_t`.
-template <typename R> struct WasmHostRet {
- using Results = WasmTypeList<R>;
-
- template <typename F, typename... A>
- static std::optional<Trap> invoke(F f, Caller cx, wasmtime_val_raw_t *raw,
- A... args) {
- auto ret = f(args...);
- Results::store(cx, raw, ret);
- return std::nullopt;
- }
-};
-
/// Host functions can return nothing
template <> struct WasmHostRet<void> {
using Results = WasmTypeList<std::tuple<>>;
@@ -258,8 +129,6 @@ template <typename R> struct WasmHostRet<Result<R, Trap>> {
}
};
-template <typename F, typename = void> struct WasmHostFunc;
-
/// Base type information for host free-function pointers being used as wasm
/// functions
template <typename R, typename... A> struct WasmHostFunc<R (*)(A...)> {
@@ -322,368 +191,65 @@ struct WasmHostFunc<T, std::void_t<decltype(&T::operator())>>
using namespace detail;
-// forward-declaration for `Func::typed` below.
-template <typename Params, typename Results> class TypedFunc;
-
-/**
- * \brief Representation of a WebAssembly function.
- *
- * This class represents a WebAssembly function, either created through
- * instantiating a module or a host function.
- *
- * Note that this type does not itself own any resources. It points to resources
- * owned within a `Store` and the `Store` must be passed in as the first
- * argument to the functions defined on `Func`. Note that if the wrong `Store`
- * is passed in then the process will be aborted.
- */
-class Func {
- friend class Val;
- friend class Instance;
- friend class Linker;
- template <typename Params, typename Results> friend class TypedFunc;
-
- wasmtime_func_t func;
-
- template <typename F>
- static wasm_trap_t *raw_callback(void *env, wasmtime_caller_t *caller,
- const wasmtime_val_t *args, size_t nargs,
- wasmtime_val_t *results, size_t nresults) {
- static_assert(alignof(Val) == alignof(wasmtime_val_t));
- static_assert(sizeof(Val) == sizeof(wasmtime_val_t));
- F *func = reinterpret_cast<F *>(env); // NOLINT
- Span<const Val> args_span(reinterpret_cast<const Val *>(args), // NOLINT
- nargs);
- Span<Val> results_span(reinterpret_cast<Val *>(results), // NOLINT
- nresults);
- Result<std::monostate, Trap> result =
- (*func)(Caller(caller), args_span, results_span);
- if (!result) {
- return result.err().capi_release();
- }
- return nullptr;
- }
-
- template <typename F>
- static wasm_trap_t *
- raw_callback_unchecked(void *env, wasmtime_caller_t *caller,
- wasmtime_val_raw_t *args_and_results,
- size_t nargs_and_results) {
- (void)nargs_and_results;
- using HostFunc = WasmHostFunc<F>;
- Caller cx(caller);
- F *func = reinterpret_cast<F *>(env); // NOLINT
- auto trap = HostFunc::invoke(*func, cx, args_and_results);
- if (trap) {
- return trap->capi_release();
- }
- return nullptr;
- }
-
- template <typename F> static void raw_finalize(void *env) {
- std::unique_ptr<F> ptr(reinterpret_cast<F *>(env)); // NOLINT
- }
-
-public:
- /// Creates a new function from the raw underlying C API representation.
- Func(wasmtime_func_t func) : func(func) {}
-
- /**
- * \brief Creates a new host-defined function.
- *
- * This constructor is used to create a host function within the store
- * provided. This is how WebAssembly can call into the host and make use of
- * external functionality.
- *
- * > **Note**: host functions created this way are more flexible but not
- * > as fast to call as those created by `Func::wrap`.
- *
- * \param cx the store to create the function within
- * \param ty the type of the function that will be created
- * \param f the host callback to be executed when this function is called.
- *
- * The parameter `f` is expected to be a lambda (or a lambda lookalike) which
- * takes three parameters:
- *
- * * The first parameter is a `Caller` to get recursive access to the store
- * and other caller state.
- * * The second parameter is a `Span<const Val>` which is the list of
- * parameters to the function. These parameters are guaranteed to be of the
- * types specified by `ty` when constructing this function.
- * * The last argument is `Span<Val>` which is where to write the return
- * values of the function. The function must produce the types of values
- * specified by `ty` or otherwise a trap will be raised.
- *
- * The parameter `f` is expected to return `Result<std::monostate, Trap>`.
- * This allows `f` to raise a trap if desired, or otherwise return no trap and
- * finish successfully. If a trap is raised then the results pointer does not
- * need to be written to.
- */
- template <typename F,
- std::enable_if_t<
- std::is_invocable_r_v<Result<std::monostate, Trap>, F, Caller,
- Span<const Val>, Span<Val>>,
- bool> = true>
- Func(Store::Context cx, const FuncType &ty, F f) : func({}) {
- wasmtime_func_new(cx.ptr, ty.ptr.get(), raw_callback<F>,
- std::make_unique<F>(f).release(), raw_finalize<F>, &func);
- }
-
- /**
- * \brief Creates a new host function from the provided callback `f`,
- * inferring the WebAssembly function type from the host signature.
- *
- * This function is akin to the `Func` constructor except that the WebAssembly
- * type does not need to be specified and additionally the signature of `f`
- * is different. The main goal of this function is to enable WebAssembly to
- * call the function `f` as-fast-as-possible without having to validate any
- * types or such.
- *
- * The function `f` can optionally take a `Caller` as its first parameter,
- * but otherwise its arguments are translated to WebAssembly types:
- *
- * * `int32_t`, `uint32_t` - `i32`
- * * `int64_t`, `uint64_t` - `i64`
- * * `float` - `f32`
- * * `double` - `f64`
- * * `std::optional<Func>` - `funcref`
- * * `std::optional<ExternRef>` - `externref`
- * * `wasmtime::V128` - `v128`
- *
- * The function may only take these arguments and if it takes any other kinds
- * of arguments then it will fail to compile.
- *
- * The function may return a few different flavors of return values:
- *
- * * `void` - interpreted as returning nothing
- * * Any type above - interpreted as a singular return value.
- * * `std::tuple<T...>` where `T` is one of the valid argument types -
- * interpreted as returning multiple values.
- * * `Result<T, Trap>` where `T` is another valid return type - interpreted as
- * a function that returns `T` to wasm but is optionally allowed to also
- * raise a trap.
- *
- * It's recommended, if possible, to use this function over the `Func`
- * constructor since this is generally easier to work with and also enables
- * a faster path for WebAssembly to call this function.
- */
- template <typename F,
- std::enable_if_t<WasmHostFunc<F>::Params::valid, bool> = true,
- std::enable_if_t<WasmHostFunc<F>::Results::valid, bool> = true>
- static Func wrap(Store::Context cx, F f) {
- using HostFunc = WasmHostFunc<F>;
- auto params = HostFunc::Params::types();
- auto results = HostFunc::Results::types();
- auto ty = FuncType::from_iters(params, results);
- wasmtime_func_t func;
- wasmtime_func_new_unchecked(cx.ptr, ty.ptr.get(), raw_callback_unchecked<F>,
- std::make_unique<F>(f).release(),
- raw_finalize<F>, &func);
- return func;
- }
-
- /**
- * \brief Invoke a WebAssembly function.
- *
- * This function will execute this WebAssembly function. This function muts be
- * defined within the `cx`'s store provided. The `params` argument is the list
- * of parameters that are passed to the wasm function, and the types of the
- * values within `params` must match the type signature of this function.
- *
- * This may return one of three values:
- *
- * * First the function could succeed, returning a vector of values
- * representing the results of the function.
- * * Otherwise a `Trap` might be generated by the WebAssembly function.
- * * Finally an `Error` could be returned indicating that `params` were not of
- * the right type.
- *
- * > **Note**: for optimized calls into WebAssembly where the function
- * > signature is statically known it's recommended to use `Func::typed` and
- * > `TypedFunc::call`.
- */
- template <typename I>
- TrapResult<std::vector<Val>> call(Store::Context cx, const I &begin,
- const I &end) const {
- std::vector<wasmtime_val_t> raw_params;
- raw_params.reserve(end - begin);
- for (auto i = begin; i != end; i++) {
- raw_params.push_back(i->val);
- }
- size_t nresults = this->type(cx)->results().size();
- std::vector<wasmtime_val_t> raw_results(nresults);
-
- wasm_trap_t *trap = nullptr;
- auto *error =
- wasmtime_func_call(cx.ptr, &func, raw_params.data(), raw_params.size(),
- raw_results.data(), raw_results.capacity(), &trap);
- if (error != nullptr) {
- return TrapError(Error(error));
- }
- if (trap != nullptr) {
- return TrapError(Trap(trap));
- }
-
- std::vector<Val> results;
- results.reserve(nresults);
- for (size_t i = 0; i < nresults; i++) {
- results.push_back(raw_results[i]);
- }
- return results;
- }
-
- /**
- * \brief Helper function for `call(Store::Context cx, const I &begin, const I
- * &end)`
- *
- * \see call(Store::Context cx, const I &begin, const I &end)
- */
- TrapResult<std::vector<Val>> call(Store::Context cx,
- const std::vector<Val> &params) const {
- return this->call(cx, params.begin(), params.end());
- }
-
- /**
- * \brief Helper function for `call(Store::Context cx, const I &begin, const I
- * &end)`
- *
- * \see call(Store::Context cx, const I &begin, const I &end)
- */
- TrapResult<std::vector<Val>>
- call(Store::Context cx, const std::initializer_list<Val> &params) const {
- return this->call(cx, params.begin(), params.end());
- }
+template <typename F>
+inline wasm_trap_t *Func::raw_callback(void *env, wasmtime_caller_t *caller,
+ const wasmtime_val_t *args, size_t nargs,
+ wasmtime_val_t *results,
+ size_t nresults) {
+ static_assert(alignof(Val) == alignof(wasmtime_val_t));
+ static_assert(sizeof(Val) == sizeof(wasmtime_val_t));
+ F *func = reinterpret_cast<F *>(env); // NOLINT
+ Span<const Val> args_span(reinterpret_cast<const Val *>(args), // NOLINT
+ nargs);
+ Span<Val> results_span(reinterpret_cast<Val *>(results), // NOLINT
+ nresults);
+ Result<std::monostate, Trap> result =
+ (*func)(Caller(caller), args_span, results_span);
+ if (!result) {
+ return result.err().capi_release();
+ }
+ return nullptr;
+}
- /// Returns the type of this function.
- FuncType type(Store::Context cx) const {
- return wasmtime_func_type(cx.ptr, &func);
+template <typename I>
+inline TrapResult<std::vector<Val>>
+Func::call(Store::Context cx, const I &begin, const I &end) const {
+ std::vector<wasmtime_val_t> raw_params;
+ raw_params.reserve(end - begin);
+ for (auto i = begin; i != end; i++) {
+ raw_params.push_back(i->val);
}
+ size_t nresults = this->type(cx)->results().size();
+ std::vector<wasmtime_val_t> raw_results(nresults);
- /**
- * \brief Statically checks this function against the provided types.
- *
- * This function will check whether it takes the statically known `Params`
- * and returns the statically known `Results`. If the type check succeeds then
- * a `TypedFunc` is returned which enables a faster method of invoking
- * WebAssembly functions.
- *
- * The `Params` and `Results` specified as template parameters here are the
- * parameters and results of the wasm function. They can either be a bare
- * type which means that the wasm takes/returns one value, or they can be a
- * `std::tuple<T...>` of types to represent multiple arguments or multiple
- * returns.
- *
- * The valid types for this function are those mentioned as the arguments
- * for `Func::wrap`.
- */
- template <typename Params, typename Results,
- std::enable_if_t<WasmTypeList<Params>::valid, bool> = true,
- std::enable_if_t<WasmTypeList<Results>::valid, bool> = true>
- Result<TypedFunc<Params, Results>, Trap> typed(Store::Context cx) const {
- auto ty = this->type(cx);
- if (!WasmTypeList<Params>::matches(ty->params()) ||
- !WasmTypeList<Results>::matches(ty->results())) {
- return Trap("static type for this function does not match actual type");
- }
- TypedFunc<Params, Results> ret(*this);
- return ret;
+ wasm_trap_t *trap = nullptr;
+ auto *error =
+ wasmtime_func_call(cx.ptr, &func, raw_params.data(), raw_params.size(),
+ raw_results.data(), raw_results.capacity(), &trap);
+ if (error != nullptr) {
+ return TrapError(Error(error));
}
-
- /// Returns the raw underlying C API function this is using.
- const wasmtime_func_t &capi() const { return func; }
-};
-
-/**
- * \brief A version of a WebAssembly `Func` where the type signature of the
- * function is statically known.
- */
-template <typename Params, typename Results> class TypedFunc {
- friend class Func;
- Func f;
- TypedFunc(Func func) : f(func) {}
-
-public:
- /**
- * \brief Calls this function with the provided parameters.
- *
- * This function is akin to `Func::call` except that since static type
- * information is available it statically takes its parameters and statically
- * returns its results.
- *
- * Note that this function still may return a `Trap` indicating that calling
- * the WebAssembly function failed.
- */
- TrapResult<Results> call(Store::Context cx, const Params &params) const {
- std::array<wasmtime_val_raw_t, std::max(WasmTypeList<Params>::size,
- WasmTypeList<Results>::size)>
- storage;
- wasmtime_val_raw_t *ptr = storage.data();
- if (ptr == nullptr)
- ptr = reinterpret_cast<wasmtime_val_raw_t *>(alignof(wasmtime_val_raw_t));
- WasmTypeList<Params>::store(cx, ptr, params);
- wasm_trap_t *trap = nullptr;
- auto *error = wasmtime_func_call_unchecked(cx.capi(), &f.func, ptr,
- storage.size(), &trap);
- if (error != nullptr) {
- return TrapError(Error(error));
- }
- if (trap != nullptr) {
- return TrapError(Trap(trap));
- }
- return WasmTypeList<Results>::load(cx, ptr);
+ if (trap != nullptr) {
+ return TrapError(Trap(trap));
}
- /// Returns the underlying un-typed `Func` for this function.
- const Func &func() const { return f; }
-};
-
-inline Val::Val(std::optional<Func> func) : val{} {
- val.kind = WASMTIME_FUNCREF;
- if (func) {
- val.of.funcref = (*func).func;
- } else {
- wasmtime_funcref_set_null(&val.of.funcref);
+ std::vector<Val> results;
+ results.reserve(nresults);
+ for (size_t i = 0; i < nresults; i++) {
+ results.push_back(raw_results[i]);
}
+ return results;
}
-inline Val::Val(Func func) : Val(std::optional(func)) {}
-inline Val::Val(ExternRef ptr) : Val(std::optional(ptr)) {}
-inline Val::Val(AnyRef ptr) : Val(std::optional(ptr)) {}
-
-inline std::optional<Func> Val::funcref() const {
- if (val.kind != WASMTIME_FUNCREF) {
- std::abort();
- }
- if (val.of.funcref.store_id == 0) {
- return std::nullopt;
- }
- return Func(val.of.funcref);
+inline TrapResult<std::vector<Val>>
+Func::call(Store::Context cx, const std::initializer_list<Val> &params) const {
+ return this->call(cx, params.begin(), params.end());
}
-/// Definition for the `funcref` native wasm type
-template <> struct detail::WasmType<std::optional<Func>> {
- /// @private
- static const bool valid = true;
- /// @private
- static const ValKind kind = ValKind::FuncRef;
- /// @private
- static void store(Store::Context cx, wasmtime_val_raw_t *p,
- const std::optional<Func> func) {
- if (func) {
- p->funcref = wasmtime_func_to_raw(cx.capi(), &func->capi());
- } else {
- p->funcref = 0;
- }
- }
- /// @private
- static std::optional<Func> load(Store::Context cx, wasmtime_val_raw_t *p) {
- if (p->funcref == 0) {
- return std::nullopt;
- }
- wasmtime_func_t ret;
- wasmtime_func_from_raw(cx.capi(), p->funcref, &ret);
- return ret;
- }
-};
+inline TrapResult<std::vector<Val>>
+Func::call(Store::Context cx, const std::vector<Val> &params) const {
+ return this->call(cx, params.begin(), params.end());
+}
} // namespace wasmtime
diff --git a/crates/c-api/include/wasmtime/gc.h b/crates/c-api/include/wasmtime/gc.h
deleted file mode 100644
index 1b0ec1f076..0000000000
--- a/crates/c-api/include/wasmtime/gc.h
+++ /dev/null
@@ -1,599 +0,0 @@
-/**
- * \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
-
-#ifdef WASMTIME_FEATURE_GC
-
-#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);
-
-// ============================================================================
-// StructRef
-// ============================================================================
-
-/**
- * \brief Discriminant for storage types in struct/array field types.
- *
- * Extends #wasmtime_valkind_t with packed storage types
- * #WASMTIME_STORAGE_KIND_I8 and #WASMTIME_STORAGE_KIND_I16.
- */
-typedef uint8_t wasmtime_storage_kind_t;
-
-/// \brief An 8-bit packed integer (only valid inside struct/array fields).
-#define WASMTIME_STORAGE_KIND_I8 9
-/// \brief A 16-bit packed integer (only valid inside struct/array fields).
-#define WASMTIME_STORAGE_KIND_I16 10
-
-/**
- * \typedef wasmtime_field_type_t
- * \brief Convenience alias for #wasmtime_field_type
- *
- * \struct wasmtime_field_type
- * \brief Describes the type and mutability of a struct field or array element.
- */
-typedef struct wasmtime_field_type {
- /// The storage type of this field. Use #WASMTIME_I32, #WASMTIME_I64,
- /// #WASMTIME_F32, etc. for value types, or #WASMTIME_STORAGE_KIND_I8 /
- /// #WASMTIME_STORAGE_KIND_I16 for packed types.
- wasmtime_storage_kind_t kind;
- /// Whether this field is mutable. `true` for mutable, `false` for
- /// immutable.
- bool mutable_;
-} wasmtime_field_type_t;
-
-/**
- * \brief An opaque handle to a WebAssembly struct type definition.
- *
- * A struct type describes the fields of a struct. It is used to create a
- * #wasmtime_struct_ref_pre_t, which can then allocate struct instances.
- *
- * Owned. Must be deleted with #wasmtime_struct_type_delete.
- */
-typedef struct wasmtime_struct_type wasmtime_struct_type_t;
-
-/**
- * \brief Create a new struct type.
- *
- * \param engine The engine to register the type with.
- * \param fields Pointer to an array of field type descriptors.
- * \param nfields Number of fields.
- *
- * \return Returns a new struct type, or NULL on error (e.g. invalid field
- * types).
- */
-WASM_API_EXTERN wasmtime_struct_type_t *
-wasmtime_struct_type_new(const wasm_engine_t *engine,
- const wasmtime_field_type_t *fields, size_t nfields);
-
-/**
- * \brief Delete a struct type.
- */
-WASM_API_EXTERN void wasmtime_struct_type_delete(wasmtime_struct_type_t *ty);
-
-/**
- * \brief An opaque, pre-allocated, and registered struct layout for faster
- * allocation.
- *
- * Created from a #wasmtime_struct_type_t and a store context. Reusable for
- * allocating many struct instances of the same type.
- *
- * Owned. Must be deleted with #wasmtime_struct_ref_pre_delete.
- */
-typedef struct wasmtime_struct_ref_pre wasmtime_struct_ref_pre_t;
-
-/**
- * \brief Create a new struct pre-allocator.
- *
- * \param context The store context.
- * \param ty The struct type.
- *
- * \return Returns a new struct ref pre-allocator.
- */
-WASM_API_EXTERN wasmtime_struct_ref_pre_t *
-wasmtime_struct_ref_pre_new(wasmtime_context_t *context,
- const wasmtime_struct_type_t *ty);
-
-/**
- * \brief Delete a struct pre-allocator.
- */
-WASM_API_EXTERN void
-wasmtime_struct_ref_pre_delete(wasmtime_struct_ref_pre_t *pre);
-
-/**
- * \typedef wasmtime_structref_t
- * \brief Convenience alias for #wasmtime_structref
- *
- * \struct wasmtime_structref
- * \brief A WebAssembly `structref` value.
- *
- * This structure represents a reference to a GC struct. It is a subtype of
- * `eqref` and `anyref`.
- *
- * Values must be explicitly unrooted via #wasmtime_structref_unroot.
- */
-typedef struct wasmtime_structref {
- /// Internal metadata.
- uint64_t store_id;
- /// Internal to Wasmtime.
- uint32_t __private1;
- /// Internal to Wasmtime.
- uint32_t __private2;
- /// Internal to Wasmtime.
- void *__private3;
-} wasmtime_structref_t;
-
-/// \brief Initialize the `ref` to a null `structref` value.
-static inline void wasmtime_structref_set_null(wasmtime_structref_t *ref) {
- ref->store_id = 0;
-}
-
-/// \brief Returns whether the provided `ref` is a null `structref` value.
-static inline bool wasmtime_structref_is_null(const wasmtime_structref_t *ref) {
- return ref->store_id == 0;
-}
-
-/**
- * \brief Allocate a new struct instance.
- *
- * \param context The store context.
- * \param pre The struct pre-allocator.
- * \param fields Pointer to array of field values (#wasmtime_val_t).
- * \param nfields Number of fields (must match the struct type).
- * \param out Receives the new structref on success.
- *
- * \return NULL on success, or a #wasmtime_error_t on failure.
- */
-WASM_API_EXTERN wasmtime_error_t *wasmtime_structref_new(
- wasmtime_context_t *context, const wasmtime_struct_ref_pre_t *pre,
- const wasmtime_val_t *fields, size_t nfields, wasmtime_structref_t *out);
-
-/**
- * \brief Clone a `structref`, creating a new root.
- */
-WASM_API_EXTERN void
-wasmtime_structref_clone(const wasmtime_structref_t *structref,
- wasmtime_structref_t *out);
-
-/**
- * \brief Unroot a `structref` to allow garbage collection.
- */
-WASM_API_EXTERN void wasmtime_structref_unroot(wasmtime_structref_t *ref);
-
-/**
- * \brief Upcast a `structref` to an `anyref`.
- */
-WASM_API_EXTERN void
-wasmtime_structref_to_anyref(const wasmtime_structref_t *structref,
- wasmtime_anyref_t *out);
-
-/**
- * \brief Upcast a `structref` to an `eqref`.
- */
-WASM_API_EXTERN void
-wasmtime_structref_to_eqref(const wasmtime_structref_t *structref,
- wasmtime_eqref_t *out);
-
-/**
- * \brief Read a field from a struct.
- *
- * \param context The store context.
- * \param structref The struct to read from (not consumed).
- * \param index The field index.
- * \param out Receives the field value on success.
- *
- * \return NULL on success, or a #wasmtime_error_t on failure.
- */
-WASM_API_EXTERN wasmtime_error_t *
-wasmtime_structref_field(wasmtime_context_t *context,
- const wasmtime_structref_t *structref, size_t index,
- wasmtime_val_t *out);
-
-/**
- * \brief Set a field of a struct.
- *
- * \param context The store context.
- * \param structref The struct to write to (not consumed).
- * \param index The field index.
- * \param val The value to write (not consumed; caller must still unroot if
- * applicable).
- *
- * \return NULL on success, or a #wasmtime_error_t on failure.
- */
-WASM_API_EXTERN wasmtime_error_t *
-wasmtime_structref_set_field(wasmtime_context_t *context,
- const wasmtime_structref_t *structref,
- size_t index, const wasmtime_val_t *val);
-
-/**
- * \brief Test whether an `eqref` is a `structref`.
- *
- * Returns `false` for null references.
- */
-WASM_API_EXTERN bool wasmtime_eqref_is_struct(wasmtime_context_t *context,
- const wasmtime_eqref_t *eqref);
-
-/**
- * \brief Downcast an `eqref` to a `structref`.
- *
- * If the given `eqref` is a `structref`, a new root for it is stored in `out`
- * and `true` is returned. Otherwise `false` is returned and `out` is set to
- * null.
- */
-WASM_API_EXTERN bool wasmtime_eqref_as_struct(wasmtime_context_t *context,
- const wasmtime_eqref_t *eqref,
- wasmtime_structref_t *out);
-
-/**
- * \brief An opaque handle to a WebAssembly array type definition.
- *
- * An array type describes the element type of an array. It is used to create a
- * #wasmtime_array_ref_pre_t, which can then allocate array instances.
- *
- * Owned. Must be deleted with #wasmtime_array_type_delete.
- */
-typedef struct wasmtime_array_type wasmtime_array_type_t;
-
-/**
- * \brief Create a new array type.
- *
- * \param engine The engine to register the type with.
- * \param field The element type descriptor.
- *
- * \return Returns a new array type.
- */
-WASM_API_EXTERN wasmtime_array_type_t *
-wasmtime_array_type_new(const wasm_engine_t *engine,
- const wasmtime_field_type_t *field);
-
-/**
- * \brief Delete an array type.
- */
-WASM_API_EXTERN void wasmtime_array_type_delete(wasmtime_array_type_t *ty);
-
-/**
- * \brief An opaque pre-allocated array layout for fast allocation.
- *
- * Created from a #wasmtime_array_type_t and a store context. Reusable for
- * allocating many array instances of the same type.
- *
- * Owned. Must be deleted with #wasmtime_array_ref_pre_delete.
- */
-typedef struct wasmtime_array_ref_pre wasmtime_array_ref_pre_t;
-
-/**
- * \brief Create a new array pre-allocator.
- *
- * \param context The store context.
- * \param ty The array type (not consumed; caller retains ownership).
- *
- * \return Returns a new array ref pre-allocator.
- */
-WASM_API_EXTERN wasmtime_array_ref_pre_t *
-wasmtime_array_ref_pre_new(wasmtime_context_t *context,
- const wasmtime_array_type_t *ty);
-
-/**
- * \brief Delete an array pre-allocator.
- */
-WASM_API_EXTERN void
-wasmtime_array_ref_pre_delete(wasmtime_array_ref_pre_t *pre);
-
-/**
- * \typedef wasmtime_arrayref_t
- * \brief Convenience alias for #wasmtime_arrayref
- *
- * \struct wasmtime_arrayref
- * \brief A WebAssembly `arrayref` value.
- *
- * This structure represents a reference to a GC array. It is a subtype of
- * `eqref` and `anyref`.
- *
- * Values must be explicitly unrooted via #wasmtime_arrayref_unroot.
- */
-typedef struct wasmtime_arrayref {
- /// Internal metadata.
- uint64_t store_id;
- /// Internal to Wasmtime.
- uint32_t __private1;
- /// Internal to Wasmtime.
- uint32_t __private2;
- /// Internal to Wasmtime.
- void *__private3;
-} wasmtime_arrayref_t;
-
-/// \brief Initialize the `ref` to a null `arrayref` value.
-static inline void wasmtime_arrayref_set_null(wasmtime_arrayref_t *ref) {
- ref->store_id = 0;
-}
-
-/// \brief Returns whether the provided `ref` is a null `arrayref` value.
-static inline bool wasmtime_arrayref_is_null(const wasmtime_arrayref_t *ref) {
- return ref->store_id == 0;
-}
-
-/**
- * \brief Allocate a new array instance.
- *
- * All elements are initialized to the same value.
- *
- * \param context The store context.
- * \param pre The array pre-allocator.
- * \param elem The initial element value.
- * \param len The number of elements.
- * \param out Receives the new arrayref on success.
- *
- * \return NULL on success, or a #wasmtime_error_t on failure.
- */
-WASM_API_EXTERN wasmtime_error_t *wasmtime_arrayref_new(
- wasmtime_context_t *context, const wasmtime_array_ref_pre_t *pre,
- const wasmtime_val_t *elem, uint32_t len, wasmtime_arrayref_t *out);
-
-/**
- * \brief Clone an `arrayref`, creating a new root.
- */
-WASM_API_EXTERN void
-wasmtime_arrayref_clone(const wasmtime_arrayref_t *arrayref,
- wasmtime_arrayref_t *out);
-
-/**
- * \brief Unroot an `arrayref` to allow garbage collection.
- */
-WASM_API_EXTERN void wasmtime_arrayref_unroot(wasmtime_arrayref_t *ref);
-
-/**
- * \brief Upcast an `arrayref` to an `anyref`.
- */
-WASM_API_EXTERN void
-wasmtime_arrayref_to_anyref(const wasmtime_arrayref_t *arrayref,
- wasmtime_anyref_t *out);
-
-/**
- * \brief Upcast an `arrayref` to an `eqref`.
- */
-WASM_API_EXTERN void
-wasmtime_arrayref_to_eqref(const wasmtime_arrayref_t *arrayref,
- wasmtime_eqref_t *out);
-
-/**
- * \brief Get the length of an array.
- *
- * \param context The store context.
- * \param arrayref The array (not consumed).
- * \param out Receives the length on success.
- *
- * \return NULL on success, or a #wasmtime_error_t on failure.
- */
-WASM_API_EXTERN wasmtime_error_t *
-wasmtime_arrayref_len(wasmtime_context_t *context,
- const wasmtime_arrayref_t *arrayref, uint32_t *out);
-
-/**
- * \brief Read an element from an array.
- *
- * \param context The store context.
- * \param arrayref The array (not consumed).
- * \param index The element index.
- * \param out Receives the element value on success.
- *
- * \return NULL on success, or a #wasmtime_error_t on failure.
- */
-WASM_API_EXTERN wasmtime_error_t *
-wasmtime_arrayref_get(wasmtime_context_t *context,
- const wasmtime_arrayref_t *arrayref, uint32_t index,
- wasmtime_val_t *out);
-
-/**
- * \brief Set an element of an array.
- *
- * \param context The store context.
- * \param arrayref The array (not consumed).
- * \param index The element index.
- * \param val The value to write.
- *
- * \return NULL on success, or a #wasmtime_error_t on failure.
- */
-WASM_API_EXTERN wasmtime_error_t *
-wasmtime_arrayref_set(wasmtime_context_t *context,
- const wasmtime_arrayref_t *arrayref, uint32_t index,
- const wasmtime_val_t *val);
-
-/**
- * \brief Test whether an `eqref` is an `arrayref`.
- *
- * Returns `false` for null references.
- */
-WASM_API_EXTERN bool wasmtime_eqref_is_array(wasmtime_context_t *context,
- const wasmtime_eqref_t *eqref);
-
-/**
- * \brief Downcast an `eqref` to an `arrayref`.
- *
- * If the given `eqref` is an `arrayref`, a new root for it is stored in `out`
- * and `true` is returned. Otherwise `false` is returned and `out` is set to
- * null.
- */
-WASM_API_EXTERN bool wasmtime_eqref_as_array(wasmtime_context_t *context,
- const wasmtime_eqref_t *eqref,
- wasmtime_arrayref_t *out);
-
-/**
- * \brief Test whether an `anyref` is an `eqref`.
- *
- * Returns `false` for null references.
- */
-WASM_API_EXTERN bool wasmtime_anyref_is_eqref(wasmtime_context_t *context,
- const wasmtime_anyref_t *anyref);
-
-/**
- * \brief Downcast an `anyref` to an `eqref`.
- *
- * If the given `anyref` is an `eqref`, a new root is stored in `out` and
- * `true` is returned. Otherwise `false` is returned and `out` is set to null.
- */
-WASM_API_EXTERN bool wasmtime_anyref_as_eqref(wasmtime_context_t *context,
- const wasmtime_anyref_t *anyref,
- wasmtime_eqref_t *out);
-
-/**
- * \brief Test whether an `anyref` is a `structref`.
- *
- * Returns `false` for null references.
- */
-WASM_API_EXTERN bool wasmtime_anyref_is_struct(wasmtime_context_t *context,
- const wasmtime_anyref_t *anyref);
-
-/**
- * \brief Downcast an `anyref` to a `structref`.
- *
- * If the given `anyref` is a `structref`, a new root is stored in `out` and
- * `true` is returned. Otherwise `false` is returned and `out` is set to null.
- */
-WASM_API_EXTERN bool wasmtime_anyref_as_struct(wasmtime_context_t *context,
- const wasmtime_anyref_t *anyref,
- wasmtime_structref_t *out);
-
-/**
- * \brief Test whether an `anyref` is an `arrayref`.
- *
- * Returns `false` for null references.
- */
-WASM_API_EXTERN bool wasmtime_anyref_is_array(wasmtime_context_t *context,
- const wasmtime_anyref_t *anyref);
-
-/**
- * \brief Downcast an `anyref` to an `arrayref`.
- *
- * If the given `anyref` is an `arrayref`, a new root is stored in `out` and
- * `true` is returned. Otherwise `false` is returned and `out` is set to null.
- */
-WASM_API_EXTERN bool wasmtime_anyref_as_array(wasmtime_context_t *context,
- const wasmtime_anyref_t *anyref,
- wasmtime_arrayref_t *out);
-
-#ifdef __cplusplus
-} // extern "C"
-#endif
-
-#endif // WASMTIME_FEATURE_GC
-#endif // WASMTIME_GC_H
diff --git a/crates/c-api/include/wasmtime/gc.hh b/crates/c-api/include/wasmtime/gc.hh
deleted file mode 100644
index 235f0e53bd..0000000000
--- a/crates/c-api/include/wasmtime/gc.hh
+++ /dev/null
@@ -1,484 +0,0 @@
-/**
- * \file wasmtime/gc.hh
- *
- * C++ API for WebAssembly GC types: eqref, structref, and arrayref.
- */
-
-#ifndef WASMTIME_GC_HH
-#define WASMTIME_GC_HH
-
-#include <wasmtime/config.hh>
-
-#ifdef WASMTIME_FEATURE_GC
-#include <vector>
-#include <wasmtime/gc.h>
-#include <wasmtime/val.hh>
-
-namespace wasmtime {
-
-class StructRef;
-class ArrayRef;
-
-/**
- * \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;
- }
-
- /// Returns `true` if this eqref is a structref.
- bool is_struct(Store::Context cx) const {
- return wasmtime_eqref_is_struct(cx.capi(), &val);
- }
-
- /// Returns `true` if this eqref is an arrayref.
- bool is_array(Store::Context cx) const {
- return wasmtime_eqref_is_array(cx.capi(), &val);
- }
-
- /// Upcast this `eqref` to an `anyref`.
- AnyRef to_anyref() const {
- wasmtime_anyref_t out;
- wasmtime_eqref_to_anyref(&val, &out);
- return AnyRef(out);
- }
-
- /// Downcast this `eqref` into a `structref`.
- //
- // as_struct() defined after StructRef below.
- inline StructRef as_struct(Store::Context cx) const;
-
- /// Downcast this `eqref` into an `arrayref`.
- //
- // as_array() defined after ArrayRef below.
- inline ArrayRef as_array(Store::Context cx) const;
-};
-
-/**
- * \brief Describes the storage type and mutability of a struct field or array
- * element.
- */
-struct FieldType {
- /// The field's storage kind.
- wasmtime_storage_kind_t kind;
- /// Whether the field is mutable or not.
- bool mutable_;
-
- /// Create a mutable field type.
- static FieldType mut_(wasmtime_storage_kind_t k) { return {k, true}; }
- /// Create an immutable field type.
- static FieldType const_(wasmtime_storage_kind_t k) { return {k, false}; }
-};
-
-/**
- * \brief Owned handle to a WebAssembly struct type definition.
- *
- * Create with StructType::create, then use with StructRefPre to allocate
- * instances.
- */
-class StructType {
- struct Deleter {
- void operator()(wasmtime_struct_type_t *p) const {
- wasmtime_struct_type_delete(p);
- }
- };
- std::unique_ptr<wasmtime_struct_type_t, Deleter> ptr;
-
-public:
- /// Create a new struct type with the given fields.
- static StructType create(const Engine &engine,
- const std::vector<FieldType> &fields) {
- static_assert(sizeof(FieldType) == sizeof(wasmtime_field_type_t));
- auto *raw = wasmtime_struct_type_new(
- engine.capi(),
- reinterpret_cast<const wasmtime_field_type_t *>(fields.data()),
- fields.size());
- StructType ty;
- ty.ptr.reset(raw);
- return ty;
- }
-
- /// Get the underlying C pointer (non-owning).
- const wasmtime_struct_type_t *capi() const { return ptr.get(); }
-
-private:
- StructType() = default;
- friend class StructRefPre;
-};
-
-/**
- * \brief Pre-allocated struct layout for fast allocation of struct instances.
- *
- * Created from a StructType and a store context. Reusable for allocating
- * many struct instances of the same type.
- */
-class StructRefPre {
- friend class StructRef;
- WASMTIME_OWN_WRAPPER(StructRefPre, wasmtime_struct_ref_pre)
-
-public:
- /// Create a new struct pre-allocator.
- static StructRefPre create(Store::Context cx, const StructType &ty) {
- auto *raw = wasmtime_struct_ref_pre_new(cx.capi(), ty.capi());
- StructRefPre pre(raw);
- return pre;
- }
-};
-
-/**
- * \brief Representation of a WebAssembly `structref` value.
- *
- * A `structref` is a reference to a GC struct instance. It is a subtype
- * of `eqref` and `anyref`.
- */
-class StructRef {
- friend class EqRef;
- friend class Val;
- friend class AnyRef;
-
- wasmtime_structref_t val;
-
-public:
- /// Create a `StructRef` from its C-API representation.
- explicit StructRef(wasmtime_structref_t val) : val(val) {}
-
- /// Clone a `StructRef`.
- StructRef(const StructRef &other) {
- wasmtime_structref_clone(&other.val, &val);
- }
-
- /// Clone a `StructRef` into this one.
- StructRef &operator=(const StructRef &other) {
- wasmtime_structref_unroot(&val);
- wasmtime_structref_clone(&other.val, &val);
- return *this;
- }
-
- /// Move a `StructRef`.
- StructRef(StructRef &&other) {
- val = other.val;
- wasmtime_structref_set_null(&other.val);
- }
-
- /// Move a `StructRef` into this one.
- StructRef &operator=(StructRef &&other) {
- wasmtime_structref_unroot(&val);
- val = other.val;
- wasmtime_structref_set_null(&other.val);
- return *this;
- }
-
- /// Unroot this `StructRef`.
- ~StructRef() { wasmtime_structref_unroot(&val); }
-
- /// Allocate a new struct instance.
- static Result<StructRef> create(Store::Context cx, const StructRefPre &pre,
- const std::vector<Val> &fields) {
- std::vector<wasmtime_val_t> c_fields;
- c_fields.reserve(fields.size());
- for (auto &f : fields) {
- c_fields.push_back(f.val);
- }
-
- wasmtime_structref_t out;
- auto *err = wasmtime_structref_new(cx.capi(), pre.capi(), c_fields.data(),
- c_fields.size(), &out);
- if (err)
- return Result<StructRef>(Error(err));
- return Result<StructRef>(StructRef(out));
- }
-
- /// Read a field from the struct.
- Result<Val> field(Store::Context cx, size_t index) const {
- wasmtime_val_t out;
- auto *err = wasmtime_structref_field(cx.capi(), &val, index, &out);
- if (err)
- return Result<Val>(Error(err));
- return Result<Val>(Val(out));
- }
-
- /// Set a field of the struct.
- Result<std::monostate> set_field(Store::Context cx, size_t index,
- const Val &value) const {
- auto *err =
- wasmtime_structref_set_field(cx.capi(), &val, index, &value.val);
- if (err)
- return Result<std::monostate>(Error(err));
- return Result<std::monostate>(std::monostate{});
- }
-
- /// Upcast to anyref.
- AnyRef to_anyref() const {
- wasmtime_anyref_t out;
- wasmtime_structref_to_anyref(&val, &out);
- return AnyRef(out);
- }
-
- /// Upcast to eqref.
- EqRef to_eqref() const {
- wasmtime_eqref_t out;
- wasmtime_structref_to_eqref(&val, &out);
- return EqRef(out);
- }
-};
-
-inline StructRef EqRef::as_struct(Store::Context cx) const {
- wasmtime_structref_t out;
- wasmtime_eqref_as_struct(cx.capi(), &val, &out);
- return StructRef(out);
-}
-
-/**
- * \brief Owned handle to a WebAssembly array type definition.
- */
-class ArrayType {
- struct Deleter {
- void operator()(wasmtime_array_type_t *p) const {
- wasmtime_array_type_delete(p);
- }
- };
- std::unique_ptr<wasmtime_array_type_t, Deleter> ptr;
-
-public:
- /// Create a new array type with the given element type.
- static ArrayType create(const Engine &engine, const FieldType &field) {
- static_assert(sizeof(FieldType) == sizeof(wasmtime_field_type_t));
- auto *raw = wasmtime_array_type_new(
- engine.capi(), reinterpret_cast<const wasmtime_field_type_t *>(&field));
- ArrayType ty;
- ty.ptr.reset(raw);
- return ty;
- }
-
- /// Get the underlying C pointer (non-owning).
- const wasmtime_array_type_t *capi() const { return ptr.get(); }
-
-private:
- ArrayType() = default;
- friend class ArrayRefPre;
-};
-
-/**
- * \brief Pre-allocated array layout for fast allocation of array instances.
- *
- * Created from a ArrayType and a store context. Reusable for allocating
- * many array instances of the same type.
- */
-class ArrayRefPre {
- friend class ArrayRef;
- WASMTIME_OWN_WRAPPER(ArrayRefPre, wasmtime_array_ref_pre)
-
-public:
- /// Create a new array pre-allocator.
- static ArrayRefPre create(Store::Context cx, const ArrayType &ty) {
- auto *raw = wasmtime_array_ref_pre_new(cx.capi(), ty.capi());
- ArrayRefPre pre(raw);
- return pre;
- }
-};
-
-/**
- * \brief Representation of a WebAssembly `arrayref` value.
- *
- * An `arrayref` is a reference to a GC array instance. It is a subtype
- * of `eqref` and `anyref`.
- */
-class ArrayRef {
- friend class EqRef;
- friend class Val;
- friend class AnyRef;
-
- wasmtime_arrayref_t val;
-
-public:
- /// Create a `ArrayRef` from its C-API representation.
- explicit ArrayRef(wasmtime_arrayref_t val) : val(val) {}
-
- /// Clone a `ArrayRef`.
- ArrayRef(const ArrayRef &other) { wasmtime_arrayref_clone(&other.val, &val); }
-
- /// Clone a `ArrayRef` into this one.
- ArrayRef &operator=(const ArrayRef &other) {
- wasmtime_arrayref_unroot(&val);
- wasmtime_arrayref_clone(&other.val, &val);
- return *this;
- }
-
- /// Move a `ArrayRef`.
- ArrayRef(ArrayRef &&other) {
- val = other.val;
- wasmtime_arrayref_set_null(&other.val);
- }
-
- /// Move a `ArrayRef` into this one.
- ArrayRef &operator=(ArrayRef &&other) {
- wasmtime_arrayref_unroot(&val);
- val = other.val;
- wasmtime_arrayref_set_null(&other.val);
- return *this;
- }
-
- /// Unroot this `ArrayRef`.
- ~ArrayRef() { wasmtime_arrayref_unroot(&val); }
-
- /// Allocate a new array with all elements set to the same value.
- static Result<ArrayRef> create(Store::Context cx, const ArrayRefPre &pre,
- const Val &elem, uint32_t len) {
- wasmtime_arrayref_t out;
- auto *err =
- wasmtime_arrayref_new(cx.capi(), pre.capi(), &elem.val, len, &out);
- if (err)
- return Result<ArrayRef>(Error(err));
- return Result<ArrayRef>(ArrayRef(out));
- }
-
- /// Get the length of the array.
- Result<uint32_t> len(Store::Context cx) const {
- uint32_t out;
- auto *err = wasmtime_arrayref_len(cx.capi(), &val, &out);
- if (err)
- return Result<uint32_t>(Error(err));
- return Result<uint32_t>(out);
- }
-
- /// Read an element from the array.
- Result<Val> get(Store::Context cx, uint32_t index) const {
- wasmtime_val_t out;
- auto *err = wasmtime_arrayref_get(cx.capi(), &val, index, &out);
- if (err)
- return Result<Val>(Error(err));
- return Result<Val>(Val(out));
- }
-
- /// Set an element of the array.
- Result<std::monostate> set(Store::Context cx, uint32_t index,
- const Val &value) const {
- auto *err = wasmtime_arrayref_set(cx.capi(), &val, index, &value.val);
- if (err)
- return Result<std::monostate>(Error(err));
- return Result<std::monostate>(std::monostate{});
- }
-
- /// Upcast to anyref.
- AnyRef to_anyref() const {
- wasmtime_anyref_t out;
- wasmtime_arrayref_to_anyref(&val, &out);
- return AnyRef(out);
- }
-
- /// Upcast to eqref.
- EqRef to_eqref() const {
- wasmtime_eqref_t out;
- wasmtime_arrayref_to_eqref(&val, &out);
- return EqRef(out);
- }
-};
-
-inline ArrayRef EqRef::as_array(Store::Context cx) const {
- wasmtime_arrayref_t out;
- wasmtime_eqref_as_array(cx.capi(), &val, &out);
- return ArrayRef(out);
-}
-
-// AnyRef downcast method definitions (declared in val.hh)
-inline bool AnyRef::is_eqref(Store::Context cx) const {
- return wasmtime_anyref_is_eqref(cx.capi(), &val);
-}
-inline bool AnyRef::is_struct(Store::Context cx) const {
- return wasmtime_anyref_is_struct(cx.capi(), &val);
-}
-inline bool AnyRef::is_array(Store::Context cx) const {
- return wasmtime_anyref_is_array(cx.capi(), &val);
-}
-inline std::optional<EqRef> AnyRef::as_eqref(Store::Context cx) const {
- wasmtime_eqref_t out;
- if (wasmtime_anyref_as_eqref(cx.capi(), &val, &out))
- return EqRef(out);
- return std::nullopt;
-}
-inline std::optional<StructRef> AnyRef::as_struct(Store::Context cx) const {
- wasmtime_structref_t out;
- if (wasmtime_anyref_as_struct(cx.capi(), &val, &out))
- return StructRef(out);
- return std::nullopt;
-}
-inline std::optional<ArrayRef> AnyRef::as_array(Store::Context cx) const {
- wasmtime_arrayref_t out;
- if (wasmtime_anyref_as_array(cx.capi(), &val, &out))
- return ArrayRef(out);
- return std::nullopt;
-}
-
-} // namespace wasmtime
-
-#endif // WASMTIME_FEATURE_GC
-
-#endif // WASMTIME_GC_HH
diff --git a/crates/c-api/include/wasmtime/helpers.hh b/crates/c-api/include/wasmtime/helpers.hh
index 6b70086587..5d1ddf135a 100644
--- a/crates/c-api/include/wasmtime/helpers.hh
+++ b/crates/c-api/include/wasmtime/helpers.hh
@@ -91,4 +91,69 @@ public: \
*/ \
bool operator!=(const name &other) const { return !(*this == other); }
+#define WASMTIME_REF_WRAPPER(name, capi_type) \
+public: \
+ /** \
+ * \brief Non-owning reference to an instance of this type. \
+ */ \
+ using Raw = capi_type##_t; \
+ \
+private: \
+ Raw raw; \
+ \
+public: \
+ /** \
+ * \brief Takes ownership of `val` and wraps it with this class. \
+ */ \
+ explicit name(Raw raw) : raw(raw) {} \
+ name(const name &other) { capi_type##_clone(&other.raw, &raw); } \
+ \
+ name &operator=(const name &other) { \
+ capi_type##_unroot(&raw); \
+ capi_type##_clone(&other.raw, &raw); \
+ return *this; \
+ } \
+ name(name &&other) { \
+ raw = other.raw; \
+ capi_type##_set_null(&other.raw); \
+ } \
+ name &operator=(name &&other) { \
+ capi_type##_unroot(&raw); \
+ raw = other.raw; \
+ capi_type##_set_null(&other.raw); \
+ return *this; \
+ } \
+ \
+ ~name() { capi_type##_unroot(&raw); } \
+ \
+ /** \
+ * \brief Returns the underlying C API pointer. \
+ */ \
+ const Raw *capi() const { return &raw; } \
+ \
+ /** \
+ * \brief Returns the underlying C API pointer. \
+ */ \
+ Raw *capi() { return &raw; }
+
+#define WASMTIME_TOP_REF_WRAPPER(name, capi_type) \
+ WASMTIME_REF_WRAPPER(name, capi_type) \
+ \
+ /** \
+ * \brief 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 = capi_type##_to_raw(cx.capi(), &raw); \
+ capi_type##_set_null(&raw); \
+ return ret; \
+ } \
+ \
+ /** \
+ * \brief Returns `wasmtime_externref_to_raw`. \
+ */ \
+ uint32_t borrow_raw(Store::Context cx) const { \
+ return capi_type##_to_raw(cx.capi(), &raw); \
+ }
+
#endif // WASMTIME_HELPERS_HH
diff --git a/crates/c-api/include/wasmtime/instance.hh b/crates/c-api/include/wasmtime/instance.hh
index 636c058b67..f9c9870823 100644
--- a/crates/c-api/include/wasmtime/instance.hh
+++ b/crates/c-api/include/wasmtime/instance.hh
@@ -5,8 +5,8 @@
#ifndef WASMTIME_INSTANCE_HH
#define WASMTIME_INSTANCE_HH
+#include <wasmtime/_func_class.hh>
#include <wasmtime/extern.hh>
-#include <wasmtime/func.hh>
#include <wasmtime/global.hh>
#include <wasmtime/instance.h>
#include <wasmtime/memory.hh>
diff --git a/crates/c-api/include/wasmtime/store.hh b/crates/c-api/include/wasmtime/store.hh
index 0ad7e9388f..87a6e037c5 100644
--- a/crates/c-api/include/wasmtime/store.hh
+++ b/crates/c-api/include/wasmtime/store.hh
@@ -5,283 +5,60 @@
#ifndef WASMTIME_STORE_HH
#define WASMTIME_STORE_HH
-#include <any>
-#include <memory>
-#include <optional>
-#include <wasmtime/conf.h>
-#include <wasmtime/engine.hh>
-#include <wasmtime/error.hh>
-#include <wasmtime/helpers.hh>
-#include <wasmtime/store.h>
-#include <wasmtime/wasi.hh>
+#include <wasmtime/_exnref_class.hh>
+#include <wasmtime/_func_class.hh>
+#include <wasmtime/_store_class.hh>
+#include <wasmtime/trap.hh>
namespace wasmtime {
-class Caller;
-class Tag;
-class Exn;
-class Trap;
-
-/// \brief An enum for the behavior before extending the epoch deadline.
-enum class DeadlineKind {
- /// Directly continue to updating the deadline and executing WebAssembly.
- Continue = WASMTIME_UPDATE_DEADLINE_CONTINUE,
- /// Yield control (via async support) then update the deadline.
- Yield = WASMTIME_UPDATE_DEADLINE_YIELD,
-};
-
-/**
- * \brief Owner of all WebAssembly objects
- *
- * A `Store` owns all WebAssembly objects such as instances, globals, functions,
- * memories, etc. A `Store` is one of the main central points about working with
- * WebAssembly since it's an argument to almost all APIs. The `Store` serves as
- * a form of "context" to give meaning to the pointers of `Func` and friends.
- *
- * A `Store` can be sent between threads but it cannot generally be shared
- * concurrently between threads. Memory associated with WebAssembly instances
- * will be deallocated when the `Store` is deallocated.
- */
-class Store {
- WASMTIME_OWN_WRAPPER(Store, wasmtime_store);
-
-private:
- static void finalizer(void *ptr) {
- std::unique_ptr<std::any> _ptr(static_cast<std::any *>(ptr));
- }
-
-public:
- /// Creates a new `Store` within the provided `Engine`.
- explicit Store(Engine &engine)
- : ptr(wasmtime_store_new(engine.capi(), nullptr, finalizer)) {}
-
- /**
- * \brief An interior pointer into a `Store`.
- *
- * A `Context` object is created from either a `Store` or a `Caller`. It is an
- * interior pointer into a `Store` and cannot be used outside the lifetime of
- * the original object it was created from.
- *
- * This object is an argument to most APIs in Wasmtime but typically doesn't
- * need to be constructed explicitly since it can be created from a `Store&`
- * or a `Caller&`.
- */
- class Context {
- friend class Global;
- friend class Table;
- friend class Memory;
- friend class Func;
- friend class Instance;
- friend class Linker;
- friend class ExternRef;
- friend class AnyRef;
- friend class EqRef;
- friend class Val;
- friend class Store;
- friend class Tag;
- wasmtime_context_t *ptr;
-
- public:
- /// Creates a context from the raw C API pointer.
- explicit Context(wasmtime_context_t *ptr) : ptr(ptr) {}
-
- /// Creates a context referencing the provided `Store`.
- Context(Store &store) : Context(wasmtime_store_context(store.ptr.get())) {}
- /// Creates a context referencing the provided `Store`.
- Context(Store *store) : Context(*store) {}
- /// Creates a context referencing the provided `Caller`.
- Context(Caller &caller);
- /// Creates a context referencing the provided `Caller`.
- Context(Caller *caller);
-
-#ifdef WASMTIME_FEATURE_GC
- /// Runs a garbage collection pass in the referenced store to collect loose
- /// `externref` values, if any are available.
- Result<std::monostate> gc() {
- auto *error = wasmtime_context_gc(ptr);
- if (error != nullptr) {
- return Error(error);
- }
- return std::monostate();
- }
-#endif
-
- /// Injects fuel to be consumed within this store.
- ///
- /// Stores start with 0 fuel and if `Config::consume_fuel` is enabled then
- /// this is required if you want to let WebAssembly actually execute.
- ///
- /// Returns an error if fuel consumption isn't enabled.
- Result<std::monostate> set_fuel(uint64_t fuel) {
- auto *error = wasmtime_context_set_fuel(ptr, fuel);
- if (error != nullptr) {
- return Error(error);
- }
- return std::monostate();
- }
-
- /// Returns the amount of fuel consumed so far by executing WebAssembly.
- ///
- /// Returns `std::nullopt` if fuel consumption is not enabled.
- Result<uint64_t> get_fuel() const {
- uint64_t fuel = 0;
- auto *error = wasmtime_context_get_fuel(ptr, &fuel);
- if (error != nullptr) {
- return Error(error);
- }
- return fuel;
- }
-
- /// Set user specified data associated with this store.
- void set_data(std::any data) const {
- finalizer(static_cast<std::any *>(wasmtime_context_get_data(ptr)));
- wasmtime_context_set_data(
- ptr, std::make_unique<std::any>(std::move(data)).release());
- }
-
- /// Get user specified data associated with this store.
- std::any &get_data() const {
- return *static_cast<std::any *>(wasmtime_context_get_data(ptr));
+/// Definition for the `funcref` native wasm type
+template <> struct detail::WasmType<std::optional<Func>> {
+ /// @private
+ static const bool valid = true;
+ /// @private
+ static const ValKind kind = ValKind::FuncRef;
+ /// @private
+ static void store(Store::Context cx, wasmtime_val_raw_t *p,
+ const std::optional<Func> func) {
+ if (func) {
+ p->funcref = wasmtime_func_to_raw(cx.capi(), &func->capi());
+ } else {
+ p->funcref = 0;
}
-
-#ifdef WASMTIME_FEATURE_WASI
- /// Configures the WASI state used by this store.
- ///
- /// This will only have an effect if used in conjunction with
- /// `Linker::define_wasi` because otherwise no host functions will use the
- /// WASI state.
- Result<std::monostate> set_wasi(WasiConfig config) {
- auto *error = wasmtime_context_set_wasi(ptr, config.capi_release());
- if (error != nullptr) {
- return Error(error);
- }
- return std::monostate();
- }
-#endif // WASMTIME_FEATURE_WASI
-
- /// Configures this store's epoch deadline to be the specified number of
- /// ticks beyond the engine's current epoch.
- ///
- /// By default the deadline is the current engine's epoch, immediately
- /// interrupting code if epoch interruption is enabled. This must be called
- /// to extend the deadline to allow interruption.
- void set_epoch_deadline(uint64_t ticks_beyond_current) {
- wasmtime_context_set_epoch_deadline(ptr, ticks_beyond_current);
- }
-
-#ifdef WASMTIME_FEATURE_GC
- /// \brief Sets the pending exception on the store and returns a Trap.
- ///
- /// This transfers ownership of `exn`. After this call, `exn` is consumed.
- /// Returns a Trap that the host callback MUST return to propagate the
- /// exception through Wasm catch blocks.
- inline Trap throw_exception(Exn exn);
-
- /// \brief Takes the pending exception from the store, if any.
- ///
- /// Returns the exception if one was pending, or std::nullopt.
- inline std::optional<Exn> take_exception();
-
- /// \brief Tests whether there is a pending exception on the store.
- inline bool has_exception();
-#endif // WASMTIME_FEATURE_GC
-
- /// \brief Returns the underlying C API pointer.
- const wasmtime_context_t *capi() const { return ptr; }
-
- /// \brief Returns the underlying C API pointer.
- wasmtime_context_t *capi() { return ptr; }
- };
-
- /// \brief Provides limits for a store. Used by hosts to limit resource
- /// consumption of instances. Use negative value to keep the default value
- /// for the limit.
- ///
- /// \param memory_size the maximum number of bytes a linear memory can grow
- /// to. Growing a linear memory beyond this limit will fail. By default,
- /// linear memory will not be limited.
- ///
- /// \param table_elements the maximum number of elements in a table.
- /// Growing a table beyond this limit will fail. By default, table elements
- /// will not be limited.
- ///
- /// \param instances the maximum number of instances that can be created
- /// for a Store. Module instantiation will fail if this limit is exceeded.
- /// This value defaults to 10,000.
- ///
- /// \param tables the maximum number of tables that can be created for a
- /// Store. Module instantiation will fail if this limit is exceeded. This
- /// value defaults to 10,000.
- ///
- /// \param memories the maximum number of linear
- /// memories that can be created for a Store. Instantiation will fail with an
- /// error if this limit is exceeded. This value defaults to 10,000.
- ///
- /// Use any negative value for the parameters that should be kept on
- /// the default values.
- ///
- /// Note that the limits are only used to limit the creation/growth of
- /// resources in the future, this does not retroactively attempt to apply
- /// limits to the store.
- void limiter(int64_t memory_size, int64_t table_elements, int64_t instances,
- int64_t tables, int64_t memories) {
- wasmtime_store_limiter(ptr.get(), memory_size, table_elements, instances,
- tables, memories);
}
-
- /// \brief Configures epoch deadline callback to C function.
- ///
- /// This function configures a store-local callback function that will be
- /// called when the running WebAssembly function has exceeded its epoch
- /// deadline. That function can:
- /// - return an error to terminate the function
- /// - set the delta argument and return DeadlineKind::Continue to update the
- /// epoch deadline delta and resume function execution.
- /// - set the delta argument, update the epoch deadline, and return
- /// DeadlineKind::Yield to yield (via async support) and resume function
- /// execution.
- template <typename F,
- std::enable_if_t<std::is_invocable_r_v<Result<DeadlineKind>, F,
- Context, uint64_t &>,
- bool> = true>
- void epoch_deadline_callback(F &&f) {
- wasmtime_store_epoch_deadline_callback(
- ptr.get(), raw_epoch_callback<std::remove_reference_t<F>>,
- std::make_unique<std::remove_reference_t<F>>(std::forward<F>(f))
- .release(),
- raw_epoch_finalizer<std::remove_reference_t<F>>);
+ /// @private
+ static std::optional<Func> load(Store::Context cx, wasmtime_val_raw_t *p) {
+ if (p->funcref == 0) {
+ return std::nullopt;
+ }
+ wasmtime_func_t ret;
+ wasmtime_func_from_raw(cx.capi(), p->funcref, &ret);
+ return ret;
}
+};
- /// Explicit function to acquire a `Context` from this store.
- Context context() { return this; }
+inline Store::Context::Context(Caller &caller)
+ : Context(wasmtime_caller_context(caller.ptr)) {}
+inline Store::Context::Context(Caller *caller) : Context(*caller) {}
#ifdef WASMTIME_FEATURE_GC
- /// Runs a garbage collection pass in the referenced store to collect loose
- /// GC-managed objects, if any are available.
- Result<std::monostate> gc() { return context().gc(); }
-#endif
-
-private:
- template <typename F>
- static wasmtime_error_t *
- raw_epoch_callback(wasmtime_context_t *context, void *data,
- uint64_t *epoch_deadline_delta,
- wasmtime_update_deadline_kind_t *update_kind) {
- auto &callback = *static_cast<F *>(data);
- Context ctx(context);
- auto result = callback(ctx, *epoch_deadline_delta);
-
- if (!result) {
- return result.err().capi_release();
- }
- *update_kind = static_cast<wasmtime_update_deadline_kind_t>(result.ok());
- return nullptr;
+inline Trap Store::Context::throw_exception(ExnRef exn) {
+ return Trap(wasmtime_context_set_exception(capi(), exn.capi()));
+}
+
+inline std::optional<ExnRef> Store::Context::take_exception() {
+ wasmtime_exnref_t exn;
+ if (wasmtime_context_take_exception(capi(), &exn)) {
+ return ExnRef(exn);
}
+ return std::nullopt;
+}
- template <typename F> static void raw_epoch_finalizer(void *data) {
- std::unique_ptr<F> _ptr(static_cast<F *>(data));
- }
-};
+inline bool Store::Context::has_exception() {
+ return wasmtime_context_has_exception(capi());
+}
+#endif
} // namespace wasmtime
diff --git a/crates/c-api/include/wasmtime/structref.h b/crates/c-api/include/wasmtime/structref.h
new file mode 100644
index 0000000000..cb967cd906
--- /dev/null
+++ b/crates/c-api/include/wasmtime/structref.h
@@ -0,0 +1,138 @@
+/**
+ * \file wasmtime/structref.h
+ *
+ * APIs for interacting with WebAssembly `structref` type in Wasmtime.
+ */
+
+#ifndef WASMTIME_STRUCTREF_H
+#define WASMTIME_STRUCTREF_H
+
+#include <wasmtime/conf.h>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <wasmtime/types/structref.h>
+#include <wasmtime/val.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief An opaque, pre-allocated, and registered struct layout for faster
+ * allocation.
+ *
+ * Created from a #wasmtime_struct_type_t and a store context. Reusable for
+ * allocating many struct instances of the same type.
+ *
+ * Owned. Must be deleted with #wasmtime_struct_ref_pre_delete.
+ */
+typedef struct wasmtime_struct_ref_pre wasmtime_struct_ref_pre_t;
+
+/**
+ * \brief Create a new struct pre-allocator.
+ *
+ * \param context The store context.
+ * \param ty The struct type.
+ *
+ * \return Returns a new struct ref pre-allocator.
+ */
+WASM_API_EXTERN wasmtime_struct_ref_pre_t *
+wasmtime_struct_ref_pre_new(wasmtime_context_t *context,
+ const wasmtime_struct_type_t *ty);
+
+/**
+ * \brief Delete a struct pre-allocator.
+ */
+WASM_API_EXTERN void
+wasmtime_struct_ref_pre_delete(wasmtime_struct_ref_pre_t *pre);
+
+/// \brief Initialize the `ref` to a null `structref` value.
+static inline void wasmtime_structref_set_null(wasmtime_structref_t *ref) {
+ ref->store_id = 0;
+}
+
+/// \brief Returns whether the provided `ref` is a null `structref` value.
+static inline bool wasmtime_structref_is_null(const wasmtime_structref_t *ref) {
+ return ref->store_id == 0;
+}
+
+/**
+ * \brief Allocate a new struct instance.
+ *
+ * \param context The store context.
+ * \param pre The struct pre-allocator.
+ * \param fields Pointer to array of field values (#wasmtime_val_t).
+ * \param nfields Number of fields (must match the struct type).
+ * \param out Receives the new structref on success.
+ *
+ * \return NULL on success, or a #wasmtime_error_t on failure.
+ */
+WASM_API_EXTERN wasmtime_error_t *wasmtime_structref_new(
+ wasmtime_context_t *context, const wasmtime_struct_ref_pre_t *pre,
+ const wasmtime_val_t *fields, size_t nfields, wasmtime_structref_t *out);
+
+/**
+ * \brief Clone a `structref`, creating a new root.
+ */
+WASM_API_EXTERN void
+wasmtime_structref_clone(const wasmtime_structref_t *structref,
+ wasmtime_structref_t *out);
+
+/**
+ * \brief Unroot a `structref` to allow garbage collection.
+ */
+WASM_API_EXTERN void wasmtime_structref_unroot(wasmtime_structref_t *ref);
+
+/**
+ * \brief Upcast a `structref` to an `anyref`.
+ */
+WASM_API_EXTERN void
+wasmtime_structref_to_anyref(const wasmtime_structref_t *structref,
+ wasmtime_anyref_t *out);
+
+/**
+ * \brief Upcast a `structref` to an `eqref`.
+ */
+WASM_API_EXTERN void
+wasmtime_structref_to_eqref(const wasmtime_structref_t *structref,
+ wasmtime_eqref_t *out);
+
+/**
+ * \brief Read a field from a struct.
+ *
+ * \param context The store context.
+ * \param structref The struct to read from (not consumed).
+ * \param index The field index.
+ * \param out Receives the field value on success.
+ *
+ * \return NULL on success, or a #wasmtime_error_t on failure.
+ */
+WASM_API_EXTERN wasmtime_error_t *
+wasmtime_structref_field(wasmtime_context_t *context,
+ const wasmtime_structref_t *structref, size_t index,
+ wasmtime_val_t *out);
+
+/**
+ * \brief Set a field of a struct.
+ *
+ * \param context The store context.
+ * \param structref The struct to write to (not consumed).
+ * \param index The field index.
+ * \param val The value to write (not consumed; caller must still unroot if
+ * applicable).
+ *
+ * \return NULL on success, or a #wasmtime_error_t on failure.
+ */
+WASM_API_EXTERN wasmtime_error_t *
+wasmtime_structref_set_field(wasmtime_context_t *context,
+ const wasmtime_structref_t *structref,
+ size_t index, const wasmtime_val_t *val);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_STRUCTREF_H
diff --git a/crates/c-api/include/wasmtime/structref.hh b/crates/c-api/include/wasmtime/structref.hh
new file mode 100644
index 0000000000..e9ab974984
--- /dev/null
+++ b/crates/c-api/include/wasmtime/structref.hh
@@ -0,0 +1,64 @@
+/**
+ * \file wasmtime/structref.hh
+ */
+
+#ifndef WASMTIME_STRUCTREF_HH
+#define WASMTIME_STRUCTREF_HH
+
+#include <wasmtime/_structref_class.hh>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <wasmtime/_anyref_class.hh>
+#include <wasmtime/_eqref_class.hh>
+#include <wasmtime/_val_class.hh>
+
+namespace wasmtime {
+
+inline Result<StructRef> StructRef::create(Store::Context cx,
+ const StructRefPre &pre,
+ const std::vector<Val> &fields) {
+ wasmtime_structref_t out;
+ auto *err = wasmtime_structref_new(
+ cx.capi(), pre.capi(),
+ reinterpret_cast<const wasmtime_val_t *>(fields.data()), fields.size(),
+ &out);
+ if (err)
+ return Result<StructRef>(Error(err));
+ return Result<StructRef>(StructRef(out));
+}
+
+inline Result<Val> StructRef::field(Store::Context cx, size_t index) const {
+ wasmtime_val_t out;
+ auto *err = wasmtime_structref_field(cx.capi(), &raw, index, &out);
+ if (err)
+ return Result<Val>(Error(err));
+ return Result<Val>(Val(out));
+}
+
+inline Result<std::monostate>
+StructRef::set_field(Store::Context cx, size_t index, const Val &value) const {
+ auto *err =
+ wasmtime_structref_set_field(cx.capi(), &raw, index, value.capi());
+ if (err)
+ return Result<std::monostate>(Error(err));
+ return Result<std::monostate>(std::monostate{});
+}
+
+inline AnyRef StructRef::to_anyref() const {
+ wasmtime_anyref_t out;
+ wasmtime_structref_to_anyref(&raw, &out);
+ return AnyRef(out);
+}
+
+inline EqRef StructRef::to_eqref() const {
+ wasmtime_eqref_t out;
+ wasmtime_structref_to_eqref(&raw, &out);
+ return EqRef(out);
+}
+
+} // namespace wasmtime
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_STRUCTREF_HH
diff --git a/crates/c-api/include/wasmtime/tag.hh b/crates/c-api/include/wasmtime/tag.hh
index fac4ae4e89..8320289a90 100644
--- a/crates/c-api/include/wasmtime/tag.hh
+++ b/crates/c-api/include/wasmtime/tag.hh
@@ -5,8 +5,8 @@
#ifndef WASMTIME_TAG_HH
#define WASMTIME_TAG_HH
+#include <wasmtime/_store_class.hh>
#include <wasmtime/error.hh>
-#include <wasmtime/store.hh>
#include <wasmtime/tag.h>
#include <wasmtime/types/tag.hh>
diff --git a/crates/c-api/include/wasmtime/types/arrayref.h b/crates/c-api/include/wasmtime/types/arrayref.h
new file mode 100644
index 0000000000..4c55eebfb1
--- /dev/null
+++ b/crates/c-api/include/wasmtime/types/arrayref.h
@@ -0,0 +1,54 @@
+/**
+ * \file wasmtime/types/arrayref.h
+ *
+ * APIs for interacting with WebAssembly GC `structref` type in Wasmtime.
+ */
+
+#ifndef WASMTIME_TYPES_ARRAYREF_H
+#define WASMTIME_TYPES_ARRAYREF_H
+
+#include <wasmtime/conf.h>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <wasm.h>
+#include <wasmtime/types/structref.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief An opaque handle to a WebAssembly array type definition.
+ *
+ * An array type describes the element type of an array. It is used to create a
+ * #wasmtime_array_ref_pre_t, which can then allocate array instances.
+ *
+ * Owned. Must be deleted with #wasmtime_array_type_delete.
+ */
+typedef struct wasmtime_array_type wasmtime_array_type_t;
+
+/**
+ * \brief Create a new array type.
+ *
+ * \param engine The engine to register the type with.
+ * \param field The element type descriptor.
+ *
+ * \return Returns a new array type.
+ */
+WASM_API_EXTERN wasmtime_array_type_t *
+wasmtime_array_type_new(const wasm_engine_t *engine,
+ const wasmtime_field_type_t *field);
+
+/**
+ * \brief Delete an array type.
+ */
+WASM_API_EXTERN void wasmtime_array_type_delete(wasmtime_array_type_t *ty);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_TYPES_ARRAYREF_H
diff --git a/crates/c-api/include/wasmtime/types/arrayref.hh b/crates/c-api/include/wasmtime/types/arrayref.hh
new file mode 100644
index 0000000000..4666615d69
--- /dev/null
+++ b/crates/c-api/include/wasmtime/types/arrayref.hh
@@ -0,0 +1,38 @@
+/**
+ * \file wasmtime/types/arrayref.hh
+ */
+
+#ifndef WASMTIME_TYPES_ARRAYREF_HH
+#define WASMTIME_TYPES_ARRAYREF_HH
+
+#include <wasmtime/conf.h>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <memory>
+#include <wasmtime/engine.hh>
+#include <wasmtime/types/arrayref.h>
+#include <wasmtime/types/structref.hh>
+
+namespace wasmtime {
+
+/**
+ * \brief Owned handle to a WebAssembly array type definition.
+ */
+class ArrayType {
+ WASMTIME_OWN_WRAPPER(ArrayType, wasmtime_array_type)
+
+ /// Create a new array type with the given element type.
+ static ArrayType create(const Engine &engine, const FieldType &field) {
+ static_assert(sizeof(FieldType) == sizeof(wasmtime_field_type_t));
+ auto *raw = wasmtime_array_type_new(
+ engine.capi(), reinterpret_cast<const wasmtime_field_type_t *>(&field));
+ return ArrayType(raw);
+ }
+};
+
+} // namespace wasmtime
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_TYPES_ARRAYREF_HH
diff --git a/crates/c-api/include/wasmtime/types/structref.h b/crates/c-api/include/wasmtime/types/structref.h
new file mode 100644
index 0000000000..4be6d0fa92
--- /dev/null
+++ b/crates/c-api/include/wasmtime/types/structref.h
@@ -0,0 +1,85 @@
+/**
+ * \file wasmtime/types/structref.h
+ *
+ * APIs for interacting with WebAssembly GC `structref` type in Wasmtime.
+ */
+
+#ifndef WASMTIME_TYPES_STRUCTREF_H
+#define WASMTIME_TYPES_STRUCTREF_H
+
+#include <wasmtime/conf.h>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <wasm.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief Discriminant for storage types in struct/array field types.
+ *
+ * Extends #wasmtime_valkind_t with packed storage types
+ * #WASMTIME_STORAGE_KIND_I8 and #WASMTIME_STORAGE_KIND_I16.
+ */
+typedef uint8_t wasmtime_storage_kind_t;
+
+/// \brief An 8-bit packed integer (only valid inside struct/array fields).
+#define WASMTIME_STORAGE_KIND_I8 9
+/// \brief A 16-bit packed integer (only valid inside struct/array fields).
+#define WASMTIME_STORAGE_KIND_I16 10
+
+/**
+ * \typedef wasmtime_field_type_t
+ * \brief Convenience alias for #wasmtime_field_type
+ *
+ * \struct wasmtime_field_type
+ * \brief Describes the type and mutability of a struct field or array element.
+ */
+typedef struct wasmtime_field_type {
+ /// The storage type of this field. Use #WASMTIME_I32, #WASMTIME_I64,
+ /// #WASMTIME_F32, etc. for value types, or #WASMTIME_STORAGE_KIND_I8 /
+ /// #WASMTIME_STORAGE_KIND_I16 for packed types.
+ wasmtime_storage_kind_t kind;
+ /// Whether this field is mutable. `true` for mutable, `false` for
+ /// immutable.
+ bool mutable_;
+} wasmtime_field_type_t;
+
+/**
+ * \brief An opaque handle to a WebAssembly struct type definition.
+ *
+ * A struct type describes the fields of a struct. It is used to create a
+ * #wasmtime_struct_ref_pre_t, which can then allocate struct instances.
+ *
+ * Owned. Must be deleted with #wasmtime_struct_type_delete.
+ */
+typedef struct wasmtime_struct_type wasmtime_struct_type_t;
+
+/**
+ * \brief Create a new struct type.
+ *
+ * \param engine The engine to register the type with.
+ * \param fields Pointer to an array of field type descriptors.
+ * \param nfields Number of fields.
+ *
+ * \return Returns a new struct type, or NULL on error (e.g. invalid field
+ * types).
+ */
+WASM_API_EXTERN wasmtime_struct_type_t *
+wasmtime_struct_type_new(const wasm_engine_t *engine,
+ const wasmtime_field_type_t *fields, size_t nfields);
+
+/**
+ * \brief Delete a struct type.
+ */
+WASM_API_EXTERN void wasmtime_struct_type_delete(wasmtime_struct_type_t *ty);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_TYPES_STRUCTREF_H
diff --git a/crates/c-api/include/wasmtime/types/structref.hh b/crates/c-api/include/wasmtime/types/structref.hh
new file mode 100644
index 0000000000..b2bf544833
--- /dev/null
+++ b/crates/c-api/include/wasmtime/types/structref.hh
@@ -0,0 +1,60 @@
+/**
+ * \file wasmtime/types/structref.hh
+ */
+
+#ifndef WASMTIME_TYPES_STRUCTREF_HH
+#define WASMTIME_TYPES_STRUCTREF_HH
+
+#include <wasmtime/conf.h>
+
+#ifdef WASMTIME_FEATURE_GC
+
+#include <memory>
+#include <vector>
+#include <wasmtime/engine.hh>
+#include <wasmtime/types/structref.h>
+
+namespace wasmtime {
+
+/**
+ * \brief Describes the storage type and mutability of a struct field or array
+ * element.
+ */
+struct FieldType {
+ /// The field's storage kind.
+ wasmtime_storage_kind_t kind;
+ /// Whether the field is mutable or not.
+ bool mutable_;
+
+ /// Create a mutable field type.
+ static FieldType mut_(wasmtime_storage_kind_t k) { return {k, true}; }
+ /// Create an immutable field type.
+ static FieldType const_(wasmtime_storage_kind_t k) { return {k, false}; }
+};
+
+/**
+ * \brief Owned handle to a WebAssembly struct type definition.
+ *
+ * Create with StructType::create, then use with StructRefPre to allocate
+ * instances.
+ */
+class StructType {
+ WASMTIME_OWN_WRAPPER(StructType, wasmtime_struct_type)
+
+ /// Create a new struct type with the given fields.
+ static StructType create(const Engine &engine,
+ const std::vector<FieldType> &fields) {
+ static_assert(sizeof(FieldType) == sizeof(wasmtime_field_type_t));
+ auto *raw = wasmtime_struct_type_new(
+ engine.capi(),
+ reinterpret_cast<const wasmtime_field_type_t *>(fields.data()),
+ fields.size());
+ return StructType(raw);
+ }
+};
+
+} // namespace wasmtime
+
+#endif // WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_TYPES_STRUCTREF_HH
diff --git a/crates/c-api/include/wasmtime/types/tag.hh b/crates/c-api/include/wasmtime/types/tag.hh
index 28ce8a8df4..6f47342761 100644
--- a/crates/c-api/include/wasmtime/types/tag.hh
+++ b/crates/c-api/include/wasmtime/types/tag.hh
@@ -19,7 +19,6 @@ namespace wasmtime {
*/
class TagType {
friend class Tag;
- friend class Exn;
struct deleter {
void operator()(wasm_tagtype_t *p) const { wasm_tagtype_delete(p); }
diff --git a/crates/c-api/include/wasmtime/val.h b/crates/c-api/include/wasmtime/val.h
index 2b5f3c32fe..6ce2bab344 100644
--- a/crates/c-api/include/wasmtime/val.h
+++ b/crates/c-api/include/wasmtime/val.h
@@ -9,16 +9,46 @@
#include <stdalign.h>
#include <wasm.h>
+#include <wasmtime/conf.h>
#include <wasmtime/extern.h>
#ifdef __cplusplus
extern "C" {
#endif
+/// \brief Discriminant stored in #wasmtime_val::kind
+typedef uint8_t wasmtime_valkind_t;
+/// \brief Value of #wasmtime_valkind_t meaning that #wasmtime_val_t is an i32
+#define WASMTIME_I32 0
+/// \brief Value of #wasmtime_valkind_t meaning that #wasmtime_val_t is an i64
+#define WASMTIME_I64 1
+/// \brief Value of #wasmtime_valkind_t meaning that #wasmtime_val_t is a f32
+#define WASMTIME_F32 2
+/// \brief Value of #wasmtime_valkind_t meaning that #wasmtime_val_t is a f64
+#define WASMTIME_F64 3
+/// \brief Value of #wasmtime_valkind_t meaning that #wasmtime_val_t is a v128
+#define WASMTIME_V128 4
+/// \brief Value of #wasmtime_valkind_t meaning that #wasmtime_val_t is a
+/// funcref
+#define WASMTIME_FUNCREF 5
+
#ifdef WASMTIME_FEATURE_GC
-/// Convenience alias for #wasmtime_eqref
-typedef struct wasmtime_eqref wasmtime_eqref_t;
+/// \brief Value of #wasmtime_valkind_t meaning that #wasmtime_val_t is an
+/// externref
+#define WASMTIME_EXTERNREF 6
+/// \brief Value of #wasmtime_valkind_t meaning that #wasmtime_val_t is an
+/// anyref
+#define WASMTIME_ANYREF 7
+/// \brief Value of #wasmtime_valkind_t meaning that #wasmtime_val_t is an
+/// exnref
+#define WASMTIME_EXNREF 8
+#endif // WASMTIME_FEATURE_GC
+
+/// \brief A 128-bit value representing the WebAssembly `v128` type. Bytes are
+/// stored in little-endian order.
+typedef uint8_t wasmtime_v128[16];
+#ifdef WASMTIME_FEATURE_GC
/**
* \typedef wasmtime_anyref_t
* \brief Convenience alias for #wasmtime_anyref
@@ -34,7 +64,7 @@ typedef struct wasmtime_eqref wasmtime_eqref_t;
* referencing the internal data requires using a `wasmtime_context_t`.
*
* Anyref values are required to be explicitly unrooted via
- * #wasmtime_anyref_unroot to enable them to be garbage-collected.
+ * `wasmtime_anyref_unroot` to enable them to be garbage-collected.
*
* If you do not unroot the value, *even if you free the corresponding
* Store*, there will be some memory leaked, because GC roots use a
@@ -56,116 +86,31 @@ typedef struct wasmtime_anyref {
void *__private3;
} wasmtime_anyref_t;
-/// \brief Helper function to initialize the `ref` provided to a null anyref
-/// value.
-static inline void wasmtime_anyref_set_null(wasmtime_anyref_t *ref) {
- ref->store_id = 0;
-}
-
-/// \brief Helper function to return whether the provided `ref` points to a null
-/// `anyref` value.
-///
-/// Note that `ref` itself should not be null as null is represented internally
-/// within a #wasmtime_anyref_t value.
-static inline bool wasmtime_anyref_is_null(const wasmtime_anyref_t *ref) {
- return ref->store_id == 0;
-}
-
-/**
- * \brief Creates a new reference pointing to the same data that `anyref`
- * points to (depending on the configured collector this might increase a
- * reference count or create a new GC root).
- *
- * The returned reference is stored in `out`.
- */
-WASM_API_EXTERN void wasmtime_anyref_clone(const wasmtime_anyref_t *anyref,
- wasmtime_anyref_t *out);
-
-/**
- * \brief Unroots the `ref` provided within the `context`.
- *
- * This API is required to enable the `ref` value provided to be
- * garbage-collected. This API itself does not necessarily garbage-collect the
- * value, but it's possible to collect it in the future after this.
- *
- * This may modify `ref` and the contents of `ref` are left in an undefined
- * state after this API is called and it should no longer be used.
- *
- * 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_anyref_t *ref);
-
-/**
- * \brief Converts a raw `anyref` value coming from #wasmtime_val_raw_t into
- * a #wasmtime_anyref_t.
- *
- * The provided `out` pointer is filled in with a reference converted from
- * `raw`.
- */
-WASM_API_EXTERN void wasmtime_anyref_from_raw(wasmtime_context_t *context,
- uint32_t raw,
- wasmtime_anyref_t *out);
-
-/**
- * \brief Converts a #wasmtime_anyref_t to a raw value suitable for storing
- * into a #wasmtime_val_raw_t.
- *
- * Note that the returned underlying value is not tracked by Wasmtime's garbage
- * collector until it enters WebAssembly. This means that a GC may release the
- * context's reference to the raw value, making the raw value invalid within the
- * context of the store. Do not perform a GC between calling this function and
- * passing it to WebAssembly.
- */
-WASM_API_EXTERN uint32_t wasmtime_anyref_to_raw(wasmtime_context_t *context,
- const wasmtime_anyref_t *ref);
-
-/**
- * \brief Create a new `i31ref` value.
- *
- * Creates a new `i31ref` value (which is a subtype of `anyref`) and returns a
- * pointer to it.
- *
- * If `i31val` does not fit in 31 bits, it is wrapped.
- */
-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.
- *
- * If the given `anyref` is an instance of `i31ref`, then its value is zero
- * extended to 32 bits, written to `dst`, and `true` is returned.
+ * \typedef wasmtime_exnref_t
+ * \brief Convenience alias for #wasmtime_exnref
*
- * If the given `anyref` is not an instance of `i31ref`, then `false` is
- * returned and `dst` is left unmodified.
- */
-WASM_API_EXTERN bool wasmtime_anyref_i31_get_u(wasmtime_context_t *context,
- const wasmtime_anyref_t *anyref,
- uint32_t *dst);
-
-/**
- * \brief Get the `anyref`'s underlying `i31ref` value, sign extended, if any.
+ * \struct wasmtime_exnref
+ * \brief A WebAssembly exception reference value.
*
- * If the given `anyref` is an instance of `i31ref`, then its value is sign
- * extended to 32 bits, written to `dst`, and `true` is returned.
+ * This structure represents an `exnref` value, which is a reference to a
+ * WebAssembly exception object. Like other GC reference types, it must be
+ * explicitly unrooted via #wasmtime_exnref_unroot to enable garbage
+ * collection.
*
- * If the given `anyref` is not an instance of `i31ref`, then `false` is
- * returned and `dst` is left unmodified.
+ * Null exnref values are represented with `store_id == 0`.
*/
-WASM_API_EXTERN bool wasmtime_anyref_i31_get_s(wasmtime_context_t *context,
- const wasmtime_anyref_t *anyref,
- int32_t *dst);
+typedef struct wasmtime_exnref {
+ /// 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_exnref_t;
/**
* \typedef wasmtime_externref_t
@@ -188,7 +133,6 @@ WASM_API_EXTERN bool wasmtime_anyref_i31_get_s(wasmtime_context_t *context,
* `wasmtime_externref_set_null`. Null can be tested for with the
* `wasmtime_externref_is_null` function.
*/
-
typedef struct wasmtime_externref {
/// Internal metadata tracking within the store, embedders should not
/// configure or modify these fields.
@@ -201,124 +145,70 @@ typedef struct wasmtime_externref {
void *__private3;
} wasmtime_externref_t;
-/// \brief Helper function to initialize the `ref` provided to a null externref
-/// value.
-static inline void wasmtime_externref_set_null(wasmtime_externref_t *ref) {
- ref->store_id = 0;
-}
-
-/// \brief Helper function to return whether the provided `ref` points to a null
-/// `externref` value.
-///
-/// Note that `ref` itself should not be null as null is represented internally
-/// within a #wasmtime_externref_t value.
-static inline bool wasmtime_externref_is_null(const wasmtime_externref_t *ref) {
- return ref->store_id == 0;
-}
-
/**
- * \brief Create a new `externref` value.
- *
- * Creates a new `externref` value wrapping the provided data, returning whether
- * it was created or not.
- *
- * \param context the store context to allocate this externref within
- * \param data the host-specific data to wrap
- * \param finalizer an optional finalizer for `data`
- * \param out where to store the created value.
+ * \typedef wasmtime_eqref_t
+ * \brief Convenience alias for #wasmtime_eqref
*
- * When the reference is reclaimed, the wrapped data is cleaned up with the
- * provided `finalizer`.
+ * \struct wasmtime_eqref
+ * \brief A WebAssembly `eqref` value.
*
- * If `true` is returned then `out` has been filled in and must be unrooted
- * in the future with #wasmtime_externref_unroot. If `false` is returned then
- * the host wasn't able to create more GC values at this time. Performing a GC
- * may free up enough space to try again.
+ * This structure represents a reference to a GC object that can be tested for
+ * equality. The subtypes of `eqref` include `structref`, `arrayref`, and
+ * `i31ref`.
*
- * If you do not unroot the value, *even if you free the corresponding
- * Store*, there will be some memory leaked, because GC roots use a
- * separate allocation to track liveness.
- */
-WASM_API_EXTERN bool wasmtime_externref_new(wasmtime_context_t *context,
- void *data,
- void (*finalizer)(void *),
- wasmtime_externref_t *out);
-
-/**
- * \brief Get an `externref`'s wrapped data
- *
- * Returns the original `data` passed to #wasmtime_externref_new. It is required
- * that `data` is not `NULL`.
- */
-WASM_API_EXTERN void *wasmtime_externref_data(wasmtime_context_t *context,
- const wasmtime_externref_t *data);
-
-/**
- * \brief Creates a new reference pointing to the same data that `ref` points
- * to (depending on the configured collector this might increase a reference
- * count or create a new GC root).
- *
- * The `out` parameter stores the cloned reference. This reference must
- * eventually be unrooted with #wasmtime_externref_unroot in the future to
- * enable GC'ing it.
+ * 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.
*/
-WASM_API_EXTERN void wasmtime_externref_clone(const wasmtime_externref_t *ref,
- wasmtime_externref_t *out);
+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 Unroots the pointer `ref` from the `context` provided.
+ * \typedef wasmtime_structref_t
+ * \brief Convenience alias for #wasmtime_structref
*
- * This function will enable future garbage collection of the value pointed to
- * by `ref` once there are no more references. The `ref` value may be mutated in
- * place by this function and its contents are undefined after this function
- * returns. It should not be used until after re-initializing it.
+ * \struct wasmtime_structref
+ * \brief A WebAssembly `structref` value.
*
- * 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_externref_t *ref);
-
-/**
- * \brief Converts a raw `externref` value coming from #wasmtime_val_raw_t into
- * a #wasmtime_externref_t.
+ * This structure represents a reference to a GC struct. It is a subtype of
+ * `eqref` and `anyref`.
*
- * The `out` reference is filled in with the non-raw version of this externref.
- * It must eventually be unrooted with #wasmtime_externref_unroot.
+ * Values must be explicitly unrooted via #wasmtime_structref_unroot.
*/
-WASM_API_EXTERN void wasmtime_externref_from_raw(wasmtime_context_t *context,
- uint32_t raw,
- wasmtime_externref_t *out);
-
-/**
- * \brief Converts a #wasmtime_externref_t to a raw value suitable for storing
- * into a #wasmtime_val_raw_t.
- *
- * Note that the returned underlying value is not tracked by Wasmtime's garbage
- * collector until it enters WebAssembly. This means that a GC may release the
- * context's reference to the raw value, making the raw value invalid within the
- * context of the store. Do not perform a GC between calling this function and
- * passing it to WebAssembly.
- */
-WASM_API_EXTERN uint32_t wasmtime_externref_to_raw(
- wasmtime_context_t *context, const wasmtime_externref_t *ref);
+typedef struct wasmtime_structref {
+ /// Internal metadata.
+ uint64_t store_id;
+ /// Internal to Wasmtime.
+ uint32_t __private1;
+ /// Internal to Wasmtime.
+ uint32_t __private2;
+ /// Internal to Wasmtime.
+ void *__private3;
+} wasmtime_structref_t;
/**
- * \typedef wasmtime_exnref_t
- * \brief Convenience alias for #wasmtime_exnref
+ * \typedef wasmtime_arrayref_t
+ * \brief Convenience alias for #wasmtime_arrayref
*
- * \struct wasmtime_exnref
- * \brief A WebAssembly exception reference value.
+ * \struct wasmtime_arrayref
+ * \brief A WebAssembly `arrayref` value.
*
- * This structure represents an `exnref` value, which is a reference to a
- * WebAssembly exception object. Like other GC reference types, it must be
- * explicitly unrooted via #wasmtime_exnref_unroot to enable garbage
- * collection.
+ * This structure represents a reference to a GC array. It is a subtype of
+ * `eqref` and `anyref`.
*
- * Null exnref values are represented with `store_id == 0`.
+ * Values must be explicitly unrooted via #wasmtime_arrayref_unroot.
*/
-typedef struct wasmtime_exnref {
- /// Internal metadata tracking within the store, embedders should not
- /// configure or modify these fields.
+typedef struct wasmtime_arrayref {
+ /// Internal metadata.
uint64_t store_id;
/// Internal to Wasmtime.
uint32_t __private1;
@@ -326,66 +216,10 @@ typedef struct wasmtime_exnref {
uint32_t __private2;
/// Internal to Wasmtime.
void *__private3;
-} wasmtime_exnref_t;
+} wasmtime_arrayref_t;
-/// \brief Helper function to initialize the `ref` provided to a null exnref
-/// value.
-static inline void wasmtime_exnref_set_null(wasmtime_exnref_t *ref) {
- ref->store_id = 0;
-}
-
-/// \brief Helper function to return whether the provided `ref` points to a null
-/// `exnref` value.
-static inline bool wasmtime_exnref_is_null(const wasmtime_exnref_t *ref) {
- return ref->store_id == 0;
-}
-
-/**
- * \brief Creates a new reference pointing to the same exception that `ref`
- * points to.
- *
- * The returned reference is stored in `out`.
- */
-WASM_API_EXTERN void wasmtime_exnref_clone(const wasmtime_exnref_t *ref,
- wasmtime_exnref_t *out);
-
-/**
- * \brief Unroots the `ref` provided, enabling future garbage collection.
- *
- * After this call, `ref` is left in an undefined state and should not be used.
- */
-WASM_API_EXTERN void wasmtime_exnref_unroot(wasmtime_exnref_t *ref);
#endif // WASMTIME_FEATURE_GC
-/// \brief Discriminant stored in #wasmtime_val::kind
-typedef uint8_t wasmtime_valkind_t;
-/// \brief Value of #wasmtime_valkind_t meaning that #wasmtime_val_t is an i32
-#define WASMTIME_I32 0
-/// \brief Value of #wasmtime_valkind_t meaning that #wasmtime_val_t is an i64
-#define WASMTIME_I64 1
-/// \brief Value of #wasmtime_valkind_t meaning that #wasmtime_val_t is a f32
-#define WASMTIME_F32 2
-/// \brief Value of #wasmtime_valkind_t meaning that #wasmtime_val_t is a f64
-#define WASMTIME_F64 3
-/// \brief Value of #wasmtime_valkind_t meaning that #wasmtime_val_t is a v128
-#define WASMTIME_V128 4
-/// \brief Value of #wasmtime_valkind_t meaning that #wasmtime_val_t is a
-/// funcref
-#define WASMTIME_FUNCREF 5
-/// \brief Value of #wasmtime_valkind_t meaning that #wasmtime_val_t is an
-/// externref
-#define WASMTIME_EXTERNREF 6
-/// \brief Value of #wasmtime_valkind_t meaning that #wasmtime_val_t is an
-/// anyref
-#define WASMTIME_ANYREF 7
-/// \brief Value of #wasmtime_valkind_t meaning that #wasmtime_val_t is an
-/// exnref
-#define WASMTIME_EXNREF 8
-
-/// \brief A 128-bit value representing the WebAssembly `v128` type. Bytes are
-/// stored in little-endian order.
-typedef uint8_t wasmtime_v128[16];
-
/**
* \typedef wasmtime_valunion_t
* \brief Convenience alias for #wasmtime_valunion
@@ -412,12 +246,12 @@ typedef union wasmtime_valunion {
wasmtime_externref_t externref;
/// Field used if #wasmtime_val_t::kind is #WASMTIME_EXNREF
wasmtime_exnref_t exnref;
+#endif // WASMTIME_FEATURE_GC
/// Field used if #wasmtime_val_t::kind is #WASMTIME_FUNCREF
///
/// Use `wasmtime_funcref_is_null` to test whether this is a null function
/// reference.
wasmtime_func_t funcref;
-#endif // WASMTIME_FEATURE_GC
/// Field used if #wasmtime_val_t::kind is #WASMTIME_V128
wasmtime_v128 v128;
} wasmtime_valunion_t;
@@ -474,6 +308,7 @@ typedef union wasmtime_val_raw {
///
/// Note that this field is always stored in a little-endian format.
wasmtime_v128 v128;
+#ifdef WASMTIME_FEATURE_GC
/// Field for when this val is a WebAssembly `anyref` value.
///
/// If this is set to 0 then it's a null anyref, otherwise this must be
@@ -490,6 +325,15 @@ typedef union wasmtime_val_raw {
///
/// Note that this field is always stored in a little-endian format.
uint32_t externref;
+ /// Field for when this val is a WebAssembly `exnref` value.
+ ///
+ /// If this is set to 0 then it's a null exnref, otherwise this must be
+ /// passed to `wasmtime_exnref_from_raw` to determine the
+ /// `wasmtime_exnref_t`.
+ ///
+ /// Note that this field is always stored in a little-endian format.
+ uint32_t exnref;
+#endif // WASMTIME_FEATURE_GC
/// Field for when this val is a WebAssembly `funcref` value.
///
/// If this is set to 0 then it's a null funcref, otherwise this must be
diff --git a/crates/c-api/include/wasmtime/val.hh b/crates/c-api/include/wasmtime/val.hh
index 32c2ce5e35..63ea04e788 100644
--- a/crates/c-api/include/wasmtime/val.hh
+++ b/crates/c-api/include/wasmtime/val.hh
@@ -5,455 +5,100 @@
#ifndef WASMTIME_VAL_HH
#define WASMTIME_VAL_HH
-#include <optional>
-#ifdef WASMTIME_FEATURE_GC
-#include <wasmtime/gc.h>
-#endif // WASMTIME_FEATURE_GC
-#include <wasmtime/store.hh>
-#include <wasmtime/types/val.hh>
-#include <wasmtime/val.h>
+#include <wasmtime/_anyref_class.hh>
+#include <wasmtime/_externref_class.hh>
+#include <wasmtime/_func_class.hh>
+#include <wasmtime/_val_class.hh>
namespace wasmtime {
-class EqRef;
-class StructRef;
-class ArrayRef;
-
-#ifdef WASMTIME_FEATURE_GC
-/**
- * \brief Representation of a WebAssembly `externref` value.
- *
- * This class represents an value that cannot be forged by WebAssembly itself.
- * All `ExternRef` values are guaranteed to be created by the host and its
- * embedding. It's suitable to place private data structures in here which
- * WebAssembly will not have access to, only other host functions will have
- * access to them.
- *
- * Note that `ExternRef` values are rooted within a `Store` and must be manually
- * unrooted via the `unroot` function. If this is not used then values will
- * never be candidates for garbage collection.
- */
-class ExternRef {
- friend class Val;
-
- wasmtime_externref_t val;
-
- static void finalizer(void *ptr) {
- std::unique_ptr<std::any> _ptr(static_cast<std::any *>(ptr));
- }
-
-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);
+inline Val::Val(std::optional<Func> func) : val{} {
+ val.kind = WASMTIME_FUNCREF;
+ if (func) {
+ val.of.funcref = (*func).func;
+ } else {
+ wasmtime_funcref_set_null(&val.of.funcref);
}
+}
- /// 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.
- 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");
- abort();
- }
- }
+inline Val::Val(Func func) : Val(std::optional(func)) {}
- /// 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));
+inline std::optional<Func> Val::funcref() const {
+ if (val.kind != WASMTIME_FUNCREF) {
+ std::abort();
}
-
- /// 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.capi(), &val);
- wasmtime_externref_set_null(&val);
- return ret;
+ if (val.of.funcref.store_id == 0) {
+ return std::nullopt;
}
-
- /// Returns `wasmtime_externref_to_raw`.
- uint32_t borrow_raw(Store::Context cx) const {
- return wasmtime_externref_to_raw(cx.capi(), &val);
- }
-};
-#endif // WASMTIME_FEATURE_GC
-
-class EqRef;
+ return Func(val.of.funcref);
+}
#ifdef WASMTIME_FEATURE_GC
-/**
- * \brief Representation of a WebAssembly `anyref` value.
- */
-class AnyRef {
- friend class Val;
-
- wasmtime_anyref_t val;
-
-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;
+inline Val::Val(std::optional<AnyRef> ptr) : val{} {
+ val.kind = WASMTIME_ANYREF;
+ if (ptr) {
+ val.of.anyref = *ptr->capi();
+ wasmtime_anyref_set_null(ptr->capi());
+ } else {
+ wasmtime_anyref_set_null(&val.of.anyref);
}
+}
- ~AnyRef() { wasmtime_anyref_unroot(&val); }
+inline Val::Val(AnyRef ptr) : Val(std::optional(ptr)) {}
- /// 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) {
- wasmtime_anyref_t other;
- wasmtime_anyref_from_i31(cx.ptr, value, &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.capi(), &val);
- wasmtime_anyref_set_null(&val);
- return ret;
- }
-
- /// Returns `wasmtime_anyref_to_raw`.
- uint32_t borrow_raw(Store::Context cx) const {
- return wasmtime_anyref_to_raw(cx.capi(), &val);
- }
-
- /// \brief If this is an `i31`, get the value zero-extended.
- std::optional<uint32_t> u31(Store::Context cx) const {
- uint32_t ret = 0;
- if (wasmtime_anyref_i31_get_u(cx.ptr, &val, &ret))
- return ret;
- return std::nullopt;
+inline std::optional<AnyRef> Val::anyref() const {
+ if (val.kind != WASMTIME_ANYREF) {
+ std::abort();
}
-
- /// \brief If this is an `i31`, get the value sign-extended.
- std::optional<int32_t> i31(Store::Context cx) const {
- int32_t ret = 0;
- if (wasmtime_anyref_i31_get_s(cx.ptr, &val, &ret))
- return ret;
+ if (wasmtime_anyref_is_null(&val.of.anyref)) {
return std::nullopt;
}
+ wasmtime_anyref_t other;
+ wasmtime_anyref_clone(&val.of.anyref, &other);
+ return AnyRef(other);
+}
- /// \brief Returns `true` if this anyref is an i31ref.
- bool is_i31(Store::Context cx) const {
- return wasmtime_anyref_is_i31(cx.ptr, &val);
+inline Val::Val(std::optional<ExternRef> ptr) : val{} {
+ val.kind = WASMTIME_EXTERNREF;
+ if (ptr) {
+ val.of.externref = *ptr->capi();
+ wasmtime_externref_set_null(ptr->capi());
+ } else {
+ wasmtime_externref_set_null(&val.of.externref);
}
+}
- /// \brief Returns `true` if this anyref is an eqref.
- inline bool is_eqref(Store::Context cx) const;
-
- /// \brief Returns `true` if this anyref is a structref.
- inline bool is_struct(Store::Context cx) const;
-
- /// \brief Returns `true` if this anyref is an arrayref.
- inline bool is_array(Store::Context cx) const;
+inline Val::Val(ExternRef ptr) : Val(std::optional(ptr)) {}
- /// \brief Downcast to eqref. Returns null eqref if not an eqref.
- inline std::optional<EqRef> as_eqref(Store::Context cx) const;
-
- /// \brief Downcast to structref. Returns null structref if not a structref.
- inline std::optional<StructRef> as_struct(Store::Context cx) const;
-
- /// \brief Downcast to arrayref. Returns null arrayref if not an arrayref.
- inline std::optional<ArrayRef> as_array(Store::Context cx) const;
-};
-#endif // WASMTIME_FEATURE_GC
-
-/// \brief Container for the `v128` WebAssembly type.
-struct V128 {
- /// \brief The little-endian bytes of the `v128` value.
- wasmtime_v128 v128;
-
- /// \brief Creates a new zero-value `v128`.
- V128() : v128{} { memset(&v128[0], 0, sizeof(wasmtime_v128)); }
-
- /// \brief Creates a new `V128` from its C API representation.
- V128(const wasmtime_v128 &v) : v128{} {
- memcpy(&v128[0], &v[0], sizeof(wasmtime_v128));
- }
-};
-
-class Func;
-
-/**
- * \brief Representation of a generic WebAssembly value.
- *
- * This is roughly equivalent to a tagged union of all possible WebAssembly
- * values. This is later used as an argument with functions, globals, tables,
- * etc.
- *
- * Note that a `Val` can represent owned GC pointers. In this case the `unroot`
- * method must be used to ensure that they can later be garbage-collected.
- */
-class Val {
- friend class Global;
- friend class Table;
- friend class Func;
- friend class Exn;
- friend class StructRef;
- friend class ArrayRef;
-
- wasmtime_val_t val;
-
- Val() : val{} {
- val.kind = WASMTIME_I32;
- val.of.i32 = 0;
- }
- Val(wasmtime_val_t val) : val(val) {}
-
-public:
- /// Creates a new `i32` WebAssembly value.
- Val(int32_t i32) : val{} {
- val.kind = WASMTIME_I32;
- val.of.i32 = i32;
- }
- /// Creates a new `i64` WebAssembly value.
- Val(int64_t i64) : val{} {
- val.kind = WASMTIME_I64;
- val.of.i64 = i64;
- }
- /// Creates a new `f32` WebAssembly value.
- Val(float f32) : val{} {
- val.kind = WASMTIME_F32;
- val.of.f32 = f32;
- }
- /// Creates a new `f64` WebAssembly value.
- Val(double f64) : val{} {
- val.kind = WASMTIME_F64;
- val.of.f64 = f64;
- }
- /// Creates a new `v128` WebAssembly value.
- Val(const V128 &v128) : val{} {
- val.kind = WASMTIME_V128;
- memcpy(&val.of.v128[0], &v128.v128[0], sizeof(wasmtime_v128));
- }
- /// Creates a new `funcref` WebAssembly value.
- Val(std::optional<Func> func);
- /// Creates a new `funcref` WebAssembly value which is not `ref.null func`.
- Val(Func func);
- /// Creates a new `externref` value.
- Val(std::optional<ExternRef> ptr) : val{} {
- 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);
- }
- }
- /// Creates a new `anyref` value.
- Val(std::optional<AnyRef> ptr) : val{} {
- 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);
- }
- }
- /// Creates a new `externref` WebAssembly value which is not `ref.null
- /// extern`.
- Val(ExternRef ptr);
- /// Creates a new `anyref` WebAssembly value which is not `ref.null
- /// 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) {
- case WASMTIME_I32:
- return ValKind::I32;
- case WASMTIME_I64:
- return ValKind::I64;
- case WASMTIME_F32:
- return ValKind::F32;
- case WASMTIME_F64:
- return ValKind::F64;
- case WASMTIME_FUNCREF:
- return ValKind::FuncRef;
- case WASMTIME_EXTERNREF:
- return ValKind::ExternRef;
- case WASMTIME_ANYREF:
- return ValKind::AnyRef;
- case WASMTIME_EXNREF:
- return ValKind::ExnRef;
- case WASMTIME_V128:
- return ValKind::V128;
- }
+inline std::optional<ExternRef> Val::externref() const {
+ if (val.kind != WASMTIME_EXTERNREF) {
std::abort();
}
-
- /// Returns the underlying `i32`, requires `kind() == KindI32` or aborts the
- /// process.
- int32_t i32() const {
- if (val.kind != WASMTIME_I32) {
- std::abort();
- }
- return val.of.i32;
- }
-
- /// Returns the underlying `i64`, requires `kind() == KindI64` or aborts the
- /// process.
- int64_t i64() const {
- if (val.kind != WASMTIME_I64) {
- std::abort();
- }
- return val.of.i64;
- }
-
- /// Returns the underlying `f32`, requires `kind() == KindF32` or aborts the
- /// process.
- float f32() const {
- if (val.kind != WASMTIME_F32) {
- std::abort();
- }
- return val.of.f32;
- }
-
- /// Returns the underlying `f64`, requires `kind() == KindF64` or aborts the
- /// process.
- double f64() const {
- if (val.kind != WASMTIME_F64) {
- std::abort();
- }
- return val.of.f64;
+ if (wasmtime_externref_is_null(&val.of.externref)) {
+ return std::nullopt;
}
+ wasmtime_externref_t other;
+ wasmtime_externref_clone(&val.of.externref, &other);
+ return ExternRef(other);
+}
- /// Returns the underlying `v128`, requires `kind() == KindV128` or aborts
- /// the process.
- V128 v128() const {
- if (val.kind != WASMTIME_V128) {
- std::abort();
- }
- return val.of.v128;
- }
+#endif // WASMTIME_FEATURE_GC
- /// Returns the underlying `externref`, requires `kind() == KindExternRef` or
- /// aborts the process.
- ///
- /// Note that `externref` is a nullable reference, hence the `optional` return
- /// value.
- std::optional<ExternRef> externref() const {
- if (val.kind != WASMTIME_EXTERNREF) {
- std::abort();
- }
- if (wasmtime_externref_is_null(&val.of.externref)) {
- return std::nullopt;
- }
- wasmtime_externref_t other;
- wasmtime_externref_clone(&val.of.externref, &other);
- return ExternRef(other);
+/// Type information for the `V128` host value used as a wasm value.
+template <> struct detail::WasmType<V128> {
+ static const bool valid = true;
+ static const ValKind kind = ValKind::V128;
+ static void store(Store::Context cx, wasmtime_val_raw_t *p, const V128 &t) {
+ (void)cx;
+ memcpy(&p->v128[0], &t.v128[0], sizeof(wasmtime_v128));
}
-
- /// Returns the underlying `anyref`, requires `kind() == KindAnyRef` or
- /// aborts the process.
- ///
- /// Note that `anyref` is a nullable reference, hence the `optional` return
- /// value.
- std::optional<AnyRef> anyref() const {
- if (val.kind != WASMTIME_ANYREF) {
- std::abort();
- }
- if (wasmtime_anyref_is_null(&val.of.anyref)) {
- return std::nullopt;
- }
- wasmtime_anyref_t other;
- wasmtime_anyref_clone(&val.of.anyref, &other);
- return AnyRef(other);
+ static V128 load(Store::Context cx, wasmtime_val_raw_t *p) {
+ (void)cx;
+ return p->v128;
}
-
- /// Returns the underlying `funcref`, requires `kind() == KindFuncRef` or
- /// aborts the process.
- ///
- /// Note that `funcref` is a nullable reference, hence the `optional` return
- /// value.
- std::optional<Func> funcref() const;
};
} // namespace wasmtime
-// fill in `Func` constructors for `Val`
-#include <wasmtime/func.hh>
-
#endif // WASMTIME_VAL_HH
diff --git a/crates/c-api/src/anyref.rs b/crates/c-api/src/anyref.rs
new file mode 100644
index 0000000000..d20a270a45
--- /dev/null
+++ b/crates/c-api/src/anyref.rs
@@ -0,0 +1,291 @@
+use crate::{WasmtimeStoreContextMut, wasmtime_arrayref_t, wasmtime_eqref_t, wasmtime_structref_t};
+use std::mem::MaybeUninit;
+use wasmtime::{AnyRef, ArrayRef, EqRef, I31, OwnedRooted, RootScope, StructRef};
+
+/// C-API representation of `anyref`.
+///
+/// This represented differently in the C API from the header to handle how
+/// this is dispatched internally. Null anyref values are represented with a
+/// `store_id` of zero, and otherwise the `rooted` field is valid.
+///
+/// Note that this relies on the Wasmtime definition of `OwnedRooted` to have
+/// a 64-bit store_id first.
+macro_rules! ref_wrapper {
+ ({
+ wasmtime: $wasmtime:ident,
+ capi: $c:ident,
+ clone: $clone:ident,
+ unroot: $unroot:ident,
+ $(
+ to_raw: $to_raw:ident,
+ from_raw: $from_raw:ident,
+ )?
+ }) => {
+ pub struct $c {
+ store_id: u64,
+ a: u32,
+ b: u32,
+ c: *const (),
+ }
+
+ impl $c {
+ pub unsafe fn as_wasmtime(&self) -> Option<wasmtime::OwnedRooted<$wasmtime>> {
+ let store_id = std::num::NonZeroU64::new(self.store_id)?;
+ Some(wasmtime::OwnedRooted::from_borrowed_raw_parts_for_c_api(
+ store_id, self.a, self.b, self.c,
+ ))
+ }
+
+ pub unsafe fn into_wasmtime(self) -> Option<wasmtime::OwnedRooted<$wasmtime>> {
+ std::mem::ManuallyDrop::new(self).to_owned()
+ }
+
+ unsafe fn to_owned(&self) -> Option<wasmtime::OwnedRooted<$wasmtime>> {
+ let store_id = std::num::NonZeroU64::new(self.store_id)?;
+ Some(wasmtime::OwnedRooted::from_owned_raw_parts_for_c_api(
+ store_id, self.a, self.b, self.c,
+ ))
+ }
+ }
+
+ impl Drop for $c {
+ fn drop(&mut self) {
+ unsafe {
+ let _ = self.to_owned();
+ }
+ }
+ }
+
+ impl From<Option<wasmtime::OwnedRooted<$wasmtime>>> for $c {
+ fn from(rooted: Option<wasmtime::OwnedRooted<$wasmtime>>) -> $c {
+ let mut ret = $c {
+ store_id: 0,
+ a: 0,
+ b: 0,
+ c: core::ptr::null(),
+ };
+ if let Some(rooted) = rooted {
+ let (store_id, a, b, c) = rooted.into_parts_for_c_api();
+ ret.store_id = store_id.get();
+ ret.a = a;
+ ret.b = b;
+ ret.c = c;
+ }
+ ret
+ }
+ }
+
+ impl From<wasmtime::OwnedRooted<$wasmtime>> for $c {
+ fn from(rooted: wasmtime::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
+ // in the async machinery in this crate.
+ unsafe impl Send for $c {}
+ unsafe impl Sync for $c {}
+
+ #[unsafe(no_mangle)]
+ pub unsafe extern "C" fn $clone(anyref: Option<&$c>, out: &mut std::mem::MaybeUninit<$c>) {
+ let anyref = anyref.and_then(|a| a.as_wasmtime());
+ out.write(anyref.into());
+ }
+
+ #[unsafe(no_mangle)]
+ pub unsafe extern "C" fn $unroot(val: Option<&mut std::mem::ManuallyDrop<$c>>) {
+ if let Some(val) = val {
+ unsafe {
+ std::mem::ManuallyDrop::drop(val);
+ }
+ }
+ }
+
+ $(
+ #[unsafe(no_mangle)]
+ pub unsafe extern "C" fn $to_raw(
+ cx: crate::WasmtimeStoreContextMut<'_>,
+ val: Option<&$c>,
+ ) -> u32 {
+ val.and_then(|v| v.as_wasmtime())
+ .and_then(|e| e.to_raw(cx).ok())
+ .unwrap_or_default()
+ }
+
+ #[unsafe(no_mangle)]
+ pub unsafe extern "C" fn $from_raw(
+ cx: crate::WasmtimeStoreContextMut<'_>,
+ raw: u32,
+ val: &mut std::mem::MaybeUninit<$c>,
+ ) {
+ let mut scope = wasmtime::RootScope::new(cx);
+ let anyref = $wasmtime::from_raw(&mut scope, raw)
+ .map(|a| a.to_owned_rooted(&mut scope).expect("in scope"));
+ crate::initialize(val, anyref.into());
+ }
+ )?
+ };
+}
+pub(crate) use ref_wrapper;
+
+ref_wrapper!({
+ wasmtime: AnyRef,
+ capi: wasmtime_anyref_t,
+ clone: wasmtime_anyref_clone,
+ unroot: wasmtime_anyref_unroot,
+ to_raw: wasmtime_anyref_to_raw,
+ from_raw: wasmtime_anyref_from_raw,
+});
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_anyref_from_i31(
+ cx: WasmtimeStoreContextMut<'_>,
+ val: u32,
+ out: &mut MaybeUninit<wasmtime_anyref_t>,
+) {
+ let mut scope = RootScope::new(cx);
+ let anyref = AnyRef::from_i31(&mut scope, I31::wrapping_u32(val));
+ let anyref = anyref.to_owned_rooted(&mut scope).expect("in scope");
+ 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<'_>,
+ anyref: Option<&wasmtime_anyref_t>,
+ dst: &mut MaybeUninit<u32>,
+) -> bool {
+ match anyref.and_then(|a| a.as_wasmtime()) {
+ Some(anyref) if anyref.is_i31(&cx).expect("OwnedRooted always in scope") => {
+ let val = anyref
+ .unwrap_i31(&cx)
+ .expect("OwnedRooted always in scope")
+ .get_u32();
+ crate::initialize(dst, val);
+ true
+ }
+ _ => false,
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_anyref_i31_get_s(
+ cx: WasmtimeStoreContextMut<'_>,
+ anyref: Option<&wasmtime_anyref_t>,
+ dst: &mut MaybeUninit<i32>,
+) -> bool {
+ match anyref.and_then(|a| a.as_wasmtime()) {
+ Some(anyref) if anyref.is_i31(&cx).expect("OwnedRooted always in scope") => {
+ let val = anyref
+ .unwrap_i31(&cx)
+ .expect("OwnedRooted always in scope")
+ .get_i32();
+ crate::initialize(dst, val);
+ true
+ }
+ _ => false,
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_anyref_is_eqref(
+ cx: WasmtimeStoreContextMut<'_>,
+ anyref: Option<&wasmtime_anyref_t>,
+) -> bool {
+ match anyref.and_then(|a| a.as_wasmtime()) {
+ Some(anyref) => anyref.is_eqref(&cx).expect("OwnedRooted always in scope"),
+ None => false,
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_anyref_as_eqref(
+ mut cx: WasmtimeStoreContextMut<'_>,
+ anyref: Option<&wasmtime_anyref_t>,
+ out: &mut MaybeUninit<wasmtime_eqref_t>,
+) -> bool {
+ if let Some(anyref) = anyref.and_then(|a| a.as_wasmtime()) {
+ let mut scope = RootScope::new(&mut cx);
+ let rooted = anyref.to_rooted(&mut scope);
+ if let Ok(Some(eqref)) = rooted.as_eqref(&mut scope) {
+ let owned = eqref.to_owned_rooted(&mut scope).expect("in scope");
+ crate::initialize(out, Some(owned).into());
+ return true;
+ }
+ }
+ crate::initialize(out, None::<OwnedRooted<EqRef>>.into());
+ false
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_anyref_is_struct(
+ cx: WasmtimeStoreContextMut<'_>,
+ anyref: Option<&wasmtime_anyref_t>,
+) -> bool {
+ match anyref.and_then(|a| a.as_wasmtime()) {
+ Some(anyref) => anyref.is_struct(&cx).expect("OwnedRooted always in scope"),
+ None => false,
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_anyref_as_struct(
+ mut cx: WasmtimeStoreContextMut<'_>,
+ anyref: Option<&wasmtime_anyref_t>,
+ out: &mut MaybeUninit<wasmtime_structref_t>,
+) -> bool {
+ if let Some(anyref) = anyref.and_then(|a| a.as_wasmtime()) {
+ let mut scope = RootScope::new(&mut cx);
+ let rooted = anyref.to_rooted(&mut scope);
+ if let Ok(Some(structref)) = rooted.as_struct(&scope) {
+ let owned = structref.to_owned_rooted(&mut scope).expect("in scope");
+ crate::initialize(out, Some(owned).into());
+ return true;
+ }
+ }
+ crate::initialize(out, None::<OwnedRooted<StructRef>>.into());
+ false
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_anyref_is_array(
+ cx: WasmtimeStoreContextMut<'_>,
+ anyref: Option<&wasmtime_anyref_t>,
+) -> bool {
+ match anyref.and_then(|a| a.as_wasmtime()) {
+ Some(anyref) => anyref.is_array(&cx).expect("OwnedRooted always in scope"),
+ None => false,
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_anyref_as_array(
+ mut cx: WasmtimeStoreContextMut<'_>,
+ anyref: Option<&wasmtime_anyref_t>,
+ out: &mut MaybeUninit<wasmtime_arrayref_t>,
+) -> bool {
+ if let Some(anyref) = anyref.and_then(|a| a.as_wasmtime()) {
+ let mut scope = RootScope::new(&mut cx);
+ let rooted = anyref.to_rooted(&mut scope);
+ if let Ok(Some(arrayref)) = rooted.as_array(&scope) {
+ let owned = arrayref.to_owned_rooted(&mut scope).expect("in scope");
+ crate::initialize(out, Some(owned).into());
+ return true;
+ }
+ }
+ crate::initialize(out, None::<OwnedRooted<ArrayRef>>.into());
+ false
+}
diff --git a/crates/c-api/src/arrayref.rs b/crates/c-api/src/arrayref.rs
new file mode 100644
index 0000000000..b05b525478
--- /dev/null
+++ b/crates/c-api/src/arrayref.rs
@@ -0,0 +1,128 @@
+use crate::{WasmtimeStoreContextMut, wasmtime_anyref_t, wasmtime_array_type_t, wasmtime_eqref_t};
+use std::mem::MaybeUninit;
+use wasmtime::{ArrayRef, ArrayRefPre, OwnedRooted, RootScope};
+
+crate::anyref::ref_wrapper!({
+ wasmtime: ArrayRef,
+ capi: wasmtime_arrayref_t,
+ clone: wasmtime_arrayref_clone,
+ unroot: wasmtime_arrayref_unroot,
+});
+
+pub struct wasmtime_array_ref_pre_t {
+ pre: ArrayRefPre,
+}
+wasmtime_c_api_macros::declare_own!(wasmtime_array_ref_pre_t);
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_array_ref_pre_new(
+ cx: WasmtimeStoreContextMut<'_>,
+ ty: &wasmtime_array_type_t,
+) -> Box<wasmtime_array_ref_pre_t> {
+ let pre = ArrayRefPre::new(cx, ty.ty.clone());
+ Box::new(wasmtime_array_ref_pre_t { pre })
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_arrayref_new(
+ mut cx: WasmtimeStoreContextMut<'_>,
+ pre: &wasmtime_array_ref_pre_t,
+ elem: &crate::wasmtime_val_t,
+ len: u32,
+ out: &mut MaybeUninit<wasmtime_arrayref_t>,
+) -> Option<Box<crate::wasmtime_error_t>> {
+ let mut scope = RootScope::new(&mut cx);
+ let val = elem.to_val(&mut scope);
+ match ArrayRef::new(&mut scope, &pre.pre, &val, len) {
+ Ok(arrayref) => {
+ let owned = arrayref
+ .to_owned_rooted(&mut scope)
+ .expect("just allocated");
+ crate::initialize(out, Some(owned).into());
+ None
+ }
+ Err(e) => {
+ crate::initialize(out, None::<OwnedRooted<ArrayRef>>.into());
+ Some(Box::new(e.into()))
+ }
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_arrayref_to_anyref(
+ arrayref: Option<&wasmtime_arrayref_t>,
+ out: &mut MaybeUninit<wasmtime_anyref_t>,
+) {
+ let anyref = arrayref
+ .and_then(|a| a.as_wasmtime())
+ .map(|a| a.to_anyref());
+ crate::initialize(out, anyref.into());
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_arrayref_to_eqref(
+ arrayref: Option<&wasmtime_arrayref_t>,
+ out: &mut MaybeUninit<wasmtime_eqref_t>,
+) {
+ let eqref = arrayref.and_then(|a| a.as_wasmtime()).map(|a| a.to_eqref());
+ crate::initialize(out, eqref.into());
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_arrayref_len(
+ cx: WasmtimeStoreContextMut<'_>,
+ arrayref: Option<&wasmtime_arrayref_t>,
+ out: &mut MaybeUninit<u32>,
+) -> Option<Box<crate::wasmtime_error_t>> {
+ let arrayref = arrayref
+ .and_then(|a| a.as_wasmtime())
+ .expect("non-null arrayref required");
+ match arrayref.len(&cx) {
+ Ok(len) => {
+ crate::initialize(out, len);
+ None
+ }
+ Err(e) => Some(Box::new(e.into())),
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_arrayref_get(
+ mut cx: WasmtimeStoreContextMut<'_>,
+ arrayref: Option<&wasmtime_arrayref_t>,
+ index: u32,
+ out: &mut MaybeUninit<crate::wasmtime_val_t>,
+) -> Option<Box<crate::wasmtime_error_t>> {
+ let arrayref = arrayref
+ .and_then(|a| a.as_wasmtime())
+ .expect("non-null arrayref required");
+ let mut scope = RootScope::new(&mut cx);
+ let rooted = arrayref.to_rooted(&mut scope);
+ match rooted.get(&mut scope, index) {
+ Ok(val) => {
+ let c_val = crate::wasmtime_val_t::from_val(&mut scope, val);
+ crate::initialize(out, c_val);
+ None
+ }
+ Err(e) => Some(Box::new(e.into())),
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_arrayref_set(
+ mut cx: WasmtimeStoreContextMut<'_>,
+ arrayref: Option<&wasmtime_arrayref_t>,
+ index: u32,
+ val: &crate::wasmtime_val_t,
+) -> Option<Box<crate::wasmtime_error_t>> {
+ let arrayref = arrayref
+ .and_then(|a| a.as_wasmtime())
+ .expect("non-null arrayref required");
+ let mut scope = RootScope::new(&mut cx);
+ let rooted = arrayref.to_rooted(&mut scope);
+ let rust_val = val.to_val(&mut scope);
+ match rooted.set(&mut scope, index, rust_val) {
+ Ok(()) => None,
+ Err(e) => Some(Box::new(e.into())),
+ }
+}
diff --git a/crates/c-api/src/async.rs b/crates/c-api/src/async.rs
index cad337e927..054f89735e 100644
--- a/crates/c-api/src/async.rs
+++ b/crates/c-api/src/async.rs
@@ -7,9 +7,7 @@ use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, Waker};
use std::{ptr, str};
-use wasmtime::{
- AsContextMut, Func, Instance, Result, RootScope, StackCreator, StackMemory, Trap, Val,
-};
+use wasmtime::{AsContextMut, Func, Instance, Result, StackCreator, StackMemory, Trap, Val};
use crate::{
WASMTIME_I32, WasmtimeCaller, WasmtimeStoreContextMut, bad_utf8, handle_result, to_str,
@@ -223,7 +221,8 @@ fn handle_call_error(
}
async fn do_func_call_async(
- mut store: RootScope<WasmtimeStoreContextMut<'_>>,
+ #[cfg(feature = "gc")] mut store: wasmtime::RootScope<WasmtimeStoreContextMut<'_>>,
+ #[cfg(not(feature = "gc"))] mut store: WasmtimeStoreContextMut<'_>,
func: &Func,
args: impl ExactSizeIterator<Item = Val>,
results: &mut [MaybeUninit<wasmtime_val_t>],
@@ -248,7 +247,7 @@ async fn do_func_call_async(
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wasmtime_func_call_async<'a>(
- store: WasmtimeStoreContextMut<'a>,
+ mut store: WasmtimeStoreContextMut<'a>,
func: &'a Func,
args: *const wasmtime_val_t,
nargs: usize,
@@ -257,14 +256,16 @@ pub unsafe extern "C" fn wasmtime_func_call_async<'a>(
trap_ret: &'a mut *mut wasm_trap_t,
err_ret: &'a mut *mut wasmtime_error_t,
) -> Box<wasmtime_call_future_t<'a>> {
- let mut scope = RootScope::new(store);
+ let _ = &mut store;
+ #[cfg(feature = "gc")]
+ let mut store = wasmtime::RootScope::new(store);
let args = crate::slice_from_raw_parts(args, nargs)
.iter()
- .map(|i| i.to_val(&mut scope))
+ .map(|i| i.to_val(&mut store))
.collect::<Vec<_>>();
let results = crate::slice_from_raw_parts_mut(results, nresults);
let fut = Box::pin(do_func_call_async(
- scope,
+ store,
func,
args.into_iter(),
results,
diff --git a/crates/c-api/src/config.rs b/crates/c-api/src/config.rs
index 3535638c29..abecac59a9 100644
--- a/crates/c-api/src/config.rs
+++ b/crates/c-api/src/config.rs
@@ -7,8 +7,8 @@ use std::os::raw::c_char;
use std::ptr;
use std::{ffi::CStr, sync::Arc};
use wasmtime::{
- Config, InstanceAllocationStrategy, LinearMemory, MemoryCreator, OptLevel, ProfilingStrategy,
- RegallocAlgorithm, Result, Strategy,
+ Config, LinearMemory, MemoryCreator, OptLevel, ProfilingStrategy, RegallocAlgorithm, Result,
+ Strategy,
};
#[cfg(feature = "pooling-allocator")]
@@ -721,7 +721,9 @@ pub extern "C" fn wasmtime_pooling_allocation_strategy_set(
pc: &wasmtime_pooling_allocation_config_t,
) {
c.config
- .allocation_strategy(InstanceAllocationStrategy::Pooling(pc.config.clone()));
+ .allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(
+ pc.config.clone(),
+ ));
}
#[unsafe(no_mangle)]
diff --git a/crates/c-api/src/eqref.rs b/crates/c-api/src/eqref.rs
new file mode 100644
index 0000000000..89f5bc1f07
--- /dev/null
+++ b/crates/c-api/src/eqref.rs
@@ -0,0 +1,136 @@
+use crate::{
+ WasmtimeStoreContextMut, wasmtime_anyref_t, wasmtime_arrayref_t, wasmtime_structref_t,
+};
+use std::mem::MaybeUninit;
+use wasmtime::{ArrayRef, EqRef, I31, OwnedRooted, RootScope, StructRef};
+
+crate::anyref::ref_wrapper!({
+ wasmtime: EqRef,
+ capi: wasmtime_eqref_t,
+ clone: wasmtime_eqref_clone,
+ unroot: wasmtime_eqref_unroot,
+});
+
+#[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
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_eqref_is_struct(
+ cx: WasmtimeStoreContextMut<'_>,
+ eqref: Option<&wasmtime_eqref_t>,
+) -> bool {
+ match eqref.and_then(|e| e.as_wasmtime()) {
+ Some(eqref) => eqref.is_struct(&cx).expect("OwnedRooted always in scope"),
+ None => false,
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_eqref_as_struct(
+ mut cx: WasmtimeStoreContextMut<'_>,
+ eqref: Option<&wasmtime_eqref_t>,
+ out: &mut MaybeUninit<wasmtime_structref_t>,
+) -> bool {
+ if let Some(eqref) = eqref.and_then(|e| e.as_wasmtime()) {
+ let mut scope = RootScope::new(&mut cx);
+ let rooted = eqref.to_rooted(&mut scope);
+ if let Ok(Some(structref)) = rooted.as_struct(&scope) {
+ let owned = structref.to_owned_rooted(&mut scope).expect("in scope");
+ crate::initialize(out, Some(owned).into());
+ return true;
+ }
+ }
+ crate::initialize(out, None::<OwnedRooted<StructRef>>.into());
+ false
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_eqref_is_array(
+ cx: WasmtimeStoreContextMut<'_>,
+ eqref: Option<&wasmtime_eqref_t>,
+) -> bool {
+ match eqref.and_then(|e| e.as_wasmtime()) {
+ Some(eqref) => eqref.is_array(&cx).expect("OwnedRooted always in scope"),
+ None => false,
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_eqref_as_array(
+ mut cx: WasmtimeStoreContextMut<'_>,
+ eqref: Option<&wasmtime_eqref_t>,
+ out: &mut MaybeUninit<wasmtime_arrayref_t>,
+) -> bool {
+ if let Some(eqref) = eqref.and_then(|e| e.as_wasmtime()) {
+ let mut scope = RootScope::new(&mut cx);
+ let rooted = eqref.to_rooted(&mut scope);
+ if let Ok(Some(arrayref)) = rooted.as_array(&scope) {
+ let owned = arrayref.to_owned_rooted(&mut scope).expect("just created");
+ crate::initialize(out, Some(owned).into());
+ return true;
+ }
+ }
+ crate::initialize(out, None::<OwnedRooted<ArrayRef>>.into());
+ false
+}
diff --git a/crates/c-api/src/exn.rs b/crates/c-api/src/exnref.rs
similarity index 66%
rename from crates/c-api/src/exn.rs
rename to crates/c-api/src/exnref.rs
index 8d516b52cc..63a192a32a 100644
--- a/crates/c-api/src/exn.rs
+++ b/crates/c-api/src/exnref.rs
@@ -1,24 +1,25 @@
-#![cfg(feature = "gc")]
use crate::{
WasmtimeStoreContextMut, handle_result, wasm_trap_t, wasmtime_error_t, wasmtime_val_t,
};
use std::mem::MaybeUninit;
use wasmtime::{AsContextMut, ExnRef, ExnRefPre, ExnType, RootScope, Tag};
-/// An opaque type representing a WebAssembly exception object.
-pub struct wasmtime_exn_t {
- exn: wasmtime::OwnedRooted<ExnRef>,
-}
-
-wasmtime_c_api_macros::declare_own!(wasmtime_exn_t);
+crate::anyref::ref_wrapper!({
+ wasmtime: ExnRef,
+ capi: wasmtime_exnref_t,
+ clone: wasmtime_exnref_clone,
+ unroot: wasmtime_exnref_unroot,
+ to_raw: wasmtime_exnref_to_raw,
+ from_raw: wasmtime_exnref_from_raw,
+});
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_exn_new(
+pub unsafe extern "C" fn wasmtime_exnref_new(
mut store: WasmtimeStoreContextMut<'_>,
tag: &Tag,
fields: *const wasmtime_val_t,
nfields: usize,
- exn_ret: &mut *mut wasmtime_exn_t,
+ exn_ret: &mut MaybeUninit<wasmtime_exnref_t>,
) -> Option<Box<wasmtime_error_t>> {
let mut scope = RootScope::new(&mut store);
@@ -34,43 +35,46 @@ pub unsafe extern "C" fn wasmtime_exn_new(
handle_result(result, |rooted| {
let owned = rooted.to_owned_rooted(&mut scope).unwrap();
- *exn_ret = Box::into_raw(Box::new(wasmtime_exn_t { exn: owned }));
+ exn_ret.write(owned.into());
})
}
#[unsafe(no_mangle)]
-pub extern "C" fn wasmtime_exn_tag(
+pub extern "C" fn wasmtime_exnref_tag(
mut store: WasmtimeStoreContextMut<'_>,
- exn: &wasmtime_exn_t,
+ exn: &wasmtime_exnref_t,
tag_ret: &mut Tag,
) -> Option<Box<wasmtime_error_t>> {
let mut scope = RootScope::new(&mut store);
- let rooted = exn.exn.to_rooted(&mut scope);
+ let rooted = unsafe { exn.as_wasmtime()?.to_rooted(&mut scope) };
handle_result(rooted.tag(&mut scope), |tag| {
*tag_ret = tag;
})
}
#[unsafe(no_mangle)]
-pub extern "C" fn wasmtime_exn_field_count(
+pub extern "C" fn wasmtime_exnref_field_count(
mut store: WasmtimeStoreContextMut<'_>,
- exn: &wasmtime_exn_t,
+ exn: &wasmtime_exnref_t,
) -> usize {
let mut scope = RootScope::new(&mut store);
- let rooted = exn.exn.to_rooted(&mut scope);
+ let rooted = match unsafe { exn.as_wasmtime() } {
+ Some(e) => e.to_rooted(&mut scope),
+ None => return 0,
+ };
let ty = rooted.ty(&scope).unwrap();
ty.fields().len()
}
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_exn_field(
+pub unsafe extern "C" fn wasmtime_exnref_field(
mut store: WasmtimeStoreContextMut<'_>,
- exn: &wasmtime_exn_t,
+ exn: &wasmtime_exnref_t,
index: usize,
val_ret: &mut MaybeUninit<wasmtime_val_t>,
) -> Option<Box<wasmtime_error_t>> {
let mut scope = RootScope::new(&mut store);
- let rooted = exn.exn.to_rooted(&mut scope);
+ let rooted = exn.as_wasmtime()?.to_rooted(&mut scope);
handle_result(rooted.field(&mut scope, index), |val| {
crate::initialize(val_ret, wasmtime_val_t::from_val(&mut scope, val));
})
@@ -79,23 +83,25 @@ pub unsafe extern "C" fn wasmtime_exn_field(
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wasmtime_context_set_exception(
mut store: WasmtimeStoreContextMut<'_>,
- exn: Box<wasmtime_exn_t>,
-) -> Box<wasm_trap_t> {
+ exn: &wasmtime_exnref_t,
+) -> Option<Box<wasm_trap_t>> {
let mut scope = RootScope::new(&mut store);
- let rooted = exn.exn.to_rooted(&mut scope);
- let thrown = scope.as_context_mut().throw::<()>(rooted).unwrap_err();
- Box::new(wasm_trap_t::new(wasmtime::Error::new(thrown)))
+ let rooted = exn.as_wasmtime()?.to_rooted(&mut scope);
+ let Err(thrown) = scope
+ .as_context_mut()
+ .throw::<std::convert::Infallible>(rooted);
+ Some(Box::new(wasm_trap_t::new(wasmtime::Error::new(thrown))))
}
#[unsafe(no_mangle)]
pub extern "C" fn wasmtime_context_take_exception(
mut store: WasmtimeStoreContextMut<'_>,
- exn_ret: &mut *mut wasmtime_exn_t,
+ out: &mut MaybeUninit<wasmtime_exnref_t>,
) -> bool {
match store.take_pending_exception() {
Some(rooted) => {
let owned = rooted.to_owned_rooted(&mut store).unwrap();
- *exn_ret = Box::into_raw(Box::new(wasmtime_exn_t { exn: owned }));
+ out.write(owned.into());
true
}
None => false,
diff --git a/crates/c-api/src/externref.rs b/crates/c-api/src/externref.rs
new file mode 100644
index 0000000000..5d96610d45
--- /dev/null
+++ b/crates/c-api/src/externref.rs
@@ -0,0 +1,44 @@
+use crate::WasmtimeStoreContextMut;
+use std::ffi::c_void;
+use std::mem::MaybeUninit;
+use wasmtime::{ExternRef, RootScope};
+
+crate::anyref::ref_wrapper!({
+ wasmtime: ExternRef,
+ capi: wasmtime_externref_t,
+ clone: wasmtime_externref_clone,
+ unroot: wasmtime_externref_unroot,
+ to_raw: wasmtime_externref_to_raw,
+ from_raw: wasmtime_externref_from_raw,
+});
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_externref_new(
+ cx: WasmtimeStoreContextMut<'_>,
+ data: *mut c_void,
+ finalizer: Option<extern "C" fn(*mut c_void)>,
+ out: &mut MaybeUninit<wasmtime_externref_t>,
+) -> bool {
+ let mut scope = RootScope::new(cx);
+ let e = match ExternRef::new(&mut scope, crate::ForeignData { data, finalizer }) {
+ Ok(e) => e,
+ Err(_) => return false,
+ };
+ let e = e.to_owned_rooted(&mut scope).expect("in scope");
+ crate::initialize(out, Some(e).into());
+ true
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_externref_data(
+ cx: WasmtimeStoreContextMut<'_>,
+ externref: Option<&wasmtime_externref_t>,
+) -> *mut c_void {
+ externref
+ .and_then(|e| e.as_wasmtime())
+ .and_then(|e| {
+ let data = e.data(cx).ok()??;
+ Some(data.downcast_ref::<crate::ForeignData>().unwrap().data)
+ })
+ .unwrap_or(core::ptr::null_mut())
+}
diff --git a/crates/c-api/src/lib.rs b/crates/c-api/src/lib.rs
index 72972336c6..eae454e1da 100644
--- a/crates/c-api/src/lib.rs
+++ b/crates/c-api/src/lib.rs
@@ -20,8 +20,6 @@ pub use wasmtime;
mod config;
mod engine;
mod error;
-#[cfg(feature = "gc")]
-mod exn;
mod r#extern;
mod func;
mod global;
@@ -31,8 +29,6 @@ mod memory;
mod module;
#[cfg(feature = "profiling")]
mod profiling;
-#[cfg(feature = "gc")]
-mod r#ref;
mod sharedmemory;
mod store;
mod table;
@@ -45,8 +41,6 @@ mod vec;
pub use crate::config::*;
pub use crate::engine::*;
pub use crate::error::*;
-#[cfg(feature = "gc")]
-pub use crate::exn::*;
pub use crate::r#extern::*;
pub use crate::func::*;
pub use crate::global::*;
@@ -54,8 +48,6 @@ pub use crate::instance::*;
pub use crate::linker::*;
pub use crate::memory::*;
pub use crate::module::*;
-#[cfg(feature = "gc")]
-pub use crate::r#ref::*;
pub use crate::store::*;
pub use crate::table::*;
pub use crate::tag::*;
@@ -64,6 +56,36 @@ pub use crate::types::*;
pub use crate::val::*;
pub use crate::vec::*;
+#[cfg(feature = "gc")]
+mod anyref;
+#[cfg(feature = "gc")]
+mod arrayref;
+#[cfg(feature = "gc")]
+mod eqref;
+#[cfg(feature = "gc")]
+mod exnref;
+#[cfg(feature = "gc")]
+mod externref;
+#[cfg(feature = "gc")]
+mod r#ref;
+#[cfg(feature = "gc")]
+mod structref;
+
+#[cfg(feature = "gc")]
+pub use crate::anyref::*;
+#[cfg(feature = "gc")]
+pub use crate::arrayref::*;
+#[cfg(feature = "gc")]
+pub use crate::eqref::*;
+#[cfg(feature = "gc")]
+pub use crate::exnref::*;
+#[cfg(feature = "gc")]
+pub use crate::externref::*;
+#[cfg(feature = "gc")]
+pub use crate::r#ref::*;
+#[cfg(feature = "gc")]
+pub use crate::structref::*;
+
#[cfg(feature = "async")]
mod r#async;
#[cfg(feature = "async")]
diff --git a/crates/c-api/src/ref.rs b/crates/c-api/src/ref.rs
index bcdf0a6f82..25e079831d 100644
--- a/crates/c-api/src/ref.rs
+++ b/crates/c-api/src/ref.rs
@@ -1,13 +1,6 @@
-#![cfg(feature = "gc")]
-
-use crate::WasmtimeStoreContextMut;
use crate::abort;
-use std::mem::{ManuallyDrop, MaybeUninit};
-use std::{num::NonZeroU64, os::raw::c_void};
-use wasmtime::{
- AnyRef, ArrayRef, ArrayRefPre, ArrayType, EqRef, ExnRef, ExternRef, FieldType, I31, Mutability,
- OwnedRooted, Ref, RootScope, StorageType, StructRef, StructRefPre, StructType, Val, ValType,
-};
+use std::os::raw::c_void;
+use wasmtime::{Ref, 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
@@ -188,845 +181,3 @@ wasmtime_c_api_macros::declare_ref!(wasm_foreign_t);
pub extern "C" fn wasm_foreign_new(_store: &crate::wasm_store_t) -> Box<wasm_foreign_t> {
abort("wasm_foreign_new")
}
-
-/// C-API representation of `anyref`.
-///
-/// This represented differently in the C API from the header to handle how
-/// this is dispatched internally. Null anyref values are represented with a
-/// `store_id` of zero, and otherwise the `rooted` field is valid.
-///
-/// Note that this relies on the Wasmtime definition of `OwnedRooted` to have
-/// a 64-bit store_id first.
-macro_rules! ref_wrapper {
- ($wasmtime:ident => $c:ident) => {
- pub struct $c {
- store_id: u64,
- a: u32,
- b: u32,
- c: *const (),
- }
-
- impl $c {
- pub unsafe fn as_wasmtime(&self) -> Option<OwnedRooted<$wasmtime>> {
- let store_id = NonZeroU64::new(self.store_id)?;
- Some(OwnedRooted::from_borrowed_raw_parts_for_c_api(
- store_id, self.a, self.b, self.c,
- ))
- }
-
- 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,
- ))
- }
- }
-
- 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 {
- store_id: 0,
- a: 0,
- b: 0,
- c: core::ptr::null(),
- };
- if let Some(rooted) = rooted {
- let (store_id, a, b, c) = rooted.into_parts_for_c_api();
- ret.store_id = store_id.get();
- ret.a = a;
- ret.b = b;
- ret.c = c;
- }
- ret
- }
- }
-
- 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
- // in the async machinery in this crate.
- unsafe impl Send for $c {}
- unsafe impl Sync for $c {}
- };
-}
-
-ref_wrapper!(AnyRef => wasmtime_anyref_t);
-ref_wrapper!(ExternRef => wasmtime_externref_t);
-ref_wrapper!(EqRef => wasmtime_eqref_t);
-ref_wrapper!(StructRef => wasmtime_structref_t);
-ref_wrapper!(ExnRef => wasmtime_exnref_t);
-
-// Opaque types for struct type and struct ref pre-allocator
-pub struct wasmtime_struct_type_t {
- ty: StructType,
-}
-wasmtime_c_api_macros::declare_own!(wasmtime_struct_type_t);
-
-pub struct wasmtime_struct_ref_pre_t {
- pre: StructRefPre,
-}
-wasmtime_c_api_macros::declare_own!(wasmtime_struct_ref_pre_t);
-
-ref_wrapper!(ArrayRef => wasmtime_arrayref_t);
-
-pub struct wasmtime_array_type_t {
- ty: ArrayType,
-}
-wasmtime_c_api_macros::declare_own!(wasmtime_array_type_t);
-
-pub struct wasmtime_array_ref_pre_t {
- pre: ArrayRefPre,
-}
-wasmtime_c_api_macros::declare_own!(wasmtime_array_ref_pre_t);
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_anyref_clone(
- anyref: Option<&wasmtime_anyref_t>,
- out: &mut MaybeUninit<wasmtime_anyref_t>,
-) {
- let anyref = anyref.and_then(|a| a.as_wasmtime());
- crate::initialize(out, anyref.into());
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_anyref_unroot(val: Option<&mut ManuallyDrop<wasmtime_anyref_t>>) {
- if let Some(val) = val {
- unsafe {
- ManuallyDrop::drop(val);
- }
- }
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_anyref_to_raw(
- cx: WasmtimeStoreContextMut<'_>,
- val: Option<&wasmtime_anyref_t>,
-) -> u32 {
- val.and_then(|v| v.as_wasmtime())
- .and_then(|e| e.to_raw(cx).ok())
- .unwrap_or_default()
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_anyref_from_raw(
- cx: WasmtimeStoreContextMut<'_>,
- raw: u32,
- val: &mut MaybeUninit<wasmtime_anyref_t>,
-) {
- let mut scope = RootScope::new(cx);
- let anyref =
- AnyRef::from_raw(&mut scope, raw).map(|a| a.to_owned_rooted(&mut scope).expect("in scope"));
- crate::initialize(val, anyref.into());
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn wasmtime_anyref_from_i31(
- cx: WasmtimeStoreContextMut<'_>,
- val: u32,
- out: &mut MaybeUninit<wasmtime_anyref_t>,
-) {
- let mut scope = RootScope::new(cx);
- let anyref = AnyRef::from_i31(&mut scope, I31::wrapping_u32(val));
- let anyref = anyref.to_owned_rooted(&mut scope).expect("in scope");
- 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<'_>,
- anyref: Option<&wasmtime_anyref_t>,
- dst: &mut MaybeUninit<u32>,
-) -> bool {
- match anyref.and_then(|a| a.as_wasmtime()) {
- Some(anyref) if anyref.is_i31(&cx).expect("OwnedRooted always in scope") => {
- let val = anyref
- .unwrap_i31(&cx)
- .expect("OwnedRooted always in scope")
- .get_u32();
- crate::initialize(dst, val);
- true
- }
- _ => false,
- }
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_anyref_i31_get_s(
- cx: WasmtimeStoreContextMut<'_>,
- anyref: Option<&wasmtime_anyref_t>,
- dst: &mut MaybeUninit<i32>,
-) -> bool {
- match anyref.and_then(|a| a.as_wasmtime()) {
- Some(anyref) if anyref.is_i31(&cx).expect("OwnedRooted always in scope") => {
- let val = anyref
- .unwrap_i31(&cx)
- .expect("OwnedRooted always in scope")
- .get_i32();
- crate::initialize(dst, val);
- true
- }
- _ => false,
- }
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn wasmtime_externref_new(
- cx: WasmtimeStoreContextMut<'_>,
- data: *mut c_void,
- finalizer: Option<extern "C" fn(*mut c_void)>,
- out: &mut MaybeUninit<wasmtime_externref_t>,
-) -> bool {
- let mut scope = RootScope::new(cx);
- let e = match ExternRef::new(&mut scope, crate::ForeignData { data, finalizer }) {
- Ok(e) => e,
- Err(_) => return false,
- };
- let e = e.to_owned_rooted(&mut scope).expect("in scope");
- crate::initialize(out, Some(e).into());
- true
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_externref_data(
- cx: WasmtimeStoreContextMut<'_>,
- externref: Option<&wasmtime_externref_t>,
-) -> *mut c_void {
- externref
- .and_then(|e| e.as_wasmtime())
- .and_then(|e| {
- let data = e.data(cx).ok()??;
- Some(data.downcast_ref::<crate::ForeignData>().unwrap().data)
- })
- .unwrap_or(core::ptr::null_mut())
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_externref_clone(
- externref: Option<&wasmtime_externref_t>,
- out: &mut MaybeUninit<wasmtime_externref_t>,
-) {
- let externref = externref.and_then(|e| e.as_wasmtime());
- crate::initialize(out, externref.into());
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_externref_unroot(
- val: Option<&mut ManuallyDrop<wasmtime_externref_t>>,
-) {
- if let Some(val) = val {
- unsafe {
- ManuallyDrop::drop(val);
- }
- }
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_externref_to_raw(
- cx: WasmtimeStoreContextMut<'_>,
- val: Option<&wasmtime_externref_t>,
-) -> u32 {
- val.and_then(|e| e.as_wasmtime())
- .and_then(|e| e.to_raw(cx).ok())
- .unwrap_or_default()
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_externref_from_raw(
- cx: WasmtimeStoreContextMut<'_>,
- raw: u32,
- val: &mut MaybeUninit<wasmtime_externref_t>,
-) {
- let mut scope = RootScope::new(cx);
- let rooted = ExternRef::from_raw(&mut scope, raw)
- .map(|e| e.to_owned_rooted(&mut scope).expect("in scope"));
- crate::initialize(val, rooted.into());
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_exnref_clone(
- exnref: Option<&wasmtime_exnref_t>,
- out: &mut MaybeUninit<wasmtime_exnref_t>,
-) {
- let exnref = exnref.and_then(|e| e.as_wasmtime());
- crate::initialize(out, exnref.into());
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_exnref_unroot(val: Option<&mut ManuallyDrop<wasmtime_exnref_t>>) {
- if let Some(val) = val {
- unsafe {
- ManuallyDrop::drop(val);
- }
- }
-}
-
-#[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
-}
-
-pub type wasmtime_storage_kind_t = u8;
-pub const WASMTIME_STORAGE_KIND_I8: wasmtime_storage_kind_t = 9;
-pub const WASMTIME_STORAGE_KIND_I16: wasmtime_storage_kind_t = 10;
-
-#[repr(C)]
-pub struct wasmtime_field_type_t {
- pub kind: wasmtime_storage_kind_t,
- pub mutable_: bool,
-}
-
-fn field_type_from_c(ft: &wasmtime_field_type_t) -> FieldType {
- let mutability = if ft.mutable_ {
- Mutability::Var
- } else {
- Mutability::Const
- };
- let storage = match ft.kind {
- WASMTIME_STORAGE_KIND_I8 => StorageType::I8,
- WASMTIME_STORAGE_KIND_I16 => StorageType::I16,
- crate::WASMTIME_I32 => StorageType::ValType(ValType::I32),
- crate::WASMTIME_I64 => StorageType::ValType(ValType::I64),
- crate::WASMTIME_F32 => StorageType::ValType(ValType::F32),
- crate::WASMTIME_F64 => StorageType::ValType(ValType::F64),
- crate::WASMTIME_V128 => StorageType::ValType(ValType::V128),
- crate::WASMTIME_FUNCREF => StorageType::ValType(ValType::FUNCREF),
- crate::WASMTIME_EXTERNREF => StorageType::ValType(ValType::EXTERNREF),
- crate::WASMTIME_ANYREF => StorageType::ValType(ValType::ANYREF),
- crate::WASMTIME_EXNREF => StorageType::ValType(ValType::EXNREF),
- other => panic!("unknown wasmtime_storage_kind_t: {other}"),
- };
- FieldType::new(mutability, storage)
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn wasmtime_struct_type_new(
- engine: &crate::wasm_engine_t,
- fields: *const wasmtime_field_type_t,
- nfields: usize,
-) -> Box<wasmtime_struct_type_t> {
- let fields = if nfields == 0 {
- &[]
- } else {
- unsafe { std::slice::from_raw_parts(fields, nfields) }
- };
- let field_types: Vec<FieldType> = fields.iter().map(field_type_from_c).collect();
- let ty = StructType::new(&engine.engine, field_types).expect("failed to create struct type");
- Box::new(wasmtime_struct_type_t { ty })
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn wasmtime_struct_ref_pre_new(
- cx: WasmtimeStoreContextMut<'_>,
- ty: &wasmtime_struct_type_t,
-) -> Box<wasmtime_struct_ref_pre_t> {
- let pre = StructRefPre::new(cx, ty.ty.clone());
- Box::new(wasmtime_struct_ref_pre_t { pre })
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_structref_new(
- mut cx: WasmtimeStoreContextMut<'_>,
- pre: &wasmtime_struct_ref_pre_t,
- fields: *const crate::wasmtime_val_t,
- nfields: usize,
- out: &mut MaybeUninit<wasmtime_structref_t>,
-) -> Option<Box<crate::wasmtime_error_t>> {
- let c_fields = if nfields == 0 {
- &[]
- } else {
- std::slice::from_raw_parts(fields, nfields)
- };
- let mut scope = RootScope::new(&mut cx);
- let vals: Vec<Val> = c_fields.iter().map(|v| v.to_val(&mut scope)).collect();
- match StructRef::new(&mut scope, &pre.pre, &vals) {
- Ok(structref) => {
- let owned = structref
- .to_owned_rooted(&mut scope)
- .expect("just allocated");
- crate::initialize(out, Some(owned).into());
- None
- }
- Err(e) => {
- crate::initialize(out, None::<OwnedRooted<StructRef>>.into());
- Some(Box::new(e.into()))
- }
- }
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_structref_clone(
- structref: Option<&wasmtime_structref_t>,
- out: &mut MaybeUninit<wasmtime_structref_t>,
-) {
- let structref = structref.and_then(|s| s.as_wasmtime());
- crate::initialize(out, structref.into());
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_structref_unroot(
- structref: Option<&mut ManuallyDrop<wasmtime_structref_t>>,
-) {
- if let Some(structref) = structref {
- ManuallyDrop::drop(structref);
- }
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_structref_to_anyref(
- structref: Option<&wasmtime_structref_t>,
- out: &mut MaybeUninit<wasmtime_anyref_t>,
-) {
- let anyref = structref
- .and_then(|s| s.as_wasmtime())
- .map(|s| s.to_anyref());
- crate::initialize(out, anyref.into());
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_structref_to_eqref(
- structref: Option<&wasmtime_structref_t>,
- out: &mut MaybeUninit<wasmtime_eqref_t>,
-) {
- let eqref = structref
- .and_then(|s| s.as_wasmtime())
- .map(|s| s.to_eqref());
- crate::initialize(out, eqref.into());
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_structref_field(
- mut cx: WasmtimeStoreContextMut<'_>,
- structref: Option<&wasmtime_structref_t>,
- index: usize,
- out: &mut MaybeUninit<crate::wasmtime_val_t>,
-) -> Option<Box<crate::wasmtime_error_t>> {
- let structref = structref
- .and_then(|s| s.as_wasmtime())
- .expect("non-null structref required");
- let mut scope = RootScope::new(&mut cx);
- let rooted = structref.to_rooted(&mut scope);
- match rooted.field(&mut scope, index) {
- Ok(val) => {
- let c_val = crate::wasmtime_val_t::from_val(&mut scope, val);
- crate::initialize(out, c_val);
- None
- }
- Err(e) => Some(Box::new(e.into())),
- }
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_structref_set_field(
- mut cx: WasmtimeStoreContextMut<'_>,
- structref: Option<&wasmtime_structref_t>,
- index: usize,
- val: &crate::wasmtime_val_t,
-) -> Option<Box<crate::wasmtime_error_t>> {
- let structref = structref
- .and_then(|s| s.as_wasmtime())
- .expect("non-null structref required");
- let mut scope = RootScope::new(&mut cx);
- let rooted = structref.to_rooted(&mut scope);
- let rust_val = val.to_val(&mut scope);
- match rooted.set_field(&mut scope, index, rust_val) {
- Ok(()) => None,
- Err(e) => Some(Box::new(e.into())),
- }
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_eqref_is_struct(
- cx: WasmtimeStoreContextMut<'_>,
- eqref: Option<&wasmtime_eqref_t>,
-) -> bool {
- match eqref.and_then(|e| e.as_wasmtime()) {
- Some(eqref) => eqref.is_struct(&cx).expect("OwnedRooted always in scope"),
- None => false,
- }
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_eqref_as_struct(
- mut cx: WasmtimeStoreContextMut<'_>,
- eqref: Option<&wasmtime_eqref_t>,
- out: &mut MaybeUninit<wasmtime_structref_t>,
-) -> bool {
- if let Some(eqref) = eqref.and_then(|e| e.as_wasmtime()) {
- let mut scope = RootScope::new(&mut cx);
- let rooted = eqref.to_rooted(&mut scope);
- if let Ok(Some(structref)) = rooted.as_struct(&scope) {
- let owned = structref.to_owned_rooted(&mut scope).expect("in scope");
- crate::initialize(out, Some(owned).into());
- return true;
- }
- }
- crate::initialize(out, None::<OwnedRooted<StructRef>>.into());
- false
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn wasmtime_array_type_new(
- engine: &crate::wasm_engine_t,
- field: &wasmtime_field_type_t,
-) -> Box<wasmtime_array_type_t> {
- let ft = field_type_from_c(field);
- let ty = ArrayType::new(&engine.engine, ft);
- Box::new(wasmtime_array_type_t { ty })
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn wasmtime_array_ref_pre_new(
- cx: WasmtimeStoreContextMut<'_>,
- ty: &wasmtime_array_type_t,
-) -> Box<wasmtime_array_ref_pre_t> {
- let pre = ArrayRefPre::new(cx, ty.ty.clone());
- Box::new(wasmtime_array_ref_pre_t { pre })
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_arrayref_new(
- mut cx: WasmtimeStoreContextMut<'_>,
- pre: &wasmtime_array_ref_pre_t,
- elem: &crate::wasmtime_val_t,
- len: u32,
- out: &mut MaybeUninit<wasmtime_arrayref_t>,
-) -> Option<Box<crate::wasmtime_error_t>> {
- let mut scope = RootScope::new(&mut cx);
- let val = elem.to_val(&mut scope);
- match ArrayRef::new(&mut scope, &pre.pre, &val, len) {
- Ok(arrayref) => {
- let owned = arrayref
- .to_owned_rooted(&mut scope)
- .expect("just allocated");
- crate::initialize(out, Some(owned).into());
- None
- }
- Err(e) => {
- crate::initialize(out, None::<OwnedRooted<ArrayRef>>.into());
- Some(Box::new(e.into()))
- }
- }
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_arrayref_clone(
- arrayref: Option<&wasmtime_arrayref_t>,
- out: &mut MaybeUninit<wasmtime_arrayref_t>,
-) {
- let arrayref = arrayref.and_then(|a| a.as_wasmtime());
- crate::initialize(out, arrayref.into());
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_arrayref_unroot(
- arrayref: Option<&mut ManuallyDrop<wasmtime_arrayref_t>>,
-) {
- if let Some(arrayref) = arrayref {
- ManuallyDrop::drop(arrayref);
- }
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_arrayref_to_anyref(
- arrayref: Option<&wasmtime_arrayref_t>,
- out: &mut MaybeUninit<wasmtime_anyref_t>,
-) {
- let anyref = arrayref
- .and_then(|a| a.as_wasmtime())
- .map(|a| a.to_anyref());
- crate::initialize(out, anyref.into());
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_arrayref_to_eqref(
- arrayref: Option<&wasmtime_arrayref_t>,
- out: &mut MaybeUninit<wasmtime_eqref_t>,
-) {
- let eqref = arrayref.and_then(|a| a.as_wasmtime()).map(|a| a.to_eqref());
- crate::initialize(out, eqref.into());
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_arrayref_len(
- cx: WasmtimeStoreContextMut<'_>,
- arrayref: Option<&wasmtime_arrayref_t>,
- out: &mut MaybeUninit<u32>,
-) -> Option<Box<crate::wasmtime_error_t>> {
- let arrayref = arrayref
- .and_then(|a| a.as_wasmtime())
- .expect("non-null arrayref required");
- match arrayref.len(&cx) {
- Ok(len) => {
- crate::initialize(out, len);
- None
- }
- Err(e) => Some(Box::new(e.into())),
- }
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_arrayref_get(
- mut cx: WasmtimeStoreContextMut<'_>,
- arrayref: Option<&wasmtime_arrayref_t>,
- index: u32,
- out: &mut MaybeUninit<crate::wasmtime_val_t>,
-) -> Option<Box<crate::wasmtime_error_t>> {
- let arrayref = arrayref
- .and_then(|a| a.as_wasmtime())
- .expect("non-null arrayref required");
- let mut scope = RootScope::new(&mut cx);
- let rooted = arrayref.to_rooted(&mut scope);
- match rooted.get(&mut scope, index) {
- Ok(val) => {
- let c_val = crate::wasmtime_val_t::from_val(&mut scope, val);
- crate::initialize(out, c_val);
- None
- }
- Err(e) => Some(Box::new(e.into())),
- }
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_arrayref_set(
- mut cx: WasmtimeStoreContextMut<'_>,
- arrayref: Option<&wasmtime_arrayref_t>,
- index: u32,
- val: &crate::wasmtime_val_t,
-) -> Option<Box<crate::wasmtime_error_t>> {
- let arrayref = arrayref
- .and_then(|a| a.as_wasmtime())
- .expect("non-null arrayref required");
- let mut scope = RootScope::new(&mut cx);
- let rooted = arrayref.to_rooted(&mut scope);
- let rust_val = val.to_val(&mut scope);
- match rooted.set(&mut scope, index, rust_val) {
- Ok(()) => None,
- Err(e) => Some(Box::new(e.into())),
- }
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_eqref_is_array(
- cx: WasmtimeStoreContextMut<'_>,
- eqref: Option<&wasmtime_eqref_t>,
-) -> bool {
- match eqref.and_then(|e| e.as_wasmtime()) {
- Some(eqref) => eqref.is_array(&cx).expect("OwnedRooted always in scope"),
- None => false,
- }
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_eqref_as_array(
- mut cx: WasmtimeStoreContextMut<'_>,
- eqref: Option<&wasmtime_eqref_t>,
- out: &mut MaybeUninit<wasmtime_arrayref_t>,
-) -> bool {
- if let Some(eqref) = eqref.and_then(|e| e.as_wasmtime()) {
- let mut scope = RootScope::new(&mut cx);
- let rooted = eqref.to_rooted(&mut scope);
- if let Ok(Some(arrayref)) = rooted.as_array(&scope) {
- let owned = arrayref.to_owned_rooted(&mut scope).expect("just created");
- crate::initialize(out, Some(owned).into());
- return true;
- }
- }
- crate::initialize(out, None::<OwnedRooted<ArrayRef>>.into());
- false
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_anyref_is_eqref(
- cx: WasmtimeStoreContextMut<'_>,
- anyref: Option<&wasmtime_anyref_t>,
-) -> bool {
- match anyref.and_then(|a| a.as_wasmtime()) {
- Some(anyref) => anyref.is_eqref(&cx).expect("OwnedRooted always in scope"),
- None => false,
- }
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_anyref_as_eqref(
- mut cx: WasmtimeStoreContextMut<'_>,
- anyref: Option<&wasmtime_anyref_t>,
- out: &mut MaybeUninit<wasmtime_eqref_t>,
-) -> bool {
- if let Some(anyref) = anyref.and_then(|a| a.as_wasmtime()) {
- let mut scope = RootScope::new(&mut cx);
- let rooted = anyref.to_rooted(&mut scope);
- if let Ok(Some(eqref)) = rooted.as_eqref(&mut scope) {
- let owned = eqref.to_owned_rooted(&mut scope).expect("in scope");
- crate::initialize(out, Some(owned).into());
- return true;
- }
- }
- crate::initialize(out, None::<OwnedRooted<EqRef>>.into());
- false
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_anyref_is_struct(
- cx: WasmtimeStoreContextMut<'_>,
- anyref: Option<&wasmtime_anyref_t>,
-) -> bool {
- match anyref.and_then(|a| a.as_wasmtime()) {
- Some(anyref) => anyref.is_struct(&cx).expect("OwnedRooted always in scope"),
- None => false,
- }
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_anyref_as_struct(
- mut cx: WasmtimeStoreContextMut<'_>,
- anyref: Option<&wasmtime_anyref_t>,
- out: &mut MaybeUninit<wasmtime_structref_t>,
-) -> bool {
- if let Some(anyref) = anyref.and_then(|a| a.as_wasmtime()) {
- let mut scope = RootScope::new(&mut cx);
- let rooted = anyref.to_rooted(&mut scope);
- if let Ok(Some(structref)) = rooted.as_struct(&scope) {
- let owned = structref.to_owned_rooted(&mut scope).expect("in scope");
- crate::initialize(out, Some(owned).into());
- return true;
- }
- }
- crate::initialize(out, None::<OwnedRooted<StructRef>>.into());
- false
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_anyref_is_array(
- cx: WasmtimeStoreContextMut<'_>,
- anyref: Option<&wasmtime_anyref_t>,
-) -> bool {
- match anyref.and_then(|a| a.as_wasmtime()) {
- Some(anyref) => anyref.is_array(&cx).expect("OwnedRooted always in scope"),
- None => false,
- }
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_anyref_as_array(
- mut cx: WasmtimeStoreContextMut<'_>,
- anyref: Option<&wasmtime_anyref_t>,
- out: &mut MaybeUninit<wasmtime_arrayref_t>,
-) -> bool {
- if let Some(anyref) = anyref.and_then(|a| a.as_wasmtime()) {
- let mut scope = RootScope::new(&mut cx);
- let rooted = anyref.to_rooted(&mut scope);
- if let Ok(Some(arrayref)) = rooted.as_array(&scope) {
- let owned = arrayref.to_owned_rooted(&mut scope).expect("in scope");
- crate::initialize(out, Some(owned).into());
- return true;
- }
- }
- crate::initialize(out, None::<OwnedRooted<ArrayRef>>.into());
- false
-}
diff --git a/crates/c-api/src/structref.rs b/crates/c-api/src/structref.rs
new file mode 100644
index 0000000000..04a8e071e2
--- /dev/null
+++ b/crates/c-api/src/structref.rs
@@ -0,0 +1,113 @@
+use crate::{WasmtimeStoreContextMut, wasmtime_anyref_t, wasmtime_eqref_t, wasmtime_struct_type_t};
+use std::mem::MaybeUninit;
+use wasmtime::{OwnedRooted, RootScope, StructRef, StructRefPre, Val};
+
+crate::anyref::ref_wrapper!({
+ wasmtime: StructRef,
+ capi: wasmtime_structref_t,
+ clone: wasmtime_structref_clone,
+ unroot: wasmtime_structref_unroot,
+});
+
+pub struct wasmtime_struct_ref_pre_t {
+ pre: StructRefPre,
+}
+wasmtime_c_api_macros::declare_own!(wasmtime_struct_ref_pre_t);
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_struct_ref_pre_new(
+ cx: WasmtimeStoreContextMut<'_>,
+ ty: &wasmtime_struct_type_t,
+) -> Box<wasmtime_struct_ref_pre_t> {
+ let pre = StructRefPre::new(cx, ty.ty.clone());
+ Box::new(wasmtime_struct_ref_pre_t { pre })
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_structref_new(
+ mut cx: WasmtimeStoreContextMut<'_>,
+ pre: &wasmtime_struct_ref_pre_t,
+ fields: *const crate::wasmtime_val_t,
+ nfields: usize,
+ out: &mut MaybeUninit<wasmtime_structref_t>,
+) -> Option<Box<crate::wasmtime_error_t>> {
+ let c_fields = crate::slice_from_raw_parts(fields, nfields);
+ let mut scope = RootScope::new(&mut cx);
+ let vals: Vec<Val> = c_fields.iter().map(|v| v.to_val(&mut scope)).collect();
+ match StructRef::new(&mut scope, &pre.pre, &vals) {
+ Ok(structref) => {
+ let owned = structref
+ .to_owned_rooted(&mut scope)
+ .expect("just allocated");
+ crate::initialize(out, Some(owned).into());
+ None
+ }
+ Err(e) => {
+ crate::initialize(out, None::<OwnedRooted<StructRef>>.into());
+ Some(Box::new(e.into()))
+ }
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_structref_to_anyref(
+ structref: Option<&wasmtime_structref_t>,
+ out: &mut MaybeUninit<wasmtime_anyref_t>,
+) {
+ let anyref = structref
+ .and_then(|s| s.as_wasmtime())
+ .map(|s| s.to_anyref());
+ crate::initialize(out, anyref.into());
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_structref_to_eqref(
+ structref: Option<&wasmtime_structref_t>,
+ out: &mut MaybeUninit<wasmtime_eqref_t>,
+) {
+ let eqref = structref
+ .and_then(|s| s.as_wasmtime())
+ .map(|s| s.to_eqref());
+ crate::initialize(out, eqref.into());
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_structref_field(
+ mut cx: WasmtimeStoreContextMut<'_>,
+ structref: Option<&wasmtime_structref_t>,
+ index: usize,
+ out: &mut MaybeUninit<crate::wasmtime_val_t>,
+) -> Option<Box<crate::wasmtime_error_t>> {
+ let structref = structref
+ .and_then(|s| s.as_wasmtime())
+ .expect("non-null structref required");
+ let mut scope = RootScope::new(&mut cx);
+ let rooted = structref.to_rooted(&mut scope);
+ match rooted.field(&mut scope, index) {
+ Ok(val) => {
+ let c_val = crate::wasmtime_val_t::from_val(&mut scope, val);
+ crate::initialize(out, c_val);
+ None
+ }
+ Err(e) => Some(Box::new(e.into())),
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_structref_set_field(
+ mut cx: WasmtimeStoreContextMut<'_>,
+ structref: Option<&wasmtime_structref_t>,
+ index: usize,
+ val: &crate::wasmtime_val_t,
+) -> Option<Box<crate::wasmtime_error_t>> {
+ let structref = structref
+ .and_then(|s| s.as_wasmtime())
+ .expect("non-null structref required");
+ let mut scope = RootScope::new(&mut cx);
+ let rooted = structref.to_rooted(&mut scope);
+ let rust_val = val.to_val(&mut scope);
+ match rooted.set_field(&mut scope, index, rust_val) {
+ Ok(()) => None,
+ Err(e) => Some(Box::new(e.into())),
+ }
+}
diff --git a/crates/c-api/src/types.rs b/crates/c-api/src/types.rs
index 99e08400fe..3551ce2358 100644
--- a/crates/c-api/src/types.rs
+++ b/crates/c-api/src/types.rs
@@ -33,3 +33,12 @@ pub use self::memory::*;
pub use self::table::*;
pub use self::tag::*;
pub use self::val::*;
+
+#[cfg(feature = "gc")]
+mod arrayref;
+#[cfg(feature = "gc")]
+mod structref;
+#[cfg(feature = "gc")]
+pub use self::arrayref::*;
+#[cfg(feature = "gc")]
+pub use self::structref::*;
diff --git a/crates/c-api/src/types/arrayref.rs b/crates/c-api/src/types/arrayref.rs
new file mode 100644
index 0000000000..ca779002ad
--- /dev/null
+++ b/crates/c-api/src/types/arrayref.rs
@@ -0,0 +1,17 @@
+use crate::wasmtime_field_type_t;
+use wasmtime::ArrayType;
+
+pub struct wasmtime_array_type_t {
+ pub(crate) ty: ArrayType,
+}
+wasmtime_c_api_macros::declare_own!(wasmtime_array_type_t);
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_array_type_new(
+ engine: &crate::wasm_engine_t,
+ field: &wasmtime_field_type_t,
+) -> Box<wasmtime_array_type_t> {
+ let ft = field.to_wasmtime();
+ let ty = ArrayType::new(&engine.engine, ft);
+ Box::new(wasmtime_array_type_t { ty })
+}
diff --git a/crates/c-api/src/types/structref.rs b/crates/c-api/src/types/structref.rs
new file mode 100644
index 0000000000..79b413b101
--- /dev/null
+++ b/crates/c-api/src/types/structref.rs
@@ -0,0 +1,53 @@
+use wasmtime::{FieldType, Mutability, StorageType, StructType, ValType};
+
+pub type wasmtime_storage_kind_t = u8;
+pub const WASMTIME_STORAGE_KIND_I8: wasmtime_storage_kind_t = 9;
+pub const WASMTIME_STORAGE_KIND_I16: wasmtime_storage_kind_t = 10;
+
+#[repr(C)]
+pub struct wasmtime_field_type_t {
+ pub kind: wasmtime_storage_kind_t,
+ pub mutable_: bool,
+}
+
+impl wasmtime_field_type_t {
+ pub(crate) fn to_wasmtime(&self) -> FieldType {
+ let mutability = if self.mutable_ {
+ Mutability::Var
+ } else {
+ Mutability::Const
+ };
+ let storage = match self.kind {
+ WASMTIME_STORAGE_KIND_I8 => StorageType::I8,
+ WASMTIME_STORAGE_KIND_I16 => StorageType::I16,
+ crate::WASMTIME_I32 => StorageType::ValType(ValType::I32),
+ crate::WASMTIME_I64 => StorageType::ValType(ValType::I64),
+ crate::WASMTIME_F32 => StorageType::ValType(ValType::F32),
+ crate::WASMTIME_F64 => StorageType::ValType(ValType::F64),
+ crate::WASMTIME_V128 => StorageType::ValType(ValType::V128),
+ crate::WASMTIME_FUNCREF => StorageType::ValType(ValType::FUNCREF),
+ crate::WASMTIME_EXTERNREF => StorageType::ValType(ValType::EXTERNREF),
+ crate::WASMTIME_ANYREF => StorageType::ValType(ValType::ANYREF),
+ crate::WASMTIME_EXNREF => StorageType::ValType(ValType::EXNREF),
+ other => panic!("unknown wasmtime_storage_kind_t: {other}"),
+ };
+ FieldType::new(mutability, storage)
+ }
+}
+
+pub struct wasmtime_struct_type_t {
+ pub(crate) ty: StructType,
+}
+wasmtime_c_api_macros::declare_own!(wasmtime_struct_type_t);
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_struct_type_new(
+ engine: &crate::wasm_engine_t,
+ fields: *const wasmtime_field_type_t,
+ nfields: usize,
+) -> Box<wasmtime_struct_type_t> {
+ let fields = unsafe { crate::slice_from_raw_parts(fields, nfields) };
+ let field_types: Vec<FieldType> = fields.iter().map(|f| f.to_wasmtime()).collect();
+ let ty = StructType::new(&engine.engine, field_types).expect("failed to create struct type");
+ Box::new(wasmtime_struct_type_t { ty })
+}
diff --git a/crates/c-api/tests/exception.cc b/crates/c-api/tests/exception.cc
index 63962b7231..ac5660a2a7 100644
--- a/crates/c-api/tests/exception.cc
+++ b/crates/c-api/tests/exception.cc
@@ -23,7 +23,7 @@ TEST(Exception, ConstructAndExamine) {
// Create an exception with payload (42, 100).
std::vector<Val> fields = {Val(int32_t(42)), Val(int64_t(100))};
- auto exn = Exn::create(cx, tag, fields).unwrap();
+ auto exn = ExnRef::create(cx, tag, fields).unwrap();
// Read back the tag and verify identity.
auto exn_tag = exn.tag(cx).unwrap();
@@ -97,8 +97,8 @@ TEST(Exception, HostThrowWasmCatch) {
auto cx2 = caller.context();
std::vector<Val> fields = {Val(int32_t(99))};
- auto exn = Exn::create(cx2, tag, fields).unwrap();
- return cx2.throw_exception(std::move(exn));
+ auto exn = ExnRef::create(cx2, tag, fields).unwrap();
+ return cx2.throw_exception(exn);
});
std::vector<Extern> imports = {throw_fn, tag};
diff --git a/crates/c-api/tests/gc.cc b/crates/c-api/tests/gc.cc
index b7fbc44501..d4889cb5f6 100644
--- a/crates/c-api/tests/gc.cc
+++ b/crates/c-api/tests/gc.cc
@@ -1,5 +1,3 @@
-#include <wasmtime/gc.hh>
-
#include <gtest/gtest.h>
#include <wasmtime.hh>
diff --git a/crates/c-api/tests/instance.cc b/crates/c-api/tests/instance.cc
index 3f4dfa911a..ce5790ef6b 100644
--- a/crates/c-api/tests/instance.cc
+++ b/crates/c-api/tests/instance.cc
@@ -1,4 +1,5 @@
#include <gtest/gtest.h>
+#include <wasmtime/func.hh>
#include <wasmtime/instance.hh>
using namespace wasmtime;
diff --git a/crates/c-api/tests/linker.cc b/crates/c-api/tests/linker.cc
index 65d3a2b038..8a1c2ce1b8 100644
--- a/crates/c-api/tests/linker.cc
+++ b/crates/c-api/tests/linker.cc
@@ -1,4 +1,5 @@
#include <gtest/gtest.h>
+#include <wasmtime/func.hh>
#include <wasmtime/linker.hh>
using namespace wasmtime;