wasmtime/runtime/gc/enabled/unrooted.rs
1//! Unrooted references: cheap, read-only references to GC objects.
2
3use crate::runtime::epoch_state::EpochStateHandle;
4use crate::runtime::vm::{GcHeap, VMGcHeader, VMGcRef};
5use crate::store::{AutoAssertNoGc, StoreOpaque};
6use crate::{
7 AnyRef, ArrayRef, ArrayType, AsContext, AsContextMut, EqRef, ExnRef, ExnType, ExternRef, GcRef,
8 HeapType, I31, OwnedRooted, Result, Rooted, StoreContext, StructRef, StructType, Tag, Val,
9 bail_bug, prelude::*,
10};
11use core::any::Any;
12use core::fmt;
13use core::hash::Hasher;
14use core::marker;
15use core::num::NonZeroU32;
16use wasmtime_environ::{VMGcKind, VMSharedTypeIndex};
17
18/// A read-only reference to a GC object, valid only until the store's
19/// GC heap next changes.
20///
21/// Unlike [`Rooted`] and [`OwnedRooted`], an `Unrooted` reference
22/// does not keep its object alive (hence, "unrooted"). This means
23/// that it could become invalid with any action that could mutate the
24/// GC heap. If it becomes invalid, APIs will fail cleanly (indicate
25/// that it is stale) rather than crashing or panicking.
26///
27/// In exchange, because `Unrooted` references are not recorded in the
28/// root set, they can be used in non-`mut` `Store` contexts, and
29/// operations on them are very cheap.
30///
31/// Getters and allocation methods return `Unrooted` references by
32/// default: the former allows full read-only heap traversal, and the
33/// latter works because *after* the allocation, the heap doesn't
34/// mutate. In both cases, the user is free to root the value
35/// themselves (see [`Unrooted::to_rooted`] or
36/// [`Unrooted::to_owned_rooted`]). This "opt-in" rooting is an
37/// intentional pay-as-you-go design choice.
38///
39/// # Invalidation
40///
41/// In general, an `Unrooted` reference may (but is not guaranteed
42/// to!) become invalid when any method that takes a `&mut Store` is
43/// invoked on the corresponding store. This includes both Wasm
44/// execution and use of host APIs, for example those that allocate or
45/// mutate GC objects.
46///
47/// # Conversions
48///
49/// Use [`Rooted::to_unrooted`] or [`OwnedRooted::to_unrooted`] to get an
50/// unrooted reference to a rooted object, and [`Unrooted::to_rooted`] or
51/// [`Unrooted::to_owned_rooted`] to root the object again, to keep it alive
52/// and usable after the heap next changes. Reading a GC reference out of an
53/// object through an unrooted reference, for example with
54/// [`Unrooted::<StructRef>::field`], gives an unrooted reference as well.
55///
56/// Since rooting any reference invalidates all unrooted references,
57/// it is not possible to root multiple unrooted references
58/// one-by-one. Instead, use [`Rooted::to_all_rooted`],
59/// [`OwnedRooted::to_all_owned_rooted`], or
60/// [`Val::ensure_all_rooted`] to root several unrooted references in
61/// a batch.
62///
63/// # Equality and Hashing
64///
65/// `Unrooted` does not implement [`PartialEq`], [`Eq`], or [`Hash`], for the
66/// same reasons that [`Rooted`] does not. Use [`Unrooted::ref_eq`] and
67/// [`Unrooted::ref_hash`] to compare and hash the referenced objects.
68pub struct Unrooted<T: GcRef> {
69 repr: Repr,
70 _phantom: marker::PhantomData<fn() -> T>,
71}
72
73/// The representation of an `Unrooted<T>`.
74///
75/// Note that this is an enum, rather than a struct with an optional heap
76/// handle, so that it has a tag with plenty of niches; this keeps `Val` small.
77#[derive(Clone, Copy, Debug)]
78enum Repr {
79 /// An `i31`, which is not an object in the heap, and so is always valid.
80 I31(NonZeroU32),
81
82 /// An object in the store's GC heap, at `raw`, valid in the version `heap`
83 /// of the heap.
84 Object {
85 // Note that this has a scary-heavyweight type (`Box`) in it,
86 // but the `EpochStateHandle` doesn't actually carry that
87 // type! It just allows us to get it from the `EpochState`
88 // container (separately passed in) when we want to.
89 heap: EpochStateHandle<Box<dyn GcHeap>>,
90 raw: NonZeroU32,
91 },
92}
93
94impl<T: GcRef> Clone for Unrooted<T> {
95 fn clone(&self) -> Self {
96 *self
97 }
98}
99
100impl<T: GcRef> Copy for Unrooted<T> {}
101
102impl<T: GcRef> fmt::Debug for Unrooted<T> {
103 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104 let name = format!("Unrooted<{}>", core::any::type_name::<T>());
105 f.debug_tuple(&name).field(&self.repr).finish()
106 }
107}
108
109impl<T: GcRef> Unrooted<T> {
110 /// An unrooted reference to `gc_ref`, which must be a `T` in `store`.
111 pub(crate) fn new(store: &StoreOpaque, gc_ref: &VMGcRef) -> Self {
112 let raw = gc_ref.as_raw_non_zero_u32();
113 let repr = if gc_ref.is_i31() {
114 Repr::I31(raw)
115 } else {
116 Repr::Object {
117 heap: store.unwrap_gc_store().gc_heap.handle(),
118 raw,
119 }
120 };
121 Unrooted {
122 repr,
123 _phantom: marker::PhantomData,
124 }
125 }
126
127 /// An unrooted reference to the `T` whose raw bits are `raw`, or `None`
128 /// for null.
129 pub(crate) fn from_raw_u32(store: &StoreOpaque, raw: u32) -> Option<Self> {
130 VMGcRef::from_raw_u32(raw).map(|gc_ref| Self::new(store, &gc_ref))
131 }
132
133 /// The referenced object, if this reference is still valid.
134 ///
135 /// The result borrows `store`, so nothing can collect garbage or otherwise
136 /// mutate the GC heap, and hence invalidate this reference, while it is in
137 /// use.
138 ///
139 /// # Panics
140 ///
141 /// Panics if this reference is associated with a different store.
142 pub(crate) fn gc_ref<'a>(&'a self, store: &'a StoreOpaque) -> Result<&'a VMGcRef> {
143 match &self.repr {
144 // `i31`s are not objects in the GC heap, so are always valid.
145 Repr::I31(raw) => Ok(VMGcRef::from_frozen_raw_u32(raw)),
146 Repr::Object { heap: handle, raw } => {
147 let heap = store
148 .optional_gc_store()
149 .map(|s| &s.gc_heap)
150 .filter(|heap| handle.belongs_to(heap));
151 let Some(heap) = heap else {
152 panic!("unrooted reference used with the wrong store");
153 };
154 ensure!(
155 handle.is_valid(heap),
156 "attempted to use an unrooted garbage-collected reference after \
157 the GC heap changed"
158 );
159 // The object is still live, since `handle` was taken when this
160 // reference was created and the heap has not changed since,
161 // and it stays so while `store` is borrowed.
162 Ok(VMGcRef::from_frozen_raw_u32(raw))
163 }
164 }
165 }
166
167 fn header<'a>(&self, store: &'a StoreOpaque) -> Result<&'a VMGcHeader> {
168 let gc_ref = self.gc_ref(store)?;
169 store.require_gc_store()?.header(&gc_ref)
170 }
171
172 /// The concrete type of the referenced object, which must be of `kind`.
173 fn type_index(&self, store: &StoreOpaque, kind: VMGcKind) -> Result<VMSharedTypeIndex> {
174 let header = self.header(store)?;
175 debug_assert!(header.matches_kind(kind));
176 match header.ty() {
177 Some(ty) => Ok(ty),
178 None => bail_bug!("{kind:?} objects should have concrete types"),
179 }
180 }
181
182 fn cast<U: GcRef>(self) -> Unrooted<U> {
183 Unrooted {
184 repr: self.repr,
185 _phantom: marker::PhantomData,
186 }
187 }
188
189 pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
190 match &self.repr {
191 Repr::I31(_) => true,
192 Repr::Object { heap: handle, .. } => store
193 .optional_gc_store()
194 .is_some_and(|s| handle.belongs_to(&s.gc_heap)),
195 }
196 }
197
198 /// Is this reference still valid?
199 ///
200 /// # Panics
201 ///
202 /// Panics if this reference is associated with a different store.
203 pub fn is_valid(&self, store: impl AsContext) -> bool {
204 self.gc_ref(store.as_context().0).is_ok()
205 }
206
207 /// Do these two unrooted references refer to the same GC object?
208 ///
209 /// This is reference equality, not Wasm-level structural equality; see
210 /// [`Rooted::ref_eq`].
211 ///
212 /// # Errors
213 ///
214 /// Returns an error if either reference is no longer valid.
215 ///
216 /// # Panics
217 ///
218 /// Panics if either reference is associated with a different store.
219 pub fn ref_eq(store: impl AsContext, a: &Self, b: &Self) -> Result<bool> {
220 let store = store.as_context().0;
221 Ok(a.gc_ref(store)? == b.gc_ref(store)?)
222 }
223
224 /// Hash the GC object that this unrooted reference refers to, consistently
225 /// with [`Unrooted::ref_eq`]; see [`Rooted::ref_hash`].
226 ///
227 /// # Errors
228 ///
229 /// Returns an error if this reference is no longer valid.
230 ///
231 /// # Panics
232 ///
233 /// Panics if this reference is associated with a different store.
234 pub fn ref_hash<H>(&self, store: impl AsContext, state: &mut H) -> Result<()>
235 where
236 H: Hasher,
237 {
238 core::hash::Hash::hash(self.gc_ref(store.as_context().0)?, state);
239 Ok(())
240 }
241
242 /// Roots the referenced object in the current LIFO rooting scope, to keep
243 /// it alive and usable after this reference becomes invalid; see
244 /// [`Rooted`].
245 ///
246 /// Rooting a reference invalidates every other unrooted reference into the
247 /// store's GC heap; use [`Rooted::to_all_rooted`] to root several references at once.
248 ///
249 /// # Errors
250 ///
251 /// Returns an error if this reference is no longer valid.
252 ///
253 /// # Panics
254 ///
255 /// Panics if this reference is associated with a different store.
256 pub fn to_rooted(&self, mut store: impl AsContextMut) -> Result<Rooted<T>> {
257 self.to_rooted_(store.as_context_mut().0)
258 }
259
260 pub(crate) fn to_rooted_(&self, store: &mut StoreOpaque) -> Result<Rooted<T>> {
261 self.gc_ref(store)?;
262 let mut store = AutoAssertNoGc::new(store);
263 Ok(self.to_rooted_unchecked(&mut store))
264 }
265
266 /// Roots the referenced object until the returned handle is dropped, to
267 /// keep it alive and usable after this reference becomes invalid; see
268 /// [`OwnedRooted`].
269 ///
270 /// Rooting a reference invalidates every other unrooted reference into the
271 /// store's GC heap; use [`OwnedRooted::to_all_owned_rooted`] to root several references at once.
272 ///
273 /// # Errors
274 ///
275 /// Returns an error if this reference is no longer valid.
276 ///
277 /// This function will return an [`OutOfMemory`](crate::OutOfMemory)
278 /// error when memory allocation fails. See the `OutOfMemory` type's
279 /// documentation for details on Wasmtime's out-of-memory handling.
280 ///
281 /// # Panics
282 ///
283 /// Panics if this reference is associated with a different store.
284 pub fn to_owned_rooted(&self, mut store: impl AsContextMut) -> Result<OwnedRooted<T>> {
285 self.to_owned_rooted_(store.as_context_mut().0)
286 }
287
288 pub(crate) fn to_owned_rooted_(&self, store: &mut StoreOpaque) -> Result<OwnedRooted<T>> {
289 self.gc_ref(store)?;
290 let mut store = AutoAssertNoGc::new(store);
291 self.to_owned_rooted_unchecked(&mut store)
292 }
293
294 /// Check that every one of `refs` is still valid, as the first step of
295 /// rooting them all at once; see [`Rooted::to_all_rooted`].
296 pub(crate) fn validate_all(store: &StoreOpaque, refs: &[Self]) -> Result<()> {
297 for r in refs {
298 r.gc_ref(store)?;
299 }
300 Ok(())
301 }
302
303 /// The referenced object, *without* checking that this reference is still
304 /// valid.
305 ///
306 /// Rooting a reference clones it and records a new root, each of which
307 /// changes the GC heap, and so invalidates every unrooted reference. To
308 /// root several unrooted references at once, we therefore check that they
309 /// are all valid first, with `gc_ref` while the heap is unchanged, and then
310 /// root each of them with this. That is correct because nothing in between
311 /// can free or move an object: we are inside a no-GC scope, and cloning
312 /// references and recording roots only ever keep objects alive.
313 ///
314 /// The caller must have checked, with `gc_ref`, that this reference was
315 /// valid, and have done nothing since then but root unrooted references in
316 /// this way, all within one `AutoAssertNoGc` scope.
317 fn unchecked_gc_ref(&self) -> VMGcRef {
318 match self.repr {
319 Repr::I31(raw) | Repr::Object { raw, .. } => VMGcRef::from_raw_non_zero_u32(raw),
320 }
321 }
322
323 /// Root this reference in the current LIFO rooting scope, after the caller
324 /// has checked that it is valid; see `unchecked_gc_ref` for the
325 /// conditions.
326 pub(crate) fn to_rooted_unchecked(&self, store: &mut AutoAssertNoGc<'_>) -> Rooted<T> {
327 let gc_ref = store.clone_gc_ref(&self.unchecked_gc_ref());
328 Rooted::new(store, gc_ref)
329 }
330
331 /// Root this reference until the returned handle is dropped, after the
332 /// caller has checked that it is valid; see `unchecked_gc_ref` for the
333 /// conditions.
334 pub(crate) fn to_owned_rooted_unchecked(
335 &self,
336 store: &mut AutoAssertNoGc<'_>,
337 ) -> Result<OwnedRooted<T>> {
338 let gc_ref = store.clone_gc_ref(&self.unchecked_gc_ref());
339 Ok(OwnedRooted::new(store, gc_ref)?)
340 }
341}
342
343impl Unrooted<AnyRef> {
344 /// The type of the referenced object; see [`AnyRef::ty`].
345 ///
346 /// # Errors
347 ///
348 /// Returns an error if this reference is no longer valid.
349 ///
350 /// # Panics
351 ///
352 /// Panics if this reference is associated with a different store.
353 pub fn ty(&self, store: impl AsContext) -> Result<HeapType> {
354 self.ty_(store.as_context().0)
355 }
356
357 pub(crate) fn ty_(&self, store: &StoreOpaque) -> Result<HeapType> {
358 AnyRef::ty_of_(store, self.gc_ref(store)?)
359 }
360
361 fn kind(&self, store: &StoreOpaque) -> Result<Option<VMGcKind>> {
362 let gc_ref = self.gc_ref(store)?;
363 if gc_ref.is_i31() {
364 return Ok(None);
365 }
366 Ok(Some(store.require_gc_store()?.kind(&gc_ref)?))
367 }
368
369 /// The referenced `i31`, if this refers to one.
370 ///
371 /// # Errors
372 ///
373 /// Returns an error if this reference is no longer valid.
374 ///
375 /// # Panics
376 ///
377 /// Panics if this reference is associated with a different store.
378 pub fn as_i31(&self, store: impl AsContext) -> Result<Option<I31>> {
379 Ok(self.gc_ref(store.as_context().0)?.as_i31().map(Into::into))
380 }
381
382 /// This reference as a reference to a struct, if it refers to one.
383 ///
384 /// # Errors
385 ///
386 /// Returns an error if this reference is no longer valid.
387 ///
388 /// # Panics
389 ///
390 /// Panics if this reference is associated with a different store.
391 pub fn as_struct(&self, store: impl AsContext) -> Result<Option<Unrooted<StructRef>>> {
392 let kind = self.kind(store.as_context().0)?;
393 Ok(kind
394 .is_some_and(|k| k.matches(VMGcKind::StructRef))
395 .then(|| self.cast()))
396 }
397
398 /// This reference as a reference to an array, if it refers to one.
399 ///
400 /// # Errors
401 ///
402 /// Returns an error if this reference is no longer valid.
403 ///
404 /// # Panics
405 ///
406 /// Panics if this reference is associated with a different store.
407 pub fn as_array(&self, store: impl AsContext) -> Result<Option<Unrooted<ArrayRef>>> {
408 let kind = self.kind(store.as_context().0)?;
409 Ok(kind
410 .is_some_and(|k| k.matches(VMGcKind::ArrayRef))
411 .then(|| self.cast()))
412 }
413}
414
415impl From<Unrooted<EqRef>> for Unrooted<AnyRef> {
416 fn from(r: Unrooted<EqRef>) -> Self {
417 r.cast()
418 }
419}
420
421impl From<Unrooted<StructRef>> for Unrooted<AnyRef> {
422 fn from(r: Unrooted<StructRef>) -> Self {
423 r.cast()
424 }
425}
426
427impl From<Unrooted<ArrayRef>> for Unrooted<AnyRef> {
428 fn from(r: Unrooted<ArrayRef>) -> Self {
429 r.cast()
430 }
431}
432
433impl Unrooted<StructRef> {
434 /// The type of the referenced struct.
435 ///
436 /// # Errors
437 ///
438 /// Returns an error if this reference is no longer valid.
439 ///
440 /// # Panics
441 ///
442 /// Panics if this reference is associated with a different store.
443 pub fn ty(&self, store: impl AsContext) -> Result<StructType> {
444 let store = store.as_context().0;
445 let index = self.type_index(store, VMGcKind::StructRef)?;
446 match StructType::from_shared_type_index(store.engine(), index) {
447 Some(ty) => Ok(ty),
448 None => bail_bug!("invalid struct type index"),
449 }
450 }
451
452 /// The value of the struct's `index`th field. `i8` and `i16` fields are
453 /// zero-extended into `Val::I32`s.
454 ///
455 /// Any GC reference in the returned value is unrooted, and so is valid only
456 /// until the store's GC heap next changes; see [`Unrooted`].
457 ///
458 /// # Errors
459 ///
460 /// Returns an error if this reference is no longer valid, or if the
461 /// struct has no `index`th field.
462 ///
463 /// # Panics
464 ///
465 /// Panics if this reference is associated with a different store.
466 pub fn field(&self, store: impl AsContext, index: usize) -> Result<Val> {
467 let store = store.as_context().0;
468 let type_index = self.type_index(store, VMGcKind::StructRef)?;
469 read_field(store, self.gc_ref(store)?, type_index, index, "struct")
470 }
471
472 /// The values of the struct's fields; see [`Unrooted::<StructRef>::field`].
473 ///
474 /// Any GC references in the returned values are unrooted, and so are valid
475 /// only until the store's GC heap next changes; see [`Unrooted`].
476 ///
477 /// # Errors
478 ///
479 /// Returns an error if this reference is no longer valid.
480 ///
481 /// # Panics
482 ///
483 /// Panics if this reference is associated with a different store.
484 pub fn fields<'a, T: 'static>(
485 &'a self,
486 store: impl Into<StoreContext<'a, T>>,
487 ) -> Result<impl ExactSizeIterator<Item = Val> + 'a> {
488 let store = store.into().0;
489 let type_index = self.type_index(store, VMGcKind::StructRef)?;
490 Fields::new(store, self.gc_ref(store)?, type_index)
491 }
492}
493
494impl Unrooted<ArrayRef> {
495 /// The type of the referenced array.
496 ///
497 /// # Errors
498 ///
499 /// Returns an error if this reference is no longer valid.
500 ///
501 /// # Panics
502 ///
503 /// Panics if this reference is associated with a different store.
504 pub fn ty(&self, store: impl AsContext) -> Result<ArrayType> {
505 let store = store.as_context().0;
506 let index = self.type_index(store, VMGcKind::ArrayRef)?;
507 match ArrayType::from_shared_type_index(store.engine(), index) {
508 Some(ty) => Ok(ty),
509 None => bail_bug!("invalid array type index"),
510 }
511 }
512
513 /// The number of elements in the array.
514 ///
515 /// # Errors
516 ///
517 /// Returns an error if this reference is no longer valid.
518 ///
519 /// # Panics
520 ///
521 /// Panics if this reference is associated with a different store.
522 pub fn len(&self, store: impl AsContext) -> Result<u32> {
523 let store = store.as_context().0;
524 self.gc_ref(store)?.as_arrayref_unchecked().len(store)
525 }
526
527 /// The value of the array's `index`th element. `i8` and `i16` elements
528 /// are zero-extended into `Val::I32`s.
529 ///
530 /// Any GC reference in the returned value is unrooted, and so is valid only
531 /// until the store's GC heap next changes; see [`Unrooted`].
532 ///
533 /// # Errors
534 ///
535 /// Returns an error if this reference is no longer valid, or if `index` is
536 /// out of bounds.
537 ///
538 /// # Panics
539 ///
540 /// Panics if this reference is associated with a different store.
541 pub fn get(&self, store: impl AsContext, index: u32) -> Result<Val> {
542 let store = store.as_context().0;
543 let gc_ref = self.gc_ref(store)?;
544 let len = gc_ref.as_arrayref_unchecked().len(store)?;
545 ensure!(
546 index < len,
547 "index out of bounds: the length is {len} but the index is {index}"
548 );
549 let type_index = self.type_index(store, VMGcKind::ArrayRef)?;
550 let ty = match ArrayType::from_shared_type_index(store.engine(), type_index) {
551 Some(ty) => ty,
552 None => bail_bug!("invalid array type index"),
553 };
554 let layout = super::gc_array_layout(store.engine(), type_index)?;
555 let Some(offset) = layout.elem_offset(index) else {
556 bail_bug!("out-of-bounds array element index");
557 };
558 gc_ref.read_val(store, ty.field_type().element_type(), offset)
559 }
560}
561
562impl Unrooted<ExnRef> {
563 /// The type of the referenced exception.
564 ///
565 /// # Errors
566 ///
567 /// Returns an error if this reference is no longer valid.
568 ///
569 /// # Panics
570 ///
571 /// Panics if this reference is associated with a different store.
572 pub fn ty(&self, store: impl AsContext) -> Result<ExnType> {
573 self.ty_(store.as_context().0)
574 }
575
576 pub(crate) fn ty_(&self, store: &StoreOpaque) -> Result<ExnType> {
577 let index = self.type_index(store, VMGcKind::ExnRef)?;
578 match ExnType::from_shared_type_index(store.engine(), index) {
579 Some(ty) => Ok(ty),
580 None => bail_bug!("invalid exception type index"),
581 }
582 }
583
584 /// The tag of the referenced exception.
585 ///
586 /// # Errors
587 ///
588 /// Returns an error if this reference is no longer valid.
589 ///
590 /// # Panics
591 ///
592 /// Panics if this reference is associated with a different store.
593 pub fn tag(&self, store: impl AsContext) -> Result<Tag> {
594 let store = store.as_context().0;
595 let (instance, index) = self.gc_ref(store)?.as_exnref_unchecked().tag(store)?;
596 match Tag::from_raw_indices(store, instance, index) {
597 Some(tag) => Ok(tag),
598 None => bail_bug!("invalid tag indices in exception object"),
599 }
600 }
601
602 /// The value of the exception's `index`th payload field.
603 ///
604 /// Any GC reference in the returned value is unrooted, and so is valid only
605 /// until the store's GC heap next changes; see [`Unrooted`].
606 ///
607 /// # Errors
608 ///
609 /// Returns an error if this reference is no longer valid, or if the
610 /// exception has no `index`th field.
611 ///
612 /// # Panics
613 ///
614 /// Panics if this reference is associated with a different store.
615 pub fn field(&self, store: impl AsContext, index: usize) -> Result<Val> {
616 let store = store.as_context().0;
617 let type_index = self.type_index(store, VMGcKind::ExnRef)?;
618 read_field(store, self.gc_ref(store)?, type_index, index, "exn")
619 }
620
621 /// The values of the exception's payload fields; see
622 /// [`Unrooted::<ExnRef>::field`].
623 ///
624 /// Any GC references in the returned values are unrooted, and so are valid
625 /// only until the store's GC heap next changes; see [`Unrooted`].
626 ///
627 /// # Errors
628 ///
629 /// Returns an error if this reference is no longer valid.
630 ///
631 /// # Panics
632 ///
633 /// Panics if this reference is associated with a different store.
634 pub fn fields<'a, T: 'static>(
635 &'a self,
636 store: impl Into<StoreContext<'a, T>>,
637 ) -> Result<impl ExactSizeIterator<Item = Val> + 'a> {
638 let store = store.into().0;
639 let type_index = self.type_index(store, VMGcKind::ExnRef)?;
640 Fields::new(store, self.gc_ref(store)?, type_index)
641 }
642}
643
644impl Unrooted<ExternRef> {
645 /// The host data of the referenced `externref`; see [`ExternRef::data`].
646 ///
647 /// # Errors
648 ///
649 /// Returns an error if this reference is no longer valid.
650 ///
651 /// # Panics
652 ///
653 /// Panics if this reference is associated with a different store.
654 pub fn data<'a, T: 'static>(
655 &self,
656 store: impl Into<StoreContext<'a, T>>,
657 ) -> Result<Option<&'a (dyn Any + Send + Sync)>> {
658 let store = store.into().0;
659 let gc_ref = self.gc_ref(store)?;
660 if gc_ref.is_i31() {
661 return Ok(None);
662 }
663 let gc_store = store.require_gc_store()?;
664 match gc_ref.as_externref(&**gc_store.gc_heap.get()) {
665 Some(externref) => Ok(Some(gc_store.externref_host_data(externref)?)),
666 None => Ok(None),
667 }
668 }
669}
670
671/// The field types of the struct or exception type `type_index`.
672fn field_types(
673 store: &StoreOpaque,
674 type_index: VMSharedTypeIndex,
675) -> Result<Vec<crate::FieldType>> {
676 if let Some(ty) = StructType::from_shared_type_index(store.engine(), type_index) {
677 return Ok(ty.fields().collect());
678 }
679 match ExnType::from_shared_type_index(store.engine(), type_index) {
680 Some(ty) => Ok(ty.fields().collect()),
681 None => bail_bug!("invalid struct or exception type index"),
682 }
683}
684
685/// Reads the `index`th field of the struct or exception `gc_ref`, of type
686/// `type_index`.
687fn read_field(
688 store: &StoreOpaque,
689 gc_ref: &VMGcRef,
690 type_index: VMSharedTypeIndex,
691 index: usize,
692 what: &str,
693) -> Result<Val> {
694 let fields = field_types(store, type_index)?;
695 let Some(field) = fields.get(index) else {
696 let len = fields.len();
697 bail!("cannot access field {index}: {what} only has {len} fields");
698 };
699 let layout = super::gc_struct_layout(store.engine(), type_index)?;
700 gc_ref.read_val(store, field.element_type(), layout.fields[index].offset)
701}
702
703/// An iterator over the fields of the struct or exception `gc_ref`.
704///
705/// Like the iterators returned by [`StructRef::fields`] and
706/// [`ExnRef::fields`], this ends early if reading a field fails, which can only
707/// happen due to a bug, since the reference was valid when this was created and
708/// `store` is borrowed, so the heap cannot change in the meantime.
709struct Fields<'a> {
710 store: &'a StoreOpaque,
711 gc_ref: &'a VMGcRef,
712 fields: Vec<crate::FieldType>,
713 layout: alloc::sync::Arc<wasmtime_environ::GcStructLayout>,
714 index: usize,
715}
716
717impl<'a> Fields<'a> {
718 fn new(
719 store: &'a StoreOpaque,
720 gc_ref: &'a VMGcRef,
721 type_index: VMSharedTypeIndex,
722 ) -> Result<Self> {
723 Ok(Fields {
724 store,
725 gc_ref,
726 fields: field_types(store, type_index)?,
727 layout: super::gc_struct_layout(store.engine(), type_index)?,
728 index: 0,
729 })
730 }
731}
732
733impl Iterator for Fields<'_> {
734 type Item = Val;
735
736 fn next(&mut self) -> Option<Val> {
737 let field = self.fields.get(self.index)?;
738 let offset = self.layout.fields[self.index].offset;
739 self.index += 1;
740 self.gc_ref
741 .read_val(self.store, field.element_type(), offset)
742 .ok()
743 }
744
745 fn size_hint(&self) -> (usize, Option<usize>) {
746 let len = self.fields.len() - self.index;
747 (len, Some(len))
748 }
749}
750
751impl ExactSizeIterator for Fields<'_> {}