1#![cfg(feature = "gc")]
3
4use crate::runtime::vm::VMGcRef;
5use crate::store::{Asyncness, StoreId};
6#[cfg(feature = "async")]
7use crate::vm::VMStore;
8use crate::vm::{self, VMGcHeader, VMStructRef};
9use crate::{AnyRef, FieldType};
10use crate::{
11 AsContext, AsContextMut, EqRef, GcHeapOutOfMemory, GcRefImpl, GcRootIndex, HeapType,
12 OwnedRooted, RefType, Rooted, StructType, Val, ValRaw, ValType, WasmTy, bail_bug,
13 prelude::*,
14 store::{AutoAssertNoGc, StoreContext, StoreOpaque, StoreResourceLimiter},
15};
16use alloc::sync::Arc;
17use core::mem::{self, MaybeUninit};
18use wasmtime_environ::{GcStructLayout, VMGcKind, VMSharedTypeIndex};
19
20pub struct StructRefPre {
66 store_id: StoreId,
67 ty: StructType,
68}
69
70impl StructRefPre {
71 pub fn new(mut store: impl AsContextMut, ty: StructType) -> Self {
79 Self::_new(store.as_context_mut().0, ty)
80 }
81
82 pub(crate) fn _new(store: &mut StoreOpaque, ty: StructType) -> Self {
83 store.insert_gc_host_alloc_type(ty.registered_type().clone());
84 let store_id = store.id();
85 StructRefPre { store_id, ty }
86 }
87
88 pub(crate) fn layout(&self) -> &GcStructLayout {
89 self.ty
90 .registered_type()
91 .layout()
92 .expect("struct types have a layout")
93 .unwrap_struct()
94 }
95
96 pub(crate) fn type_index(&self) -> VMSharedTypeIndex {
97 self.ty.registered_type().index()
98 }
99}
100
101#[derive(Debug)]
160#[repr(transparent)]
161pub struct StructRef {
162 pub(super) inner: GcRootIndex,
163}
164
165unsafe impl GcRefImpl for StructRef {
166 fn transmute_ref(index: &GcRootIndex) -> &Self {
167 let me: &Self = unsafe { mem::transmute(index) };
169
170 assert!(matches!(
172 me,
173 Self {
174 inner: GcRootIndex { .. },
175 }
176 ));
177
178 me
179 }
180}
181
182impl Rooted<StructRef> {
183 #[inline]
185 pub fn to_anyref(self) -> Rooted<AnyRef> {
186 self.unchecked_cast()
187 }
188
189 #[inline]
191 pub fn to_eqref(self) -> Rooted<EqRef> {
192 self.unchecked_cast()
193 }
194}
195
196impl OwnedRooted<StructRef> {
197 #[inline]
199 pub fn to_anyref(self) -> OwnedRooted<AnyRef> {
200 self.unchecked_cast()
201 }
202
203 #[inline]
205 pub fn to_eqref(self) -> OwnedRooted<EqRef> {
206 self.unchecked_cast()
207 }
208}
209
210impl StructRef {
211 pub fn new(
243 mut store: impl AsContextMut,
244 allocator: &StructRefPre,
245 fields: &[Val],
246 ) -> Result<Rooted<StructRef>> {
247 let (mut limiter, store) = store
248 .as_context_mut()
249 .0
250 .validate_sync_resource_limiter_and_store_opaque()?;
251 vm::assert_ready(Self::_new_async(
252 store,
253 limiter.as_mut(),
254 allocator,
255 fields,
256 Asyncness::No,
257 ))
258 }
259
260 #[cfg(feature = "async")]
287 pub async fn new_async(
288 mut store: impl AsContextMut,
289 allocator: &StructRefPre,
290 fields: &[Val],
291 ) -> Result<Rooted<StructRef>> {
292 let (mut limiter, store) = store.as_context_mut().0.resource_limiter_and_store_opaque();
293 Self::_new_async(store, limiter.as_mut(), allocator, fields, Asyncness::Yes).await
294 }
295
296 pub(crate) async fn _new_async(
297 store: &mut StoreOpaque,
298 limiter: Option<&mut StoreResourceLimiter<'_>>,
299 allocator: &StructRefPre,
300 fields: &[Val],
301 asyncness: Asyncness,
302 ) -> Result<Rooted<StructRef>> {
303 Self::type_check_fields(store, allocator, fields)?;
304 store
305 .retry_after_gc_async(limiter, (), asyncness, |store, ()| {
306 Self::new_unchecked(store, allocator, fields)
307 })
308 .await
309 }
310
311 fn type_check_fields(
313 store: &mut StoreOpaque,
314 allocator: &StructRefPre,
315 fields: &[Val],
316 ) -> Result<(), Error> {
317 let expected_len = allocator.ty.fields().len();
318 let actual_len = fields.len();
319 ensure!(
320 actual_len == expected_len,
321 "expected {expected_len} fields, got {actual_len}"
322 );
323 for (ty, val) in allocator.ty.fields().zip(fields) {
324 assert!(
325 val.comes_from_same_store(store),
326 "field value comes from the wrong store",
327 );
328 val.validate_rooted().context("unrooted field value")?;
330 let ty = ty.element_type().unpack();
331 val.ensure_matches_ty(store, ty)
332 .context("field type mismatch")?;
333 }
334 Ok(())
335 }
336
337 fn new_unchecked(
342 store: &mut StoreOpaque,
343 allocator: &StructRefPre,
344 fields: &[Val],
345 ) -> Result<Rooted<StructRef>> {
346 assert_eq!(
347 store.id(),
348 allocator.store_id,
349 "attempted to use a `StructRefPre` with the wrong store"
350 );
351
352 let structref = store
355 .require_gc_store_mut()?
356 .alloc_uninit_struct(allocator.type_index(), &allocator.layout())
357 .context("unrecoverable error when allocating new `structref`")?
358 .map_err(|n| GcHeapOutOfMemory::new((), n))?;
359
360 let mut store = AutoAssertNoGc::new(store);
365 match (|| {
366 for (index, (ty, val)) in allocator.ty.fields().zip(fields).enumerate() {
367 structref.initialize_field(
368 &mut store,
369 allocator.layout(),
370 ty.element_type(),
371 index,
372 *val,
373 )?;
374 }
375 Ok(())
376 })() {
377 Ok(()) => Ok(Rooted::new(&mut store, structref.into())),
378 Err(e) => {
379 store
380 .require_gc_store_mut()?
381 .dealloc_uninit_struct(structref)?;
382 Err(e)
383 }
384 }
385 }
386
387 #[inline]
388 pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
389 self.inner.comes_from_same_store(store)
390 }
391
392 pub fn ty(&self, store: impl AsContext) -> Result<StructType> {
402 self._ty(store.as_context().0)
403 }
404
405 pub(crate) fn _ty(&self, store: &StoreOpaque) -> Result<StructType> {
406 assert!(self.comes_from_same_store(store));
407 let index = self.type_index(store)?;
408 match StructType::from_shared_type_index(store.engine(), index) {
409 Some(ty) => Ok(ty),
410 None => bail_bug!("invalid struct type index"),
411 }
412 }
413
414 pub fn matches_ty(&self, store: impl AsContext, ty: &StructType) -> Result<bool> {
427 self._matches_ty(store.as_context().0, ty)
428 }
429
430 pub(crate) fn _matches_ty(&self, store: &StoreOpaque, ty: &StructType) -> Result<bool> {
431 assert!(self.comes_from_same_store(store));
432 Ok(self._ty(store)?.matches(ty))
433 }
434
435 pub(crate) fn ensure_matches_ty(&self, store: &StoreOpaque, ty: &StructType) -> Result<()> {
436 if !self.comes_from_same_store(store) {
437 bail!("function used with wrong store");
438 }
439 if self._matches_ty(store, ty)? {
440 Ok(())
441 } else {
442 let actual_ty = self._ty(store)?;
443 bail!("type mismatch: expected `(ref {ty})`, found `(ref {actual_ty})`")
444 }
445 }
446
447 pub fn fields<'a, T: 'static>(
466 &'a self,
467 store: impl Into<StoreContext<'a, T>>,
468 ) -> Result<impl ExactSizeIterator<Item = Val> + 'a> {
469 self._fields(store.into().0)
470 }
471
472 pub(crate) fn _fields<'a>(
473 &'a self,
474 store: &'a StoreOpaque,
475 ) -> Result<impl ExactSizeIterator<Item = Val> + 'a> {
476 assert!(self.comes_from_same_store(store));
477
478 let gc_ref = self.inner.try_gc_ref(store)?;
479 let header = store.require_gc_store()?.header(gc_ref)?;
480 debug_assert!(header.matches_kind(VMGcKind::StructRef));
481
482 let index = match header.ty() {
483 Some(index) => index,
484 None => bail_bug!("structrefs should have concrete types"),
485 };
486 let ty = match StructType::from_shared_type_index(store.engine(), index) {
487 Some(ty) => ty,
488 None => bail_bug!("invalid struct type index"),
489 };
490 let len = ty.fields().len();
491
492 return Ok(Fields {
493 structref: self,
494 store,
495 index: 0,
496 len,
497 });
498
499 struct Fields<'a> {
500 structref: &'a StructRef,
501 store: &'a StoreOpaque,
502 index: usize,
503 len: usize,
504 }
505
506 impl Iterator for Fields<'_> {
507 type Item = Val;
508
509 #[inline]
510 fn next(&mut self) -> Option<Self::Item> {
511 let i = self.index;
512 debug_assert!(i <= self.len);
513 if i >= self.len {
514 return None;
515 }
516 self.index += 1;
517 self.structref._field(self.store, i).ok()
518 }
519
520 #[inline]
521 fn size_hint(&self) -> (usize, Option<usize>) {
522 let len = self.len - self.index;
523 (len, Some(len))
524 }
525 }
526
527 impl ExactSizeIterator for Fields<'_> {
528 #[inline]
529 fn len(&self) -> usize {
530 self.len - self.index
531 }
532 }
533 }
534
535 fn header<'a>(&self, store: &'a StoreOpaque) -> Result<&'a VMGcHeader> {
536 assert!(self.comes_from_same_store(&store));
537 let gc_ref = self.inner.try_gc_ref(store)?;
538 Ok(store.require_gc_store()?.header(gc_ref)?)
539 }
540
541 fn structref<'a>(&self, store: &'a StoreOpaque) -> Result<&'a VMStructRef> {
542 assert!(self.comes_from_same_store(&store));
543 let gc_ref = self.inner.try_gc_ref(store)?;
544 debug_assert!(self.header(store)?.matches_kind(VMGcKind::StructRef));
545 Ok(gc_ref.as_structref_unchecked())
546 }
547
548 fn layout(&self, store: &StoreOpaque) -> Result<Arc<GcStructLayout>> {
549 assert!(self.comes_from_same_store(&store));
550 let type_index = self.type_index(store)?;
551 super::gc_struct_layout(store.engine(), type_index)
552 }
553
554 fn field_ty(&self, store: &StoreOpaque, field: usize) -> Result<FieldType> {
555 let ty = self._ty(store)?;
556 match ty.field(field) {
557 Some(f) => Ok(f),
558 None => {
559 let len = ty.fields().len();
560 bail!("cannot access field {field}: struct only has {len} fields")
561 }
562 }
563 }
564
565 pub fn field(&self, store: impl AsContext, index: usize) -> Result<Val> {
585 self._field(store.as_context().0, index)
586 }
587
588 pub(crate) fn _field(&self, store: &StoreOpaque, index: usize) -> Result<Val> {
589 assert!(self.comes_from_same_store(store));
590 let structref = self.structref(store)?;
591 let field_ty = self.field_ty(store, index)?;
592 let layout = self.layout(store)?;
593 structref.read_field(store, &layout, field_ty.element_type(), index)
594 }
595
596 pub fn set_field(&self, mut store: impl AsContextMut, index: usize, value: Val) -> Result<()> {
616 self._set_field(store.as_context_mut().0, index, value)
617 }
618
619 pub(crate) fn _set_field(
620 &self,
621 store: &mut StoreOpaque,
622 index: usize,
623 value: Val,
624 ) -> Result<()> {
625 assert!(self.comes_from_same_store(store));
626 value
627 .validate_rooted()
628 .with_context(|| format!("cannot set field {index}: unrooted value"))?;
629 let mut store = AutoAssertNoGc::new(store);
630
631 let field_ty = self.field_ty(&store, index)?;
632 ensure!(
633 field_ty.mutability().is_var(),
634 "cannot set field {index}: field is not mutable"
635 );
636
637 value
638 .ensure_matches_ty(&store, &field_ty.element_type().unpack())
639 .with_context(|| format!("cannot set field {index}: type mismatch"))?;
640
641 let layout = self.layout(&store)?;
642 let structref = self.structref(&store)?.unchecked_copy();
643
644 structref.write_field(&mut store, &layout, field_ty.element_type(), index, value)
645 }
646
647 pub(crate) fn type_index(&self, store: &StoreOpaque) -> Result<VMSharedTypeIndex> {
648 let gc_ref = self.inner.try_gc_ref(store)?;
649 let header = store.require_gc_store()?.header(gc_ref)?;
650 debug_assert!(header.matches_kind(VMGcKind::StructRef));
651 match header.ty() {
652 Some(ty) => Ok(ty),
653 None => bail_bug!("structrefs should have concrete types"),
654 }
655 }
656
657 pub(crate) fn from_cloned_gc_ref(
663 store: &mut AutoAssertNoGc<'_>,
664 gc_ref: VMGcRef,
665 ) -> Rooted<Self> {
666 debug_assert!(gc_ref.is_structref(&**store.unwrap_gc_store().gc_heap.get()));
667 Rooted::new(store, gc_ref)
668 }
669}
670
671unsafe impl WasmTy for Rooted<StructRef> {
672 #[inline]
673 fn valtype() -> ValType {
674 ValType::Ref(RefType::new(false, HeapType::Struct))
675 }
676
677 #[inline]
678 fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
679 self.comes_from_same_store(store)
680 }
681
682 #[inline]
683 fn dynamic_concrete_type_check(
684 &self,
685 store: &StoreOpaque,
686 _nullable: bool,
687 ty: &HeapType,
688 ) -> Result<()> {
689 match ty {
690 HeapType::Any | HeapType::Eq | HeapType::Struct => Ok(()),
691 HeapType::ConcreteStruct(ty) => self.ensure_matches_ty(store, ty),
692
693 HeapType::Extern
694 | HeapType::NoExtern
695 | HeapType::Func
696 | HeapType::ConcreteFunc(_)
697 | HeapType::NoFunc
698 | HeapType::I31
699 | HeapType::Array
700 | HeapType::ConcreteArray(_)
701 | HeapType::None
702 | HeapType::NoCont
703 | HeapType::Cont
704 | HeapType::ConcreteCont(_)
705 | HeapType::NoExn
706 | HeapType::Exn => bail!(
707 "type mismatch: expected `(ref {ty})`, got `(ref {})`",
708 self._ty(store)?,
709 ),
710 }
711 }
712
713 fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
714 self.wasm_ty_store(store, ptr, ValRaw::anyref)
715 }
716
717 unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
718 Self::wasm_ty_load(store, ptr.get_anyref(), StructRef::from_cloned_gc_ref)
719 }
720}
721
722unsafe impl WasmTy for Option<Rooted<StructRef>> {
723 #[inline]
724 fn valtype() -> ValType {
725 ValType::STRUCTREF
726 }
727
728 #[inline]
729 fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
730 self.map_or(true, |x| x.comes_from_same_store(store))
731 }
732
733 #[inline]
734 fn dynamic_concrete_type_check(
735 &self,
736 store: &StoreOpaque,
737 nullable: bool,
738 ty: &HeapType,
739 ) -> Result<()> {
740 match self {
741 Some(s) => Rooted::<StructRef>::dynamic_concrete_type_check(s, store, nullable, ty),
742 None => {
743 ensure!(
744 nullable,
745 "expected a non-null reference, but found a null reference"
746 );
747 Ok(())
748 }
749 }
750 }
751
752 #[inline]
753 fn is_vmgcref_and_points_to_object(&self) -> bool {
754 self.is_some()
755 }
756
757 fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
758 <Rooted<StructRef>>::wasm_ty_option_store(self, store, ptr, ValRaw::anyref)
759 }
760
761 unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
762 <Rooted<StructRef>>::wasm_ty_option_load(
763 store,
764 ptr.get_anyref(),
765 StructRef::from_cloned_gc_ref,
766 )
767 }
768}
769
770unsafe impl WasmTy for OwnedRooted<StructRef> {
771 #[inline]
772 fn valtype() -> ValType {
773 ValType::Ref(RefType::new(false, HeapType::Struct))
774 }
775
776 #[inline]
777 fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
778 self.comes_from_same_store(store)
779 }
780
781 #[inline]
782 fn dynamic_concrete_type_check(
783 &self,
784 store: &StoreOpaque,
785 _: bool,
786 ty: &HeapType,
787 ) -> Result<()> {
788 match ty {
789 HeapType::Any | HeapType::Eq | HeapType::Struct => Ok(()),
790 HeapType::ConcreteStruct(ty) => self.ensure_matches_ty(store, ty),
791
792 HeapType::Extern
793 | HeapType::NoExtern
794 | HeapType::Func
795 | HeapType::ConcreteFunc(_)
796 | HeapType::NoFunc
797 | HeapType::I31
798 | HeapType::Array
799 | HeapType::ConcreteArray(_)
800 | HeapType::None
801 | HeapType::NoCont
802 | HeapType::Cont
803 | HeapType::ConcreteCont(_)
804 | HeapType::NoExn
805 | HeapType::Exn => bail!(
806 "type mismatch: expected `(ref {ty})`, got `(ref {})`",
807 self._ty(store)?,
808 ),
809 }
810 }
811
812 fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
813 self.wasm_ty_store(store, ptr, ValRaw::anyref)
814 }
815
816 unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
817 Self::wasm_ty_load(store, ptr.get_anyref(), StructRef::from_cloned_gc_ref)
818 }
819}
820
821unsafe impl WasmTy for Option<OwnedRooted<StructRef>> {
822 #[inline]
823 fn valtype() -> ValType {
824 ValType::STRUCTREF
825 }
826
827 #[inline]
828 fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
829 self.as_ref()
830 .map_or(true, |x| x.comes_from_same_store(store))
831 }
832
833 #[inline]
834 fn dynamic_concrete_type_check(
835 &self,
836 store: &StoreOpaque,
837 nullable: bool,
838 ty: &HeapType,
839 ) -> Result<()> {
840 match self {
841 Some(s) => {
842 OwnedRooted::<StructRef>::dynamic_concrete_type_check(s, store, nullable, ty)
843 }
844 None => {
845 ensure!(
846 nullable,
847 "expected a non-null reference, but found a null reference"
848 );
849 Ok(())
850 }
851 }
852 }
853
854 #[inline]
855 fn is_vmgcref_and_points_to_object(&self) -> bool {
856 self.is_some()
857 }
858
859 fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
860 <OwnedRooted<StructRef>>::wasm_ty_option_store(self, store, ptr, ValRaw::anyref)
861 }
862
863 unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
864 <OwnedRooted<StructRef>>::wasm_ty_option_load(
865 store,
866 ptr.get_anyref(),
867 StructRef::from_cloned_gc_ref,
868 )
869 }
870}