1use crate::runtime::vm::VMGcRef;
4use crate::store::{Asyncness, StoreId, StoreResourceLimiter};
5#[cfg(feature = "async")]
6use crate::vm::VMStore;
7use crate::vm::{self, VMExnRef, VMGcHeader};
8use crate::{
9 AsContext, AsContextMut, GcRefImpl, GcRootIndex, HeapType, OwnedRooted, RefType, Rooted, Val,
10 ValRaw, ValType, WasmTy,
11 store::{AutoAssertNoGc, StoreOpaque},
12};
13use crate::{ExnType, FieldType, GcHeapOutOfMemory, StoreContext, Tag, bail_bug, prelude::*};
14use alloc::sync::Arc;
15use core::mem;
16use core::mem::MaybeUninit;
17use wasmtime_environ::{GcStructLayout, VMGcKind, VMSharedTypeIndex};
18
19pub struct ExnRefPre {
69 store_id: StoreId,
70 ty: ExnType,
71}
72
73impl ExnRefPre {
74 pub fn new(mut store: impl AsContextMut, ty: ExnType) -> Self {
82 Self::_new(store.as_context_mut().0, ty)
83 }
84
85 pub(crate) fn _new(store: &mut StoreOpaque, ty: ExnType) -> Self {
86 store.insert_gc_host_alloc_type(ty.registered_type().clone());
87 let store_id = store.id();
88 ExnRefPre { store_id, ty }
89 }
90
91 pub(crate) fn layout(&self) -> &GcStructLayout {
92 self.ty
93 .registered_type()
94 .layout()
95 .expect("exn types have a layout")
96 .unwrap_struct()
97 }
98
99 pub(crate) fn type_index(&self) -> VMSharedTypeIndex {
100 self.ty.registered_type().index()
101 }
102}
103
104#[derive(Debug)]
115#[repr(transparent)]
116pub struct ExnRef {
117 pub(super) inner: GcRootIndex,
118}
119
120unsafe impl GcRefImpl for ExnRef {
121 fn transmute_ref(index: &GcRootIndex) -> &Self {
122 let me: &Self = unsafe { mem::transmute(index) };
124
125 assert!(matches!(
127 me,
128 Self {
129 inner: GcRootIndex { .. },
130 }
131 ));
132
133 me
134 }
135}
136
137impl ExnRef {
138 pub fn from_raw(mut store: impl AsContextMut, raw: u32) -> Option<Rooted<Self>> {
169 let mut store = AutoAssertNoGc::new(store.as_context_mut().0);
170 Self::_from_raw(&mut store, raw)
171 }
172
173 pub(crate) fn _from_raw(store: &mut AutoAssertNoGc, raw: u32) -> Option<Rooted<Self>> {
175 let gc_ref = VMGcRef::from_raw_u32(raw)?;
176 let gc_ref = store.clone_gc_ref(&gc_ref);
177 Some(Self::from_cloned_gc_ref(store, gc_ref))
178 }
179
180 pub fn new(
214 mut store: impl AsContextMut,
215 allocator: &ExnRefPre,
216 tag: &Tag,
217 fields: &[Val],
218 ) -> Result<Rooted<ExnRef>> {
219 let (mut limiter, store) = store
220 .as_context_mut()
221 .0
222 .validate_sync_resource_limiter_and_store_opaque()?;
223 vm::assert_ready(Self::_new_async(
224 store,
225 limiter.as_mut(),
226 allocator,
227 tag,
228 fields,
229 Asyncness::No,
230 ))
231 }
232
233 #[cfg(feature = "async")]
262 pub async fn new_async(
263 mut store: impl AsContextMut,
264 allocator: &ExnRefPre,
265 tag: &Tag,
266 fields: &[Val],
267 ) -> Result<Rooted<ExnRef>> {
268 let (mut limiter, store) = store.as_context_mut().0.resource_limiter_and_store_opaque();
269 Self::_new_async(
270 store,
271 limiter.as_mut(),
272 allocator,
273 tag,
274 fields,
275 Asyncness::Yes,
276 )
277 .await
278 }
279
280 pub(crate) async fn _new_async(
281 store: &mut StoreOpaque,
282 limiter: Option<&mut StoreResourceLimiter<'_>>,
283 allocator: &ExnRefPre,
284 tag: &Tag,
285 fields: &[Val],
286 asyncness: Asyncness,
287 ) -> Result<Rooted<ExnRef>> {
288 Self::type_check_tag_and_fields(store, allocator, tag, fields)?;
289 store
290 .retry_after_gc_async(limiter, (), asyncness, |store, ()| {
291 Self::new_unchecked(store, allocator, tag, fields)
292 })
293 .await
294 }
295
296 fn type_check_tag_and_fields(
299 store: &mut StoreOpaque,
300 allocator: &ExnRefPre,
301 tag: &Tag,
302 fields: &[Val],
303 ) -> Result<(), Error> {
304 assert!(
305 tag.comes_from_same_store(store),
306 "tag comes from the wrong store"
307 );
308 ensure!(
309 tag.wasmtime_ty(store).signature.unwrap_engine_type_index()
310 == allocator.ty.tag_type().ty().type_index(),
311 "incorrect signature for tag when creating exception object"
312 );
313 let expected_len = allocator.ty.fields().len();
314 let actual_len = fields.len();
315 ensure!(
316 actual_len == expected_len,
317 "expected {expected_len} fields, got {actual_len}"
318 );
319 for (ty, val) in allocator.ty.fields().zip(fields) {
320 assert!(
321 val.comes_from_same_store(store),
322 "field value comes from the wrong store",
323 );
324 val.validate_rooted().context("unrooted field value")?;
326 let ty = ty.element_type().unpack();
327 val.ensure_matches_ty(store, ty)
328 .context("field type mismatch")?;
329 }
330 Ok(())
331 }
332
333 fn new_unchecked(
338 store: &mut StoreOpaque,
339 allocator: &ExnRefPre,
340 tag: &Tag,
341 fields: &[Val],
342 ) -> Result<Rooted<ExnRef>> {
343 assert_eq!(
344 store.id(),
345 allocator.store_id,
346 "attempted to use a `ExnRefPre` with the wrong store"
347 );
348
349 let exnref = store
352 .require_gc_store_mut()?
353 .alloc_uninit_exn(allocator.type_index(), &allocator.layout())
354 .context("unrecoverable error when allocating new `exnref`")?
355 .map_err(|n| GcHeapOutOfMemory::new((), n))?;
356
357 let mut store = AutoAssertNoGc::new(store);
362 match (|| {
363 let (instance, index) = tag.to_raw_indices();
364 exnref.initialize_tag(&mut store, instance, index)?;
365 for (index, (ty, val)) in allocator.ty.fields().zip(fields).enumerate() {
366 exnref.initialize_field(
367 &mut store,
368 allocator.layout(),
369 ty.element_type(),
370 index,
371 *val,
372 )?;
373 }
374 Ok(())
375 })() {
376 Ok(()) => Ok(Rooted::new(&mut store, exnref.into())),
377 Err(e) => {
378 store.require_gc_store_mut()?.dealloc_uninit_exn(exnref)?;
379 Err(e)
380 }
381 }
382 }
383
384 pub(crate) fn type_index(&self, store: &StoreOpaque) -> Result<VMSharedTypeIndex> {
385 let gc_ref = self.inner.try_gc_ref(store)?;
386 let header = store.require_gc_store()?.header(gc_ref)?;
387 debug_assert!(header.matches_kind(VMGcKind::ExnRef));
388 match header.ty() {
389 Some(ty) => Ok(ty),
390 None => bail_bug!("exnrefs should have concrete types"),
391 }
392 }
393
394 pub(crate) fn from_cloned_gc_ref(
401 store: &mut AutoAssertNoGc<'_>,
402 gc_ref: VMGcRef,
403 ) -> Rooted<Self> {
404 debug_assert!(
405 store
406 .unwrap_gc_store()
407 .kind(&gc_ref)
408 .unwrap()
409 .matches(VMGcKind::ExnRef)
410 );
411 Rooted::new(store, gc_ref)
412 }
413
414 #[inline]
415 pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
416 self.inner.comes_from_same_store(store)
417 }
418
419 pub fn to_raw(&self, mut store: impl AsContextMut) -> Result<u32> {
432 let mut store = AutoAssertNoGc::new(store.as_context_mut().0);
433 self._to_raw(&mut store)
434 }
435
436 pub(crate) fn _to_raw(&self, store: &mut AutoAssertNoGc<'_>) -> Result<u32> {
437 self.inner.expose_gc_ref_to_wasm(store).map(|r| r.get())
438 }
439
440 pub fn ty(&self, store: impl AsContext) -> Result<ExnType> {
450 self._ty(store.as_context().0)
451 }
452
453 pub(crate) fn _ty(&self, store: &StoreOpaque) -> Result<ExnType> {
454 assert!(self.comes_from_same_store(store));
455 let index = self.type_index(store)?;
456 match ExnType::from_shared_type_index(store.engine(), index) {
457 Some(ty) => Ok(ty),
458 None => bail_bug!("invalid exception type index"),
459 }
460 }
461
462 pub fn matches_ty(&self, store: impl AsContext, ty: &HeapType) -> Result<bool> {
474 self._matches_ty(store.as_context().0, ty)
475 }
476
477 pub(crate) fn _matches_ty(&self, store: &StoreOpaque, ty: &HeapType) -> Result<bool> {
478 assert!(self.comes_from_same_store(store));
479 self.inner.try_gc_ref(store)?;
480 Ok(HeapType::Exn.matches(ty))
481 }
482
483 pub(crate) fn ensure_matches_ty(&self, store: &StoreOpaque, ty: &HeapType) -> Result<()> {
484 if !self.comes_from_same_store(store) {
485 bail!("function used with wrong store");
486 }
487 if self._matches_ty(store, ty)? {
488 Ok(())
489 } else {
490 let actual_ty = self._ty(store)?;
491 bail!("type mismatch: expected `(ref {ty})`, found `(ref {actual_ty})`")
492 }
493 }
494
495 pub fn fields<'a, T: 'static>(
511 &'a self,
512 store: impl Into<StoreContext<'a, T>>,
513 ) -> Result<impl ExactSizeIterator<Item = Val> + 'a> {
514 self._fields(store.into().0)
515 }
516
517 pub(crate) fn _fields<'a>(
518 &'a self,
519 store: &'a StoreOpaque,
520 ) -> Result<impl ExactSizeIterator<Item = Val> + 'a> {
521 assert!(self.comes_from_same_store(store));
522
523 let gc_ref = self.inner.try_gc_ref(store)?;
524 let header = store.require_gc_store()?.header(gc_ref)?;
525 debug_assert!(header.matches_kind(VMGcKind::ExnRef));
526
527 let index = match header.ty() {
528 Some(index) => index,
529 None => bail_bug!("exnrefs should have concrete types"),
530 };
531 let ty = match ExnType::from_shared_type_index(store.engine(), index) {
532 Some(ty) => ty,
533 None => bail_bug!("invalid exception type index"),
534 };
535 let len = ty.fields().len();
536
537 return Ok(Fields {
538 exnref: self,
539 store,
540 index: 0,
541 len,
542 });
543
544 struct Fields<'a> {
545 exnref: &'a ExnRef,
546 store: &'a StoreOpaque,
547 index: usize,
548 len: usize,
549 }
550
551 impl Iterator for Fields<'_> {
552 type Item = Val;
553
554 #[inline]
555 fn next(&mut self) -> Option<Self::Item> {
556 let i = self.index;
557 debug_assert!(i <= self.len);
558 if i >= self.len {
559 return None;
560 }
561 self.index += 1;
562 self.exnref._field(self.store, i).ok()
563 }
564
565 #[inline]
566 fn size_hint(&self) -> (usize, Option<usize>) {
567 let len = self.len - self.index;
568 (len, Some(len))
569 }
570 }
571
572 impl ExactSizeIterator for Fields<'_> {
573 #[inline]
574 fn len(&self) -> usize {
575 self.len - self.index
576 }
577 }
578 }
579
580 fn header<'a>(&self, store: &'a StoreOpaque) -> Result<&'a VMGcHeader> {
581 assert!(self.comes_from_same_store(&store));
582 let gc_ref = self.inner.try_gc_ref(store)?;
583 Ok(store.require_gc_store()?.header(gc_ref)?)
584 }
585
586 fn exnref<'a>(&self, store: &'a StoreOpaque) -> Result<&'a VMExnRef> {
587 assert!(self.comes_from_same_store(&store));
588 let gc_ref = self.inner.try_gc_ref(store)?;
589 debug_assert!(self.header(store)?.matches_kind(VMGcKind::ExnRef));
590 Ok(gc_ref.as_exnref_unchecked())
591 }
592
593 fn layout(&self, store: &StoreOpaque) -> Result<Arc<GcStructLayout>> {
594 assert!(self.comes_from_same_store(&store));
595 let type_index = self.type_index(store)?;
596 super::gc_struct_layout(store.engine(), type_index)
597 }
598
599 fn field_ty(&self, store: &StoreOpaque, field: usize) -> Result<FieldType> {
600 let ty = self._ty(store)?;
601 match ty.field(field) {
602 Some(f) => Ok(f),
603 None => {
604 let len = ty.fields().len();
605 bail!("cannot access field {field}: exn only has {len} fields")
606 }
607 }
608 }
609
610 pub fn field(&self, store: impl AsContext, index: usize) -> Result<Val> {
627 self._field(store.as_context().0, index)
628 }
629
630 pub(crate) fn _field(&self, store: &StoreOpaque, index: usize) -> Result<Val> {
631 assert!(self.comes_from_same_store(store));
632 let exnref = self.exnref(store)?;
633 let field_ty = self.field_ty(store, index)?;
634 let layout = self.layout(store)?;
635 exnref.read_field(store, &layout, field_ty.element_type(), index)
636 }
637
638 pub fn tag(&self, store: impl AsContext) -> Result<Tag> {
648 let store = store.as_context().0;
649 assert!(self.comes_from_same_store(store));
650 let (instance, index) = self.exnref(store)?.tag(store)?;
651 match Tag::from_raw_indices(store, instance, index) {
652 Some(tag) => Ok(tag),
653 None => bail_bug!("invalid tag indices in exception object"),
654 }
655 }
656}
657
658unsafe impl WasmTy for Rooted<ExnRef> {
659 #[inline]
660 fn valtype() -> ValType {
661 ValType::Ref(RefType::new(false, HeapType::Exn))
662 }
663
664 #[inline]
665 fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
666 self.comes_from_same_store(store)
667 }
668
669 #[inline]
670 fn dynamic_concrete_type_check(
671 &self,
672 store: &StoreOpaque,
673 _nullable: bool,
674 ty: &HeapType,
675 ) -> Result<()> {
676 self.ensure_matches_ty(store, ty)
677 }
678
679 fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
680 self.wasm_ty_store(store, ptr, ValRaw::anyref)
681 }
682
683 unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
684 Self::wasm_ty_load(store, ptr.get_anyref(), ExnRef::from_cloned_gc_ref)
685 }
686}
687
688unsafe impl WasmTy for Option<Rooted<ExnRef>> {
689 #[inline]
690 fn valtype() -> ValType {
691 ValType::EXNREF
692 }
693
694 #[inline]
695 fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
696 self.map_or(true, |x| x.comes_from_same_store(store))
697 }
698
699 #[inline]
700 fn dynamic_concrete_type_check(
701 &self,
702 store: &StoreOpaque,
703 nullable: bool,
704 ty: &HeapType,
705 ) -> Result<()> {
706 match self {
707 Some(a) => a.ensure_matches_ty(store, ty),
708 None => {
709 ensure!(
710 nullable,
711 "expected a non-null reference, but found a null reference"
712 );
713 Ok(())
714 }
715 }
716 }
717
718 #[inline]
719 fn is_vmgcref_and_points_to_object(&self) -> bool {
720 self.is_some()
721 }
722
723 fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
724 <Rooted<ExnRef>>::wasm_ty_option_store(self, store, ptr, ValRaw::anyref)
725 }
726
727 unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
728 <Rooted<ExnRef>>::wasm_ty_option_load(store, ptr.get_anyref(), ExnRef::from_cloned_gc_ref)
729 }
730}
731
732unsafe impl WasmTy for OwnedRooted<ExnRef> {
733 #[inline]
734 fn valtype() -> ValType {
735 ValType::Ref(RefType::new(false, HeapType::Exn))
736 }
737
738 #[inline]
739 fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
740 self.comes_from_same_store(store)
741 }
742
743 #[inline]
744 fn dynamic_concrete_type_check(
745 &self,
746 store: &StoreOpaque,
747 _nullable: bool,
748 ty: &HeapType,
749 ) -> Result<()> {
750 self.ensure_matches_ty(store, ty)
751 }
752
753 fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
754 self.wasm_ty_store(store, ptr, ValRaw::anyref)
755 }
756
757 unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
758 Self::wasm_ty_load(store, ptr.get_anyref(), ExnRef::from_cloned_gc_ref)
759 }
760}
761
762unsafe impl WasmTy for Option<OwnedRooted<ExnRef>> {
763 #[inline]
764 fn valtype() -> ValType {
765 ValType::EXNREF
766 }
767
768 #[inline]
769 fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
770 self.as_ref()
771 .map_or(true, |x| x.comes_from_same_store(store))
772 }
773
774 #[inline]
775 fn dynamic_concrete_type_check(
776 &self,
777 store: &StoreOpaque,
778 nullable: bool,
779 ty: &HeapType,
780 ) -> Result<()> {
781 match self {
782 Some(a) => a.ensure_matches_ty(store, ty),
783 None => {
784 ensure!(
785 nullable,
786 "expected a non-null reference, but found a null reference"
787 );
788 Ok(())
789 }
790 }
791 }
792
793 #[inline]
794 fn is_vmgcref_and_points_to_object(&self) -> bool {
795 self.is_some()
796 }
797
798 fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
799 <OwnedRooted<ExnRef>>::wasm_ty_option_store(self, store, ptr, ValRaw::anyref)
800 }
801
802 unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
803 <OwnedRooted<ExnRef>>::wasm_ty_option_load(
804 store,
805 ptr.get_anyref(),
806 ExnRef::from_cloned_gc_ref,
807 )
808 }
809}