wasmtime/runtime/gc/enabled/rooting.rs
1//! Garbage collection rooting APIs.
2//!
3//! Rooting prevents GC objects from being collected while they are actively
4//! being used.
5//!
6//! ## Goals
7//!
8//! We have a few sometimes-conflicting goals with our GC rooting APIs:
9//!
10//! 1. Safety: It should never be possible to get a use-after-free bug because
11//! the user misused the rooting APIs, the collector "mistakenly" determined
12//! an object was unreachable and collected it, and then the user tried to
13//! access the object. This is our highest priority.
14//!
15//! 2. Moving GC: Our rooting APIs should moving collectors (such as
16//! generational and compacting collectors) where an object might get
17//! relocated after a collection and we need to update the GC root's pointer
18//! to the moved object. This means we either need cooperation and internal
19//! mutability from individual GC roots as well as the ability to enumerate
20//! all GC roots on the native Rust stack, or we need a level of indirection.
21//!
22//! 3. Performance: Our rooting APIs should generally be as low-overhead as
23//! possible. They definitely shouldn't require synchronization and locking
24//! to create, access, and drop GC roots.
25//!
26//! 4. Ergonomics: Our rooting APIs should be, if not a pleasure, then at least
27//! not a burden for users. Additionally, the API's types should be `Sync`
28//! and `Send` so that they work well with async Rust.
29//!
30//! The two main design axes that trade off the above goals are:
31//!
32//! - Where the GC reference itself is held. A root object could
33//! directly hold the underlying GC reference (offset into the GC
34//! storage area), which would allow more efficient dereferencing
35//! and access to the referred-to GC object. However, goal (2)
36//! requires that the GC is able to update references when objects
37//! move during a GC. Thus, such "direct roots" would need to be
38//! registered somehow in a global root registry, and would need to
39//! unregister themselves when dropped.
40//!
41//! The alternative is to hold some indirect kind of reference to a
42//! GC reference, with the latter stored directly in the `Store` so
43//! the GC can update it freely. This adds one pointer-chasing hop
44//! to accesses, but works much more nicely with ownership
45//! semantics. Logically, the `Store` "owns" the actual pointers;
46//! and rooting types own the slots that they are stored in.
47//!
48//! For the above reasons, all of our rooting types below use
49//! indirection. This avoids the need for an unsafe
50//! intrusive-linked-list for global registration, or a shared
51//! reference to a mutex-protected registry, or some other
52//! error-prone technique.
53//!
54//! - How unrooting occurs. Ideally, a rooting type would implement
55//! the Rust `Drop` trait and unroot itself when the Rust value is
56//! dropped. However, because the rooting state is held in the
57//! `Store`, this direct approach would imply keeping a shared,
58//! mutex-protected handle to the registry in every rooting
59//! object. This would add synchronization overhead to the common
60//! case, and in general would be a bad tradeoff.
61//!
62//! However, there are several other approaches:
63//!
64//! - The user could use an RAII wrapper that *does* own the `Store`,
65//! and defines a "scope" in which roots are created and then
66//! bulk-unrooted at the close of the scope.
67//! - The rooting type could hold a shared reference to some state
68//! *other* than the full registry, and update a flag in that
69//! state indicating it has been dropped; the `Store` could then
70//! later observe that flag and remove the root. This would have
71//! some allocation cost, but the shared state would be
72//! independent of the `Store` and specific to each root, so would
73//! impose no synchronization overhead between different roots or
74//! the GC itself.
75//! - The rooting type could provide a fully manual `unroot` method,
76//! allowing the user to make use of their own knowledge of their
77//! application's lifetimes and semantics and remove roots when
78//! appropriate.
79//!
80//! We provide an implementation of the first two of these
81//! strategies below in `Rooted` and `OwnedRooted`. The last, fully
82//! manual, approach is too difficult to use correctly (it cannot
83//! implement Rust's `Drop` trait, but there is no way in Rust to
84//! enforce that a value must be consumed rather than dropped) so it
85//! is not implemented.
86//!
87//! ## Two Flavors of Rooting API
88//!
89//! Okay, with that out of the way, this module provides two flavors
90//! of rooting API. One for the common, scoped lifetime case, and one that
91//! carries ownership until dropped, and can work as an RAII handle
92//! that interacts well with Rust ownership semantics (but at a minor
93//! performance cost):
94//!
95//! 1. `RootScope` and `Rooted<T>`: These are used for temporarily rooting GC
96//! objects for the duration of a scope. The internal implementation takes
97//! advantage of the LIFO property inherent in scopes, making creating and
98//! dropping `Rooted<T>`s and `RootScope`s super fast and roughly equivalent
99//! to bump allocation.
100//!
101//! This type is vaguely similar to V8's [`HandleScope`].
102//!
103//! [`HandleScope`]: https://v8.github.io/api/head/classv8_1_1HandleScope.html
104//!
105//! Note that `Rooted<T>` can't be statically tied to its context scope via a
106//! lifetime parameter, unfortunately, as that would allow the creation of
107//! only one `Rooted<T>` at a time, since the `Rooted<T>` would take a borrow
108//! of the whole context.
109//!
110//! This supports the common use case for rooting and provides good
111//! ergonomics.
112//!
113//! 2. `OwnedRooted<T>`: This is a root that manages rooting and
114//! unrooting automatically with its lifetime as a Rust value. In
115//! other words, the continued existence of the Rust value ensures
116//! the rooting of the underlying GC reference; and when the Rust
117//! value is dropped, the underlying GC reference is no longer
118//! rooted.
119//!
120//! Internally, this root holds a shared reference to a
121//! *root-specific* bit of state that is also tracked and observed
122//! by the `Store`. This means that there is minor memory
123//! allocation overhead (an `Arc<()>`) for each such root; this
124//! memory is shared over all clones of this root. The rooted GC
125//! reference is *logically* unrooted as soon as the last clone of
126//! this root is dropped. Internally the root may still exist until
127//! the next GC, or "root trim" when another `OwnedRooted` is
128//! created, but that is unobservable externally, and will not
129//! result in any additional GC object lifetime because it is
130//! always cleaned up before a gc.
131//!
132//! This type is roughly similar to SpiderMonkey's [`PersistentRooted<T>`],
133//! although they register roots on a per-thread `JSContext`, avoiding
134//! mutation costs in a way that is not viable for Wasmtime (which needs
135//! `Store`s to be `Send`).
136//!
137//! [`PersistentRooted<T>`]: http://devdoc.net/web/developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS::PersistentRooted.html
138//!
139//! At the end of the day, all of the above root types are just tagged
140//! indices into the store's `RootSet`. This indirection allows
141//! working with Rust's borrowing discipline (we use `&mut Store` to
142//! represent mutable access to the GC heap) while still allowing
143//! rooted references to be moved around without tying up the whole
144//! store in borrows. Additionally, and crucially, this indirection
145//! allows us to update the *actual* GC pointers in the `RootSet` and
146//! support moving GCs (again, as mentioned above).
147//!
148//! ## Unrooted References
149//!
150//! We generally don't expose *unrooted* GC references in the Wasmtime API at
151//! this time -- and I expect it will be a very long time before we do, but in
152//! the limit we may want to let users define their own GC-managed types that
153//! participate in GC tracing and all that -- so we don't have to worry about
154//! failure to root an object causing use-after-free bugs or failing to update a
155//! GC root pointer after a moving GC as long as users stick to our safe rooting
156//! APIs. (The one exception is `ValRaw`, which does hold raw GC references. But
157//! with `ValRaw` all bets are off and safety is 100% up to the user.)
158//!
159//! We do, however, have to worry about these things internally. So first of
160//! all, try to avoid ever working with unrooted GC references if you
161//! can. However, if you really must, consider also using an `AutoAssertNoGc`
162//! across the block of code that is manipulating raw GC references.
163
164use crate::runtime::vm::{GcRootsList, GcStore, VMGcRef};
165use crate::{
166 AsContext, AsContextMut, GcRef, Result, RootedGcRef,
167 error::OutOfMemory,
168 store::{AsStoreOpaque, AutoAssertNoGc, StoreId, StoreOpaque},
169};
170use crate::{ValRaw, prelude::*};
171use alloc::sync::{Arc, Weak};
172use core::any;
173use core::marker;
174use core::mem::{self, MaybeUninit};
175use core::num::{NonZeroU32, NonZeroU64, NonZeroUsize};
176use core::{
177 fmt::{self, Debug},
178 hash::{Hash, Hasher},
179 ops::{Deref, DerefMut},
180};
181use wasmtime_core::slab::{Id as SlabId, Slab};
182
183mod sealed {
184 use super::*;
185
186 /// Sealed, `wasmtime`-internal trait for GC references.
187 ///
188 /// # Safety
189 ///
190 /// All types implementing this trait must:
191 ///
192 /// * Be a newtype of a `GcRootIndex`
193 ///
194 /// * Not implement `Copy` or `Clone`
195 ///
196 /// * Only have `&self` methods.
197 pub unsafe trait GcRefImpl: Sized {
198 /// Transmute a `&GcRootIndex` into an `&Self`.
199 fn transmute_ref(index: &GcRootIndex) -> &Self;
200 }
201
202 /// Sealed, `wasmtime`-internal trait for the common methods on rooted GC
203 /// references.
204 pub trait RootedGcRefImpl<T: GcRef> {
205 /// Get this rooted GC reference's raw `VMGcRef` out of the store's GC
206 /// root set.
207 ///
208 /// Returns `None` for objects that have since been unrooted (eg because
209 /// its associated `RootedScope` was dropped).
210 ///
211 /// Panics if this root is not associated with the given store.
212 fn get_gc_ref<'a>(&self, store: &'a StoreOpaque) -> Option<&'a VMGcRef>;
213
214 /// Same as `get_gc_ref` but returns an error instead of `None` for
215 /// objects that have been unrooted.
216 fn try_gc_ref<'a>(&self, store: &'a StoreOpaque) -> Result<&'a VMGcRef> {
217 self.get_gc_ref(store).ok_or_else(|| {
218 format_err!("attempted to use a garbage-collected object that has been unrooted")
219 })
220 }
221
222 /// Get a clone of this rooted GC reference's raw `VMGcRef` out of the
223 /// store's GC root set.
224 ///
225 /// Returns `None` for objects that have since been unrooted (eg because
226 /// its associated `RootedScope` was dropped).
227 ///
228 /// Panics if this root is not associated with the given store.
229 fn clone_gc_ref(&self, store: &mut AutoAssertNoGc<'_>) -> Option<VMGcRef> {
230 let gc_ref = self.get_gc_ref(store)?.unchecked_copy();
231 Some(store.clone_gc_ref(&gc_ref))
232 }
233
234 /// Same as `clone_gc_ref` but returns an error instead of `None` for
235 /// objects that have been unrooted.
236 fn try_clone_gc_ref(&self, store: &mut AutoAssertNoGc<'_>) -> Result<VMGcRef> {
237 let gc_ref = self.try_gc_ref(store)?.unchecked_copy();
238 Ok(store.clone_gc_ref(&gc_ref))
239 }
240 }
241}
242pub(crate) use sealed::*;
243
244/// The index of a GC root inside a particular store's GC root set.
245///
246/// Can be either a LIFO- or owned-rooted object, depending on the
247/// `PackedIndex`.
248///
249/// Every `T` such that `T: GcRef` must be a newtype over this `GcRootIndex`.
250#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
251// Just `pub` to avoid `warn(private_interfaces)` in public APIs, which we can't
252// `allow(...)` on our MSRV yet.
253#[doc(hidden)]
254#[repr(C)] // NB: if this layout changes be sure to change the C API as well
255pub struct GcRootIndex {
256 store_id: StoreId,
257 generation: u32,
258 index: PackedIndex,
259}
260
261const _: () = {
262 // NB: these match the C API which should also be updated if this changes
263 assert!(mem::size_of::<GcRootIndex>() == 16);
264 assert!(mem::align_of::<GcRootIndex>() == mem::align_of::<u64>());
265};
266
267impl GcRootIndex {
268 #[inline]
269 pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
270 self.store_id == store.id()
271 }
272
273 /// Same as `RootedGcRefImpl::get_gc_ref` but not associated with any
274 /// particular `T: GcRef`.
275 ///
276 /// We must avoid triggering a GC while holding onto the resulting raw
277 /// `VMGcRef` to avoid use-after-free bugs and similar. The `'a` lifetime
278 /// threaded from the `store` to the result will normally prevent GCs
279 /// statically, at compile time, since performing a GC requires a mutable
280 /// borrow of the store. However, if you call `VMGcRef::unchecked_copy` on
281 /// the resulting GC reference, then all bets are off and this invariant is
282 /// up to you to manually uphold. Failure to uphold this invariant is memory
283 /// safe but will lead to general incorrectness such as panics and wrong
284 /// results.
285 ///
286 /// # Panics
287 ///
288 /// Panics if `self` is not associated with the given store.
289 pub(crate) fn get_gc_ref<'a>(&self, store: &'a StoreOpaque) -> Option<&'a VMGcRef> {
290 assert!(
291 self.comes_from_same_store(store),
292 "object used with wrong store"
293 );
294 if let Some(index) = self.index.as_lifo() {
295 let entry = store.gc_roots().lifo_roots.get(index)?;
296 if entry.generation == self.generation {
297 Some(&entry.gc_ref)
298 } else {
299 None
300 }
301 } else if let Some(id) = self.index.as_owned() {
302 let gc_ref = store.gc_roots().owned_rooted.get(id);
303 debug_assert!(gc_ref.is_some());
304 gc_ref
305 } else {
306 unreachable!()
307 }
308 }
309
310 /// Same as `get_gc_ref` but returns an error instead of `None` if
311 /// the GC reference has been unrooted.
312 ///
313 /// # Panics
314 ///
315 /// Panics if `self` is not associated with the given store.
316 pub(crate) fn try_gc_ref<'a>(&self, store: &'a StoreOpaque) -> Result<&'a VMGcRef> {
317 self.get_gc_ref(store).ok_or_else(|| {
318 format_err!("attempted to use a garbage-collected object that has been unrooted")
319 })
320 }
321
322 /// Same as `RootedGcRefImpl::clone_gc_ref` but not associated with any
323 /// particular `T: GcRef`.
324 pub(crate) fn try_clone_gc_ref(&self, store: &mut AutoAssertNoGc<'_>) -> Result<VMGcRef> {
325 let gc_ref = self.try_gc_ref(store)?.unchecked_copy();
326 Ok(store.clone_gc_ref(&gc_ref))
327 }
328
329 /// Exposes this value's raw `VMGcRef` to wasm as a `u32`.
330 pub(crate) fn expose_gc_ref_to_wasm(
331 &self,
332 store: &mut AutoAssertNoGc<'_>,
333 ) -> Result<NonZeroU32> {
334 let gc_ref = self.try_clone_gc_ref(store)?;
335
336 let raw = match store.optional_gc_store_mut() {
337 Some(s) => s.expose_gc_ref_to_wasm(gc_ref)?,
338 None => {
339 // NB: do not force the allocation of a GC heap just because the
340 // program is using `i31ref`s.
341 debug_assert!(gc_ref.is_i31());
342 gc_ref.as_raw_non_zero_u32()
343 }
344 };
345
346 Ok(raw)
347 }
348}
349
350/// This is a bit-packed version of
351///
352/// ```ignore
353/// enum {
354/// Lifo(usize),
355/// Owned(SlabId),
356/// }
357/// ```
358///
359/// where the high bit is the discriminant and the lower 31 bits are the
360/// payload.
361#[derive(Clone, Copy, PartialEq, Eq, Hash)]
362#[repr(transparent)]
363struct PackedIndex(u32);
364
365impl Debug for PackedIndex {
366 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367 if let Some(index) = self.as_lifo() {
368 f.debug_tuple("PackedIndex::Lifo").field(&index).finish()
369 } else if let Some(id) = self.as_owned() {
370 f.debug_tuple("PackedIndex::Owned").field(&id).finish()
371 } else {
372 unreachable!()
373 }
374 }
375}
376
377impl PackedIndex {
378 const DISCRIMINANT_MASK: u32 = 0b1 << 31;
379 const LIFO_DISCRIMINANT: u32 = 0b0 << 31;
380 const OWNED_DISCRIMINANT: u32 = 0b1 << 31;
381 const PAYLOAD_MASK: u32 = !Self::DISCRIMINANT_MASK;
382
383 fn new_lifo(index: usize) -> PackedIndex {
384 let index32 = u32::try_from(index).unwrap();
385 assert_eq!(index32 & Self::DISCRIMINANT_MASK, 0);
386 let packed = PackedIndex(Self::LIFO_DISCRIMINANT | index32);
387 debug_assert!(packed.is_lifo());
388 debug_assert_eq!(packed.as_lifo(), Some(index));
389 debug_assert!(!packed.is_owned());
390 debug_assert!(packed.as_owned().is_none());
391 packed
392 }
393
394 fn new_owned(id: SlabId) -> PackedIndex {
395 let raw = id.into_raw();
396 assert_eq!(raw & Self::DISCRIMINANT_MASK, 0);
397 let packed = PackedIndex(Self::OWNED_DISCRIMINANT | raw);
398 debug_assert!(packed.is_owned());
399 debug_assert_eq!(packed.as_owned(), Some(id));
400 debug_assert!(!packed.is_lifo());
401 debug_assert!(packed.as_lifo().is_none());
402 packed
403 }
404
405 fn discriminant(&self) -> u32 {
406 self.0 & Self::DISCRIMINANT_MASK
407 }
408
409 fn is_lifo(&self) -> bool {
410 self.discriminant() == Self::LIFO_DISCRIMINANT
411 }
412
413 fn is_owned(&self) -> bool {
414 self.discriminant() == Self::OWNED_DISCRIMINANT
415 }
416
417 fn payload(&self) -> u32 {
418 self.0 & Self::PAYLOAD_MASK
419 }
420
421 fn as_lifo(&self) -> Option<usize> {
422 if self.is_lifo() {
423 Some(usize::try_from(self.payload()).unwrap())
424 } else {
425 None
426 }
427 }
428
429 fn as_owned(&self) -> Option<SlabId> {
430 if self.is_owned() {
431 Some(SlabId::try_from_raw(self.payload()).unwrap())
432 } else {
433 None
434 }
435 }
436}
437
438/// The set of all embedder-API GC roots in a single store/heap.
439#[derive(Debug, Default)]
440pub(crate) struct RootSet {
441 /// GC roots with arbitrary lifetime that are unrooted when
442 /// liveness flags are cleared (seen during a trimming pass), for
443 /// use with `OwnedRooted<T>`.
444 owned_rooted: Slab<VMGcRef>,
445
446 /// List of liveness flags and corresponding `SlabId`s into the
447 /// `owned_rooted` slab.
448 liveness_flags: Vec<(Weak<()>, SlabId)>,
449
450 /// High-water mark for liveness flag trimming. We use this to
451 /// ensure we have amortized constant-time behavior on adding
452 /// roots. See note below on `trim_liveness_flags()`.
453 liveness_trim_high_water: Option<NonZeroUsize>,
454
455 /// Strictly LIFO-ordered GC roots, for use with `RootScope` and
456 /// `Rooted<T>`.
457 lifo_roots: Vec<LifoRoot>,
458
459 /// Generation counter for entries to prevent ABA bugs with `RootScope` and
460 /// `Rooted<T>`.
461 lifo_generation: u32,
462}
463
464#[derive(Debug)]
465struct LifoRoot {
466 generation: u32,
467 gc_ref: VMGcRef,
468}
469
470impl RootSet {
471 pub(crate) fn trace_roots(&mut self, gc_roots_list: &mut GcRootsList) {
472 log::trace!("Begin trace user LIFO roots");
473 for root in &mut self.lifo_roots {
474 unsafe {
475 gc_roots_list.add_vmgcref_root((&mut root.gc_ref).into(), "user LIFO root");
476 }
477 }
478 log::trace!("End trace user LIFO roots");
479
480 log::trace!("Begin trace user owned roots");
481 for (_id, root) in self.owned_rooted.iter_mut() {
482 unsafe {
483 gc_roots_list.add_vmgcref_root(root.into(), "user owned root");
484 }
485 }
486 log::trace!("End trace user owned roots");
487 }
488
489 /// Enter a LIFO rooting scope.
490 ///
491 /// Returns an integer that should be passed unmodified to `exit_lifo_scope`
492 /// when the scope is finished.
493 ///
494 /// Calls to `{enter,exit}_lifo_scope` must happen in a strict LIFO order.
495 #[inline]
496 pub(crate) fn enter_lifo_scope(&self) -> usize {
497 self.lifo_roots.len()
498 }
499
500 /// Exit a LIFO rooting scope.
501 ///
502 /// The `scope` argument must be the result of the corresponding
503 /// `enter_lifo_scope` call.
504 ///
505 /// Calls to `{enter,exit}_lifo_scope` must happen in a strict LIFO order.
506 #[inline]
507 pub(crate) fn exit_lifo_scope(&mut self, gc_store: Option<&mut GcStore>, scope: usize) {
508 debug_assert!(self.lifo_roots.len() >= scope);
509
510 // If we actually have roots to unroot, call an out-of-line slow path.
511 if self.lifo_roots.len() > scope {
512 self.exit_lifo_scope_slow(gc_store, scope);
513 }
514 }
515
516 #[inline(never)]
517 #[cold]
518 fn exit_lifo_scope_slow(&mut self, mut gc_store: Option<&mut GcStore>, scope: usize) {
519 // Note that this explicitly uses `wrapping_add` to avoid panicking on
520 // overflow. This is intended to assist with the lifetime issues on the
521 // host but is not required for memory safety, so in the event of a
522 // wraparound it may mean that preexisting issues on the host go
523 // undetected.
524 self.lifo_generation = self.lifo_generation.wrapping_add(1);
525
526 // TODO: In the case where we have a tracing GC that doesn't need to
527 // drop barriers, this should really be:
528 //
529 // self.lifo_roots.truncate(scope);
530
531 let mut lifo_roots = mem::take(&mut self.lifo_roots);
532 for root in lifo_roots.drain(scope..) {
533 // Only drop the GC reference if we actually have a GC store. How
534 // can we have a GC reference but not a GC store? If we've only
535 // created `i31refs`, we never force a GC store's allocation. This
536 // is fine because `i31ref`s never need drop barriers.
537 if let Some(gc_store) = &mut gc_store {
538 gc_store.drop_gc_ref(root.gc_ref);
539 }
540 }
541 self.lifo_roots = lifo_roots;
542 }
543
544 pub(crate) fn with_lifo_scope<S, T>(store: &mut S, f: impl FnOnce(&mut S) -> T) -> T
545 where
546 S: ?Sized + DerefMut<Target = StoreOpaque>,
547 {
548 let scope = store.gc_roots().enter_lifo_scope();
549 let ret = f(store);
550 store.exit_gc_lifo_scope(scope);
551 ret
552 }
553
554 pub(crate) fn push_lifo_root(&mut self, store_id: StoreId, gc_ref: VMGcRef) -> GcRootIndex {
555 let generation = self.lifo_generation;
556 let index = self.lifo_roots.len();
557 let index = PackedIndex::new_lifo(index);
558 self.lifo_roots.push(LifoRoot { generation, gc_ref });
559 GcRootIndex {
560 store_id,
561 generation,
562 index,
563 }
564 }
565
566 /// Trim any stale (dropped) owned roots.
567 ///
568 /// `OwnedRooted` is implemented in a way that avoids the need to
569 /// have or keep a reference to the store (and thus this struct)
570 /// during its drop operation: to allow it to be independent, it
571 /// holds a shared reference to some other memory and sets that
572 /// "liveness flag" appropriately, then we later observe dead
573 /// liveness flags during a periodic scan and actually deallocate
574 /// the roots. We use an `Arc<()>` for this: it permits cheap
575 /// cloning, and it has minimal memory overhead. We hold a weak
576 /// ref in a list alongside the actual `GcRootIndex`, and we free
577 /// that index in the slab of owned roots when we observe that
578 /// only our weak ref remains.
579 ///
580 /// This trim step is logically separate from a full GC, though it
581 /// would not be very productive to do a GC without doing a
582 /// root-trim first: the root-trim should be quite a lot cheaper,
583 /// and it will allow for more garbage to exist.
584 ///
585 /// There is, additionally, nothing stopping us from doing trims
586 /// more often than just before each GC, and there are reasons
587 /// this could be a good idea: for example, a user program that
588 /// creates and removes many roots (perhaps as it accesses the GC
589 /// object graph) but ultimately is dealing with a static graph,
590 /// without further allocation, may need the "root set" to be GC'd
591 /// independently from the actual heap. Thus, we could trim before
592 /// adding a new root to ensure we don't grow that unboundedly (or
593 /// force an otherwise unneeded GC).
594 ///
595 /// The first case, just before GC, wants a "full trim": there's
596 /// no reason not to unroot as much as possible before we do the
597 /// expensive work of tracing the whole heap.
598 ///
599 /// On the other hand, the second case, adding a new root, wants a
600 /// kind of trim that is amortized constant time. Consider: if we
601 /// have some threshold for the trim, say N roots, and the user
602 /// program continually adds and removes one root such that it
603 /// goes just over the threshold, we might scan all N liveness
604 /// flags for each step, resulting in quadratic behavior overall.
605 ///
606 /// Thus, we implement a "high water mark" algorithm to guard
607 /// against this latter case: on the add-a-new-root case, we trim
608 /// only if the list is longer than the high water mark, and we
609 /// set the high water mark each time based on the after-trim
610 /// size. See below for details on this algorithm.
611 ///
612 /// `eager` chooses whether we eagerly trim roots or pre-filter
613 /// using the high-water mark.
614 ///
615 /// # Growth Algorithm
616 ///
617 /// We want to balance two factors: we must ensure that the
618 /// algorithmic complexity of creating a new root is amortized
619 /// O(1), and we must ensure that repeated creation and deletion
620 /// of roots without any GC must result in a root-set that has a
621 /// size linear in the actual live-root-set size. Stated formally:
622 ///
623 /// 1. Root creation must be O(1), amortized
624 /// 2. liveness_flags.len() must be O(|max live owned roots|),
625 /// i.e., must not grow to larger than a constant multiple of
626 /// the maximum working-root-set size of the program.
627 ///
628 /// Note that a naive exponential-growth-of-threshold algorithm,
629 /// where we trim when the root set reaches 1, 2, 4, 8, 16, 32,
630 /// ... elements, provides the first but *not* the second
631 /// property. A workload that has a constant live root set but
632 /// creates and drops roots constantly (say, as it's traversing a
633 /// static graph and moving "fingers" through it) will cause the
634 /// `liveness_flags` array to grow unboundedly.
635 ///
636 /// Instead, it turns out that we can achieve both of these goals
637 /// with a simple rule: we trim when the root list length reaches
638 /// a high-water mark; and then *after* trimming, we set the
639 /// high-water mark equal to the resulting live-root count
640 /// multiplied by a factor (e.g., 2).
641 ///
642 /// ## Proof
643 ///
644 /// - Root creation is O(1)
645 ///
646 /// Assume a sequence of root creation and drop events (and no
647 /// GCs, with a static GC graph, in the worst case -- only roots
648 /// are changing). We want to show that after N root creations,
649 /// we have incurred only only O(N) cost scanning the
650 /// `liveness_flags` list over the whole sequence.
651 ///
652 /// Assume a default high-water mark of D (e.g., 8) at
653 /// initialization with an empty root list.
654 ///
655 /// Consider "epochs" in the sequence split by trim events where
656 /// we scan the root list. Proceed by induction over epochs to
657 /// show: after each epoch, we will have scanned at most 2N
658 /// roots after N root creations.
659 ///
660 /// (These epochs don't exist in the algorithm: this is just a
661 /// mechanism to analyze the behavior.)
662 ///
663 /// Base case: after the first epoch, with D root creations, we
664 /// will scan D roots.
665 ///
666 /// Induction step: we have created N roots and scanned at most
667 /// 2N roots. After previous scan, L roots are still live; then
668 /// we set the high-water mark for next scan at 2L. The list
669 /// already has L, so after another L root creations, the epoch
670 /// ends. We will then incur a scan cost of 2L (the full
671 /// list). At that point we have thus seen N + L root creations,
672 /// with 2N + 2L scan cost; the invariant holds.
673 ///
674 /// (It's counter-intuitive that *not* raising the high-water
675 /// mark exponentially can still result in a constant amortized
676 /// cost! One intuition to understand this is that each root
677 /// that remains alive after a scan pushes the next high-water
678 /// mark up by one, so requires a new root creation to "pay for"
679 /// its next scan. So any given root may be scanned many times,
680 /// but each such root ensures other root creations happen to
681 /// maintain the amortized cost.)
682 ///
683 /// - `liveness_flags.len()` is always O(|max live roots|)
684 ///
685 /// Before the first trim, we have between 0 and D live roots,
686 /// which is O(1) (`D` is a compile-time constant).
687 ///
688 /// Just after a trim, the `liveness_flags` list has only live
689 /// roots, and the max live-root count is at least the count at
690 /// this time, so the property holds.
691 ///
692 /// The instantaneous maximum number of live roots is greater
693 /// than or equal to the maximum number of live roots observed
694 /// during a trim. (The trim is just some point in time, and the
695 /// max at some point in time is at most the overall max.)
696 ///
697 /// The high-water mark is set at 2 * `liveness_flags.len()`
698 /// after a trim, i.e., the number of live roots at that
699 /// time. We trim when we reach the high-water mark. So the
700 /// length of the array cannot exceed 2 *
701 /// `liveness_flags.len()`, which is less than or equal to the
702 /// overall max. So transitively, the list length at any time is
703 /// always O(|max live roots|).
704 ///
705 /// We thus have tight bounds (deterministic, not randomized) for
706 /// all possible sequences of root creation/dropping, ensuring
707 /// robustness.
708 pub(crate) fn trim_liveness_flags(&mut self, gc_store: &mut GcStore, eager: bool) {
709 const DEFAULT_HIGH_WATER: usize = 8;
710 const GROWTH_FACTOR: usize = 2;
711 let high_water_mark = self
712 .liveness_trim_high_water
713 .map(|x| x.get())
714 .unwrap_or(DEFAULT_HIGH_WATER);
715 if !eager && self.liveness_flags.len() < high_water_mark {
716 return;
717 }
718
719 self.liveness_flags.retain(|(flag, index)| {
720 if flag.strong_count() == 0 {
721 // No more `OwnedRooted` instances are holding onto
722 // this; dealloc the index and drop our Weak.
723 let gc_ref = self.owned_rooted.dealloc(*index);
724 gc_store.drop_gc_ref(gc_ref);
725 // Don't retain in the list.
726 false
727 } else {
728 // Retain in the list.
729 true
730 }
731 });
732
733 let post_trim_len = self.liveness_flags.len();
734 let high_water_mark = core::cmp::max(
735 DEFAULT_HIGH_WATER,
736 post_trim_len.saturating_mul(GROWTH_FACTOR),
737 );
738 self.liveness_trim_high_water = Some(NonZeroUsize::new(high_water_mark).unwrap());
739 }
740}
741
742/// A scoped, rooted reference to a garbage-collected `T`.
743///
744/// A `Rooted<T>` is a strong handle to a garbage-collected `T`, preventing its
745/// referent (and anything else transitively referenced) from being collected by
746/// the GC during the scope within which this `Rooted<T>` was created.
747///
748/// When the context exits this `Rooted<T>`'s scope, the underlying GC object is
749/// automatically unrooted and any further attempts to use access the underlying
750/// object will return errors or otherwise fail.
751///
752/// `Rooted<T>` dereferences to its underlying `T`, allowing you to call `T`'s
753/// methods.
754///
755/// # Example
756///
757/// ```
758/// # use wasmtime::*;
759/// # fn _foo() -> Result<()> {
760/// let mut store = Store::<()>::default();
761///
762/// // Allocating a GC object returns a `Rooted<T>`.
763/// let hello: Rooted<ExternRef> = ExternRef::new(&mut store, "hello")?;
764///
765/// // Because `Rooted<T>` derefs to `T`, we can call `T` methods on a
766/// // `Rooted<T>`. For example, we can call the `ExternRef::data` method when we
767/// // have a `Rooted<ExternRef>`.
768/// let data = hello
769/// .data(&store)?
770/// .ok_or_else(|| Error::msg("externref has no host data"))?
771/// .downcast_ref::<&str>()
772/// .ok_or_else(|| Error::msg("not a str"))?;
773/// assert_eq!(*data, "hello");
774///
775/// // A `Rooted<T>` roots its underlying GC object for the duration of the
776/// // scope of the store/caller/context that was passed to the method that created
777/// // it. If we only want to keep a GC reference rooted and alive temporarily, we
778/// // can introduce new scopes with `RootScope`.
779/// {
780/// let mut scope = RootScope::new(&mut store);
781///
782/// // This `Rooted<T>` is automatically unrooted after `scope` is dropped,
783/// // allowing the collector to reclaim its GC object in the next GC.
784/// let scoped_ref = ExternRef::new(&mut scope, "goodbye");
785/// }
786///
787/// let module = Module::new(store.engine(), r#"
788/// (module
789/// (global (export "global") (mut externref) (ref.null extern))
790/// (table (export "table") 10 externref)
791/// (func (export "func") (param externref) (result externref)
792/// local.get 0
793/// )
794/// )
795/// "#)?;
796/// let instance = Instance::new(&mut store, &module, &[])?;
797///
798/// // GC references returned from calls into Wasm also return (optional, if the
799/// // Wasm type is nullable) `Rooted<T>`s.
800/// let result: Option<Rooted<_>> = instance
801/// .get_typed_func::<Option<Rooted<ExternRef>>, Option<Rooted<ExternRef>>>(&mut store, "func")?
802/// .call(&mut store, Some(hello))?;
803///
804/// // Getting a GC reference from a Wasm instance's exported global or table
805/// // yields an unrooted reference, which we can choose to root as a `Rooted<T>`.
806///
807/// let global = instance
808/// .get_global(&mut store, "global")
809/// .ok_or_else(|| Error::msg("missing `global` export"))?;
810/// let global_val = global.get(&mut store);
811/// let global_ref: Option<Rooted<_>> = global_val
812/// .externref()
813/// .ok_or_else(|| Error::msg("not an externref"))?
814/// .map(|r| r.to_rooted(&mut store))
815/// .transpose()?;
816///
817/// let table = instance.get_table(&mut store, "table").unwrap();
818/// let table_elem = table
819/// .get(&mut store, 3)
820/// .ok_or_else(|| Error::msg("table out of bounds"))?;
821/// let table_elem_ref: Option<Rooted<_>> = table_elem
822/// .as_extern()
823/// .ok_or_else(|| Error::msg("not an externref"))?
824/// .map(|r| r.to_rooted(&mut store))
825/// .transpose()?;
826/// # Ok(())
827/// # }
828/// ```
829///
830/// # Differences Between `Rooted<T>` and `OwnedRooted<T>`
831///
832/// While `Rooted<T>` is automatically unrooted when its scope is
833/// exited, this means that `Rooted<T>` is only valid for strictly
834/// last-in-first-out (LIFO, aka stack order) lifetimes. This is in
835/// contrast to [`OwnedRooted<T>`][crate::OwnedRooted], which supports
836/// rooting GC objects for arbitrary lifetimes.
837///
838/// | Type | Supported Lifetimes | Unrooting | Cost |
839/// |----------------------------------------------|-----------------------------|-----------|----------------------------------|
840/// | [`Rooted<T>`][crate::Rooted] | Strictly LIFO / stack order | Automatic | very low (LIFO array) |
841/// | [`OwnedRooted<T>`][crate::OwnedRooted] | Arbitrary | Automatic | medium (separate `Arc` to track) |
842///
843/// `Rooted<T>` should suffice for most use cases, and provides decent
844/// ergonomics. In cases where LIFO scopes are difficult to reason
845/// about, e.g. heap-managed data structures, or when they may cause
846/// erroneous behavior, e.g. in errors that are propagated up the call
847/// stack, `OwnedRooted<T>` provides very safe ergonomics but at a
848/// small dynamic cost for the separate tracking allocation.
849///
850/// # Scopes
851///
852/// Wasmtime automatically creates two kinds of scopes:
853///
854/// 1. A [`Store`][crate::Store] is the outermost rooting scope. Creating a
855/// `Root<T>` directly inside a `Store` permanently roots the underlying
856/// object.
857///
858/// 2. A [`Caller`][crate::Caller] provides a rooting scope for the duration of
859/// a call from Wasm into a host function. Any objects rooted in a `Caller`
860/// will be unrooted after the host function returns. Note that there can be
861/// nested `Caller` scopes in the case where Wasm calls a host function,
862/// creating the first `Caller` and its rooting scope , and then the host
863/// function calls a Wasm function which then calls another host function,
864/// creating a second `Caller` and a second rooting scope. This nesting can
865/// be arbitrarily deep.
866///
867/// Additionally, if you would like to define finer-grained rooting scopes,
868/// Wasmtime provides the [`RootScope`][crate::RootScope] type.
869///
870/// Scopes are always nested in a last-in-first-out (LIFO) order. An outer scope
871/// is never exited (and the `Rooted<T>`s defined within it are never
872/// automatically unrooted) while an inner scope is still active. All inner
873/// scopes are exited before their outer scopes.
874///
875/// The following diagram illustrates various rooting scopes over time, how they
876/// nest, and when their `Rooted<T>`s are automatically unrooted:
877///
878/// ```text
879/// ----- new Store
880/// |
881/// |
882/// | let a: Rooted<T> = ...;
883/// |
884/// |
885/// | ----- call into Wasm
886/// | |
887/// | |
888/// | | ----- Wasm calls host function F
889/// | | |
890/// | | |
891/// | | | let b: Rooted<T> = ...;
892/// | | |
893/// | | |
894/// | | | ----- F calls into Wasm
895/// | | | |
896/// | | | |
897/// | | | | ----- Wasm call host function G
898/// | | | | |
899/// | | | | |
900/// | | | | | let c: Rooted<T> = ...;
901/// | | | | |
902/// | | | | |
903/// | | | | ----- return to Wasm from host function G (unroots `c`)
904/// | | | |
905/// | | | |
906/// | | | ----- Wasm returns to F
907/// | | |
908/// | | |
909/// | | ----- return from host function F (unroots `b`)
910/// | |
911/// | |
912/// | ----- return from Wasm
913/// |
914/// |
915/// | ----- let scope1 = RootScope::new(...);
916/// | |
917/// | |
918/// | | let d: Rooted<T> = ...;
919/// | |
920/// | |
921/// | | ----- let scope2 = RootScope::new(...);
922/// | | |
923/// | | |
924/// | | | let e: Rooted<T> = ...;
925/// | | |
926/// | | |
927/// | | ----- drop `scope2` (unroots `e`)
928/// | |
929/// | |
930/// | ----- drop `scope1` (unroots `d`)
931/// |
932/// |
933/// ----- drop Store (unroots `a`)
934/// ```
935///
936/// A `Rooted<T>` can be used successfully as long as it is still rooted so, in
937/// the above diagram, `d` is valid inside `scope2` because `scope2` is wholly
938/// contained within the scope `d` was rooted within (`scope1`).
939///
940/// See also the documentation for [`RootScope`][crate::RootScope].
941#[repr(transparent)]
942pub struct Rooted<T: GcRef> {
943 inner: GcRootIndex,
944 _phantom: marker::PhantomData<T>,
945}
946
947impl<T: GcRef> Clone for Rooted<T> {
948 fn clone(&self) -> Self {
949 Rooted {
950 inner: self.inner,
951 _phantom: marker::PhantomData,
952 }
953 }
954}
955
956impl<T: GcRef> Copy for Rooted<T> {}
957
958impl<T: GcRef> Debug for Rooted<T> {
959 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
960 let name = format!("Rooted<{}>", any::type_name::<T>());
961 f.debug_struct(&name).field("inner", &self.inner).finish()
962 }
963}
964
965impl<T: GcRef> RootedGcRefImpl<T> for Rooted<T> {
966 fn get_gc_ref<'a>(&self, store: &'a StoreOpaque) -> Option<&'a VMGcRef> {
967 assert!(
968 self.comes_from_same_store(store),
969 "object used with wrong store"
970 );
971 let index = self.inner.index.as_lifo().unwrap();
972 let entry = store.gc_roots().lifo_roots.get(index)?;
973 if entry.generation == self.inner.generation {
974 Some(&entry.gc_ref)
975 } else {
976 None
977 }
978 }
979}
980
981impl<T: GcRef> Deref for Rooted<T> {
982 type Target = T;
983
984 fn deref(&self) -> &Self::Target {
985 T::transmute_ref(&self.inner)
986 }
987}
988
989impl<T: GcRef> Rooted<T> {
990 /// Push the given `VMGcRef` onto our LIFO root set.
991 ///
992 /// `gc_ref` should belong to `store`'s heap; failure to uphold this is
993 /// memory safe but will result in general failures down the line such as
994 /// panics or incorrect results.
995 ///
996 /// `gc_ref` should be a GC reference pointing to an instance of the GC type
997 /// that `T` represents. Failure to uphold this invariant is memory safe but
998 /// will result in general incorrectness such as panics and wrong results.
999 pub(crate) fn new(store: &mut AutoAssertNoGc<'_>, gc_ref: VMGcRef) -> Rooted<T> {
1000 let id = store.id();
1001 let roots = store.gc_roots_mut();
1002 let inner = roots.push_lifo_root(id, gc_ref);
1003 Rooted {
1004 inner,
1005 _phantom: marker::PhantomData,
1006 }
1007 }
1008
1009 /// Create a new `Rooted<T>` from a `GcRootIndex`.
1010 ///
1011 /// Note that `Rooted::from_gc_root_index(my_rooted.index)` is not
1012 /// necessarily an identity function, as it allows changing the `T` type
1013 /// parameter.
1014 ///
1015 /// The given index should be a LIFO index of a GC reference pointing to an
1016 /// instance of the GC type that `T` represents. Failure to uphold this
1017 /// invariant is memory safe but will result in general incorrectness such
1018 /// as panics and wrong results.
1019 pub(crate) fn from_gc_root_index(inner: GcRootIndex) -> Rooted<T> {
1020 debug_assert!(inner.index.is_lifo());
1021 Rooted {
1022 inner,
1023 _phantom: marker::PhantomData,
1024 }
1025 }
1026
1027 #[inline]
1028 pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
1029 debug_assert!(self.inner.index.is_lifo());
1030 self.inner.comes_from_same_store(store)
1031 }
1032
1033 /// Create an [`OwnedRooted<T>`][crate::OwnedRooted] holding onto the
1034 /// same GC object as `self`.
1035 ///
1036 /// Returns `None` if `self` is used outside of its scope and has therefore
1037 /// been unrooted.
1038 ///
1039 /// This does not unroot `self`, and `self` remains valid until its
1040 /// associated scope is exited.
1041 ///
1042 /// # Panics
1043 ///
1044 /// Panics if this object is not associate with the given store.
1045 ///
1046 /// # Example
1047 ///
1048 /// ```
1049 /// # use wasmtime::*;
1050 /// # fn _foo() -> Result<()> {
1051 /// let mut store = Store::<()>::default();
1052 ///
1053 /// let y: OwnedRooted<_> = {
1054 /// // Create a nested rooting scope.
1055 /// let mut scope = RootScope::new(&mut store);
1056 ///
1057 /// // `x` is only rooted within this nested scope.
1058 /// let x: Rooted<_> = ExternRef::new(&mut scope, "hello!")?;
1059 ///
1060 /// // Extend `x`'s rooting past its scope's lifetime by converting it
1061 /// // to an `OwnedRooted`.
1062 /// x.to_owned_rooted(&mut scope)?
1063 /// };
1064 ///
1065 /// // Now we can still access the reference outside the scope it was
1066 /// // originally defined within.
1067 /// let data = y.data(&store)?.expect("should have host data");
1068 /// let data = data.downcast_ref::<&str>().expect("host data should be str");
1069 /// assert_eq!(*data, "hello!");
1070 /// # Ok(())
1071 /// # }
1072 /// ```
1073 pub fn to_owned_rooted(&self, mut store: impl AsContextMut) -> Result<OwnedRooted<T>> {
1074 self.to_owned_rooted_(store.as_context_mut().0)
1075 }
1076
1077 pub(crate) fn to_owned_rooted_(&self, store: &mut StoreOpaque) -> Result<OwnedRooted<T>> {
1078 let mut store = AutoAssertNoGc::new(store);
1079 let gc_ref = self.try_clone_gc_ref(&mut store)?;
1080 Ok(OwnedRooted::new(&mut store, gc_ref)?)
1081 }
1082
1083 /// Get an [`Unrooted<T>`](crate::Unrooted) reference to the same GC
1084 /// object, which is valid until the store's GC heap next changes.
1085 ///
1086 /// Unlike rooting, this needs only shared access to the store.
1087 ///
1088 /// # Errors
1089 ///
1090 /// Returns an error if this reference has been unrooted.
1091 ///
1092 /// # Panics
1093 ///
1094 /// Panics if this reference is associated with a different store.
1095 pub fn to_unrooted(&self, store: impl AsContext) -> Result<crate::Unrooted<T>> {
1096 self.to_unrooted_(store.as_context().0)
1097 }
1098
1099 pub(crate) fn to_unrooted_(&self, store: &StoreOpaque) -> Result<crate::Unrooted<T>> {
1100 let gc_ref = self.try_gc_ref(store)?;
1101 Ok(crate::Unrooted::new(store, gc_ref))
1102 }
1103
1104 /// Root all of the given unrooted references in the current LIFO rooting
1105 /// scope, pushing their roots onto `out` in the same order.
1106 ///
1107 /// Taking `out` as a parameter, rather than returning a new `Vec`, lets
1108 /// callers reuse an existing allocation.
1109 ///
1110 /// Any single rooting operation, such as
1111 /// [`Unrooted::to_rooted`](crate::Unrooted::to_rooted), changes
1112 /// the store's GC heap, and so invalidates *every* unrooted
1113 /// reference into it, not just the one that was rooted. Rooting a
1114 /// list of unrooted references one at a time therefore fails when
1115 /// perfoming the second rooting action. This function solves for
1116 /// that use-case by providing a *batched* rooting action.
1117 ///
1118 /// See [`Val::ensure_all_rooted`](crate::Val::ensure_all_rooted) for the
1119 /// same operation on [`Val`](crate::Val)s, and
1120 /// [`OwnedRooted::to_all_owned_rooted`] to root the references until the
1121 /// returned handles are dropped instead.
1122 ///
1123 /// # Errors
1124 ///
1125 /// Returns an error, and roots nothing and leaves `out` unchanged, if any
1126 /// of `refs` is no longer valid.
1127 ///
1128 /// This function will return an [`OutOfMemory`](crate::OutOfMemory)
1129 /// error when memory allocation fails. See the `OutOfMemory` type's
1130 /// documentation for details on Wasmtime's out-of-memory handling.
1131 ///
1132 /// # Panics
1133 ///
1134 /// Panics if any of `refs` is associated with a different store.
1135 pub fn to_all_rooted(
1136 mut store: impl AsContextMut,
1137 refs: &[crate::Unrooted<T>],
1138 out: &mut Vec<Rooted<T>>,
1139 ) -> Result<()> {
1140 let store = store.as_context_mut().0;
1141 crate::Unrooted::validate_all(store, refs)?;
1142 reserve_for_all_rooted(out, refs.len())?;
1143 let mut store = AutoAssertNoGc::new(store);
1144 out.extend(refs.iter().map(|r| r.to_rooted_unchecked(&mut store)));
1145 Ok(())
1146 }
1147
1148 /// Are these two `Rooted<T>`s the same GC root?
1149 ///
1150 /// Note that this function can return `false` even when `a` and `b` are
1151 /// rooting the same underlying GC object, but the object was rooted
1152 /// multiple times (for example in different scopes). Use
1153 /// [`Rooted::ref_eq`][crate::Rooted::ref_eq] to test whether these are
1154 /// references to the same underlying GC object or not.
1155 ///
1156 /// # Example
1157 ///
1158 /// ```
1159 /// # use wasmtime::*;
1160 /// # fn foo() -> Result<()> {
1161 /// let mut store = Store::<()>::default();
1162 ///
1163 /// let a = ExternRef::new(&mut store, "hello")?;
1164 /// let b = a;
1165 ///
1166 /// // `a` and `b` are the same GC root.
1167 /// assert!(Rooted::rooted_eq(a, b));
1168 ///
1169 /// {
1170 /// let mut scope = RootScope::new(&mut store);
1171 ///
1172 /// // `c` is a different GC root, in a different scope, even though it
1173 /// // is rooting the same object.
1174 /// let c = a.to_owned_rooted(&mut scope)?.to_rooted(&mut scope);
1175 /// assert!(!Rooted::rooted_eq(a, c));
1176 /// }
1177 ///
1178 /// let x = ExternRef::new(&mut store, "goodbye")?;
1179 ///
1180 /// // `a` and `x` are different GC roots, rooting different objects.
1181 /// assert!(!Rooted::rooted_eq(a, x));
1182 /// # Ok(())
1183 /// # }
1184 /// ```
1185 pub fn rooted_eq(a: Self, b: Self) -> bool {
1186 a.inner == b.inner
1187 }
1188
1189 /// Are these two GC roots referencing the same underlying GC object?
1190 ///
1191 /// This function will return `true` even when `a` and `b` are different GC
1192 /// roots (for example because they were rooted in different scopes) if they
1193 /// are rooting the same underlying GC object. To only test whether they are
1194 /// the same GC root, and not whether they are rooting the same GC object,
1195 /// use [`Rooted::rooted_eq`][crate::Rooted::rooted_eq].
1196 ///
1197 /// Returns an error if either `a` or `b` has been unrooted, for example
1198 /// because the scope it was rooted within has been exited.
1199 ///
1200 /// Because this method takes any `impl RootedGcRef<T>` arguments, it can be
1201 /// used to compare, for example, a `Rooted<T>` and a `OwnedRooted<T>`.
1202 ///
1203 /// # Panics
1204 ///
1205 /// Panics if either `a` or `b` is not associated with the given `store`.
1206 ///
1207 /// # Example
1208 ///
1209 /// ```
1210 /// # use wasmtime::*;
1211 /// # fn foo() -> Result<()> {
1212 /// let mut store = Store::<()>::default();
1213 ///
1214 /// let a = ExternRef::new(&mut store, "hello")?;
1215 /// let b = a;
1216 ///
1217 /// // `a` and `b` are rooting the same object.
1218 /// assert!(Rooted::ref_eq(&store, &a, &b)?);
1219 ///
1220 /// {
1221 /// let mut scope = RootScope::new(&mut store);
1222 ///
1223 /// // `c` is a different GC root, in a different scope, but still
1224 /// // rooting the same object.
1225 /// let c = a.to_owned_rooted(&mut scope)?.to_rooted(&mut scope);
1226 /// assert!(!Rooted::ref_eq(&scope, &a, &c)?);
1227 /// }
1228 ///
1229 /// let x = ExternRef::new(&mut store, "goodbye")?;
1230 ///
1231 /// // `a` and `x` are rooting different objects.
1232 /// assert!(!Rooted::ref_eq(&store, &a, &x)?);
1233 ///
1234 /// // You can also compare `Rooted<T>`s and `OwnedRooted<T>`s with this
1235 /// // function.
1236 /// let d = a.to_owned_rooted(&mut store)?;
1237 /// assert!(Rooted::ref_eq(&store, &a, &d)?);
1238 /// # Ok(())
1239 /// # }
1240 /// ```
1241 pub fn ref_eq(
1242 store: impl AsContext,
1243 a: &impl RootedGcRef<T>,
1244 b: &impl RootedGcRef<T>,
1245 ) -> Result<bool> {
1246 let store = store.as_context().0;
1247 Self::_ref_eq(store, a, b)
1248 }
1249
1250 pub(crate) fn _ref_eq(
1251 store: &StoreOpaque,
1252 a: &impl RootedGcRef<T>,
1253 b: &impl RootedGcRef<T>,
1254 ) -> Result<bool> {
1255 let a = a.try_gc_ref(store)?;
1256 let b = b.try_gc_ref(store)?;
1257 Ok(a == b)
1258 }
1259
1260 /// Hash this root.
1261 ///
1262 /// Note that, similar to `Rooted::rooted_eq`, this only operates on the
1263 /// root and *not* the underlying GC reference. That means that two
1264 /// different rootings of the same object will hash to different values
1265 /// (modulo hash collisions). If this is undesirable, use the
1266 /// [`ref_hash`][crate::Rooted::ref_hash] method instead.
1267 pub fn rooted_hash<H>(&self, state: &mut H)
1268 where
1269 H: Hasher,
1270 {
1271 self.inner.hash(state);
1272 }
1273
1274 /// Hash the underlying rooted object reference.
1275 ///
1276 /// Note that, similar to `Rooted::ref_eq`, and operates on the underlying
1277 /// rooted GC object reference, not the root. That means that two
1278 /// *different* rootings of the same object will hash to the *same*
1279 /// value. If this is undesirable, use the
1280 /// [`rooted_hash`][crate::Rooted::rooted_hash] method instead.
1281 pub fn ref_hash<H>(&self, store: impl AsContext, state: &mut H) -> Result<()>
1282 where
1283 H: Hasher,
1284 {
1285 let gc_ref = self.try_gc_ref(store.as_context().0)?;
1286 gc_ref.hash(state);
1287 Ok(())
1288 }
1289
1290 /// Cast `self` to a `Rooted<U>`.
1291 ///
1292 /// It is the caller's responsibility to ensure that `self` is actually a
1293 /// `U`. Failure to uphold this invariant will be memory safe but will
1294 /// result in general incorrectness such as panics and wrong results.
1295 pub(crate) fn unchecked_cast<U: GcRef>(self) -> Rooted<U> {
1296 Rooted::from_gc_root_index(self.inner)
1297 }
1298
1299 /// Common implementation of the `WasmTy::store` trait method for all
1300 /// `Rooted<T>`s.
1301 pub(super) fn wasm_ty_store(
1302 self,
1303 store: &mut AutoAssertNoGc<'_>,
1304 ptr: &mut MaybeUninit<ValRaw>,
1305 val_raw: impl Fn(u32) -> ValRaw,
1306 ) -> Result<()> {
1307 let raw = self.inner.expose_gc_ref_to_wasm(store)?;
1308 ptr.write(val_raw(raw.get()));
1309 Ok(())
1310 }
1311
1312 /// Common implementation of the `WasmTy::load` trait method for all
1313 /// `Rooted<T>`s.
1314 pub(super) fn wasm_ty_load(
1315 store: &mut AutoAssertNoGc<'_>,
1316 raw_gc_ref: u32,
1317 from_cloned_gc_ref: impl Fn(&mut AutoAssertNoGc<'_>, VMGcRef) -> Self,
1318 ) -> Self {
1319 debug_assert_ne!(raw_gc_ref, 0);
1320 let gc_ref = VMGcRef::from_raw_u32(raw_gc_ref).expect("non-null");
1321
1322 let gc_ref = match store.optional_gc_store_mut() {
1323 Some(s) => s.clone_gc_ref(&gc_ref),
1324 None => {
1325 // NB: do not force the allocation of a GC heap just because the
1326 // program is using `i31ref`s.
1327 debug_assert!(gc_ref.is_i31());
1328 gc_ref.unchecked_copy()
1329 }
1330 };
1331
1332 from_cloned_gc_ref(store, gc_ref)
1333 }
1334
1335 /// Common implementation of the `WasmTy::store` trait method for all
1336 /// `Option<Rooted<T>>`s.
1337 pub(super) fn wasm_ty_option_store(
1338 me: Option<Self>,
1339 store: &mut AutoAssertNoGc<'_>,
1340 ptr: &mut MaybeUninit<ValRaw>,
1341 val_raw: impl Fn(u32) -> ValRaw,
1342 ) -> Result<()> {
1343 match me {
1344 Some(me) => me.wasm_ty_store(store, ptr, val_raw),
1345 None => {
1346 ptr.write(val_raw(0));
1347 Ok(())
1348 }
1349 }
1350 }
1351
1352 /// Common implementation of the `WasmTy::load` trait method for all
1353 /// `Option<Rooted<T>>`s.
1354 pub(super) fn wasm_ty_option_load(
1355 store: &mut AutoAssertNoGc<'_>,
1356 raw_gc_ref: u32,
1357 from_cloned_gc_ref: impl Fn(&mut AutoAssertNoGc<'_>, VMGcRef) -> Self,
1358 ) -> Option<Self> {
1359 let gc_ref = VMGcRef::from_raw_u32(raw_gc_ref)?;
1360 let gc_ref = store.clone_gc_ref(&gc_ref);
1361 Some(from_cloned_gc_ref(store, gc_ref))
1362 }
1363
1364 pub(crate) fn try_gc_ref<'a>(&self, store: &'a StoreOpaque) -> Result<&'a VMGcRef> {
1365 <Self as RootedGcRefImpl<_>>::try_gc_ref(self, store)
1366 }
1367
1368 pub(crate) fn try_clone_gc_ref(&self, store: &mut AutoAssertNoGc<'_>) -> Result<VMGcRef> {
1369 <Self as RootedGcRefImpl<_>>::try_clone_gc_ref(self, store)
1370 }
1371}
1372
1373/// Nested rooting scopes.
1374///
1375/// `RootScope` allows the creation or nested rooting scopes for use with
1376/// [`Rooted<T>`][crate::Rooted]. This allows for fine-grained control over how
1377/// long a set of [`Rooted<T>`][crate::Rooted]s are strongly held alive, giving
1378/// gives you the tools necessary to avoid holding onto GC objects longer than
1379/// necessary. `Rooted<T>`s created within a `RootScope` are automatically
1380/// unrooted when the `RootScope` is dropped. For more details on
1381/// [`Rooted<T>`][crate::Rooted] lifetimes and their interaction with rooting
1382/// scopes, see [`Rooted<T>`][crate::Rooted]'s documentation.
1383///
1384/// A `RootScope<C>` wraps a `C: AsContextMut` (that is, anything that
1385/// represents exclusive access to a [`Store`][crate::Store]) and in turn
1386/// implements [`AsContext`][crate::AsContext] and
1387/// [`AsContextMut`][crate::AsContextMut] in terms of its underlying
1388/// `C`. Therefore, `RootScope<C>` can be used anywhere you would use the
1389/// underlying `C`, for example in the [`Global::get`][crate::Global::get]
1390/// method. Any `Rooted<T>`s created by a method that a `RootScope<C>` was
1391/// passed as context to are tied to the `RootScope<C>`'s scope and
1392/// automatically unrooted when the scope is dropped.
1393///
1394/// # Example
1395///
1396/// ```
1397/// # use wasmtime::*;
1398/// # fn _foo() -> Result<()> {
1399/// let mut store = Store::<()>::default();
1400///
1401/// let a: Rooted<_>;
1402/// let b: Rooted<_>;
1403/// let c: Rooted<_>;
1404///
1405/// // Root `a` in the store's scope. It will be rooted for the duration of the
1406/// // store's lifetime.
1407/// a = ExternRef::new(&mut store, 42)?;
1408///
1409/// // `a` is rooted, so we can access its data successfully.
1410/// assert!(a.data(&store).is_ok());
1411///
1412/// {
1413/// let mut scope1 = RootScope::new(&mut store);
1414///
1415/// // Root `b` in `scope1`.
1416/// b = ExternRef::new(&mut scope1, 36)?;
1417///
1418/// // Both `a` and `b` are rooted.
1419/// assert!(a.data(&scope1).is_ok());
1420/// assert!(b.data(&scope1).is_ok());
1421///
1422/// {
1423/// let mut scope2 = RootScope::new(&mut scope1);
1424///
1425/// // Root `c` in `scope2`.
1426/// c = ExternRef::new(&mut scope2, 36)?;
1427///
1428/// // All of `a`, `b`, and `c` are rooted.
1429/// assert!(a.data(&scope2).is_ok());
1430/// assert!(b.data(&scope2).is_ok());
1431/// assert!(c.data(&scope2).is_ok());
1432///
1433/// // Drop `scope2`.
1434/// }
1435///
1436/// // Now `a` and `b` are still rooted, but `c` was unrooted when we dropped
1437/// // `scope2`.
1438/// assert!(a.data(&scope1).is_ok());
1439/// assert!(b.data(&scope1).is_ok());
1440/// assert!(c.data(&scope1).is_err());
1441///
1442/// // Drop `scope1`.
1443/// }
1444///
1445/// // And now only `a` is still rooted. Both `b` and `c` were unrooted when we
1446/// // dropped their respective rooting scopes.
1447/// assert!(a.data(&store).is_ok());
1448/// assert!(b.data(&store).is_err());
1449/// assert!(c.data(&store).is_err());
1450/// # Ok(())
1451/// # }
1452/// ```
1453pub struct RootScope<C>
1454where
1455 C: AsContextMut,
1456{
1457 store: C,
1458 scope: usize,
1459}
1460
1461impl<C> Drop for RootScope<C>
1462where
1463 C: AsContextMut,
1464{
1465 fn drop(&mut self) {
1466 self.store.as_context_mut().0.exit_gc_lifo_scope(self.scope);
1467 }
1468}
1469
1470impl<C> RootScope<C>
1471where
1472 C: AsContextMut,
1473{
1474 // NB: we MUST NOT expose a method like
1475 //
1476 // pub fn store(&mut self) -> &mut Store { ... }
1477 //
1478 // because callers could do treacherous things like
1479 //
1480 // let scope1 = RootScope::new(&mut store1);
1481 // let scope2 = RootScope::new(&mut store2);
1482 // std::mem::swap(scope1.store(), scope2.store());
1483 //
1484 // and then we would start truncate the store's GC root set's LIFO roots to
1485 // the wrong lengths.
1486 //
1487 // Instead, we just implement `AsContext[Mut]` for `RootScope`.
1488
1489 /// Construct a new scope for rooting GC objects.
1490 ///
1491 /// # Example
1492 ///
1493 /// ```
1494 /// # use wasmtime::*;
1495 /// let mut store = Store::<()>::default();
1496 ///
1497 /// {
1498 /// let mut scope = RootScope::new(&mut store);
1499 ///
1500 /// // Temporarily root GC objects in this nested rooting scope...
1501 /// }
1502 /// ```
1503 pub fn new(store: C) -> Self {
1504 let scope = store.as_context().0.gc_roots().enter_lifo_scope();
1505 RootScope { store, scope }
1506 }
1507
1508 fn gc_roots(&mut self) -> &mut RootSet {
1509 self.store.as_context_mut().0.gc_roots_mut()
1510 }
1511
1512 fn lifo_roots(&mut self) -> &mut Vec<LifoRoot> {
1513 &mut self.gc_roots().lifo_roots
1514 }
1515
1516 /// Reserve enough capacity for `additional` GC roots in this scope.
1517 ///
1518 /// # Example
1519 ///
1520 /// ```
1521 /// # use wasmtime::*;
1522 /// let mut store = Store::<()>::default();
1523 ///
1524 /// {
1525 /// let mut scope = RootScope::new(&mut store);
1526 ///
1527 /// // Ensure we have enough storage pre-allocated to root five GC
1528 /// // references inside this scope without any underlying reallocation.
1529 /// scope.reserve(5);
1530 ///
1531 /// // ...
1532 /// }
1533 /// ```
1534 pub fn reserve(&mut self, additional: usize) {
1535 self.lifo_roots().reserve(additional);
1536 }
1537}
1538
1539impl<T> AsContext for RootScope<T>
1540where
1541 T: AsContextMut,
1542{
1543 type Data = T::Data;
1544
1545 fn as_context(&self) -> crate::StoreContext<'_, Self::Data> {
1546 self.store.as_context()
1547 }
1548}
1549
1550impl<T> AsContextMut for RootScope<T>
1551where
1552 T: AsContextMut,
1553{
1554 fn as_context_mut(&mut self) -> crate::StoreContextMut<'_, Self::Data> {
1555 self.store.as_context_mut()
1556 }
1557}
1558
1559/// Internal version of `RootScope` that only wraps a `&mut StoreOpaque` rather
1560/// than a whole `impl AsContextMut<Data = T>`.
1561pub(crate) struct OpaqueRootScope<S>
1562where
1563 S: AsStoreOpaque,
1564{
1565 store: S,
1566 scope: usize,
1567}
1568
1569impl<S> Drop for OpaqueRootScope<S>
1570where
1571 S: AsStoreOpaque,
1572{
1573 fn drop(&mut self) {
1574 self.store.as_store_opaque().exit_gc_lifo_scope(self.scope);
1575 }
1576}
1577
1578impl<S> Deref for OpaqueRootScope<S>
1579where
1580 S: AsStoreOpaque,
1581{
1582 type Target = S;
1583
1584 fn deref(&self) -> &Self::Target {
1585 &self.store
1586 }
1587}
1588
1589// XXX: Don't use this `DerefMut` implementation to `mem::{swap,replace}` or
1590// etc... the underlying `StoreOpaque` in a `OpaqueRootScope`! That will result
1591// in truncating the store's GC root set's LIFO roots to the wrong length.
1592//
1593// We don't implement `DerefMut` for `RootScope` for exactly this reason, but
1594// allow it for `OpaqueRootScope` because it is only Wasmtime-internal and not
1595// publicly exported.
1596impl<S> DerefMut for OpaqueRootScope<S>
1597where
1598 S: AsStoreOpaque,
1599{
1600 fn deref_mut(&mut self) -> &mut Self::Target {
1601 &mut self.store
1602 }
1603}
1604
1605impl<S> OpaqueRootScope<S>
1606where
1607 S: AsStoreOpaque,
1608{
1609 pub(crate) fn new(mut store: S) -> Self {
1610 let scope = store.as_store_opaque().gc_roots().enter_lifo_scope();
1611 OpaqueRootScope { store, scope }
1612 }
1613}
1614
1615/// A rooted reference to a garbage-collected `T` with automatic lifetime.
1616///
1617/// An `OwnedRooted<T>` is a strong handle to a garbage-collected `T`,
1618/// preventing its referent (and anything else transitively referenced) from
1619/// being collected by the GC until it is dropped.
1620///
1621/// An `OwnedRooted<T>` keeps its rooted GC object alive at least
1622/// until the `OwnedRooted<T>` itself is dropped. The
1623/// "de-registration" of the root is automatic and is triggered (in a
1624/// deferred way) by the drop of this type.
1625///
1626/// The primary way to create an `OwnedRooted<T>` is to promote a temporary
1627/// `Rooted<T>` into an `OwnedRooted<T>` via its
1628/// [`to_owned_rooted`][crate::Rooted::to_owned_rooted] method.
1629///
1630/// `OwnedRooted<T>` dereferences to its underlying `T`, allowing you to call
1631/// `T`'s methods.
1632///
1633/// # Example
1634///
1635/// ```
1636/// # use wasmtime::*;
1637/// # fn _foo() -> Result<()> {
1638/// let mut store = Store::<Option<OwnedRooted<ExternRef>>>::default();
1639///
1640/// // Create our `OwnedRooted` in a nested scope to avoid rooting it for
1641/// // the duration of the store's lifetime.
1642/// let x = {
1643/// let mut scope = RootScope::new(&mut store);
1644/// let x = ExternRef::new(&mut scope, 1234)?;
1645/// x.to_owned_rooted(&mut scope)?
1646/// };
1647///
1648/// // Place `x` into our store.
1649/// *store.data_mut() = Some(x);
1650///
1651/// // Do a bunch stuff that may or may not access, replace, or take `x`...
1652/// # Ok(())
1653/// # }
1654/// ```
1655pub struct OwnedRooted<T>
1656where
1657 T: GcRef,
1658{
1659 inner: GcRootIndex,
1660 liveness_flag: Arc<()>,
1661 _phantom: marker::PhantomData<T>,
1662}
1663
1664const _: () = {
1665 use crate::{AnyRef, ExternRef};
1666
1667 // NB: these match the C API which should also be updated if this changes.
1668 //
1669 // The size is really "16 + pointer + alignment", which is either
1670 // 20 bytes on some 32-bit platforms or 24 bytes on other 32-bit
1671 // platforms (e.g., riscv32, which adds an extra 4 bytes of
1672 // padding) and 64-bit platforms.
1673 assert!(
1674 mem::size_of::<OwnedRooted<AnyRef>>() >= 16 && mem::size_of::<OwnedRooted<AnyRef>>() <= 24
1675 );
1676 assert!(mem::align_of::<OwnedRooted<AnyRef>>() == mem::align_of::<u64>());
1677 assert!(
1678 mem::size_of::<OwnedRooted<ExternRef>>() >= 16
1679 && mem::size_of::<OwnedRooted<ExternRef>>() <= 24
1680 );
1681 assert!(mem::align_of::<OwnedRooted<ExternRef>>() == mem::align_of::<u64>());
1682};
1683
1684impl<T: GcRef> Debug for OwnedRooted<T> {
1685 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1686 let name = format!("OwnedRooted<{}>", any::type_name::<T>());
1687 f.debug_struct(&name).field("inner", &self.inner).finish()
1688 }
1689}
1690
1691impl<T: GcRef> Deref for OwnedRooted<T> {
1692 type Target = T;
1693
1694 fn deref(&self) -> &Self::Target {
1695 T::transmute_ref(&self.inner)
1696 }
1697}
1698
1699impl<T: GcRef> Clone for OwnedRooted<T> {
1700 fn clone(&self) -> Self {
1701 OwnedRooted {
1702 inner: self.inner,
1703 liveness_flag: self.liveness_flag.clone(),
1704 _phantom: marker::PhantomData,
1705 }
1706 }
1707}
1708
1709impl<T> OwnedRooted<T>
1710where
1711 T: GcRef,
1712{
1713 /// Construct a new owned GC root.
1714 ///
1715 /// `gc_ref` should belong to `store`'s heap; failure to uphold this is
1716 /// memory safe but will result in general failures down the line such as
1717 /// panics or incorrect results.
1718 ///
1719 /// `gc_ref` should be a GC reference pointing to an instance of the GC type
1720 /// that `T` represents. Failure to uphold this invariant is memory safe but
1721 /// will result in general incorrectness such as panics and wrong results.
1722 pub(crate) fn new(
1723 store: &mut AutoAssertNoGc<'_>,
1724 gc_ref: VMGcRef,
1725 ) -> Result<Self, OutOfMemory> {
1726 // We always have the opportunity to trim and unregister stale
1727 // owned roots whenever we have a mut borrow to the store. We
1728 // take the opportunity to do so here to avoid tying growth of
1729 // the root-set to the GC frequency -- it is much cheaper to
1730 // eagerly trim these roots. Note that the trimming keeps a
1731 // "high water mark" that grows exponentially, so we have
1732 // amortized constant time even though an individual trim
1733 // takes time linear in the number of roots.
1734 store.trim_gc_liveness_flags(false);
1735
1736 let roots = store.gc_roots_mut();
1737 let id = roots.owned_rooted.alloc(gc_ref)?;
1738 let liveness_flag = Arc::new(());
1739 roots
1740 .liveness_flags
1741 .push((Arc::downgrade(&liveness_flag), id));
1742 Ok(OwnedRooted {
1743 inner: GcRootIndex {
1744 store_id: store.id(),
1745 generation: 0,
1746 index: PackedIndex::new_owned(id),
1747 },
1748 liveness_flag,
1749 _phantom: marker::PhantomData,
1750 })
1751 }
1752
1753 #[inline]
1754 pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
1755 debug_assert!(self.inner.index.is_owned());
1756 self.inner.comes_from_same_store(store)
1757 }
1758
1759 /// Clone this `OwnedRooted<T>` into a `Rooted<T>`.
1760 ///
1761 /// This operation does not consume or unroot this `OwnedRooted<T>`.
1762 ///
1763 /// The underlying GC object is re-rooted in the given context's scope. The
1764 /// resulting `Rooted<T>` is only valid during the given context's
1765 /// scope. See the [`Rooted<T>`][crate::Rooted] documentation for more
1766 /// details on rooting scopes.
1767 ///
1768 /// This operation does not consume or unroot this `OwnedRooted<T>`.
1769 ///
1770 /// # Panics
1771 ///
1772 /// Panics if this object is not associated with the given context's store.
1773 ///
1774 /// # Example
1775 ///
1776 /// ```
1777 /// # use wasmtime::*;
1778 /// # fn _foo() -> Result<()> {
1779 /// let mut store = Store::<()>::default();
1780 ///
1781 /// let root1: Rooted<_>;
1782 ///
1783 /// let owned = {
1784 /// let mut scope = RootScope::new(&mut store);
1785 /// root1 = ExternRef::new(&mut scope, 1234)?;
1786 /// root1.to_owned_rooted(&mut scope)?
1787 /// };
1788 ///
1789 /// // `root1` is no longer accessible because it was unrooted when `scope`
1790 /// // was dropped.
1791 /// assert!(root1.data(&store).is_err());
1792 ///
1793 /// // But we can re-root `owned` into this scope.
1794 /// let root2 = owned.to_rooted(&mut store);
1795 /// assert!(root2.data(&store).is_ok());
1796 /// # Ok(())
1797 /// # }
1798 /// ```
1799 pub fn to_rooted(&self, mut context: impl AsContextMut) -> Rooted<T> {
1800 self.to_rooted_(context.as_context_mut().0)
1801 }
1802
1803 pub(crate) fn to_rooted_(&self, store: &mut StoreOpaque) -> Rooted<T> {
1804 assert!(
1805 self.comes_from_same_store(store),
1806 "object used with wrong store"
1807 );
1808 let mut store = AutoAssertNoGc::new(store);
1809 let gc_ref = self.clone_gc_ref(&mut store).unwrap();
1810 Rooted::new(&mut store, gc_ref)
1811 }
1812
1813 /// Get an [`Unrooted<T>`](crate::Unrooted) reference to the same GC
1814 /// object, which is valid until the store's GC heap next changes.
1815 ///
1816 /// Unlike rooting, this needs only shared access to the store.
1817 ///
1818 /// # Errors
1819 ///
1820 /// Returns an error if this reference is not associated with `store`'s
1821 /// GC heap.
1822 ///
1823 /// # Panics
1824 ///
1825 /// Panics if this reference is associated with a different store.
1826 pub fn to_unrooted(&self, store: impl AsContext) -> Result<crate::Unrooted<T>> {
1827 self.to_unrooted_(store.as_context().0)
1828 }
1829
1830 pub(crate) fn to_unrooted_(&self, store: &StoreOpaque) -> Result<crate::Unrooted<T>> {
1831 let gc_ref = self.try_gc_ref(store)?;
1832 Ok(crate::Unrooted::new(store, gc_ref))
1833 }
1834
1835 /// Root all of the given unrooted references until the returned handles
1836 /// are dropped, returning the handles in the same order.
1837 ///
1838 /// Any single rooting operation, such as
1839 /// [`Unrooted::to_rooted`](crate::Unrooted::to_rooted), changes
1840 /// the store's GC heap, and so invalidates *every* unrooted
1841 /// reference into it, not just the one that was rooted. Rooting a
1842 /// list of unrooted references one at a time therefore fails once
1843 /// the second reference is rooted. This function solves that
1844 /// use-case by providing a *batched* rooting operation.
1845 ///
1846 /// See [`Rooted::to_all_rooted`] to root the references in the current
1847 /// LIFO rooting scope instead.
1848 ///
1849 /// # Errors
1850 ///
1851 /// Returns an error, and roots nothing and leaves `out` unchanged, if any
1852 /// of `refs` is no longer valid.
1853 ///
1854 /// This function will return an [`OutOfMemory`](crate::OutOfMemory)
1855 /// error when memory allocation fails, in which case `out` is also left
1856 /// unchanged. See the `OutOfMemory` type's documentation for details on
1857 /// Wasmtime's out-of-memory handling.
1858 ///
1859 /// # Panics
1860 ///
1861 /// Panics if any of `refs` is associated with a different store.
1862 pub fn to_all_owned_rooted(
1863 mut store: impl AsContextMut,
1864 refs: &[crate::Unrooted<T>],
1865 out: &mut Vec<OwnedRooted<T>>,
1866 ) -> Result<()> {
1867 let store = store.as_context_mut().0;
1868 crate::Unrooted::validate_all(store, refs)?;
1869 reserve_for_all_rooted(out, refs.len())?;
1870 let original_len = out.len();
1871 let mut store = AutoAssertNoGc::new(store);
1872 for r in refs {
1873 match r.to_owned_rooted_unchecked(&mut store) {
1874 Ok(owned) => out.push(owned),
1875 Err(e) => {
1876 out.truncate(original_len);
1877 return Err(e);
1878 }
1879 }
1880 }
1881 Ok(())
1882 }
1883
1884 /// Are these two GC roots referencing the same underlying GC object?
1885 ///
1886 /// This function will return `true` even when `a` and `b` are different GC
1887 /// roots (for example because they were rooted in different scopes) if they
1888 /// are rooting the same underlying GC object.
1889 ///
1890 /// Because this method takes any `impl RootedGcRef<T>` arguments, it can be
1891 /// used to compare, for example, a `Rooted<T>` and an `OwnedRooted<T>`.
1892 ///
1893 /// # Panics
1894 ///
1895 /// Panics if either `a` or `b` is not associated with the given `store`.
1896 ///
1897 /// # Example
1898 ///
1899 /// ```
1900 /// # use wasmtime::*;
1901 /// # fn foo() -> Result<()> {
1902 /// let mut store = Store::<()>::default();
1903 ///
1904 /// let a;
1905 /// let b;
1906 /// let x;
1907 ///
1908 /// {
1909 /// let mut scope = RootScope::new(&mut store);
1910 ///
1911 /// a = ExternRef::new(&mut scope, "hello")?.to_owned_rooted(&mut scope)?;
1912 /// b = a.clone();
1913 ///
1914 /// // `a` and `b` are rooting the same object.
1915 /// assert!(OwnedRooted::ref_eq(&scope, &a, &b)?);
1916 ///
1917 /// // `c` is a different GC root, is in a different scope, and is a
1918 /// // `Rooted<T>` instead of a `OwnedRooted<T>`, but is still rooting
1919 /// // the same object.
1920 /// let c = a.to_rooted(&mut scope);
1921 /// assert!(OwnedRooted::ref_eq(&scope, &a, &c)?);
1922 ///
1923 /// x = ExternRef::new(&mut scope, "goodbye")?.to_owned_rooted(&mut scope)?;
1924 ///
1925 /// // `a` and `x` are rooting different objects.
1926 /// assert!(!OwnedRooted::ref_eq(&scope, &a, &x)?);
1927 /// }
1928 /// # Ok(())
1929 /// # }
1930 /// ```
1931 pub fn ref_eq(
1932 store: impl AsContext,
1933 a: &impl RootedGcRef<T>,
1934 b: &impl RootedGcRef<T>,
1935 ) -> Result<bool> {
1936 Rooted::ref_eq(store, a, b)
1937 }
1938
1939 /// Hash this root.
1940 ///
1941 /// Note that, similar to `Rooted::rooted_eq`, this only operates on the
1942 /// root and *not* the underlying GC reference. That means that two
1943 /// different rootings of the same object will hash to different values
1944 /// (modulo hash collisions). If this is undesirable, use the
1945 /// [`ref_hash`][crate::OwnedRooted::ref_hash] method instead.
1946 pub fn rooted_hash<H>(&self, state: &mut H)
1947 where
1948 H: Hasher,
1949 {
1950 self.inner.hash(state);
1951 }
1952
1953 /// Hash the underlying rooted object reference.
1954 ///
1955 /// Note that, similar to `Rooted::ref_eq`, and operates on the underlying
1956 /// rooted GC object reference, not the root. That means that two
1957 /// *different* rootings of the same object will hash to the *same*
1958 /// value. If this is undesirable, use the
1959 /// [`rooted_hash`][crate::Rooted::rooted_hash] method instead.
1960 pub fn ref_hash<H>(&self, store: impl AsContext, state: &mut H)
1961 where
1962 H: Hasher,
1963 {
1964 let gc_ref = self
1965 .get_gc_ref(store.as_context().0)
1966 .expect("OwnedRooted's get_gc_ref is infallible");
1967 gc_ref.hash(state);
1968 }
1969
1970 /// Cast `self` to an `OwnedRooted<U>`.
1971 ///
1972 /// It is the caller's responsibility to ensure that `self` is actually a
1973 /// `U`. Failure to uphold this invariant will be memory safe but will
1974 /// result in general incorrectness such as panics and wrong results.
1975 pub(crate) fn unchecked_cast<U: GcRef>(self) -> OwnedRooted<U> {
1976 OwnedRooted {
1977 inner: self.inner,
1978 liveness_flag: self.liveness_flag,
1979 _phantom: core::marker::PhantomData,
1980 }
1981 }
1982
1983 /// Common implementation of the `WasmTy::store` trait method for all
1984 /// `OwnedRooted<T>`s.
1985 pub(super) fn wasm_ty_store(
1986 self,
1987 store: &mut AutoAssertNoGc<'_>,
1988 ptr: &mut MaybeUninit<ValRaw>,
1989 val_raw: impl Fn(u32) -> ValRaw,
1990 ) -> Result<()> {
1991 let raw = self.inner.expose_gc_ref_to_wasm(store)?;
1992 ptr.write(val_raw(raw.get()));
1993 Ok(())
1994 }
1995
1996 /// Common implementation of the `WasmTy::load` trait method for all
1997 /// `OwnedRooted<T>`s.
1998 pub(super) fn wasm_ty_load(
1999 store: &mut AutoAssertNoGc<'_>,
2000 raw_gc_ref: u32,
2001 from_cloned_gc_ref: impl Fn(&mut AutoAssertNoGc<'_>, VMGcRef) -> Rooted<T>,
2002 ) -> Self {
2003 debug_assert_ne!(raw_gc_ref, 0);
2004 let gc_ref = VMGcRef::from_raw_u32(raw_gc_ref).expect("non-null");
2005 let gc_ref = store.clone_gc_ref(&gc_ref);
2006 RootSet::with_lifo_scope(store, |store| {
2007 let rooted = from_cloned_gc_ref(store, gc_ref);
2008 rooted.to_owned_rooted_(store).expect("rooted is in scope")
2009 })
2010 }
2011
2012 /// Common implementation of the `WasmTy::store` trait method for all
2013 /// `Option<OwnedRooted<T>>`s.
2014 pub(super) fn wasm_ty_option_store(
2015 me: Option<Self>,
2016 store: &mut AutoAssertNoGc<'_>,
2017 ptr: &mut MaybeUninit<ValRaw>,
2018 val_raw: impl Fn(u32) -> ValRaw,
2019 ) -> Result<()> {
2020 match me {
2021 Some(me) => me.wasm_ty_store(store, ptr, val_raw),
2022 None => {
2023 ptr.write(val_raw(0));
2024 Ok(())
2025 }
2026 }
2027 }
2028
2029 /// Common implementation of the `WasmTy::load` trait method for all
2030 /// `Option<OwnedRooted<T>>`s.
2031 pub(super) fn wasm_ty_option_load(
2032 store: &mut AutoAssertNoGc<'_>,
2033 raw_gc_ref: u32,
2034 from_cloned_gc_ref: impl Fn(&mut AutoAssertNoGc<'_>, VMGcRef) -> Rooted<T>,
2035 ) -> Option<Self> {
2036 let gc_ref = VMGcRef::from_raw_u32(raw_gc_ref)?;
2037 let gc_ref = store.clone_gc_ref(&gc_ref);
2038 RootSet::with_lifo_scope(store, |store| {
2039 let rooted = from_cloned_gc_ref(store, gc_ref);
2040 Some(rooted.to_owned_rooted_(store).expect("rooted is in scope"))
2041 })
2042 }
2043
2044 #[doc(hidden)]
2045 pub fn into_parts_for_c_api(self) -> (NonZeroU64, u32, u32, *const ()) {
2046 (
2047 self.inner.store_id.as_raw(),
2048 self.inner.generation,
2049 self.inner.index.0,
2050 Arc::into_raw(self.liveness_flag),
2051 )
2052 }
2053
2054 #[doc(hidden)]
2055 pub unsafe fn from_borrowed_raw_parts_for_c_api(
2056 a: NonZeroU64,
2057 b: u32,
2058 c: u32,
2059 d: *const (),
2060 ) -> OwnedRooted<T> {
2061 // We are given a *borrow* of the Arc. This is a little
2062 // sketchy because `Arc::from_raw()` takes *ownership* of the
2063 // passed-in pointer, so we need to clone then forget that
2064 // original.
2065 let liveness_flag = {
2066 let original = unsafe { Arc::from_raw(d) };
2067 let clone = original.clone();
2068 core::mem::forget(original);
2069 clone
2070 };
2071 OwnedRooted {
2072 inner: GcRootIndex {
2073 store_id: StoreId::from_raw(a),
2074 generation: b,
2075 index: PackedIndex(c),
2076 },
2077 liveness_flag,
2078 _phantom: marker::PhantomData,
2079 }
2080 }
2081
2082 #[doc(hidden)]
2083 pub unsafe fn from_owned_raw_parts_for_c_api(
2084 a: NonZeroU64,
2085 b: u32,
2086 c: u32,
2087 d: *const (),
2088 ) -> OwnedRooted<T> {
2089 let liveness_flag = unsafe { Arc::from_raw(d) };
2090 OwnedRooted {
2091 inner: GcRootIndex {
2092 store_id: StoreId::from_raw(a),
2093 generation: b,
2094 index: PackedIndex(c),
2095 },
2096 liveness_flag,
2097 _phantom: marker::PhantomData,
2098 }
2099 }
2100}
2101
2102impl<T: GcRef> RootedGcRefImpl<T> for OwnedRooted<T> {
2103 fn get_gc_ref<'a>(&self, store: &'a StoreOpaque) -> Option<&'a VMGcRef> {
2104 assert!(
2105 self.comes_from_same_store(store),
2106 "object used with wrong store"
2107 );
2108
2109 let id = self.inner.index.as_owned().unwrap();
2110 store.gc_roots().owned_rooted.get(id)
2111 }
2112}
2113
2114/// Reserve room for `additional` more roots in `out`, for
2115/// [`Rooted::to_all_rooted`] and [`OwnedRooted::to_all_owned_rooted`], so that
2116/// pushing them cannot fail.
2117fn reserve_for_all_rooted<R>(out: &mut Vec<R>, additional: usize) -> Result<(), OutOfMemory> {
2118 out.try_reserve(additional).map_err(|_| {
2119 OutOfMemory::new(
2120 out.len()
2121 .saturating_add(additional)
2122 .saturating_mul(mem::size_of::<R>()),
2123 )
2124 })
2125}
2126#[cfg(test)]
2127mod tests {
2128 use crate::ExternRef;
2129
2130 use super::*;
2131
2132 #[test]
2133 fn sizes() {
2134 // Try to keep tabs on the size of these things. Don't want them growing
2135 // unintentionally.
2136 assert_eq!(std::mem::size_of::<Rooted<ExternRef>>(), 16);
2137 assert!(std::mem::size_of::<OwnedRooted<ExternRef>>() <= 24);
2138 }
2139}