wasmtime/runtime/vm/gc/enabled/
structref.rs

1use super::{truncate_i32_to_i16, truncate_i32_to_i8};
2use crate::{
3    prelude::*,
4    runtime::vm::{GcHeap, GcStore, VMGcRef},
5    store::AutoAssertNoGc,
6    vm::{FuncRefTableId, SendSyncPtr},
7    AnyRef, ExternRef, Func, HeapType, RootedGcRefImpl, StorageType, Val, ValType,
8};
9use core::fmt;
10use wasmtime_environ::{GcStructLayout, VMGcKind};
11
12/// A `VMGcRef` that we know points to a `struct`.
13///
14/// Create a `VMStructRef` via `VMGcRef::into_structref` and
15/// `VMGcRef::as_structref`, or their untyped equivalents
16/// `VMGcRef::into_structref_unchecked` and `VMGcRef::as_structref_unchecked`.
17///
18/// Note: This is not a `TypedGcRef<_>` because each collector can have a
19/// different concrete representation of `structref` that they allocate inside
20/// their heaps.
21#[derive(Debug, PartialEq, Eq, Hash)]
22#[repr(transparent)]
23pub struct VMStructRef(VMGcRef);
24
25impl fmt::Pointer for VMStructRef {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        fmt::Pointer::fmt(&self.0, f)
28    }
29}
30
31impl From<VMStructRef> for VMGcRef {
32    #[inline]
33    fn from(x: VMStructRef) -> Self {
34        x.0
35    }
36}
37
38impl VMGcRef {
39    /// Is this `VMGcRef` pointing to a `struct`?
40    pub fn is_structref(&self, gc_heap: &(impl GcHeap + ?Sized)) -> bool {
41        if self.is_i31() {
42            return false;
43        }
44
45        let header = gc_heap.header(&self);
46        header.kind().matches(VMGcKind::StructRef)
47    }
48
49    /// Create a new `VMStructRef` from the given `gc_ref`.
50    ///
51    /// If this is not a GC reference to an `structref`, `Err(self)` is
52    /// returned.
53    pub fn into_structref(self, gc_heap: &impl GcHeap) -> Result<VMStructRef, VMGcRef> {
54        if self.is_structref(gc_heap) {
55            Ok(self.into_structref_unchecked())
56        } else {
57            Err(self)
58        }
59    }
60
61    /// Create a new `VMStructRef` from `self` without actually checking that
62    /// `self` is an `structref`.
63    ///
64    /// This method does not check that `self` is actually an `structref`, but
65    /// it should be. Failure to uphold this invariant is memory safe but will
66    /// result in general incorrectness down the line such as panics or wrong
67    /// results.
68    #[inline]
69    pub fn into_structref_unchecked(self) -> VMStructRef {
70        debug_assert!(!self.is_i31());
71        VMStructRef(self)
72    }
73
74    /// Get this GC reference as an `structref` reference, if it actually is an
75    /// `structref` reference.
76    pub fn as_structref(&self, gc_heap: &(impl GcHeap + ?Sized)) -> Option<&VMStructRef> {
77        if self.is_structref(gc_heap) {
78            Some(self.as_structref_unchecked())
79        } else {
80            None
81        }
82    }
83
84    /// Get this GC reference as an `structref` reference without checking if it
85    /// actually is an `structref` reference.
86    ///
87    /// Calling this method on a non-`structref` reference is memory safe, but
88    /// will lead to general incorrectness like panics and wrong results.
89    pub fn as_structref_unchecked(&self) -> &VMStructRef {
90        debug_assert!(!self.is_i31());
91        let ptr = self as *const VMGcRef;
92        let ret = unsafe { &*ptr.cast() };
93        assert!(matches!(ret, VMStructRef(VMGcRef { .. })));
94        ret
95    }
96}
97
98impl VMStructRef {
99    /// Get the underlying `VMGcRef`.
100    pub fn as_gc_ref(&self) -> &VMGcRef {
101        &self.0
102    }
103
104    /// Clone this `VMStructRef`, running any GC barriers as necessary.
105    pub fn clone(&self, gc_store: &mut GcStore) -> Self {
106        Self(gc_store.clone_gc_ref(&self.0))
107    }
108
109    /// Explicitly drop this `structref`, running GC drop barriers as necessary.
110    pub fn drop(self, gc_store: &mut GcStore) {
111        gc_store.drop_gc_ref(self.0);
112    }
113
114    /// Copy this `VMStructRef` without running the GC's clone barriers.
115    ///
116    /// Prefer calling `clone(&mut GcStore)` instead! This is mostly an internal
117    /// escape hatch for collector implementations.
118    ///
119    /// Failure to run GC barriers when they would otherwise be necessary can
120    /// lead to leaks, panics, and wrong results. It cannot lead to memory
121    /// unsafety, however.
122    pub fn unchecked_copy(&self) -> Self {
123        Self(self.0.unchecked_copy())
124    }
125
126    /// Read a field of the given `StorageType` into a `Val`.
127    ///
128    /// `i8` and `i16` fields are zero-extended into `Val::I32(_)`s.
129    ///
130    /// Does not check that the field is actually of type `ty`. That is the
131    /// caller's responsibility. Failure to do so is memory safe, but will lead
132    /// to general incorrectness such as panics and wrong results.
133    ///
134    /// Panics on out-of-bounds accesses.
135    pub fn read_field(
136        &self,
137        store: &mut AutoAssertNoGc,
138        layout: &GcStructLayout,
139        ty: &StorageType,
140        field: usize,
141    ) -> Val {
142        let offset = layout.fields[field];
143        let data = store.unwrap_gc_store_mut().gc_object_data(self.as_gc_ref());
144        match ty {
145            StorageType::I8 => Val::I32(data.read_u8(offset).into()),
146            StorageType::I16 => Val::I32(data.read_u16(offset).into()),
147            StorageType::ValType(ValType::I32) => Val::I32(data.read_i32(offset)),
148            StorageType::ValType(ValType::I64) => Val::I64(data.read_i64(offset)),
149            StorageType::ValType(ValType::F32) => Val::F32(data.read_u32(offset)),
150            StorageType::ValType(ValType::F64) => Val::F64(data.read_u64(offset)),
151            StorageType::ValType(ValType::V128) => Val::V128(data.read_v128(offset)),
152            StorageType::ValType(ValType::Ref(r)) => match r.heap_type().top() {
153                HeapType::Extern => {
154                    let raw = data.read_u32(offset);
155                    Val::ExternRef(ExternRef::_from_raw(store, raw))
156                }
157                HeapType::Any => {
158                    let raw = data.read_u32(offset);
159                    Val::AnyRef(AnyRef::_from_raw(store, raw))
160                }
161                HeapType::Func => {
162                    let func_ref_id = data.read_u32(offset);
163                    let func_ref_id = FuncRefTableId::from_raw(func_ref_id);
164                    let func_ref = store
165                        .unwrap_gc_store()
166                        .func_ref_table
167                        .get_untyped(func_ref_id);
168                    Val::FuncRef(unsafe {
169                        func_ref.map(|p| Func::from_vm_func_ref(store, p.as_non_null()))
170                    })
171                }
172                otherwise => unreachable!("not a top type: {otherwise:?}"),
173            },
174        }
175    }
176
177    /// Write the given value into this struct at the given offset.
178    ///
179    /// Returns an error if `val` is a GC reference that has since been
180    /// unrooted.
181    ///
182    /// Does not check that `val` matches `ty`, nor that the field is actually
183    /// of type `ty`. Checking those things is the caller's responsibility.
184    /// Failure to do so is memory safe, but will lead to general incorrectness
185    /// such as panics and wrong results.
186    ///
187    /// Panics on out-of-bounds accesses.
188    pub fn write_field(
189        &self,
190        store: &mut AutoAssertNoGc,
191        layout: &GcStructLayout,
192        ty: &StorageType,
193        field: usize,
194        val: Val,
195    ) -> Result<()> {
196        debug_assert!(val._matches_ty(&store, &ty.unpack())?);
197
198        let offset = layout.fields[field];
199        let mut data = store.gc_store_mut()?.gc_object_data(self.as_gc_ref());
200        match val {
201            Val::I32(i) if ty.is_i8() => data.write_i8(offset, truncate_i32_to_i8(i)),
202            Val::I32(i) if ty.is_i16() => data.write_i16(offset, truncate_i32_to_i16(i)),
203            Val::I32(i) => data.write_i32(offset, i),
204            Val::I64(i) => data.write_i64(offset, i),
205            Val::F32(f) => data.write_u32(offset, f),
206            Val::F64(f) => data.write_u64(offset, f),
207            Val::V128(v) => data.write_v128(offset, v),
208
209            // For GC-managed references, we need to take care to run the
210            // appropriate barriers, even when we are writing null references
211            // into the struct.
212            //
213            // POD-read the old value into a local copy, run the GC write
214            // barrier on that local copy, and then POD-write the updated
215            // value back into the struct. This avoids transmuting the inner
216            // data, which would probably be fine, but this approach is
217            // Obviously Correct and should get us by for now. If LLVM isn't
218            // able to elide some of these unnecessary copies, and this
219            // method is ever hot enough, we can always come back and clean
220            // it up in the future.
221            Val::ExternRef(e) => {
222                let raw = data.read_u32(offset);
223                let mut gc_ref = VMGcRef::from_raw_u32(raw);
224                let e = match e {
225                    Some(e) => Some(e.try_gc_ref(store)?.unchecked_copy()),
226                    None => None,
227                };
228                store.gc_store_mut()?.write_gc_ref(&mut gc_ref, e.as_ref());
229                let mut data = store.gc_store_mut()?.gc_object_data(self.as_gc_ref());
230                data.write_u32(offset, gc_ref.map_or(0, |r| r.as_raw_u32()));
231            }
232            Val::AnyRef(a) => {
233                let raw = data.read_u32(offset);
234                let mut gc_ref = VMGcRef::from_raw_u32(raw);
235                let a = match a {
236                    Some(a) => Some(a.try_gc_ref(store)?.unchecked_copy()),
237                    None => None,
238                };
239                store.gc_store_mut()?.write_gc_ref(&mut gc_ref, a.as_ref());
240                let mut data = store.gc_store_mut()?.gc_object_data(self.as_gc_ref());
241                data.write_u32(offset, gc_ref.map_or(0, |r| r.as_raw_u32()));
242            }
243
244            Val::FuncRef(f) => {
245                let f = f.map(|f| SendSyncPtr::new(f.vm_func_ref(store)));
246                let id = unsafe { store.gc_store_mut()?.func_ref_table.intern(f) };
247                store
248                    .gc_store_mut()?
249                    .gc_object_data(self.as_gc_ref())
250                    .write_u32(offset, id.into_raw());
251            }
252        }
253        Ok(())
254    }
255
256    /// Initialize a field in this structref that is currently uninitialized.
257    ///
258    /// The difference between this method and `write_field` is that GC barriers
259    /// are handled differently. When overwriting an initialized field (aka
260    /// `write_field`) we need to call the full write GC write barrier, which
261    /// logically drops the old GC reference and clones the new GC
262    /// reference. When we are initializing a field for the first time, there is
263    /// no old GC reference that is being overwritten and which we need to drop,
264    /// so we only need to clone the new GC reference.
265    ///
266    /// Calling this method on a structref that has already had the associated
267    /// field initialized will result in GC bugs. These are memory safe but will
268    /// lead to generally incorrect behavior such as panics, leaks, and
269    /// incorrect results.
270    ///
271    /// Does not check that `val` matches `ty`, nor that the field is actually
272    /// of type `ty`. Checking those things is the caller's responsibility.
273    /// Failure to do so is memory safe, but will lead to general incorrectness
274    /// such as panics and wrong results.
275    ///
276    /// Returns an error if `val` is a GC reference that has since been
277    /// unrooted.
278    ///
279    /// Panics on out-of-bounds accesses.
280    pub fn initialize_field(
281        &self,
282        store: &mut AutoAssertNoGc,
283        layout: &GcStructLayout,
284        ty: &StorageType,
285        field: usize,
286        val: Val,
287    ) -> Result<()> {
288        debug_assert!(val._matches_ty(&store, &ty.unpack())?);
289        let offset = layout.fields[field];
290        match val {
291            Val::I32(i) if ty.is_i8() => store
292                .gc_store_mut()?
293                .gc_object_data(self.as_gc_ref())
294                .write_i8(offset, truncate_i32_to_i8(i)),
295            Val::I32(i) if ty.is_i16() => store
296                .gc_store_mut()?
297                .gc_object_data(self.as_gc_ref())
298                .write_i16(offset, truncate_i32_to_i16(i)),
299            Val::I32(i) => store
300                .gc_store_mut()?
301                .gc_object_data(self.as_gc_ref())
302                .write_i32(offset, i),
303            Val::I64(i) => store
304                .gc_store_mut()?
305                .gc_object_data(self.as_gc_ref())
306                .write_i64(offset, i),
307            Val::F32(f) => store
308                .gc_store_mut()?
309                .gc_object_data(self.as_gc_ref())
310                .write_u32(offset, f),
311            Val::F64(f) => store
312                .gc_store_mut()?
313                .gc_object_data(self.as_gc_ref())
314                .write_u64(offset, f),
315            Val::V128(v) => store
316                .gc_store_mut()?
317                .gc_object_data(self.as_gc_ref())
318                .write_v128(offset, v),
319
320            // NB: We don't need to do a write barrier when initializing a
321            // field, because there is nothing being overwritten. Therefore, we
322            // just the clone barrier.
323            Val::ExternRef(x) => {
324                let x = match x {
325                    None => 0,
326                    Some(x) => x.try_clone_gc_ref(store)?.as_raw_u32(),
327                };
328                store
329                    .gc_store_mut()?
330                    .gc_object_data(self.as_gc_ref())
331                    .write_u32(offset, x);
332            }
333            Val::AnyRef(x) => {
334                let x = match x {
335                    None => 0,
336                    Some(x) => x.try_clone_gc_ref(store)?.as_raw_u32(),
337                };
338                store
339                    .gc_store_mut()?
340                    .gc_object_data(self.as_gc_ref())
341                    .write_u32(offset, x);
342            }
343
344            Val::FuncRef(f) => {
345                let f = f.map(|f| SendSyncPtr::new(f.vm_func_ref(store)));
346                let id = unsafe { store.gc_store_mut()?.func_ref_table.intern(f) };
347                store
348                    .gc_store_mut()?
349                    .gc_object_data(self.as_gc_ref())
350                    .write_u32(offset, id.into_raw());
351            }
352        }
353        Ok(())
354    }
355}