A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Exceptions: implement C API. (#12861)
Chris Fallin0dbb6f3d4ee4
diff --git a/crates/c-api/include/wasmtime.h b/crates/c-api/include/wasmtime.hindex 814da24344..3150cc055b 100644--- a/crates/c-api/include/wasmtime.h+++ b/crates/c-api/include/wasmtime.h@@ -190,6 +190,7 @@#include <wasmtime/config.h>#include <wasmtime/engine.h>#include <wasmtime/error.h>+#include <wasmtime/exn.h>#include <wasmtime/extern.h>#include <wasmtime/func.h>#include <wasmtime/global.h>@@ -201,6 +202,7 @@#include <wasmtime/sharedmemory.h>#include <wasmtime/store.h>#include <wasmtime/table.h>+#include <wasmtime/tag.h>#include <wasmtime/trap.h>#include <wasmtime/val.h>#include <wasmtime/async.h>diff --git a/crates/c-api/include/wasmtime.hh b/crates/c-api/include/wasmtime.hhindex 9a7c11cb4a..3d7ccf15c1 100644--- a/crates/c-api/include/wasmtime.hh+++ b/crates/c-api/include/wasmtime.hh@@ -38,6 +38,7 @@#include <wasmtime/config.hh>#include <wasmtime/engine.hh>#include <wasmtime/error.hh>+#include <wasmtime/exn.hh>#include <wasmtime/extern.hh>#include <wasmtime/func.hh>#include <wasmtime/global.hh>@@ -47,6 +48,7 @@#include <wasmtime/module.hh>#include <wasmtime/store.hh>#include <wasmtime/table.hh>+#include <wasmtime/tag.hh>#include <wasmtime/trap.hh>#include <wasmtime/types.hh>#include <wasmtime/val.hh>diff --git a/crates/c-api/include/wasmtime/exn.h b/crates/c-api/include/wasmtime/exn.hnew file mode 100644index 0000000000..effc5d383c--- /dev/null+++ b/crates/c-api/include/wasmtime/exn.h@@ -0,0 +1,166 @@+/**+ * \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_Hdiff --git a/crates/c-api/include/wasmtime/exn.hh b/crates/c-api/include/wasmtime/exn.hhnew file mode 100644index 0000000000..12ea8f3075--- /dev/null+++ b/crates/c-api/include/wasmtime/exn.hh@@ -0,0 +1,122 @@+/**+ * \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_HHdiff --git a/crates/c-api/include/wasmtime/extern.h b/crates/c-api/include/wasmtime/extern.hindex 51675b970d..113d1e22e9 100644--- a/crates/c-api/include/wasmtime/extern.h+++ b/crates/c-api/include/wasmtime/extern.h@@ -10,6 +10,7 @@#include <wasmtime/module.h>#include <wasmtime/sharedmemory.h>#include <wasmtime/store.h>+#include <wasmtime/tag.h>#ifdef __cplusplusextern "C" {@@ -105,6 +106,9 @@ typedef uint8_t wasmtime_extern_kind_t;/// \brief Value of #wasmtime_extern_kind_t meaning that #wasmtime_extern_t is a/// shared memory#define WASMTIME_EXTERN_SHAREDMEMORY 4+/// \brief Value of #wasmtime_extern_kind_t meaning that #wasmtime_extern_t is a+/// tag+#define WASMTIME_EXTERN_TAG 5/*** \typedef wasmtime_extern_union_t@@ -127,6 +131,8 @@ typedef union wasmtime_extern_union {wasmtime_memory_t memory;/// Field used if #wasmtime_extern_t::kind is #WASMTIME_EXTERN_SHAREDMEMORYstruct wasmtime_sharedmemory *sharedmemory;+ /// Field used if #wasmtime_extern_t::kind is #WASMTIME_EXTERN_TAG+ wasmtime_tag_t tag;} wasmtime_extern_union_t;/**diff --git a/crates/c-api/include/wasmtime/extern.hh b/crates/c-api/include/wasmtime/extern.hhindex 5bab44a3aa..05407facdd 100644--- a/crates/c-api/include/wasmtime/extern.hh+++ b/crates/c-api/include/wasmtime/extern.hh@@ -11,6 +11,7 @@#include <wasmtime/global.hh>#include <wasmtime/memory.hh>#include <wasmtime/table.hh>+#include <wasmtime/tag.hh>namespace wasmtime {@@ -27,6 +28,8 @@ static Extern cvt_extern(wasmtime_extern_t &e) {return Memory(e.of.memory);case WASMTIME_EXTERN_TABLE:return Table(e.of.table);+ case WASMTIME_EXTERN_TAG:+ return Tag(e.of.tag);}std::abort();}@@ -44,6 +47,9 @@ static void cvt_extern(const Extern &e, wasmtime_extern_t &raw) {} else if (const auto *memory = std::get_if<Memory>(&e)) {raw.kind = WASMTIME_EXTERN_MEMORY;raw.of.memory = memory->capi();+ } else if (const auto *tag = std::get_if<Tag>(&e)) {+ raw.kind = WASMTIME_EXTERN_TAG;+ raw.of.tag = tag->capi();} else {std::abort();}diff --git a/crates/c-api/include/wasmtime/extern_declare.hh b/crates/c-api/include/wasmtime/extern_declare.hhindex 3b4257e9ff..78cb27d591 100644--- a/crates/c-api/include/wasmtime/extern_declare.hh+++ b/crates/c-api/include/wasmtime/extern_declare.hh@@ -12,10 +12,11 @@ class Global;class Func;class Memory;class Table;+class Tag;/// \typedef Extern/// \brief Representation of an external WebAssembly item-typedef std::variant<Func, Global, Memory, Table> Extern;+typedef std::variant<Func, Global, Memory, Table, Tag> Extern;} // namespace wasmtimediff --git a/crates/c-api/include/wasmtime/instance.hh b/crates/c-api/include/wasmtime/instance.hhindex 1aa75a060f..636c058b67 100644--- a/crates/c-api/include/wasmtime/instance.hh+++ b/crates/c-api/include/wasmtime/instance.hh@@ -13,6 +13,7 @@#include <wasmtime/module.hh>#include <wasmtime/store.hh>#include <wasmtime/table.hh>+#include <wasmtime/tag.hh>namespace wasmtime {diff --git a/crates/c-api/include/wasmtime/store.hh b/crates/c-api/include/wasmtime/store.hhindex 1f386751b7..bffd7fc632 100644--- a/crates/c-api/include/wasmtime/store.hh+++ b/crates/c-api/include/wasmtime/store.hh@@ -18,6 +18,9 @@namespace wasmtime {class Caller;+class Tag;+class Exn;+class Trap;/// \brief An enum for the behavior before extending the epoch deadline.enum class DeadlineKind {@@ -74,6 +77,7 @@ public:friend class AnyRef;friend class Val;friend class Store;+ friend class Tag;wasmtime_context_t *ptr;public:@@ -162,6 +166,23 @@ public: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; }diff --git a/crates/c-api/include/wasmtime/tag.h b/crates/c-api/include/wasmtime/tag.hnew file mode 100644index 0000000000..9335a6a05a--- /dev/null+++ b/crates/c-api/include/wasmtime/tag.h@@ -0,0 +1,75 @@+/**+ * \file wasmtime/tag.h+ *+ * \brief Wasmtime APIs for interacting with WebAssembly tags.+ *+ * Tags are used to create and identify exception objects. A tag describes+ * the signature (payload types) of exceptions created with it.+ */++#ifndef WASMTIME_TAG_H+#define WASMTIME_TAG_H++#include <wasm.h>+#include <wasmtime/error.h>+#include <wasmtime/store.h>++#ifdef __cplusplus+extern "C" {+#endif++/// \brief Representation of a tag in Wasmtime.+///+/// Tags in Wasmtime are represented as an index into a store and don't+/// have any data or destructor associated with the #wasmtime_tag_t value.+/// Tags cannot interoperate between #wasmtime_store_t instances and if the+/// wrong tag is passed to the wrong store then it may trigger an assertion+/// to abort the process.+typedef struct wasmtime_tag {+ struct {+ /// Internal identifier of what store this belongs to, never zero.+ uint64_t store_id;+ /// Private field for Wasmtime.+ uint32_t __private1;+ };+ /// Private field for Wasmtime.+ uint32_t __private2;+} wasmtime_tag_t;++/// \brief Value of #wasmtime_extern_kind_t meaning that #wasmtime_extern_t is a+/// tag+#define WASMTIME_EXTERN_TAG 5++/**+ * \brief Creates a new host-defined tag.+ *+ * \param store the store in which to create the tag+ * \param tt the tag type that describes the tag's exception payload+ * \param ret on success, filled with the new tag+ *+ * \return NULL on success, otherwise an error describing the failure.+ */+WASM_API_EXTERN wasmtime_error_t *wasmtime_tag_new(wasmtime_context_t *store,+ const wasm_tagtype_t *tt,+ wasmtime_tag_t *ret);++/**+ * \brief Returns the type of the given tag.+ *+ * The returned #wasm_tagtype_t is owned by the caller.+ */+WASM_API_EXTERN wasm_tagtype_t *+wasmtime_tag_type(const wasmtime_context_t *store, const wasmtime_tag_t *tag);++/**+ * \brief Tests whether two tags are identical (same definition).+ */+WASM_API_EXTERN bool wasmtime_tag_eq(const wasmtime_context_t *store,+ const wasmtime_tag_t *a,+ const wasmtime_tag_t *b);++#ifdef __cplusplus+} // extern "C"+#endif++#endif // WASMTIME_TAG_Hdiff --git a/crates/c-api/include/wasmtime/tag.hh b/crates/c-api/include/wasmtime/tag.hhnew file mode 100644index 0000000000..fac4ae4e89--- /dev/null+++ b/crates/c-api/include/wasmtime/tag.hh@@ -0,0 +1,65 @@+/**+ * \file wasmtime/tag.hh+ */++#ifndef WASMTIME_TAG_HH+#define WASMTIME_TAG_HH++#include <wasmtime/error.hh>+#include <wasmtime/store.hh>+#include <wasmtime/tag.h>+#include <wasmtime/types/tag.hh>++namespace wasmtime {++/**+ * \brief A WebAssembly tag.+ *+ * Tags are used to identify exception types. A tag describes the payload+ * signature of exceptions created with it.+ *+ * 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 `Tag`. Note that if the wrong `Store`+ * is passed in then the process will be aborted.+ */+class Tag {+ friend class Instance;+ wasmtime_tag_t tag;++public:+ /// Creates a tag from the raw underlying C API representation.+ Tag(wasmtime_tag_t tag) : tag(tag) {}++ /**+ * \brief Create a new host-defined tag.+ *+ * \param cx the store in which to create the tag+ * \param ty the tag type describing the exception payload+ */+ static Result<Tag> create(Store::Context cx, const TagType &ty) {+ wasmtime_tag_t tag;+ auto *error = wasmtime_tag_new(cx.ptr, ty.ptr.get(), &tag);+ if (error != nullptr) {+ return Error(error);+ }+ return Tag(tag);+ }++ /// Returns the type of this tag.+ TagType type(Store::Context cx) const {+ return TagType(wasmtime_tag_type(cx.ptr, &tag));+ }++ /// Tests whether two tags are identical.+ bool eq(Store::Context cx, const Tag &other) const {+ return wasmtime_tag_eq(cx.ptr, &tag, &other.tag);+ }++ /// Returns the raw underlying C API tag this is using.+ const wasmtime_tag_t &capi() const { return tag; }+};++} // namespace wasmtime++#endif // WASMTIME_TAG_HHdiff --git a/crates/c-api/include/wasmtime/types/tag.hh b/crates/c-api/include/wasmtime/types/tag.hhindex 5f4180af79..28ce8a8df4 100644--- a/crates/c-api/include/wasmtime/types/tag.hh+++ b/crates/c-api/include/wasmtime/types/tag.hh@@ -18,6 +18,9 @@ namespace wasmtime {* payload types (and whose results are empty under the current proposal).*/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/types/val.hh b/crates/c-api/include/wasmtime/types/val.hhindex 7dc524784b..a42d445b6d 100644--- a/crates/c-api/include/wasmtime/types/val.hh+++ b/crates/c-api/include/wasmtime/types/val.hh@@ -30,6 +30,8 @@ enum class ValKind {FuncRef,/// WebAssembly's `anyref` typeAnyRef,+ /// WebAssembly's `exnref` type+ ExnRef,};/// Helper X macro to construct statement for each enumerator in `ValKind`.@@ -42,6 +44,7 @@ enum class ValKind {X(ExternRef, "externref", WASM_EXTERNREF) \X(FuncRef, "funcref", WASM_FUNCREF) \X(AnyRef, "anyref", WASMTIME_ANYREF) \+ X(ExnRef, "exnref", WASMTIME_EXNREF) \X(V128, "v128", WASMTIME_V128)/// \brief Used to print a ValKind.diff --git a/crates/c-api/include/wasmtime/val.h b/crates/c-api/include/wasmtime/val.hindex 9d7e2aea94..e1de440ff5 100644--- a/crates/c-api/include/wasmtime/val.h+++ b/crates/c-api/include/wasmtime/val.h@@ -288,6 +288,60 @@ WASM_API_EXTERN void wasmtime_externref_from_raw(wasmtime_context_t *context,WASM_API_EXTERN uint32_t wasmtime_externref_to_raw(wasmtime_context_t *context, const wasmtime_externref_t *ref);+/**+ * \typedef wasmtime_exnref_t+ * \brief Convenience alias for #wasmtime_exnref+ *+ * \struct wasmtime_exnref+ * \brief A WebAssembly exception reference 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.+ *+ * Null exnref values are represented with `store_id == 0`.+ */+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;++/// \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 Discriminant stored in #wasmtime_val::kindtypedef uint8_t wasmtime_valkind_t;/// \brief Value of #wasmtime_valkind_t meaning that #wasmtime_val_t is an i32@@ -309,6 +363,9 @@ typedef uint8_t wasmtime_valkind_t;/// \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.@@ -337,6 +394,8 @@ typedef union wasmtime_valunion {wasmtime_anyref_t anyref;/// Field used if #wasmtime_val_t::kind is #WASMTIME_EXTERNREFwasmtime_externref_t externref;+ /// Field used if #wasmtime_val_t::kind is #WASMTIME_EXNREF+ wasmtime_exnref_t exnref;/// Field used if #wasmtime_val_t::kind is #WASMTIME_FUNCREF////// Use `wasmtime_funcref_is_null` to test whether this is a null function@@ -464,7 +523,8 @@ typedef struct wasmtime_val {* \brief Unroot the value contained by `val`.** This function will unroot any GC references that `val` points to, for- * example if it has the `WASMTIME_EXTERNREF` or `WASMTIME_ANYREF` kinds. This+ * example if it has the `WASMTIME_EXTERNREF`, `WASMTIME_ANYREF`, or+ * `WASMTIME_EXNREF` kinds. This* function leaves `val` in an undefined state and it should not be used again* without re-initializing.*diff --git a/crates/c-api/include/wasmtime/val.hh b/crates/c-api/include/wasmtime/val.hhindex 5902042dff..bca399085b 100644--- a/crates/c-api/include/wasmtime/val.hh+++ b/crates/c-api/include/wasmtime/val.hh@@ -205,6 +205,7 @@ class Val {friend class Global;friend class Table;friend class Func;+ friend class Exn;wasmtime_val_t val;@@ -317,6 +318,8 @@ public:return ValKind::ExternRef;case WASMTIME_ANYREF:return ValKind::AnyRef;+ case WASMTIME_EXNREF:+ return ValKind::ExnRef;case WASMTIME_V128:return ValKind::V128;}diff --git a/crates/c-api/src/exn.rs b/crates/c-api/src/exn.rsnew file mode 100644index 0000000000..618644170f--- /dev/null+++ b/crates/c-api/src/exn.rs@@ -0,0 +1,107 @@+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);++#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_exn_new(+ mut store: WasmtimeStoreContextMut<'_>,+ tag: &Tag,+ fields: *const wasmtime_val_t,+ nfields: usize,+ exn_ret: &mut *mut wasmtime_exn_t,+) -> Option<Box<wasmtime_error_t>> {+ let mut scope = RootScope::new(&mut store);++ let result = (|| {+ let tag_ty = tag.ty(&scope);+ let exn_type = ExnType::from_tag_type(&tag_ty)?;+ let allocator = ExnRefPre::new(&mut scope, exn_type);+ let raw_fields = crate::slice_from_raw_parts(fields, nfields);+ let field_vals: Vec<wasmtime::Val> =+ raw_fields.iter().map(|f| f.to_val(&mut scope)).collect();+ ExnRef::new(&mut scope, &allocator, tag, &field_vals)+ })();++ 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 }));+ })+}++#[unsafe(no_mangle)]+pub extern "C" fn wasmtime_exn_tag(+ mut store: WasmtimeStoreContextMut<'_>,+ exn: &wasmtime_exn_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);+ handle_result(rooted.tag(&mut scope), |tag| {+ *tag_ret = tag;+ })+}++#[unsafe(no_mangle)]+pub extern "C" fn wasmtime_exn_field_count(+ mut store: WasmtimeStoreContextMut<'_>,+ exn: &wasmtime_exn_t,+) -> usize {+ let mut scope = RootScope::new(&mut store);+ let rooted = exn.exn.to_rooted(&mut scope);+ let ty = rooted.ty(&scope).unwrap();+ ty.fields().len()+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_exn_field(+ mut store: WasmtimeStoreContextMut<'_>,+ exn: &wasmtime_exn_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);+ handle_result(rooted.field(&mut scope, index), |val| {+ crate::initialize(val_ret, wasmtime_val_t::from_val(&mut scope, val));+ })+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_context_set_exception(+ mut store: WasmtimeStoreContextMut<'_>,+ exn: Box<wasmtime_exn_t>,+) -> 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)))+}++#[unsafe(no_mangle)]+pub extern "C" fn wasmtime_context_take_exception(+ mut store: WasmtimeStoreContextMut<'_>,+ exn_ret: &mut *mut wasmtime_exn_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 }));+ true+ }+ None => false,+ }+}++#[unsafe(no_mangle)]+pub extern "C" fn wasmtime_context_has_exception(store: WasmtimeStoreContextMut<'_>) -> bool {+ store.has_pending_exception()+}diff --git a/crates/c-api/src/extern.rs b/crates/c-api/src/extern.rsindex b32eb801f1..ae54173d8f 100644--- a/crates/c-api/src/extern.rs+++ b/crates/c-api/src/extern.rs@@ -3,7 +3,7 @@ use crate::{wasm_global_t, wasm_memory_t, wasm_table_t,};use std::mem::ManuallyDrop;-use wasmtime::{Extern, Func, Global, Memory, SharedMemory, Table};+use wasmtime::{Extern, Func, Global, Memory, SharedMemory, Table, Tag};#[derive(Clone)]pub struct wasm_extern_t {@@ -23,7 +23,7 @@ pub extern "C" fn wasm_extern_kind(e: &wasm_extern_t) -> wasm_externkind_t {Extern::SharedMemory(_) => panic!("Shared Memory no implemented for wasm_* types. Please use wasmtime_* types instead"),- Extern::Tag(_) => todo!(), // FIXME: #10252 C embedder API for exceptions and control tags.+ Extern::Tag(_) => crate::types::WASMTIME_EXTERNTYPE_TAG,}}@@ -86,6 +86,7 @@ pub const WASMTIME_EXTERN_GLOBAL: wasmtime_extern_kind_t = 1;pub const WASMTIME_EXTERN_TABLE: wasmtime_extern_kind_t = 2;pub const WASMTIME_EXTERN_MEMORY: wasmtime_extern_kind_t = 3;pub const WASMTIME_EXTERN_SHAREDMEMORY: wasmtime_extern_kind_t = 4;+pub const WASMTIME_EXTERN_TAG: wasmtime_extern_kind_t = 5;#[repr(C)]pub union wasmtime_extern_union {@@ -94,6 +95,7 @@ pub union wasmtime_extern_union {pub global: Global,pub memory: Memory,pub sharedmemory: ManuallyDrop<Box<SharedMemory>>,+ pub tag: Tag,}impl Drop for wasmtime_extern_t {@@ -114,6 +116,7 @@ impl wasmtime_extern_t {WASMTIME_EXTERN_TABLE => Extern::Table(self.of.table),WASMTIME_EXTERN_MEMORY => Extern::Memory(self.of.memory),WASMTIME_EXTERN_SHAREDMEMORY => Extern::SharedMemory((**self.of.sharedmemory).clone()),+ WASMTIME_EXTERN_TAG => Extern::Tag(self.of.tag),other => panic!("unknown wasmtime_extern_kind_t: {other}"),}}@@ -144,7 +147,10 @@ impl From<Extern> for wasmtime_extern_t {sharedmemory: ManuallyDrop::new(Box::new(sharedmemory)),},},- Extern::Tag(_) => todo!(), // FIXME: #10252 C embedder API for exceptions and control tags.+ Extern::Tag(tag) => wasmtime_extern_t {+ kind: WASMTIME_EXTERN_TAG,+ of: wasmtime_extern_union { tag },+ },}}}diff --git a/crates/c-api/src/func.rs b/crates/c-api/src/func.rsindex 4ff396e146..6200f12146 100644--- a/crates/c-api/src/func.rs+++ b/crates/c-api/src/func.rs@@ -403,7 +403,7 @@ pub unsafe extern "C" fn wasmtime_func_call_unchecked(}fn store_err(err: Error, trap_ret: &mut *mut wasm_trap_t) -> Option<Box<wasmtime_error_t>> {- if err.is::<Trap>() {+ if err.is::<Trap>() || err.is::<wasmtime::ThrownException>() {*trap_ret = Box::into_raw(Box::new(wasm_trap_t::new(err)));None} else {diff --git a/crates/c-api/src/lib.rs b/crates/c-api/src/lib.rsindex 5d5abad2a2..4d9fdce174 100644--- a/crates/c-api/src/lib.rs+++ b/crates/c-api/src/lib.rs@@ -20,6 +20,7 @@ pub use wasmtime;mod config;mod engine;mod error;+mod exn;mod r#extern;mod func;mod global;@@ -33,6 +34,7 @@ mod r#ref;mod sharedmemory;mod store;mod table;+mod tag;mod trap;mod types;mod val;@@ -41,6 +43,7 @@ mod vec;pub use crate::config::*;pub use crate::engine::*;pub use crate::error::*;+pub use crate::exn::*;pub use crate::r#extern::*;pub use crate::func::*;pub use crate::global::*;@@ -51,6 +54,7 @@ pub use crate::module::*;pub use crate::r#ref::*;pub use crate::store::*;pub use crate::table::*;+pub use crate::tag::*;pub use crate::trap::*;pub use crate::types::*;pub use crate::val::*;diff --git a/crates/c-api/src/ref.rs b/crates/c-api/src/ref.rsindex b890f03c74..a6dea92071 100644--- a/crates/c-api/src/ref.rs+++ b/crates/c-api/src/ref.rs@@ -1,7 +1,7 @@use crate::{WasmtimeStoreContextMut, abort};use std::mem::{ManuallyDrop, MaybeUninit};use std::{num::NonZeroU64, os::raw::c_void, ptr};-use wasmtime::{AnyRef, ExternRef, I31, OwnedRooted, Ref, RootScope, Val};+use wasmtime::{AnyRef, ExnRef, ExternRef, I31, OwnedRooted, Ref, RootScope, Val};/// `*mut wasm_ref_t` is a reference type (`externref` or `funcref`), as seen by/// the C API. Because we do not have a uniform representation for `funcref`s@@ -258,6 +258,7 @@ macro_rules! ref_wrapper {ref_wrapper!(AnyRef => wasmtime_anyref_t);ref_wrapper!(ExternRef => wasmtime_externref_t);+ref_wrapper!(ExnRef => wasmtime_exnref_t);#[unsafe(no_mangle)]pub unsafe extern "C" fn wasmtime_anyref_clone(@@ -421,3 +422,21 @@ pub unsafe extern "C" fn wasmtime_externref_from_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);+ }+ }+}diff --git a/crates/c-api/src/tag.rs b/crates/c-api/src/tag.rsnew file mode 100644index 0000000000..bf23b8a648--- /dev/null+++ b/crates/c-api/src/tag.rs@@ -0,0 +1,34 @@+use crate::{+ WasmtimeStoreContext, WasmtimeStoreContextMut, handle_result, wasm_tagtype_t, wasmtime_error_t,+};+use std::mem::MaybeUninit;+use wasmtime::Tag;++/// Creates a new host-defined tag with the given type.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasmtime_tag_new(+ mut store: WasmtimeStoreContextMut<'_>,+ tt: &wasm_tagtype_t,+ ret: &mut MaybeUninit<Tag>,+) -> Option<Box<wasmtime_error_t>> {+ let tag_type = tt.to_tag_type(store.engine());+ handle_result(Tag::new(&mut store, &tag_type), |tag| {+ ret.write(tag);+ })+}++/// Returns the type of this tag.+#[unsafe(no_mangle)]+pub extern "C" fn wasmtime_tag_type(+ store: WasmtimeStoreContext<'_>,+ tag: &Tag,+) -> Box<wasm_tagtype_t> {+ let ty = tag.ty(store);+ Box::new(wasm_tagtype_t::from_tag_type(ty))+}++/// Tests whether two tags are the same (identity equality).+#[unsafe(no_mangle)]+pub extern "C" fn wasmtime_tag_eq(store: WasmtimeStoreContext<'_>, a: &Tag, b: &Tag) -> bool {+ Tag::eq(a, b, store)+}diff --git a/crates/c-api/src/types/tag.rs b/crates/c-api/src/types/tag.rsindex 249313de73..8f22f4bf03 100644--- a/crates/c-api/src/types/tag.rs+++ b/crates/c-api/src/types/tag.rs@@ -1,6 +1,6 @@use crate::{CExternType, CFuncType, wasm_externtype_t, wasm_functype_t};use std::cell::OnceCell;-use wasmtime::TagType;+use wasmtime::{Engine, TagType};#[repr(transparent)]#[derive(Clone)]@@ -46,6 +46,19 @@ impl wasm_tagtype_t {_ => unsafe { std::hint::unreachable_unchecked() },}}++ /// Converts this C tag type into a Wasmtime `TagType`.+ pub(crate) fn to_tag_type(&self, engine: &Engine) -> TagType {+ let func_type = self.cty().ty.ty(engine);+ TagType::new(func_type)+ }++ /// Creates a `wasm_tagtype_t` from a Wasmtime `TagType`.+ pub(crate) fn from_tag_type(ty: TagType) -> wasm_tagtype_t {+ wasm_tagtype_t {+ ext: wasm_externtype_t::from_cextern_type(CExternType::Tag(CTagType::new(ty))),+ }+ }}/// Creates a new tag type from a function type describing the exception payload.diff --git a/crates/c-api/src/types/val.rs b/crates/c-api/src/types/val.rsindex 57f10d35b0..baf134e6b4 100644--- a/crates/c-api/src/types/val.rs+++ b/crates/c-api/src/types/val.rs@@ -65,3 +65,4 @@ pub const WASMTIME_V128: wasmtime_valkind_t = 4;pub const WASMTIME_FUNCREF: wasmtime_valkind_t = 5;pub const WASMTIME_EXTERNREF: wasmtime_valkind_t = 6;pub const WASMTIME_ANYREF: wasmtime_valkind_t = 7;+pub const WASMTIME_EXNREF: wasmtime_valkind_t = 8;diff --git a/crates/c-api/src/val.rs b/crates/c-api/src/val.rsindex 8da29cc8d7..8d8ff86dfc 100644--- a/crates/c-api/src/val.rs+++ b/crates/c-api/src/val.rs@@ -1,7 +1,7 @@use crate::r#ref::ref_to_val;use crate::{WASM_I32, from_valtype, into_valtype, wasm_ref_t, wasm_valkind_t, wasmtime_anyref_t,- wasmtime_externref_t, wasmtime_valkind_t,+ wasmtime_exnref_t, wasmtime_externref_t, wasmtime_valkind_t,};use std::mem::{ManuallyDrop, MaybeUninit};use std::ptr;@@ -148,6 +148,7 @@ pub union wasmtime_val_union {pub f64: u64,pub anyref: ManuallyDrop<wasmtime_anyref_t>,pub externref: ManuallyDrop<wasmtime_externref_t>,+ pub exnref: ManuallyDrop<wasmtime_exnref_t>,pub funcref: wasmtime_func_t,pub v128: [u8; 16],}@@ -168,6 +169,9 @@ impl Drop for wasmtime_val_t {crate::WASMTIME_EXTERNREF => {let _ = ManuallyDrop::take(&mut self.of.externref);}+ crate::WASMTIME_EXNREF => {+ let _ = ManuallyDrop::take(&mut self.of.exnref);+ }_ => {}}}@@ -179,12 +183,14 @@ unsafe impl Send for wasmtime_val_unionwhereOption<Box<wasmtime_anyref_t>>: Send,Option<Box<wasmtime_externref_t>>: Send,+ Option<Box<wasmtime_exnref_t>>: Send,{}unsafe impl Sync for wasmtime_val_unionwhereOption<Box<wasmtime_anyref_t>>: Sync,Option<Box<wasmtime_externref_t>>: Sync,+ Option<Box<wasmtime_exnref_t>>: Sync,{}@@ -268,7 +274,12 @@ impl wasmtime_val_t {funcref: func.into(),},},- Val::ExnRef(_) => crate::abort("exnrefs not yet supported in C API"),+ Val::ExnRef(e) => wasmtime_val_t {+ kind: crate::WASMTIME_EXNREF,+ of: wasmtime_val_union {+ exnref: ManuallyDrop::new(e.and_then(|e| e.to_owned_rooted(cx).ok()).into()),+ },+ },Val::V128(val) => wasmtime_val_t {kind: crate::WASMTIME_V128,of: wasmtime_val_union {@@ -308,6 +319,9 @@ impl wasmtime_val_t {Val::ExternRef(self.of.externref.as_wasmtime().map(|e| e.to_rooted(cx)))}crate::WASMTIME_FUNCREF => Val::FuncRef(self.of.funcref.as_wasmtime()),+ crate::WASMTIME_EXNREF => {+ Val::ExnRef(self.of.exnref.as_wasmtime().map(|e| e.to_rooted(cx)))+ }other => panic!("unknown wasmtime_valkind_t: {other}"),}}@@ -330,6 +344,9 @@ pub unsafe extern "C" fn wasmtime_val_clone(crate::WASMTIME_EXTERNREF => wasmtime_val_union {externref: ManuallyDrop::new(src.of.externref.as_wasmtime().into()),},+ crate::WASMTIME_EXNREF => wasmtime_val_union {+ exnref: ManuallyDrop::new(src.of.exnref.as_wasmtime().into()),+ },crate::WASMTIME_I32 => wasmtime_val_union { i32: src.of.i32 },crate::WASMTIME_I64 => wasmtime_val_union { i64: src.of.i64 },crate::WASMTIME_F32 => wasmtime_val_union { f32: src.of.f32 },diff --git a/crates/c-api/tests/CMakeLists.txt b/crates/c-api/tests/CMakeLists.txtindex f18adad6d2..81fa7b004b 100644--- a/crates/c-api/tests/CMakeLists.txt+++ b/crates/c-api/tests/CMakeLists.txt@@ -31,6 +31,7 @@ add_capi_test(tests FILESexport_type.ccextern_type.cctag_type.cc+ exception.ccfunc.cccomponent/instantiate.cccomponent/define_module.ccdiff --git a/crates/c-api/tests/exception.cc b/crates/c-api/tests/exception.ccnew file mode 100644index 0000000000..63962b7231--- /dev/null+++ b/crates/c-api/tests/exception.cc@@ -0,0 +1,217 @@+#include <gtest/gtest.h>+#include <wasmtime.hh>++using namespace wasmtime;++static Engine make_engine() {+ Config config;+ config.wasm_exceptions(true);+ return Engine(std::move(config));+}++TEST(Exception, ConstructAndExamine) {+ auto engine = make_engine();+ Store store(engine);+ auto cx = store.context();++ // Create a tag type with (i32, i64) payload.+ FuncType ft({ValKind::I32, ValKind::I64}, {});+ TagType tt(ft);++ // Create a tag instance.+ auto tag = Tag::create(cx, tt).unwrap();++ // 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();++ // Read back the tag and verify identity.+ auto exn_tag = exn.tag(cx).unwrap();+ EXPECT_TRUE(tag.eq(cx, exn_tag));++ // Read field count.+ EXPECT_EQ(exn.field_count(cx), 2u);++ // Read fields.+ auto f0 = exn.field(cx, 0).unwrap();+ EXPECT_EQ(f0.kind(), ValKind::I32);+ EXPECT_EQ(f0.i32(), 42);++ auto f1 = exn.field(cx, 1).unwrap();+ EXPECT_EQ(f1.kind(), ValKind::I64);+ EXPECT_EQ(f1.i64(), 100);+}++TEST(Exception, TagFromModule) {+ auto engine = make_engine();+ Store store(engine);+ auto cx = store.context();++ Module module = Module::compile(engine, "(module"+ " (tag $t (param i32))"+ " (export \"t\" (tag $t))"+ ")")+ .unwrap();++ auto instance = Instance::create(cx, module, {}).unwrap();+ auto ext = instance.get(cx, "t");+ ASSERT_TRUE(ext.has_value());+ auto tag = std::get<Tag>(*ext);++ auto tt = tag.type(cx);+ auto func = tt->functype();+ EXPECT_EQ(func->params().size(), 1u);+ EXPECT_EQ(func->params().begin()->kind(), ValKind::I32);+}++TEST(Exception, HostThrowWasmCatch) {+ auto engine = make_engine();+ Store store(engine);+ auto cx = store.context();++ FuncType tag_ft({ValKind::I32}, {});+ TagType tt(tag_ft);+ auto tag = Tag::create(cx, tt).unwrap();++ Module module =+ Module::compile(engine, "(module"+ " (import \"host\" \"throw\" (func $throw))"+ " (import \"host\" \"tag\" (tag $t (param i32)))"+ " (func (export \"run\") (result i32)"+ " (block $done (result i32)"+ " (try_table (catch 0 $done)"+ " (call $throw)"+ " )"+ " (unreachable)"+ " )"+ " )"+ ")")+ .unwrap();++ FuncType throw_ft({}, {});+ Func throw_fn(cx, throw_ft,+ [&](Caller caller, Span<const Val> args,+ Span<Val> results) -> Result<std::monostate, Trap> {+ (void)args;+ (void)results;+ 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));+ });++ std::vector<Extern> imports = {throw_fn, tag};+ auto instance = Instance::create(cx, module, imports).unwrap();++ auto run_ext = instance.get(cx, "run");+ ASSERT_TRUE(run_ext.has_value());+ auto run_fn = std::get<Func>(*run_ext);+ auto result = run_fn.call(cx, {});+ ASSERT_TRUE(result);+ ASSERT_EQ(result.ok().size(), 1u);+ EXPECT_EQ(result.ok()[0].i32(), 99);+}++TEST(Exception, ExnRefRoundTripThroughVal) {+ auto engine = make_engine();+ Store store(engine);+ auto cx = store.context();++ // A module that throws an exception and catches it as an exnref.+ Module module =+ Module::compile(engine, "(module"+ " (tag $t (param i32))"+ " (export \"tag\" (tag $t))"+ " (func (export \"make_exnref\") (result exnref)"+ " (block $done (result exnref)"+ " (try_table (catch_all_ref $done)"+ " (throw $t (i32.const 55))"+ " )"+ " (unreachable)"+ " )"+ " )"+ ")")+ .unwrap();++ auto instance = Instance::create(cx, module, {}).unwrap();++ auto tag_ext = instance.get(cx, "tag");+ ASSERT_TRUE(tag_ext.has_value());+ auto tag = std::get<Tag>(*tag_ext);++ auto make_fn = std::get<Func>(*instance.get(cx, "make_exnref"));+ auto result = make_fn.call(cx, {});+ ASSERT_TRUE(result);+ ASSERT_EQ(result.ok().size(), 1u);++ // The returned value should be an exnref.+ auto &exnref_val = result.ok()[0];+ EXPECT_EQ(exnref_val.kind(), ValKind::ExnRef);++ // Pass the exnref back into a wasm function that extracts the i32 payload.+ Module module2 =+ Module::compile(engine,+ "(module"+ " (import \"host\" \"tag\" (tag $t (param i32)))"+ " (func (export \"read\") (param exnref) (result i32)"+ " (block $done (result i32)"+ " (try_table (catch 0 $done)"+ " (throw_ref (local.get 0))"+ " )"+ " (unreachable)"+ " )"+ " )"+ ")")+ .unwrap();++ std::vector<Extern> imports2 = {tag};+ auto instance2 = Instance::create(cx, module2, imports2).unwrap();+ auto read_fn = std::get<Func>(*instance2.get(cx, "read"));++ // Call with the exnref we got back from the first module.+ std::vector<Val> args = {std::move(exnref_val)};+ auto result2 = read_fn.call(cx, args);+ ASSERT_TRUE(result2);+ ASSERT_EQ(result2.ok().size(), 1u);+ EXPECT_EQ(result2.ok()[0].i32(), 55);+}++TEST(Exception, WasmThrowHostCatch) {+ auto engine = make_engine();+ Store store(engine);+ auto cx = store.context();++ Module module = Module::compile(engine, "(module"+ " (tag $t (param i32))"+ " (export \"tag\" (tag $t))"+ " (func (export \"throw\")"+ " (throw $t (i32.const 77))"+ " )"+ ")")+ .unwrap();++ auto instance = Instance::create(cx, module, {}).unwrap();++ auto tag_ext = instance.get(cx, "tag");+ ASSERT_TRUE(tag_ext.has_value());+ auto tag = std::get<Tag>(*tag_ext);++ auto throw_ext = instance.get(cx, "throw");+ ASSERT_TRUE(throw_ext.has_value());+ auto throw_fn = std::get<Func>(*throw_ext);++ auto result = throw_fn.call(cx, {});+ ASSERT_FALSE(result);++ ASSERT_TRUE(cx.has_exception());+ auto exn = cx.take_exception();+ ASSERT_TRUE(exn.has_value());++ auto exn_tag = exn->tag(cx).unwrap();+ EXPECT_TRUE(tag.eq(cx, exn_tag));++ EXPECT_EQ(exn->field_count(cx), 1u);+ auto f0 = exn->field(cx, 0).unwrap();+ EXPECT_EQ(f0.i32(), 77);+}