wasmtime/runtime/component/resources/any.rs
1//! This module defines the `ResourceAny` type in the public API of Wasmtime,
2//! which represents a dynamically typed resource handle that could either be
3//! owned by the guest or the host.
4//!
5//! This is in contrast with `Resource<T>`, for example, and `ResourceAny` has
6//! more "state" behind it. Specifically a `ResourceAny` has a type and a
7//! `HostResourceIndex` which points inside of a `HostResourceData` structure
8//! inside of a store. The `ResourceAny::resource_drop` method, or a conversion
9//! to `Resource<T>`, is required to be called to avoid leaking data within a
10//! store.
11
12use crate::component::func::{LiftContext, LowerContext, bad_type_info, desc};
13use crate::component::matching::InstanceType;
14use crate::component::resources::host::{HostResource, HostResourceType};
15use crate::component::resources::{HostResourceIndex, HostResourceTables};
16use crate::component::{ComponentType, Lift, Lower, Resource, ResourceDynamic, ResourceType};
17use crate::prelude::*;
18use crate::runtime::vm::ValRaw;
19use crate::{AsContextMut, StoreContextMut, Trap};
20use core::mem::MaybeUninit;
21use core::ptr::NonNull;
22use wasmtime_environ::component::{CanonicalAbiInfo, InterfaceType};
23
24/// Representation of a resource in the component model, either a guest-defined
25/// or a host-defined resource.
26///
27/// This type is similar to [`Resource`] except that it can be used to represent
28/// any resource, either host or guest. This type cannot be directly constructed
29/// and is only available if the guest returns it to the host (e.g. a function
30/// returning a guest-defined resource) or by a conversion from [`Resource`] via
31/// [`ResourceAny::try_from_resource`].
32/// This type also does not carry a static type parameter `T` for example and
33/// does not have as much information about its type.
34/// This means that it's possible to get runtime type-errors when
35/// using this type because it cannot statically prevent mismatching resource
36/// types.
37///
38/// Like [`Resource`] this type represents either an `own` or a `borrow`
39/// resource internally. Unlike [`Resource`], however, a [`ResourceAny`] must
40/// always be explicitly destroyed with the [`ResourceAny::resource_drop`]
41/// method. This will update internal dynamic state tracking and invoke the
42/// WebAssembly-defined destructor for a resource, if any.
43///
44/// Note that it is required to call `resource_drop` for all instances of
45/// [`ResourceAny`]: even borrows. Both borrows and own handles have state
46/// associated with them that must be discarded by the time they're done being
47/// used.
48#[derive(Debug, PartialEq, Eq, Copy, Clone)]
49pub struct ResourceAny {
50 idx: HostResourceIndex,
51 ty: ResourceType,
52 owned: bool,
53}
54
55impl ResourceAny {
56 pub(crate) fn new(idx: HostResourceIndex, ty: ResourceType, owned: bool) -> ResourceAny {
57 ResourceAny { idx, ty, owned }
58 }
59
60 /// Attempts to convert an imported [`Resource`] into [`ResourceAny`].
61 ///
62 /// * `resource` is the resource to convert.
63 /// * `store` is the store to place the returned resource into.
64 ///
65 /// The returned `ResourceAny` will not have a destructor attached to it
66 /// meaning that if `resource_drop` is called then it will not invoked a
67 /// host-defined destructor. This is similar to how `Resource<T>` does not
68 /// have a destructor associated with it.
69 ///
70 /// # Errors
71 ///
72 /// This method will return an error if `resource` has already been "taken"
73 /// and has ownership transferred elsewhere which can happen in situations
74 /// such as when it's already lowered into a component.
75 pub fn try_from_resource<T: 'static>(
76 resource: Resource<T>,
77 store: impl AsContextMut,
78 ) -> Result<Self> {
79 resource.try_into_resource_any(store)
80 }
81
82 /// See [`Resource::try_from_resource_any`]
83 pub fn try_into_resource<T: 'static>(self, store: impl AsContextMut) -> Result<Resource<T>> {
84 Resource::try_from_resource_any(self, store)
85 }
86
87 /// See [`ResourceDynamic::try_from_resource_any`]
88 pub fn try_into_resource_dynamic(self, store: impl AsContextMut) -> Result<ResourceDynamic> {
89 ResourceDynamic::try_from_resource_any(self, store)
90 }
91
92 /// See [`Resource::try_from_resource_any`]
93 pub(crate) fn try_into_host_resource<T, D>(
94 self,
95 mut store: impl AsContextMut,
96 ) -> Result<HostResource<T, D>>
97 where
98 T: HostResourceType<D>,
99 D: PartialEq + Send + Sync + Copy + 'static,
100 {
101 let store = store.as_context_mut();
102 let mut tables = HostResourceTables::new_host(store.0);
103 let ResourceAny { idx, ty, owned } = self;
104 let ty = T::typecheck(ty).ok_or_else(|| anyhow::anyhow!("resource type mismatch"))?;
105 if owned {
106 let rep = tables.host_resource_lift_own(idx)?;
107 Ok(HostResource::new_own(rep, ty))
108 } else {
109 // For borrowed handles, first acquire the `rep` via lifting the
110 // borrow. Afterwards though remove any dynamic state associated
111 // with this borrow. `Resource<T>` doesn't participate in dynamic
112 // state tracking and it's assumed embedders know what they're
113 // doing, so the drop call will clear out that a borrow is active
114 //
115 // Note that the result of `drop` should always be `None` as it's a
116 // borrowed handle, so assert so.
117 let rep = tables.host_resource_lift_borrow(idx)?;
118 let res = tables.host_resource_drop(idx)?;
119 assert!(res.is_none());
120 Ok(HostResource::new_borrow(rep, ty))
121 }
122 }
123
124 /// Returns the corresponding type associated with this resource, either a
125 /// host-defined type or a guest-defined type.
126 ///
127 /// This can be compared against [`ResourceType::host`] for example to see
128 /// if it's a host-resource or against a type extracted with
129 /// [`Instance::get_resource`] to see if it's a guest-defined resource.
130 ///
131 /// [`Instance::get_resource`]: crate::component::Instance::get_resource
132 pub fn ty(&self) -> ResourceType {
133 self.ty
134 }
135
136 /// Returns whether this is an owned resource, and if not it's a borrowed
137 /// resource.
138 pub fn owned(&self) -> bool {
139 self.owned
140 }
141
142 /// Destroy this resource and release any state associated with it.
143 ///
144 /// This is required to be called (or the async version) for all instances
145 /// of [`ResourceAny`] to ensure that state associated with this resource is
146 /// properly cleaned up. For owned resources this may execute the
147 /// guest-defined destructor if applicable (or the host-defined destructor
148 /// if one was specified).
149 pub fn resource_drop(self, mut store: impl AsContextMut) -> Result<()> {
150 let mut store = store.as_context_mut();
151 assert!(
152 !store.0.async_support(),
153 "must use `resource_drop_async` when async support is enabled on the config"
154 );
155 self.resource_drop_impl(&mut store.as_context_mut())
156 }
157
158 /// Same as [`ResourceAny::resource_drop`] except for use with async stores
159 /// to execute the destructor asynchronously.
160 #[cfg(feature = "async")]
161 pub async fn resource_drop_async(self, mut store: impl AsContextMut<Data: Send>) -> Result<()> {
162 let mut store = store.as_context_mut();
163 assert!(
164 store.0.async_support(),
165 "cannot use `resource_drop_async` without enabling async support in the config"
166 );
167 store
168 .on_fiber(|store| self.resource_drop_impl(store))
169 .await?
170 }
171
172 fn resource_drop_impl<T: 'static>(self, store: &mut StoreContextMut<'_, T>) -> Result<()> {
173 // Attempt to remove `self.idx` from the host table in `store`.
174 //
175 // This could fail if the index is invalid or if this is removing an
176 // `Own` entry which is currently being borrowed.
177 let pair = HostResourceTables::new_host(store.0).host_resource_drop(self.idx)?;
178
179 let (rep, slot) = match (pair, self.owned) {
180 (Some(pair), true) => pair,
181
182 // A `borrow` was removed from the table and no further
183 // destruction, e.g. the destructor, is required so we're done.
184 (None, false) => return Ok(()),
185
186 _ => unreachable!(),
187 };
188
189 // Implement the reentrance check required by the canonical ABI. Note
190 // that this happens whether or not a destructor is present.
191 //
192 // Note that this should be safe because the raw pointer access in
193 // `flags` is valid due to `store` being the owner of the flags and
194 // flags are never destroyed within the store.
195 if let Some(flags) = slot.flags {
196 unsafe {
197 if !flags.may_enter() {
198 bail!(Trap::CannotEnterComponent);
199 }
200 }
201 }
202
203 let dtor = match slot.dtor {
204 Some(dtor) => dtor.as_non_null(),
205 None => return Ok(()),
206 };
207 let mut args = [ValRaw::u32(rep)];
208
209 // This should be safe because `dtor` has been checked to belong to the
210 // `store` provided which means it's valid and still alive. Additionally
211 // destructors have al been previously type-checked and are guaranteed
212 // to take one i32 argument and return no results, so the parameters
213 // here should be configured correctly.
214 unsafe { crate::Func::call_unchecked_raw(store, dtor, NonNull::from(&mut args)) }
215 }
216
217 fn lower_to_index<U>(&self, cx: &mut LowerContext<'_, U>, ty: InterfaceType) -> Result<u32> {
218 match ty {
219 InterfaceType::Own(t) => {
220 if cx.resource_type(t) != self.ty {
221 bail!("mismatched resource types");
222 }
223 let rep = cx.host_resource_lift_own(self.idx)?;
224 cx.guest_resource_lower_own(t, rep)
225 }
226 InterfaceType::Borrow(t) => {
227 if cx.resource_type(t) != self.ty {
228 bail!("mismatched resource types");
229 }
230 let rep = cx.host_resource_lift_borrow(self.idx)?;
231 cx.guest_resource_lower_borrow(t, rep)
232 }
233 _ => bad_type_info(),
234 }
235 }
236
237 fn lift_from_index(cx: &mut LiftContext<'_>, ty: InterfaceType, index: u32) -> Result<Self> {
238 match ty {
239 InterfaceType::Own(t) => {
240 let ty = cx.resource_type(t);
241 let (rep, dtor, flags) = cx.guest_resource_lift_own(t, index)?;
242 let idx = cx.host_resource_lower_own(rep, dtor, flags)?;
243 Ok(ResourceAny {
244 idx,
245 ty,
246 owned: true,
247 })
248 }
249 InterfaceType::Borrow(t) => {
250 let ty = cx.resource_type(t);
251 let rep = cx.guest_resource_lift_borrow(t, index)?;
252 let idx = cx.host_resource_lower_borrow(rep)?;
253 Ok(ResourceAny {
254 idx,
255 ty,
256 owned: false,
257 })
258 }
259 _ => bad_type_info(),
260 }
261 }
262}
263
264unsafe impl ComponentType for ResourceAny {
265 const ABI: CanonicalAbiInfo = CanonicalAbiInfo::SCALAR4;
266
267 type Lower = <u32 as ComponentType>::Lower;
268
269 fn typecheck(ty: &InterfaceType, _types: &InstanceType<'_>) -> Result<()> {
270 match ty {
271 InterfaceType::Own(_) | InterfaceType::Borrow(_) => Ok(()),
272 other => bail!("expected `own` or `borrow`, found `{}`", desc(other)),
273 }
274 }
275}
276
277unsafe impl Lower for ResourceAny {
278 fn linear_lower_to_flat<T>(
279 &self,
280 cx: &mut LowerContext<'_, T>,
281 ty: InterfaceType,
282 dst: &mut MaybeUninit<Self::Lower>,
283 ) -> Result<()> {
284 self.lower_to_index(cx, ty)?
285 .linear_lower_to_flat(cx, InterfaceType::U32, dst)
286 }
287
288 fn linear_lower_to_memory<T>(
289 &self,
290 cx: &mut LowerContext<'_, T>,
291 ty: InterfaceType,
292 offset: usize,
293 ) -> Result<()> {
294 self.lower_to_index(cx, ty)?
295 .linear_lower_to_memory(cx, InterfaceType::U32, offset)
296 }
297}
298
299unsafe impl Lift for ResourceAny {
300 fn linear_lift_from_flat(
301 cx: &mut LiftContext<'_>,
302 ty: InterfaceType,
303 src: &Self::Lower,
304 ) -> Result<Self> {
305 let index = u32::linear_lift_from_flat(cx, InterfaceType::U32, src)?;
306 ResourceAny::lift_from_index(cx, ty, index)
307 }
308
309 fn linear_lift_from_memory(
310 cx: &mut LiftContext<'_>,
311 ty: InterfaceType,
312 bytes: &[u8],
313 ) -> Result<Self> {
314 let index = u32::linear_lift_from_memory(cx, InterfaceType::U32, bytes)?;
315 ResourceAny::lift_from_index(cx, ty, index)
316 }
317}