1 //! Working with GC `struct` objects. 2 3 use crate::runtime::vm::VMGcRef; 4 use crate::store::StoreId; 5 use crate::vm::{VMGcHeader, VMStructRef}; 6 use crate::{AnyRef, FieldType}; 7 use crate::{ 8 AsContext, AsContextMut, EqRef, GcHeapOutOfMemory, GcRefImpl, GcRootIndex, HeapType, 9 ManuallyRooted, RefType, Rooted, StructType, Val, ValRaw, ValType, WasmTy, 10 prelude::*, 11 store::{AutoAssertNoGc, StoreContextMut, StoreOpaque}, 12 }; 13 use core::mem::{self, MaybeUninit}; 14 use wasmtime_environ::{GcLayout, GcStructLayout, VMGcKind, VMSharedTypeIndex}; 15 16 /// An allocator for a particular Wasm GC struct type. 17 /// 18 /// Every `StructRefPre` is associated with a particular 19 /// [`Store`][crate::Store] and a particular [StructType][crate::StructType]. 20 /// 21 /// Reusing an allocator across many allocations amortizes some per-type runtime 22 /// overheads inside Wasmtime. A `StructRefPre` is to `StructRef`s as an 23 /// `InstancePre` is to `Instance`s. 24 /// 25 /// # Example 26 /// 27 /// ``` 28 /// use wasmtime::*; 29 /// 30 /// # fn foo() -> Result<()> { 31 /// let mut config = Config::new(); 32 /// config.wasm_function_references(true); 33 /// config.wasm_gc(true); 34 /// 35 /// let engine = Engine::new(&config)?; 36 /// let mut store = Store::new(&engine, ()); 37 /// 38 /// // Define a struct type. 39 /// let struct_ty = StructType::new( 40 /// store.engine(), 41 /// [FieldType::new(Mutability::Var, StorageType::I8)], 42 /// )?; 43 /// 44 /// // Create an allocator for the struct type. 45 /// let allocator = StructRefPre::new(&mut store, struct_ty); 46 /// 47 /// { 48 /// let mut scope = RootScope::new(&mut store); 49 /// 50 /// // Allocate a bunch of instances of our struct type using the same 51 /// // allocator! This is faster than creating a new allocator for each 52 /// // instance we want to allocate. 53 /// for i in 0..10 { 54 /// StructRef::new(&mut scope, &allocator, &[Val::I32(i)])?; 55 /// } 56 /// } 57 /// # Ok(()) 58 /// # } 59 /// # foo().unwrap(); 60 /// ``` 61 pub struct StructRefPre { 62 store_id: StoreId, 63 ty: StructType, 64 } 65 66 impl StructRefPre { 67 /// Create a new `StructRefPre` that is associated with the given store 68 /// and type. 69 pub fn new(mut store: impl AsContextMut, ty: StructType) -> Self { 70 Self::_new(store.as_context_mut().0, ty) 71 } 72 73 pub(crate) fn _new(store: &mut StoreOpaque, ty: StructType) -> Self { 74 store.insert_gc_host_alloc_type(ty.registered_type().clone()); 75 let store_id = store.id(); 76 77 StructRefPre { store_id, ty } 78 } 79 80 pub(crate) fn layout(&self) -> &GcStructLayout { 81 self.ty 82 .registered_type() 83 .layout() 84 .expect("struct types have a layout") 85 .unwrap_struct() 86 } 87 88 pub(crate) fn type_index(&self) -> VMSharedTypeIndex { 89 self.ty.registered_type().index() 90 } 91 } 92 93 /// A reference to a GC-managed `struct` instance. 94 /// 95 /// WebAssembly `struct`s are static, fixed-length, ordered sequences of 96 /// fields. Fields are named by index, not by identifier; in this way, they are 97 /// similar to Rust's tuples. Each field is mutable or constant and stores 98 /// unpacked [`Val`][crate::Val]s or packed 8-/16-bit integers. 99 /// 100 /// Like all WebAssembly references, these are opaque and unforgeable to Wasm: 101 /// they cannot be faked and Wasm cannot, for example, cast the integer 102 /// `0x12345678` into a reference, pretend it is a valid `structref`, and trick 103 /// the host into dereferencing it and segfaulting or worse. 104 /// 105 /// Note that you can also use `Rooted<StructRef>` and 106 /// `ManuallyRooted<StructRef>` as a type parameter with 107 /// [`Func::typed`][crate::Func::typed]- and 108 /// [`Func::wrap`][crate::Func::wrap]-style APIs. 109 /// 110 /// # Example 111 /// 112 /// ``` 113 /// use wasmtime::*; 114 /// 115 /// # fn foo() -> Result<()> { 116 /// let mut config = Config::new(); 117 /// config.wasm_function_references(true); 118 /// config.wasm_gc(true); 119 /// 120 /// let engine = Engine::new(&config)?; 121 /// let mut store = Store::new(&engine, ()); 122 /// 123 /// // Define a struct type. 124 /// let struct_ty = StructType::new( 125 /// store.engine(), 126 /// [FieldType::new(Mutability::Var, StorageType::I8)], 127 /// )?; 128 /// 129 /// // Create an allocator for the struct type. 130 /// let allocator = StructRefPre::new(&mut store, struct_ty); 131 /// 132 /// { 133 /// let mut scope = RootScope::new(&mut store); 134 /// 135 /// // Allocate an instance of the struct type. 136 /// let my_struct = StructRef::new(&mut scope, &allocator, &[Val::I32(42)])?; 137 /// 138 /// // That instance's field should have the expected value. 139 /// let val = my_struct.field(&mut scope, 0)?.unwrap_i32(); 140 /// assert_eq!(val, 42); 141 /// 142 /// // And we can update the field's value because it is a mutable field. 143 /// my_struct.set_field(&mut scope, 0, Val::I32(36))?; 144 /// let new_val = my_struct.field(&mut scope, 0)?.unwrap_i32(); 145 /// assert_eq!(new_val, 36); 146 /// } 147 /// # Ok(()) 148 /// # } 149 /// # foo().unwrap(); 150 /// ``` 151 #[derive(Debug)] 152 #[repr(transparent)] 153 pub struct StructRef { 154 pub(super) inner: GcRootIndex, 155 } 156 157 unsafe impl GcRefImpl for StructRef { 158 fn transmute_ref(index: &GcRootIndex) -> &Self { 159 // Safety: `StructRef` is a newtype of a `GcRootIndex`. 160 let me: &Self = unsafe { mem::transmute(index) }; 161 162 // Assert we really are just a newtype of a `GcRootIndex`. 163 assert!(matches!( 164 me, 165 Self { 166 inner: GcRootIndex { .. }, 167 } 168 )); 169 170 me 171 } 172 } 173 174 impl Rooted<StructRef> { 175 /// Upcast this `structref` into an `anyref`. 176 #[inline] 177 pub fn to_anyref(self) -> Rooted<AnyRef> { 178 self.unchecked_cast() 179 } 180 181 /// Upcast this `structref` into an `eqref`. 182 #[inline] 183 pub fn to_eqref(self) -> Rooted<EqRef> { 184 self.unchecked_cast() 185 } 186 } 187 188 impl ManuallyRooted<StructRef> { 189 /// Upcast this `structref` into an `anyref`. 190 #[inline] 191 pub fn to_anyref(self) -> ManuallyRooted<AnyRef> { 192 self.unchecked_cast() 193 } 194 195 /// Upcast this `structref` into an `eqref`. 196 #[inline] 197 pub fn to_eqref(self) -> ManuallyRooted<EqRef> { 198 self.unchecked_cast() 199 } 200 } 201 202 impl StructRef { 203 /// Synchronously allocate a new `struct` and get a reference to it. 204 /// 205 /// # Automatic Garbage Collection 206 /// 207 /// If the GC heap is at capacity, and there isn't room for allocating this 208 /// new struct, then this method will automatically trigger a synchronous 209 /// collection in an attempt to free up space in the GC heap. 210 /// 211 /// # Errors 212 /// 213 /// If the given `fields` values' types do not match the field types of the 214 /// `allocator`'s struct type, an error is returned. 215 /// 216 /// If the allocation cannot be satisfied because the GC heap is currently 217 /// out of memory, then a [`GcHeapOutOfMemory<()>`][crate::GcHeapOutOfMemory] 218 /// error is returned. The allocation might succeed on a second attempt if 219 /// you drop some rooted GC references and try again. 220 /// 221 /// # Panics 222 /// 223 /// Panics if your engine is configured for async; use 224 /// [`StructRef::new_async`][crate::StructRef::new_async] to perform 225 /// synchronous allocation instead. 226 /// 227 /// Panics if the allocator, or any of the field values, is not associated 228 /// with the given store. 229 pub fn new( 230 mut store: impl AsContextMut, 231 allocator: &StructRefPre, 232 fields: &[Val], 233 ) -> Result<Rooted<StructRef>> { 234 Self::_new(store.as_context_mut().0, allocator, fields) 235 } 236 237 pub(crate) fn _new( 238 store: &mut StoreOpaque, 239 allocator: &StructRefPre, 240 fields: &[Val], 241 ) -> Result<Rooted<StructRef>> { 242 assert!( 243 !store.async_support(), 244 "use `StructRef::new_async` with asynchronous stores" 245 ); 246 Self::type_check_fields(store, allocator, fields)?; 247 store.retry_after_gc((), |store, ()| { 248 Self::new_unchecked(store, allocator, fields) 249 }) 250 } 251 252 /// Asynchronously allocate a new `struct` and get a reference to it. 253 /// 254 /// # Automatic Garbage Collection 255 /// 256 /// If the GC heap is at capacity, and there isn't room for allocating this 257 /// new struct, then this method will automatically trigger a synchronous 258 /// collection in an attempt to free up space in the GC heap. 259 /// 260 /// # Errors 261 /// 262 /// If the given `fields` values' types do not match the field types of the 263 /// `allocator`'s struct type, an error is returned. 264 /// 265 /// If the allocation cannot be satisfied because the GC heap is currently 266 /// out of memory, then a [`GcHeapOutOfMemory<()>`][crate::GcHeapOutOfMemory] 267 /// error is returned. The allocation might succeed on a second attempt if 268 /// you drop some rooted GC references and try again. 269 /// 270 /// # Panics 271 /// 272 /// Panics if your engine is not configured for async; use 273 /// [`StructRef::new`][crate::StructRef::new] to perform synchronous 274 /// allocation instead. 275 /// 276 /// Panics if the allocator, or any of the field values, is not associated 277 /// with the given store. 278 #[cfg(feature = "async")] 279 pub async fn new_async( 280 mut store: impl AsContextMut, 281 allocator: &StructRefPre, 282 fields: &[Val], 283 ) -> Result<Rooted<StructRef>> { 284 Self::_new_async(store.as_context_mut().0, allocator, fields).await 285 } 286 287 #[cfg(feature = "async")] 288 pub(crate) async fn _new_async( 289 store: &mut StoreOpaque, 290 allocator: &StructRefPre, 291 fields: &[Val], 292 ) -> Result<Rooted<StructRef>> { 293 assert!( 294 store.async_support(), 295 "use `StructRef::new` with synchronous stores" 296 ); 297 Self::type_check_fields(store, allocator, fields)?; 298 store 299 .retry_after_gc_async((), |store, ()| { 300 Self::new_unchecked(store, allocator, fields) 301 }) 302 .await 303 } 304 305 /// Like `Self::new` but caller's must ensure that if the store is 306 /// configured for async, this is only ever called from on a fiber stack. 307 pub(crate) unsafe fn new_maybe_async( 308 store: &mut StoreOpaque, 309 allocator: &StructRefPre, 310 fields: &[Val], 311 ) -> Result<Rooted<StructRef>> { 312 Self::type_check_fields(store, allocator, fields)?; 313 unsafe { 314 store.retry_after_gc_maybe_async((), |store, ()| { 315 Self::new_unchecked(store, allocator, fields) 316 }) 317 } 318 } 319 320 /// Type check the field values before allocating a new struct. 321 fn type_check_fields( 322 store: &mut StoreOpaque, 323 allocator: &StructRefPre, 324 fields: &[Val], 325 ) -> Result<(), Error> { 326 let expected_len = allocator.ty.fields().len(); 327 let actual_len = fields.len(); 328 ensure!( 329 actual_len == expected_len, 330 "expected {expected_len} fields, got {actual_len}" 331 ); 332 for (ty, val) in allocator.ty.fields().zip(fields) { 333 assert!( 334 val.comes_from_same_store(store), 335 "field value comes from the wrong store", 336 ); 337 let ty = ty.element_type().unpack(); 338 val.ensure_matches_ty(store, ty) 339 .context("field type mismatch")?; 340 } 341 Ok(()) 342 } 343 344 /// Given that the field values have already been type checked, allocate a 345 /// new struct. 346 /// 347 /// Does not attempt GC+retry on OOM, that is the caller's responsibility. 348 fn new_unchecked( 349 store: &mut StoreOpaque, 350 allocator: &StructRefPre, 351 fields: &[Val], 352 ) -> Result<Rooted<StructRef>> { 353 assert_eq!( 354 store.id(), 355 allocator.store_id, 356 "attempted to use a `StructRefPre` with the wrong store" 357 ); 358 359 // Allocate the struct and write each field value into the appropriate 360 // offset. 361 let structref = store 362 .require_gc_store_mut()? 363 .alloc_uninit_struct(allocator.type_index(), &allocator.layout()) 364 .context("unrecoverable error when allocating new `structref`")? 365 .map_err(|n| GcHeapOutOfMemory::new((), n))?; 366 367 // From this point on, if we get any errors, then the struct is not 368 // fully initialized, so we need to eagerly deallocate it before the 369 // next GC where the collector might try to interpret one of the 370 // uninitialized fields as a GC reference. 371 let mut store = AutoAssertNoGc::new(store); 372 match (|| { 373 for (index, (ty, val)) in allocator.ty.fields().zip(fields).enumerate() { 374 structref.initialize_field( 375 &mut store, 376 allocator.layout(), 377 ty.element_type(), 378 index, 379 *val, 380 )?; 381 } 382 Ok(()) 383 })() { 384 Ok(()) => Ok(Rooted::new(&mut store, structref.into())), 385 Err(e) => { 386 store 387 .require_gc_store_mut()? 388 .dealloc_uninit_struct(structref); 389 Err(e) 390 } 391 } 392 } 393 394 #[inline] 395 pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool { 396 self.inner.comes_from_same_store(store) 397 } 398 399 /// Get this `structref`'s type. 400 /// 401 /// # Errors 402 /// 403 /// Return an error if this reference has been unrooted. 404 /// 405 /// # Panics 406 /// 407 /// Panics if this reference is associated with a different store. 408 pub fn ty(&self, store: impl AsContext) -> Result<StructType> { 409 self._ty(store.as_context().0) 410 } 411 412 pub(crate) fn _ty(&self, store: &StoreOpaque) -> Result<StructType> { 413 assert!(self.comes_from_same_store(store)); 414 let index = self.type_index(store)?; 415 Ok(StructType::from_shared_type_index(store.engine(), index)) 416 } 417 418 /// Does this `structref` match the given type? 419 /// 420 /// That is, is this struct's type a subtype of the given type? 421 /// 422 /// # Errors 423 /// 424 /// Return an error if this reference has been unrooted. 425 /// 426 /// # Panics 427 /// 428 /// Panics if this reference is associated with a different store or if the 429 /// type is not associated with the store's engine. 430 pub fn matches_ty(&self, store: impl AsContext, ty: &StructType) -> Result<bool> { 431 self._matches_ty(store.as_context().0, ty) 432 } 433 434 pub(crate) fn _matches_ty(&self, store: &StoreOpaque, ty: &StructType) -> Result<bool> { 435 assert!(self.comes_from_same_store(store)); 436 Ok(self._ty(store)?.matches(ty)) 437 } 438 439 pub(crate) fn ensure_matches_ty(&self, store: &StoreOpaque, ty: &StructType) -> Result<()> { 440 if !self.comes_from_same_store(store) { 441 bail!("function used with wrong store"); 442 } 443 if self._matches_ty(store, ty)? { 444 Ok(()) 445 } else { 446 let actual_ty = self._ty(store)?; 447 bail!("type mismatch: expected `(ref {ty})`, found `(ref {actual_ty})`") 448 } 449 } 450 451 /// Get the values of this struct's fields. 452 /// 453 /// Note that `i8` and `i16` field values are zero-extended into 454 /// `Val::I32(_)`s. 455 /// 456 /// # Errors 457 /// 458 /// Return an error if this reference has been unrooted. 459 /// 460 /// # Panics 461 /// 462 /// Panics if this reference is associated with a different store. 463 pub fn fields<'a, T: 'static>( 464 &'a self, 465 store: impl Into<StoreContextMut<'a, T>>, 466 ) -> Result<impl ExactSizeIterator<Item = Val> + 'a> { 467 self._fields(store.into().0) 468 } 469 470 pub(crate) fn _fields<'a>( 471 &'a self, 472 store: &'a mut StoreOpaque, 473 ) -> Result<impl ExactSizeIterator<Item = Val> + 'a> { 474 assert!(self.comes_from_same_store(store)); 475 let store = AutoAssertNoGc::new(store); 476 477 let gc_ref = self.inner.try_gc_ref(&store)?; 478 let header = store.require_gc_store()?.header(gc_ref); 479 debug_assert!(header.kind().matches(VMGcKind::StructRef)); 480 481 let index = header.ty().expect("structrefs should have concrete types"); 482 let ty = StructType::from_shared_type_index(store.engine(), index); 483 let len = ty.fields().len(); 484 485 return Ok(Fields { 486 structref: self, 487 store, 488 index: 0, 489 len, 490 }); 491 492 struct Fields<'a, 'b> { 493 structref: &'a StructRef, 494 store: AutoAssertNoGc<'b>, 495 index: usize, 496 len: usize, 497 } 498 499 impl Iterator for Fields<'_, '_> { 500 type Item = Val; 501 502 #[inline] 503 fn next(&mut self) -> Option<Self::Item> { 504 let i = self.index; 505 debug_assert!(i <= self.len); 506 if i >= self.len { 507 return None; 508 } 509 self.index += 1; 510 Some(self.structref._field(&mut self.store, i).unwrap()) 511 } 512 513 #[inline] 514 fn size_hint(&self) -> (usize, Option<usize>) { 515 let len = self.len - self.index; 516 (len, Some(len)) 517 } 518 } 519 520 impl ExactSizeIterator for Fields<'_, '_> { 521 #[inline] 522 fn len(&self) -> usize { 523 self.len - self.index 524 } 525 } 526 } 527 528 fn header<'a>(&self, store: &'a AutoAssertNoGc<'_>) -> Result<&'a VMGcHeader> { 529 assert!(self.comes_from_same_store(&store)); 530 let gc_ref = self.inner.try_gc_ref(store)?; 531 Ok(store.require_gc_store()?.header(gc_ref)) 532 } 533 534 fn structref<'a>(&self, store: &'a AutoAssertNoGc<'_>) -> Result<&'a VMStructRef> { 535 assert!(self.comes_from_same_store(&store)); 536 let gc_ref = self.inner.try_gc_ref(store)?; 537 debug_assert!(self.header(store)?.kind().matches(VMGcKind::StructRef)); 538 Ok(gc_ref.as_structref_unchecked()) 539 } 540 541 fn layout(&self, store: &AutoAssertNoGc<'_>) -> Result<GcStructLayout> { 542 assert!(self.comes_from_same_store(&store)); 543 let type_index = self.type_index(store)?; 544 let layout = store 545 .engine() 546 .signatures() 547 .layout(type_index) 548 .expect("struct types should have GC layouts"); 549 match layout { 550 GcLayout::Struct(s) => Ok(s), 551 GcLayout::Array(_) => unreachable!(), 552 GcLayout::Exception(_) => unreachable!(), 553 } 554 } 555 556 fn field_ty(&self, store: &StoreOpaque, field: usize) -> Result<FieldType> { 557 let ty = self._ty(store)?; 558 match ty.field(field) { 559 Some(f) => Ok(f), 560 None => { 561 let len = ty.fields().len(); 562 bail!("cannot access field {field}: struct only has {len} fields") 563 } 564 } 565 } 566 567 /// Get this struct's `index`th field. 568 /// 569 /// Note that `i8` and `i16` field values are zero-extended into 570 /// `Val::I32(_)`s. 571 /// 572 /// # Errors 573 /// 574 /// Returns an `Err(_)` if the index is out of bounds or this reference has 575 /// been unrooted. 576 /// 577 /// # Panics 578 /// 579 /// Panics if this reference is associated with a different store. 580 pub fn field(&self, mut store: impl AsContextMut, index: usize) -> Result<Val> { 581 let mut store = AutoAssertNoGc::new(store.as_context_mut().0); 582 self._field(&mut store, index) 583 } 584 585 pub(crate) fn _field(&self, store: &mut AutoAssertNoGc<'_>, index: usize) -> Result<Val> { 586 assert!(self.comes_from_same_store(store)); 587 let structref = self.structref(store)?.unchecked_copy(); 588 let field_ty = self.field_ty(store, index)?; 589 let layout = self.layout(store)?; 590 Ok(structref.read_field(store, &layout, field_ty.element_type(), index)) 591 } 592 593 /// Set this struct's `index`th field. 594 /// 595 /// # Errors 596 /// 597 /// Returns an error in the following scenarios: 598 /// 599 /// * When given a value of the wrong type, such as trying to set an `f32` 600 /// field to an `i64` value. 601 /// 602 /// * When the field is not mutable. 603 /// 604 /// * When this struct does not have an `index`th field, i.e. `index` is out 605 /// of bounds. 606 /// 607 /// * When `value` is a GC reference that has since been unrooted. 608 /// 609 /// # Panics 610 /// 611 /// Panics if this reference is associated with a different store. 612 pub fn set_field(&self, mut store: impl AsContextMut, index: usize, value: Val) -> Result<()> { 613 self._set_field(store.as_context_mut().0, index, value) 614 } 615 616 pub(crate) fn _set_field( 617 &self, 618 store: &mut StoreOpaque, 619 index: usize, 620 value: Val, 621 ) -> Result<()> { 622 assert!(self.comes_from_same_store(store)); 623 let mut store = AutoAssertNoGc::new(store); 624 625 let field_ty = self.field_ty(&store, index)?; 626 ensure!( 627 field_ty.mutability().is_var(), 628 "cannot set field {index}: field is not mutable" 629 ); 630 631 value 632 .ensure_matches_ty(&store, &field_ty.element_type().unpack()) 633 .with_context(|| format!("cannot set field {index}: type mismatch"))?; 634 635 let layout = self.layout(&store)?; 636 let structref = self.structref(&store)?.unchecked_copy(); 637 638 structref.write_field(&mut store, &layout, field_ty.element_type(), index, value) 639 } 640 641 pub(crate) fn type_index(&self, store: &StoreOpaque) -> Result<VMSharedTypeIndex> { 642 let gc_ref = self.inner.try_gc_ref(store)?; 643 let header = store.require_gc_store()?.header(gc_ref); 644 debug_assert!(header.kind().matches(VMGcKind::StructRef)); 645 Ok(header.ty().expect("structrefs should have concrete types")) 646 } 647 648 /// Create a new `Rooted<StructRef>` from the given GC reference. 649 /// 650 /// `gc_ref` should point to a valid `structref` and should belong to the 651 /// store's GC heap. Failure to uphold these invariants is memory safe but 652 /// will lead to general incorrectness such as panics or wrong results. 653 pub(crate) fn from_cloned_gc_ref( 654 store: &mut AutoAssertNoGc<'_>, 655 gc_ref: VMGcRef, 656 ) -> Rooted<Self> { 657 debug_assert!(gc_ref.is_structref(&*store.unwrap_gc_store().gc_heap)); 658 Rooted::new(store, gc_ref) 659 } 660 } 661 662 unsafe impl WasmTy for Rooted<StructRef> { 663 #[inline] 664 fn valtype() -> ValType { 665 ValType::Ref(RefType::new(false, HeapType::Struct)) 666 } 667 668 #[inline] 669 fn compatible_with_store(&self, store: &StoreOpaque) -> bool { 670 self.comes_from_same_store(store) 671 } 672 673 #[inline] 674 fn dynamic_concrete_type_check( 675 &self, 676 store: &StoreOpaque, 677 _nullable: bool, 678 ty: &HeapType, 679 ) -> Result<()> { 680 match ty { 681 HeapType::Any | HeapType::Eq | HeapType::Struct => Ok(()), 682 HeapType::ConcreteStruct(ty) => self.ensure_matches_ty(store, ty), 683 684 HeapType::Extern 685 | HeapType::NoExtern 686 | HeapType::Func 687 | HeapType::ConcreteFunc(_) 688 | HeapType::NoFunc 689 | HeapType::I31 690 | HeapType::Array 691 | HeapType::ConcreteArray(_) 692 | HeapType::None 693 | HeapType::NoCont 694 | HeapType::Cont 695 | HeapType::ConcreteCont(_) 696 | HeapType::NoExn 697 | HeapType::Exn 698 | HeapType::ConcreteExn(_) => bail!( 699 "type mismatch: expected `(ref {ty})`, got `(ref {})`", 700 self._ty(store)?, 701 ), 702 } 703 } 704 705 fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> { 706 self.wasm_ty_store(store, ptr, ValRaw::anyref) 707 } 708 709 unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self { 710 Self::wasm_ty_load(store, ptr.get_anyref(), StructRef::from_cloned_gc_ref) 711 } 712 } 713 714 unsafe impl WasmTy for Option<Rooted<StructRef>> { 715 #[inline] 716 fn valtype() -> ValType { 717 ValType::STRUCTREF 718 } 719 720 #[inline] 721 fn compatible_with_store(&self, store: &StoreOpaque) -> bool { 722 self.map_or(true, |x| x.comes_from_same_store(store)) 723 } 724 725 #[inline] 726 fn dynamic_concrete_type_check( 727 &self, 728 store: &StoreOpaque, 729 nullable: bool, 730 ty: &HeapType, 731 ) -> Result<()> { 732 match self { 733 Some(s) => Rooted::<StructRef>::dynamic_concrete_type_check(s, store, nullable, ty), 734 None => { 735 ensure!( 736 nullable, 737 "expected a non-null reference, but found a null reference" 738 ); 739 Ok(()) 740 } 741 } 742 } 743 744 #[inline] 745 fn is_vmgcref_and_points_to_object(&self) -> bool { 746 self.is_some() 747 } 748 749 fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> { 750 <Rooted<StructRef>>::wasm_ty_option_store(self, store, ptr, ValRaw::anyref) 751 } 752 753 unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self { 754 <Rooted<StructRef>>::wasm_ty_option_load( 755 store, 756 ptr.get_anyref(), 757 StructRef::from_cloned_gc_ref, 758 ) 759 } 760 } 761 762 unsafe impl WasmTy for ManuallyRooted<StructRef> { 763 #[inline] 764 fn valtype() -> ValType { 765 ValType::Ref(RefType::new(false, HeapType::Struct)) 766 } 767 768 #[inline] 769 fn compatible_with_store(&self, store: &StoreOpaque) -> bool { 770 self.comes_from_same_store(store) 771 } 772 773 #[inline] 774 fn dynamic_concrete_type_check( 775 &self, 776 store: &StoreOpaque, 777 _: bool, 778 ty: &HeapType, 779 ) -> Result<()> { 780 match ty { 781 HeapType::Any | HeapType::Eq | HeapType::Struct => Ok(()), 782 HeapType::ConcreteStruct(ty) => self.ensure_matches_ty(store, ty), 783 784 HeapType::Extern 785 | HeapType::NoExtern 786 | HeapType::Func 787 | HeapType::ConcreteFunc(_) 788 | HeapType::NoFunc 789 | HeapType::I31 790 | HeapType::Array 791 | HeapType::ConcreteArray(_) 792 | HeapType::None 793 | HeapType::NoCont 794 | HeapType::Cont 795 | HeapType::ConcreteCont(_) 796 | HeapType::NoExn 797 | HeapType::Exn 798 | HeapType::ConcreteExn(_) => bail!( 799 "type mismatch: expected `(ref {ty})`, got `(ref {})`", 800 self._ty(store)?, 801 ), 802 } 803 } 804 805 fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> { 806 self.wasm_ty_store(store, ptr, ValRaw::anyref) 807 } 808 809 unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self { 810 Self::wasm_ty_load(store, ptr.get_anyref(), StructRef::from_cloned_gc_ref) 811 } 812 } 813 814 unsafe impl WasmTy for Option<ManuallyRooted<StructRef>> { 815 #[inline] 816 fn valtype() -> ValType { 817 ValType::STRUCTREF 818 } 819 820 #[inline] 821 fn compatible_with_store(&self, store: &StoreOpaque) -> bool { 822 self.as_ref() 823 .map_or(true, |x| x.comes_from_same_store(store)) 824 } 825 826 #[inline] 827 fn dynamic_concrete_type_check( 828 &self, 829 store: &StoreOpaque, 830 nullable: bool, 831 ty: &HeapType, 832 ) -> Result<()> { 833 match self { 834 Some(s) => { 835 ManuallyRooted::<StructRef>::dynamic_concrete_type_check(s, store, nullable, ty) 836 } 837 None => { 838 ensure!( 839 nullable, 840 "expected a non-null reference, but found a null reference" 841 ); 842 Ok(()) 843 } 844 } 845 } 846 847 #[inline] 848 fn is_vmgcref_and_points_to_object(&self) -> bool { 849 self.is_some() 850 } 851 852 fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> { 853 <ManuallyRooted<StructRef>>::wasm_ty_option_store(self, store, ptr, ValRaw::anyref) 854 } 855 856 unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self { 857 <ManuallyRooted<StructRef>>::wasm_ty_option_load( 858 store, 859 ptr.get_anyref(), 860 StructRef::from_cloned_gc_ref, 861 ) 862 } 863 } 864