Skip to content

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

Support resources in the C API of Wasmtime (#11920)

Alex Crichtondbc21cde5478
diff --git a/crates/c-api/include/wasmtime/component/linker.h b/crates/c-api/include/wasmtime/component/linker.h
index c61d98df5a..a64ac3ddb6 100644
--- a/crates/c-api/include/wasmtime/component/linker.h
+++ b/crates/c-api/include/wasmtime/component/linker.h
@@ -157,6 +157,29 @@ wasmtime_component_linker_add_wasip2(wasmtime_component_linker_t *linker);
#endif // WASMTIME_FEATURE_WASI
+/// Type of the callback used in
+/// #wasmtime_component_linker_instance_add_resource
+typedef wasmtime_error_t *(*wasmtime_component_resource_destructor_t)(
+ void *, wasmtime_context_t *, uint32_t);
+
+/**
+ * \brief Defines a new resource type within this instance.
+ *
+ * This can be used to define a new resource type that the guest will be able
+ * to import. Here the `resource` is a type, often a host-defined type, which
+ * can be used to distinguish and definie different types of resources. A
+ * destruction callback is also specified via `destructor` which has private
+ * data `data` along with an optional `finalizer` for the `data` too.
+ *
+ * \return on success `NULL`, otherwise an error
+ */
+WASM_API_EXTERN wasmtime_error_t *
+wasmtime_component_linker_instance_add_resource(
+ wasmtime_component_linker_instance_t *linker_instance, const char *name,
+ size_t name_len, const wasmtime_component_resource_type_t *resource,
+ wasmtime_component_resource_destructor_t destructor, void *data,
+ void (*finalizer)(void *));
+
/**
* \brief Deletes a #wasmtime_component_linker_instance_t
*
diff --git a/crates/c-api/include/wasmtime/component/linker.hh b/crates/c-api/include/wasmtime/component/linker.hh
index c63bd154ed..0e61bbdb72 100644
--- a/crates/c-api/include/wasmtime/component/linker.hh
+++ b/crates/c-api/include/wasmtime/component/linker.hh
@@ -116,6 +116,42 @@ public:
return Error(error);
}
+ return std::monostate();
+ }
+
+private:
+ template <typename F>
+ static wasmtime_error_t *
+ raw_resource_destructor_callback(void *env, wasmtime_context_t *store,
+ uint32_t rep) {
+ F *func = reinterpret_cast<F *>(env);
+ Result<std::monostate> result = (*func)(Store::Context(store), rep);
+ if (!result) {
+ return result.err().release();
+ }
+ return nullptr;
+ }
+
+public:
+ /// \brief Defines a new resource in this linker with the provided
+ /// destructor.
+ template <typename F,
+ std::enable_if_t<std::is_invocable_r_v<Result<std::monostate>, F,
+ Store::Context, uint32_t>,
+ bool> = true>
+ Result<std::monostate> add_resource(std::string_view name,
+ const ResourceType &ty, F &&f) {
+ auto *error = wasmtime_component_linker_instance_add_resource(
+ ptr.get(), name.data(), name.length(), ty.capi(),
+ raw_resource_destructor_callback<std::remove_reference_t<F>>,
+ std::make_unique<std::remove_reference_t<F>>(std::forward<F>(f))
+ .release(),
+ raw_finalize<std::remove_reference_t<F>>);
+
+ if (error != nullptr) {
+ return Error(error);
+ }
+
return std::monostate();
}
};
diff --git a/crates/c-api/include/wasmtime/component/val.h b/crates/c-api/include/wasmtime/component/val.h
index 2373534885..bae8d94eb2 100644
--- a/crates/c-api/include/wasmtime/component/val.h
+++ b/crates/c-api/include/wasmtime/component/val.h
@@ -9,11 +9,243 @@
#include <stdint.h>
#include <wasm.h>
+#include <wasmtime/store.h>
#ifdef __cplusplus
extern "C" {
#endif
+/// \brief Represents the type of a component resource.
+///
+/// This is an opaque structure which represents the type of a resource. This
+/// can be used to equate the type of two resources together to see if they are
+/// the same.
+typedef struct wasmtime_component_resource_type
+ wasmtime_component_resource_type_t;
+
+/// \brief Creates a new resource type representing a host-defined resource.
+///
+/// This function creates a new `wasmtime_component_resource_type_t` which
+/// represents a host-defined resource identified by the `ty` integer argument
+/// provided. Two host resources with different `ty` arguments are considered
+/// not-equal in terms of resource types. Through this the host can create
+/// distinct types of resources at runtime to ensure that components are also
+/// required to keep resources distinct.
+///
+/// The pointer returned from this function must be deallocated with
+/// `wasmtime_component_resource_type_delete`.
+WASM_API_EXTERN
+wasmtime_component_resource_type_t *
+wasmtime_component_resource_type_new_host(uint32_t ty);
+
+/// \brief Clones a resource type.
+///
+/// Creates a new owned copy of a resource type.
+///
+/// The pointer returned from this function must be deallocated with
+/// `wasmtime_component_resource_type_delete`.
+WASM_API_EXTERN
+wasmtime_component_resource_type_t *wasmtime_component_resource_type_clone(
+ const wasmtime_component_resource_type_t *ty);
+
+/// \brief Compares two resource types for equality.
+///
+/// Returns whether `a` and `b` point to logically the same resource type under
+/// the hood.
+WASM_API_EXTERN
+bool wasmtime_component_resource_type_equal(
+ const wasmtime_component_resource_type_t *a,
+ const wasmtime_component_resource_type_t *b);
+
+/// \brief Deallocates a resource type.
+///
+/// This will deallocate the pointer `resource` any any memory that it might
+/// own.
+WASM_API_EXTERN
+void wasmtime_component_resource_type_delete(
+ wasmtime_component_resource_type_t *resource);
+
+/// \brief Represents a component resource which can be either guest-owned or
+/// host-owned.
+///
+/// This type is an opaque type used to represent any component model resource.
+/// Internally this tracks information about ownership, type, etc. Values of
+/// this type have dynamic ownership guarantees associated with them. Notably
+/// from a component-model perspective values of this type must either be
+/// converted to a host resource with `wasmtime_component_resource_any_to_host`
+/// or dropped via `wasmtime_component_resource_any_drop`. This is required to
+/// handle various metadata tracking appropriately, and if this is not done
+/// then the resource will be leaked into the store and a trap may be raised.
+///
+/// Note that this type also has dynamic memory allocations associated with it
+/// and users must call `wasmtime_component_resource_any_delete` to deallocate
+/// the host-side resources. This destructor can be called in an RAII fashion
+/// and will only clean up memory, not metadata related to the resource.
+/// It is required to call `wasmtime_component_resource_any_delete` to prevent
+/// leaking memory on the host. It's highly recommended to call
+/// `wasmtime_component_resource_any_drop` to avoid leaking memory in a
+/// long-lived store, but if this is forgotten then deallocating the store will
+/// deallocate all memory still.
+typedef struct wasmtime_component_resource_any
+ wasmtime_component_resource_any_t;
+
+/// \brief Gets the type of a component resource.
+///
+/// Returns an owned `wasmtime_component_resource_type_t` which represents the
+/// type of this resource.
+///
+/// The pointer returned from this function must be deallocated with
+/// `wasmtime_component_resource_type_delete`.
+WASM_API_EXTERN
+wasmtime_component_resource_type_t *wasmtime_component_resource_any_type(
+ const wasmtime_component_resource_any_t *resource);
+
+/// \brief Clones a component resource.
+///
+/// Creates a new owned copy of a component resource. Note that the returned
+/// resource still logically refers to the same resource as before, but this
+/// can be convenient from an API perspective. Calls to
+/// `wasmtime_component_resource_any_drop` need only happen
+/// once-per-logical-resource, not once-per-handle-to-the-resource. Note though
+/// that calls to `wasmtime_component_resource_any_delete` must happen
+/// once-per-handle-to-the-resource.
+///
+/// The pointer returned from this function must be deallocated with
+/// `wasmtime_component_resource_any_delete`.
+WASM_API_EXTERN
+wasmtime_component_resource_any_t *wasmtime_component_resource_any_clone(
+ const wasmtime_component_resource_any_t *resource);
+
+/// \brief Returns whether this resource is an `own`, or a `borrow` in the
+/// component model.
+WASM_API_EXTERN
+bool wasmtime_component_resource_any_owned(
+ const wasmtime_component_resource_any_t *resource);
+
+/// \brief Drops a component resource.
+///
+/// This function is required to be called per "logical resource" to clean up
+/// any borrow-tracking state in the store, for example. Additionally this may
+/// invoke WebAssembly if it's a guest-owned resource with a destructor
+/// associated with it.
+///
+/// This operation is not to be confused with
+/// `wasmtime_component_resource_any_delete` which deallocates host-related
+/// memory for this resource. After `wasmtime_component_resource_any_drop` is
+/// called it's still required to call
+/// `wasmtime_component_resource_any_delete`.
+WASM_API_EXTERN
+wasmtime_error_t *wasmtime_component_resource_any_drop(
+ wasmtime_context_t *ctx, const wasmtime_component_resource_any_t *resource);
+
+/// \brief Deallocates a component resource.
+///
+/// This function deallocates any host-side memory associated with this
+/// resource. This function does not perform any component-model related
+/// cleanup, and `wasmtime_component_resource_any_drop` is required for that.
+WASM_API_EXTERN
+void wasmtime_component_resource_any_delete(
+ wasmtime_component_resource_any_t *resource);
+
+/// \brief Represents a host-defined component resource.
+///
+/// This structure is similar to `wasmtime_component_resource_any_t` except
+/// that it unconditionally represents an embedder-defined resource via this
+/// API. Host resources have a "rep" which is a 32-bit integer whose meaning
+/// is defined by the host. This "rep" is trusted in the sense that the guest
+/// cannot forge this so the embedder is the only one that can view this.
+///
+/// Host resources also have a 32-bit type whose meaning is also defined by the
+/// host and has no meaning internally. This is used to distinguish different
+/// types of resources from one another.
+///
+/// Also note that unlike `wasmtime_component_resource_any_t` host resources
+/// do not have a "drop" operation. It's up to the host to define what it means
+/// to drop an owned resource and handle that appropriately.
+typedef struct wasmtime_component_resource_host
+ wasmtime_component_resource_host_t;
+
+/// \brief Creates a new host-defined component resource.
+///
+/// This function creates a new host-defined component resource with the
+/// provided parameters. The `owned` parameter indicates whether this resource
+/// is an `own` or a `borrow` in the component model. The `rep` and `ty`
+/// parameters are 32-bit integers which only have meaning to the embedder and
+/// are plumbed through with this resource.
+///
+/// The pointer returned from this function must be deallocated with
+/// `wasmtime_component_resource_host_delete`.
+WASM_API_EXTERN
+wasmtime_component_resource_host_t *
+wasmtime_component_resource_host_new(bool owned, uint32_t rep, uint32_t ty);
+
+/// \brief Clones a host-defined component resource.
+///
+/// Creates a new owned copy of a host-defined component resource. Note that the
+/// returned resource still logically refers to the same resource as before,
+/// but this can be convenient from an API perspective.
+///
+/// The pointer returned from this function must be deallocated with
+/// `wasmtime_component_resource_host_delete`.
+WASM_API_EXTERN
+wasmtime_component_resource_host_t *wasmtime_component_resource_host_clone(
+ const wasmtime_component_resource_host_t *resource);
+
+/// \brief Gets the "rep" of a host-defined component resource.
+///
+/// Returns the 32-bit integer "rep" associated with this resource. This is a
+/// trusted value that guests cannot forge.
+WASM_API_EXTERN
+uint32_t wasmtime_component_resource_host_rep(
+ const wasmtime_component_resource_host_t *resource);
+
+/// \brief Gets the "type" of a host-defined component resource.
+///
+/// Returns the 32-bit integer "type" associated with this resource. This is a
+/// trusted value that guests cannot forge.
+WASM_API_EXTERN
+uint32_t wasmtime_component_resource_host_type(
+ const wasmtime_component_resource_host_t *resource);
+
+/// \brief Returns whether this host-defined resource is an `own` or a `borrow`
+/// in the component model.
+WASM_API_EXTERN
+bool wasmtime_component_resource_host_owned(
+ const wasmtime_component_resource_host_t *resource);
+
+/// \brief Deallocates a host-defined component resource.
+///
+/// This function deallocates any host-side memory associated with this
+/// resource.
+WASM_API_EXTERN
+void wasmtime_component_resource_host_delete(
+ wasmtime_component_resource_host_t *resource);
+
+/// \brief Attempts to convert a `wasmtime_component_resource_any_t` into a
+/// `wasmtime_component_resource_host_t`.
+///
+/// This function will attempt to convert the provided `resource` into a
+/// host-defined resource. If the resource is indeed host-defined then a new
+/// owned `wasmtime_component_resource_host_t` is returned via `ret`. If the
+/// resource is guest-defined then an error is returned and `ret` is not
+/// modified.
+///
+/// If no error is returned then the pointer written to `ret` must be
+/// deallocated with `wasmtime_component_resource_host_delete`.
+WASM_API_EXTERN
+wasmtime_error_t *wasmtime_component_resource_any_to_host(
+ wasmtime_context_t *ctx, const wasmtime_component_resource_any_t *resource,
+ wasmtime_component_resource_host_t **ret);
+
+/// \brief Same as `wasmtime_component_resource_any_to_host` except for
+/// converting the other way around.
+///
+/// This can fail in some edge-case scenarios but typically does not fail.
+WASM_API_EXTERN
+wasmtime_error_t *wasmtime_component_resource_host_to_any(
+ wasmtime_context_t *ctx, const wasmtime_component_resource_host_t *resource,
+ wasmtime_component_resource_any_t **ret);
+
/// \brief Discriminant used in #wasmtime_component_val_t::kind
typedef uint8_t wasmtime_component_valkind_t;
@@ -80,6 +312,9 @@ typedef uint8_t wasmtime_component_valkind_t;
/// \brief Value of #wasmtime_component_valkind_t meaning that
/// #wasmtime_component_val_t is flags
#define WASMTIME_COMPONENT_FLAGS 20
+/// \brief Value of #wasmtime_component_valkind_t meaning that
+/// #wasmtime_component_val_t is a resource
+#define WASMTIME_COMPONENT_RESOURCE 21
struct wasmtime_component_val;
struct wasmtime_component_valrecord_entry;
@@ -180,6 +415,9 @@ typedef union {
wasmtime_component_valresult_t result;
/// Field used if #wasmtime_component_val_t::kind is #WASMTIME_COMPONENT_FLAGS
wasmtime_component_valflags_t flags;
+ /// Field used if #wasmtime_component_val_t::kind is
+ /// #WASMTIME_COMPONENT_RESOURCE
+ wasmtime_component_resource_any_t *resource;
} wasmtime_component_valunion_t;
/// \brief Represents possible runtime values which a component function can
diff --git a/crates/c-api/include/wasmtime/component/val.hh b/crates/c-api/include/wasmtime/component/val.hh
index 0c29bfbb03..2a51d30fb2 100644
--- a/crates/c-api/include/wasmtime/component/val.hh
+++ b/crates/c-api/include/wasmtime/component/val.hh
@@ -8,11 +8,13 @@
#ifdef WASMTIME_FEATURE_COMPONENT_MODEL
#include <assert.h>
+#include <memory>
#include <optional>
#include <string_view>
#include <utility>
#include <vector>
#include <wasmtime/component/val.h>
+#include <wasmtime/store.hh>
namespace wasmtime {
namespace component {
@@ -414,6 +416,201 @@ public:
}
};
+/// Class representing a component model `resource` value which is either a
+/// guest or host-defined resource.
+class ResourceType {
+ struct deleter {
+ void operator()(wasmtime_component_resource_type_t *p) const {
+ wasmtime_component_resource_type_delete(p);
+ }
+ };
+
+ std::unique_ptr<wasmtime_component_resource_type_t, deleter> ptr;
+
+public:
+ /// \brief Takes ownership of `raw` and wraps it with this class.
+ explicit ResourceType(wasmtime_component_resource_type_t *raw) : ptr(raw) {}
+
+ /// \brief Creates a new host resource type with the specified `ty`
+ /// identifier.
+ explicit ResourceType(uint32_t ty)
+ : ptr(wasmtime_component_resource_type_new_host(ty)) {}
+
+ /// Copies another resource into this one.
+ ResourceType(const ResourceType &other)
+ : ptr(wasmtime_component_resource_type_clone(other.ptr.get())) {}
+ /// Copies another resource into this one.
+ ResourceType &operator=(const ResourceType &other) {
+ ptr.reset(wasmtime_component_resource_type_clone(other.ptr.get()));
+ return *this;
+ }
+ ~ResourceType() = default;
+ /// Moves resources from another resource into this one.
+ ResourceType(ResourceType &&other) = default;
+ /// Moves resources from another resource into this one.
+ ResourceType &operator=(ResourceType &&other) = default;
+
+ /// \brief Compares two resource types for equality.
+ bool operator==(const ResourceType &b) const {
+ return wasmtime_component_resource_type_equal(capi(), b.capi());
+ }
+
+ /// \brief Compares two resource types for inequality.
+ bool operator!=(const ResourceType &b) const {
+ return !wasmtime_component_resource_type_equal(capi(), b.capi());
+ }
+
+ /// \brief Returns the underlying C API pointer.
+ const wasmtime_component_resource_type_t *capi() const { return ptr.get(); }
+
+ /// \brief Returns the underlying C API pointer.
+ wasmtime_component_resource_type_t *capi() { return ptr.get(); }
+};
+
+class ResourceHost;
+
+/// Class representing a component model `resource` value which is either a
+/// guest or host-defined resource.
+class ResourceAny {
+ struct deleter {
+ void operator()(wasmtime_component_resource_any_t *p) const {
+ wasmtime_component_resource_any_delete(p);
+ }
+ };
+
+ std::unique_ptr<wasmtime_component_resource_any_t, deleter> ptr;
+
+public:
+ /// \brief Takes ownership of `raw` and wraps it with this class.
+ explicit ResourceAny(wasmtime_component_resource_any_t *raw) : ptr(raw) {}
+
+ /// Copies another resource into this one.
+ ResourceAny(const ResourceAny &other)
+ : ptr(wasmtime_component_resource_any_clone(other.ptr.get())) {}
+ /// Copies another resource into this one.
+ ResourceAny &operator=(const ResourceAny &other) {
+ ptr.reset(wasmtime_component_resource_any_clone(other.ptr.get()));
+ return *this;
+ }
+ ~ResourceAny() = default;
+ /// Moves resources from another resource into this one.
+ ResourceAny(ResourceAny &&other) = default;
+ /// Moves resources from another resource into this one.
+ ResourceAny &operator=(ResourceAny &&other) = default;
+
+ /// \brief Returns the underlying C API pointer.
+ const wasmtime_component_resource_any_t *capi() const { return ptr.get(); }
+
+ /// \brief Returns the underlying C API pointer.
+ wasmtime_component_resource_any_t *capi() { return ptr.get(); }
+
+ /// \brief Gives up ownership of the underlying C pointer to the caller.
+ wasmtime_component_resource_any_t *capi_release() { return ptr.release(); }
+
+ /// \brief Returns whether this resource is owned.
+ bool owned() const { return wasmtime_component_resource_any_owned(capi()); }
+
+ /// \brief Returns the type of this resource.
+ ResourceType type() const {
+ wasmtime_component_resource_type_t *ty =
+ wasmtime_component_resource_any_type(capi());
+ return ResourceType(ty);
+ }
+
+ /// \brief Drops this resource in the component-model sense, cleaning up
+ /// borrow state and executing the wasm destructor, if any.
+ Result<std::monostate> drop(Store::Context cx) const {
+ wasmtime_error_t *err =
+ wasmtime_component_resource_any_drop(cx.capi(), capi());
+ if (err)
+ return Error(err);
+ return std::monostate();
+ }
+
+ /// \brief Attempts to convert this resource to a host-defined resource.
+ Result<ResourceHost> to_host(Store::Context cx) const;
+
+ /**
+ * Converts the raw C API representation to this class without taking
+ * ownership.
+ */
+ static const ResourceAny *
+ from_capi(wasmtime_component_resource_any_t *const *capi) {
+ return reinterpret_cast<const ResourceAny *>(capi);
+ }
+};
+
+/// Class representing a component model `resource` value which is a host-owned
+/// resource.
+class ResourceHost {
+ struct deleter {
+ void operator()(wasmtime_component_resource_host_t *p) const {
+ wasmtime_component_resource_host_delete(p);
+ }
+ };
+
+ std::unique_ptr<wasmtime_component_resource_host_t, deleter> ptr;
+
+public:
+ /// \brief Takes ownership of `raw` and wraps it with this class.
+ explicit ResourceHost(wasmtime_component_resource_host_t *raw) : ptr(raw) {}
+
+ /// Copies another resource into this one.
+ ResourceHost(const ResourceHost &other)
+ : ptr(wasmtime_component_resource_host_clone(other.ptr.get())) {}
+ /// Copies another resource into this one.
+ ResourceHost &operator=(const ResourceHost &other) {
+ ptr.reset(wasmtime_component_resource_host_clone(other.ptr.get()));
+ return *this;
+ }
+ ~ResourceHost() = default;
+ /// Moves resources from another resource into this one.
+ ResourceHost(ResourceHost &&other) = default;
+ /// Moves resources from another resource into this one.
+ ResourceHost &operator=(ResourceHost &&other) = default;
+
+ /// \brief Returns the underlying C API pointer.
+ const wasmtime_component_resource_host_t *capi() const { return ptr.get(); }
+
+ /// \brief Returns the underlying C API pointer.
+ wasmtime_component_resource_host_t *capi() { return ptr.get(); }
+
+ /// \brief Creates a new host-defined resource with the specified `owned`,
+ /// `rep`, and `ty` identifiers.
+ ResourceHost(bool owned, uint32_t rep, uint32_t ty)
+ : ptr(wasmtime_component_resource_host_new(owned, rep, ty)) {}
+
+ /// \brief Returns whether this resource is owned.
+ bool owned() const { return wasmtime_component_resource_host_owned(capi()); }
+
+ /// \brief Returns the "rep" identifier associated with this resource.
+ uint32_t rep() const { return wasmtime_component_resource_host_rep(capi()); }
+
+ /// \brief Returns the "type" identifier associated with this resource.
+ uint32_t type() const {
+ return wasmtime_component_resource_host_type(capi());
+ }
+
+ /// \brief Converts this host-defined resource into a generic resource-any.
+ Result<ResourceAny> to_any(Store::Context cx) const {
+ wasmtime_component_resource_any_t *out;
+ wasmtime_error_t *err =
+ wasmtime_component_resource_host_to_any(cx.capi(), capi(), &out);
+ if (err)
+ return Error(err);
+ return ResourceAny(out);
+ }
+};
+
+inline Result<ResourceHost> ResourceAny::to_host(Store::Context cx) const {
+ wasmtime_component_resource_host_t *out;
+ wasmtime_error_t *err =
+ wasmtime_component_resource_any_to_host(cx.capi(), capi(), &out);
+ if (err)
+ return Error(err);
+ return ResourceHost(out);
+}
+
/**
* \brief Class representing an instantiated WebAssembly component.
*/
@@ -569,6 +766,12 @@ public:
Flags::transfer(std::move(f.raw), raw.of.flags);
}
+ /// Creates a new resource value.
+ Val(ResourceAny r) {
+ raw.kind = WASMTIME_COMPONENT_RESOURCE;
+ raw.of.resource = r.capi_release();
+ }
+
/// \brief Returns whether this value is a boolean.
bool is_bool() const { return raw.kind == WASMTIME_COMPONENT_BOOL; }
@@ -748,6 +951,15 @@ public:
assert(is_flags());
return *Flags::from_capi(&raw.of.flags);
}
+
+ /// \brief Returns whether this value is a resource.
+ bool is_resource() const { return raw.kind == WASMTIME_COMPONENT_RESOURCE; }
+
+ /// \brief Returns the flags value, only valid if `is_flags()`.
+ const ResourceAny &get_resource() const {
+ assert(is_resource());
+ return *ResourceAny::from_capi(&raw.of.resource);
+ }
};
#undef VAL_REPR
diff --git a/crates/c-api/src/component/func.rs b/crates/c-api/src/component/func.rs
index 7f8fb82388..104fde0412 100644
--- a/crates/c-api/src/component/func.rs
+++ b/crates/c-api/src/component/func.rs
@@ -13,8 +13,8 @@ pub unsafe extern "C" fn wasmtime_component_func_call(
results: *mut wasmtime_component_val_t,
results_len: usize,
) -> Option<Box<wasmtime_error_t>> {
- let c_args = unsafe { std::slice::from_raw_parts(args, args_len) };
- let c_results = unsafe { std::slice::from_raw_parts_mut(results, results_len) };
+ let c_args = unsafe { crate::slice_from_raw_parts(args, args_len) };
+ let c_results = unsafe { crate::slice_from_raw_parts_mut(results, results_len) };
let args = c_args.iter().map(Val::from).collect::<Vec<_>>();
let mut results = vec![Val::Bool(false); results_len];
diff --git a/crates/c-api/src/component/linker.rs b/crates/c-api/src/component/linker.rs
index f005448112..fc56d2e3c9 100644
--- a/crates/c-api/src/component/linker.rs
+++ b/crates/c-api/src/component/linker.rs
@@ -1,10 +1,9 @@
-use std::ffi::c_void;
-
-use wasmtime::component::{Instance, Linker, LinkerInstance, Val};
-
use crate::{
- WasmtimeStoreContextMut, WasmtimeStoreData, wasm_engine_t, wasmtime_error_t, wasmtime_module_t,
+ WasmtimeStoreContextMut, WasmtimeStoreData, wasm_engine_t, wasmtime_component_resource_type_t,
+ wasmtime_error_t, wasmtime_module_t,
};
+use std::ffi::c_void;
+use wasmtime::component::{Instance, Linker, LinkerInstance, Val};
use super::{wasmtime_component_t, wasmtime_component_val_t};
@@ -19,7 +18,7 @@ pub struct wasmtime_component_linker_instance_t<'a> {
}
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_component_linker_new(
+pub extern "C" fn wasmtime_component_linker_new(
engine: &wasm_engine_t,
) -> Box<wasmtime_component_linker_t> {
Box::new(wasmtime_component_linker_t {
@@ -28,7 +27,7 @@ pub unsafe extern "C" fn wasmtime_component_linker_new(
}
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_component_linker_allow_shadowing(
+pub extern "C" fn wasmtime_component_linker_allow_shadowing(
linker: &mut wasmtime_component_linker_t,
allow: bool,
) {
@@ -36,7 +35,7 @@ pub unsafe extern "C" fn wasmtime_component_linker_allow_shadowing(
}
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_component_linker_root(
+pub extern "C" fn wasmtime_component_linker_root(
linker: &mut wasmtime_component_linker_t,
) -> Box<wasmtime_component_linker_instance_t<'_>> {
Box::new(wasmtime_component_linker_instance_t {
@@ -45,7 +44,7 @@ pub unsafe extern "C" fn wasmtime_component_linker_root(
}
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_component_linker_instantiate(
+pub extern "C" fn wasmtime_component_linker_instantiate(
linker: &wasmtime_component_linker_t,
context: WasmtimeStoreContextMut<'_>,
component: &wasmtime_component_t,
@@ -56,10 +55,7 @@ pub unsafe extern "C" fn wasmtime_component_linker_instantiate(
}
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_component_linker_delete(
- _linker: Box<wasmtime_component_linker_t>,
-) {
-}
+pub extern "C" fn wasmtime_component_linker_delete(_linker: Box<wasmtime_component_linker_t>) {}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wasmtime_component_linker_instance_add_instance<'a>(
@@ -169,6 +165,39 @@ pub unsafe extern "C" fn wasmtime_component_linker_add_wasip2(
crate::handle_result(result, |_| ())
}
+pub type wasmtime_component_resource_destructor_t =
+ extern "C" fn(*mut c_void, WasmtimeStoreContextMut<'_>, u32) -> Option<Box<wasmtime_error_t>>;
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_component_linker_instance_add_resource(
+ linker_instance: &mut wasmtime_component_linker_instance_t,
+ name: *const u8,
+ name_len: usize,
+ ty: &wasmtime_component_resource_type_t,
+ callback: wasmtime_component_resource_destructor_t,
+ data: *mut c_void,
+ finalizer: Option<extern "C" fn(*mut c_void)>,
+) -> Option<Box<wasmtime_error_t>> {
+ let name = unsafe { std::slice::from_raw_parts(name, name_len) };
+ let Ok(name) = std::str::from_utf8(name) else {
+ return crate::bad_utf8();
+ };
+
+ let foreign = crate::ForeignData { data, finalizer };
+
+ let result = linker_instance
+ .linker_instance
+ .resource(name, ty.ty, move |ctx, rep| {
+ let _ = &foreign;
+ if let Some(res) = callback(foreign.data, ctx, rep) {
+ return Err((*res).into());
+ }
+ Ok(())
+ });
+
+ crate::handle_result(result, |_| ())
+}
+
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wasmtime_component_linker_instance_delete(
_linker_instance: Box<wasmtime_component_linker_instance_t>,
diff --git a/crates/c-api/src/component/val.rs b/crates/c-api/src/component/val.rs
index dfedf5dc33..fa7ccfd556 100644
--- a/crates/c-api/src/component/val.rs
+++ b/crates/c-api/src/component/val.rs
@@ -1,11 +1,9 @@
-use wasmtime::component::Val;
-
-use crate::wasm_name_t;
-
+use crate::{WasmtimeStoreContextMut, handle_result, wasm_name_t, wasmtime_error_t};
use std::mem;
use std::mem::{ManuallyDrop, MaybeUninit};
use std::ptr;
use std::slice;
+use wasmtime::component::{ResourceAny, ResourceDynamic, ResourceType, Val};
crate::declare_vecs! {
(
@@ -232,6 +230,7 @@ pub enum wasmtime_component_val_t {
Option(Option<Box<Self>>),
Result(wasmtime_component_valresult_t),
Flags(wasmtime_component_valflags_t),
+ Resource(Box<wasmtime_component_resource_any_t>),
}
impl Default for wasmtime_component_val_t {
@@ -273,6 +272,7 @@ impl From<&wasmtime_component_val_t> for Val {
}
wasmtime_component_val_t::Result(x) => Val::Result(x.into()),
wasmtime_component_val_t::Flags(x) => Val::Flags(x.into()),
+ wasmtime_component_val_t::Resource(x) => Val::Resource(x.resource),
}
}
}
@@ -306,7 +306,11 @@ impl From<&Val> for wasmtime_component_val_t {
),
Val::Result(x) => wasmtime_component_val_t::Result(x.into()),
Val::Flags(x) => wasmtime_component_val_t::Flags(x.as_slice().into()),
- Val::Resource(_resource_any) => todo!(),
+ Val::Resource(resource_any) => {
+ wasmtime_component_val_t::Resource(Box::new(wasmtime_component_resource_any_t {
+ resource: *resource_any,
+ }))
+ }
Val::Future(_) => todo!(),
Val::Stream(_) => todo!(),
Val::ErrorContext(_) => todo!(),
@@ -315,17 +319,17 @@ impl From<&Val> for wasmtime_component_val_t {
}
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_component_val_new(
+pub extern "C" fn wasmtime_component_val_new(
src: &mut wasmtime_component_val_t,
) -> Box<wasmtime_component_val_t> {
Box::new(mem::replace(src, wasmtime_component_val_t::default()))
}
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_component_val_free(_dst: Option<Box<wasmtime_component_val_t>>) {}
+pub extern "C" fn wasmtime_component_val_free(_dst: Option<Box<wasmtime_component_val_t>>) {}
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasmtime_component_val_clone(
+pub extern "C" fn wasmtime_component_val_clone(
src: &wasmtime_component_val_t,
dst: &mut MaybeUninit<wasmtime_component_val_t>,
) {
@@ -340,3 +344,180 @@ pub unsafe extern "C" fn wasmtime_component_val_delete(
ManuallyDrop::drop(value);
}
}
+
+#[repr(C)]
+pub struct wasmtime_component_resource_type_t {
+ pub(crate) ty: ResourceType,
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_component_resource_type_new_host(
+ ty: u32,
+) -> Box<wasmtime_component_resource_type_t> {
+ Box::new(wasmtime_component_resource_type_t {
+ ty: ResourceType::host_dynamic(ty),
+ })
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_component_resource_type_clone(
+ ty: &wasmtime_component_resource_type_t,
+) -> Box<wasmtime_component_resource_type_t> {
+ Box::new(wasmtime_component_resource_type_t { ty: ty.ty })
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_component_resource_type_equal(
+ a: &wasmtime_component_resource_type_t,
+ b: &wasmtime_component_resource_type_t,
+) -> bool {
+ a.ty == b.ty
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_component_resource_type_delete(
+ _resource: Option<Box<wasmtime_component_resource_type_t>>,
+) {
+}
+
+#[repr(C)]
+#[derive(Clone)]
+pub struct wasmtime_component_resource_any_t {
+ resource: ResourceAny,
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_component_resource_any_type(
+ resource: &wasmtime_component_resource_any_t,
+) -> Box<wasmtime_component_resource_type_t> {
+ Box::new(wasmtime_component_resource_type_t {
+ ty: resource.resource.ty(),
+ })
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_component_resource_any_clone(
+ resource: &wasmtime_component_resource_any_t,
+) -> Box<wasmtime_component_resource_any_t> {
+ Box::new(wasmtime_component_resource_any_t {
+ resource: resource.resource,
+ })
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_component_resource_any_owned(
+ resource: &wasmtime_component_resource_any_t,
+) -> bool {
+ resource.resource.owned()
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_component_resource_any_drop(
+ store: WasmtimeStoreContextMut<'_>,
+ resource: &wasmtime_component_resource_any_t,
+) -> Option<Box<wasmtime_error_t>> {
+ handle_result(resource.resource.resource_drop(store), |()| ())
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_component_resource_any_delete(
+ _resource: Option<Box<wasmtime_component_resource_any_t>>,
+) {
+}
+
+#[repr(C)]
+pub struct wasmtime_component_resource_host_t {
+ resource: ResourceDynamic,
+}
+
+impl wasmtime_component_resource_host_t {
+ // "poor man's clone"
+ fn resource(&self) -> ResourceDynamic {
+ let rep = self.resource.rep();
+ let ty = self.resource.ty();
+ if self.resource.owned() {
+ ResourceDynamic::new_own(rep, ty)
+ } else {
+ ResourceDynamic::new_borrow(rep, ty)
+ }
+ }
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_component_resource_host_new(
+ owned: bool,
+ rep: u32,
+ ty: u32,
+) -> Box<wasmtime_component_resource_host_t> {
+ Box::new(wasmtime_component_resource_host_t {
+ resource: if owned {
+ ResourceDynamic::new_own(rep, ty)
+ } else {
+ ResourceDynamic::new_borrow(rep, ty)
+ },
+ })
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_component_resource_host_clone(
+ resource: &wasmtime_component_resource_host_t,
+) -> Box<wasmtime_component_resource_host_t> {
+ Box::new(wasmtime_component_resource_host_t {
+ resource: resource.resource(),
+ })
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_component_resource_host_rep(
+ resource: &wasmtime_component_resource_host_t,
+) -> u32 {
+ resource.resource.rep()
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_component_resource_host_type(
+ resource: &wasmtime_component_resource_host_t,
+) -> u32 {
+ resource.resource.ty()
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_component_resource_host_owned(
+ resource: &wasmtime_component_resource_host_t,
+) -> bool {
+ resource.resource.owned()
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_component_resource_host_delete(
+ _resource: Option<Box<wasmtime_component_resource_host_t>>,
+) {
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_component_resource_any_to_host(
+ store: WasmtimeStoreContextMut<'_>,
+ resource: &wasmtime_component_resource_any_t,
+ ret: &mut MaybeUninit<Box<wasmtime_component_resource_host_t>>,
+) -> Option<Box<wasmtime_error_t>> {
+ handle_result(
+ resource.resource.try_into_resource_dynamic(store),
+ |resource| {
+ ret.write(Box::new(wasmtime_component_resource_host_t { resource }));
+ },
+ )
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_component_resource_host_to_any(
+ store: WasmtimeStoreContextMut<'_>,
+ resource: &wasmtime_component_resource_host_t,
+ ret: &mut MaybeUninit<Box<wasmtime_component_resource_any_t>>,
+) -> Option<Box<wasmtime_error_t>> {
+ handle_result(
+ resource.resource().try_into_resource_any(store),
+ |resource| {
+ ret.write(Box::new(wasmtime_component_resource_any_t { resource }));
+ },
+ )
+}
diff --git a/crates/c-api/tests/component/values.cc b/crates/c-api/tests/component/values.cc
index e880cc2f9d..dbc8db0960 100644
--- a/crates/c-api/tests/component/values.cc
+++ b/crates/c-api/tests/component/values.cc
@@ -61,12 +61,31 @@ static std::string echo_component(std::string_view type, std::string_view func,
}
struct Context {
- Engine engine;
Store store;
Store::Context context;
- Component component;
Instance instance;
Func func;
+
+ static Context New(Engine &engine, std::string_view component_text,
+ Linker &linker) {
+ Store store(engine);
+ const auto context = store.context();
+ Component component = Component::compile(engine, component_text).unwrap();
+
+ auto f = component.export_index(nullptr, "call");
+
+ EXPECT_TRUE(f);
+
+ auto instance = linker.instantiate(context, component).unwrap();
+ auto func = *instance.get_func(context, *f);
+
+ return Context{
+ .store = std::move(store),
+ .context = context,
+ .instance = instance,
+ .func = func,
+ };
+ }
};
typedef Result<std::monostate> (*host_func_t)(Store::Context, Span<const Val>,
@@ -74,30 +93,11 @@ typedef Result<std::monostate> (*host_func_t)(Store::Context, Span<const Val>,
static Context create(std::string_view type, std::string_view body,
std::string_view host_params, host_func_t callback) {
- auto component_text = echo_component(type, body, host_params);
Engine engine;
- Store store(engine);
- const auto context = store.context();
- Component component = Component::compile(engine, component_text).unwrap();
-
- auto f = component.export_index(nullptr, "call");
-
- EXPECT_TRUE(f);
-
Linker linker(engine);
linker.root().add_func("do", callback).unwrap();
-
- auto instance = linker.instantiate(context, component).unwrap();
- auto func = *instance.get_func(context, *f);
-
- return Context{
- .engine = engine,
- .store = std::move(store),
- .context = context,
- .component = component,
- .instance = instance,
- .func = func,
- };
+ auto component_text = echo_component(type, body, host_params);
+ return Context::New(engine, component_text, linker);
}
TEST(component, value_record) {
@@ -850,3 +850,244 @@ TEST(component, flags) {
EXPECT_EQ(f3.size(), 3);
EXPECT_EQ(f.size(), 3);
}
+
+TEST(component, value_host_resource) {
+ static const uint32_t RESOURCE_TYPE = 100;
+
+ static const auto check = [](Store::Context cx, const Val &v, uint32_t rep) {
+ EXPECT_TRUE(v.is_resource());
+ const ResourceAny &f = v.get_resource();
+ EXPECT_EQ(f.type(), ResourceType(RESOURCE_TYPE));
+ ResourceHost r = f.to_host(cx).unwrap();
+ EXPECT_EQ(r.rep(), rep);
+ EXPECT_EQ(r.type(), RESOURCE_TYPE);
+ };
+
+ static const auto make = [](Store::Context cx, uint32_t rep) -> Val {
+ return ResourceHost(true, rep, RESOURCE_TYPE).to_any(cx).unwrap();
+ };
+
+ Engine engine;
+ Linker linker(engine);
+ {
+ LinkerInstance i = linker.root();
+
+ i.add_resource(
+ "r", ResourceType(RESOURCE_TYPE),
+ +[](Store::Context, uint32_t rep) -> Result<std::monostate> {
+ EXPECT_EQ(rep, 42);
+ return std::monostate();
+ })
+ .unwrap();
+
+ i.add_func(
+ "f",
+ +[](Store::Context cx, Span<const Val> args,
+ Span<Val> rets) -> Result<std::monostate> {
+ EXPECT_EQ(args.size(), 1);
+ check(cx, args[0], 42);
+
+ EXPECT_EQ(rets.size(), 1);
+ rets[0] = make(cx, 43);
+ return std::monostate();
+ })
+ .unwrap();
+ }
+
+ auto ctx = Context::New(engine,
+ R"(
+(component
+ (import "r" (type $r (sub resource)))
+ (import "f" (func $f (param "a" (own $r)) (result (own $r))))
+ (core func $f (canon lower (func $f)))
+
+ (core module $m
+ (import "" "f" (func $f (param i32) (result i32)))
+
+ (func (export "call") (param i32) (result i32)
+ local.get 0
+ call $f)
+ )
+
+ (core instance $m (instantiate $m
+ (with "" (instance
+ (export "f" (func $f))
+ ))
+ ))
+
+ (func (export "call") (param "a" (own $r)) (result (own $r))
+ (canon lift (core func $m "call")))
+)
+)",
+ linker);
+
+ auto arg = make(ctx.context, 42);
+ auto res = Val(false);
+
+ ctx.func.call(ctx.context, Span<const Val>(&arg, 1), Span<Val>(&res, 1))
+ .unwrap();
+ ctx.func.post_return(ctx.context).unwrap();
+
+ check(ctx.context, res, 43);
+}
+
+TEST(component, value_guest_resource) {
+ Engine engine;
+ Linker linker(engine);
+ Store store(engine);
+
+ Component c = Component::compile(engine,
+ R"(
+(component
+ (core module $a
+ (global $g (mut i32) (i32.const 0))
+
+ (func (export "dtor") (param i32) (global.set $g (local.get 0)))
+ (func (export "last-dtor-rep") (result i32) global.get $g)
+ )
+ (core instance $a (instantiate $a))
+ (type $r' (resource (rep i32) (dtor (func $a "dtor"))))
+ (export $r "r" (type $r'))
+
+ (core func $new (canon resource.new $r))
+ (core func $drop (canon resource.drop $r))
+
+ (core module $b
+ (import "" "new" (func $new (param i32) (result i32)))
+ (import "" "drop" (func $drop (param i32)))
+
+ (func (export "new") (param i32) (result i32)
+ local.get 0
+ call $new)
+
+ (func (export "rep") (param i32) (result i32)
+ local.get 0)
+
+ (func (export "drop") (param i32)
+ local.get 0
+ call $drop)
+ )
+ (core instance $b (instantiate $b
+ (with "" (instance
+ (export "new" (func $new))
+ (export "drop" (func $drop))
+ ))
+ ))
+
+ (func (export "new") (param "x" u32) (result (own $r))
+ (canon lift (core func $b "new")))
+ (func (export "rep") (param "x" (borrow $r)) (result u32)
+ (canon lift (core func $b "rep")))
+ (func (export "drop") (param "x" (own $r))
+ (canon lift (core func $b "drop")))
+ (func (export "last-dtor-rep") (result u32)
+ (canon lift (core func $a "last-dtor-rep")))
+
+)
+)")
+ .unwrap();
+
+ auto instance = linker.instantiate(store, c).unwrap();
+ auto new_index = *instance.get_export_index(store, nullptr, "new");
+ auto rep_index = *instance.get_export_index(store, nullptr, "rep");
+ auto drop_index = *instance.get_export_index(store, nullptr, "drop");
+ auto last_dtor_rep_index =
+ *instance.get_export_index(store, nullptr, "last-dtor-rep");
+ auto new_func = *instance.get_func(store, new_index);
+ auto rep_func = *instance.get_func(store, rep_index);
+ auto drop_func = *instance.get_func(store, drop_index);
+ auto last_dtor_rep_func = *instance.get_func(store, last_dtor_rep_index);
+
+ auto arg1 = Val(uint32_t(100));
+ auto res1 = Val(false);
+ new_func.call(store, Span<const Val>(&arg1, 1), Span<Val>(&res1, 1)).unwrap();
+ new_func.post_return(store).unwrap();
+
+ auto arg2 = Val(uint32_t(101));
+ auto res2 = Val(false);
+ new_func.call(store, Span<const Val>(&arg2, 1), Span<Val>(&res2, 1)).unwrap();
+ new_func.post_return(store).unwrap();
+
+ {
+ EXPECT_TRUE(res1.is_resource());
+ EXPECT_TRUE(res2.is_resource());
+ const auto &resource1 = res1.get_resource();
+ const auto &resource2 = res2.get_resource();
+ EXPECT_NE(resource1.type(), ResourceType(100));
+ EXPECT_NE(resource2.type(), ResourceType(100));
+ EXPECT_EQ(resource1.type(), resource2.type());
+ EXPECT_FALSE(resource1.to_host(store));
+ EXPECT_FALSE(resource2.to_host(store));
+ EXPECT_TRUE(resource1.owned());
+ EXPECT_TRUE(resource2.owned());
+ arg1 = resource1;
+ arg2 = resource2;
+ }
+
+ rep_func.call(store, Span<const Val>(&arg1, 1), Span<Val>(&res1, 1)).unwrap();
+ rep_func.post_return(store).unwrap();
+ rep_func.call(store, Span<const Val>(&arg2, 1), Span<Val>(&res2, 1)).unwrap();
+ rep_func.post_return(store).unwrap();
+
+ EXPECT_TRUE(res1.is_u32());
+ EXPECT_TRUE(res2.is_u32());
+ EXPECT_EQ(res1.get_u32(), 100);
+ EXPECT_EQ(res2.get_u32(), 101);
+
+ Val last_rep(false);
+ last_dtor_rep_func.call(store, Span<const Val>(), Span<Val>(&last_rep, 1))
+ .unwrap();
+ last_dtor_rep_func.post_return(store).unwrap();
+ EXPECT_EQ(last_rep.get_u32(), 0);
+
+ drop_func.call(store, Span<const Val>(&arg1, 1), Span<Val>()).unwrap();
+ drop_func.post_return(store).unwrap();
+
+ last_dtor_rep_func.call(store, Span<const Val>(), Span<Val>(&last_rep, 1))
+ .unwrap();
+ last_dtor_rep_func.post_return(store).unwrap();
+ EXPECT_EQ(last_rep.get_u32(), 100);
+
+ arg2.get_resource().drop(store).unwrap();
+
+ last_dtor_rep_func.call(store, Span<const Val>(), Span<Val>(&last_rep, 1))
+ .unwrap();
+ last_dtor_rep_func.post_return(store).unwrap();
+ EXPECT_EQ(last_rep.get_u32(), 101);
+}
+
+TEST(component, resources) {
+ ResourceHost r1(true, 1, 2);
+ EXPECT_TRUE(r1.owned());
+ EXPECT_EQ(r1.rep(), 1);
+ EXPECT_EQ(r1.type(), 2);
+
+ ResourceHost r2 = r1;
+ EXPECT_TRUE(r1.owned());
+ EXPECT_EQ(r1.rep(), 1);
+ EXPECT_EQ(r1.type(), 2);
+ EXPECT_TRUE(r2.owned());
+ EXPECT_EQ(r2.rep(), 1);
+ EXPECT_EQ(r2.type(), 2);
+
+ Engine engine;
+ Store store(engine);
+ ResourceAny r3 = r2.to_any(store).unwrap();
+ EXPECT_TRUE(r3.owned());
+ ResourceType t3 = r3.type();
+ EXPECT_EQ(t3, ResourceType(2));
+
+ ResourceHost r4 = r3.to_host(store).unwrap();
+ EXPECT_TRUE(r4.owned());
+ EXPECT_EQ(r4.rep(), 1);
+ EXPECT_EQ(r4.type(), 2);
+
+ EXPECT_FALSE(r3.drop(store));
+ EXPECT_TRUE(r4.to_any(store).unwrap().drop(store));
+
+ Val v = r4.to_any(store).unwrap();
+ EXPECT_TRUE(v.is_resource());
+ const ResourceAny &r5 = v.get_resource();
+ EXPECT_TRUE(r5.owned());
+ EXPECT_EQ(r5.type(), ResourceType(2));
+}