Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Add more defense-in-depth checks of IDs and such coming out of the GC heap (#14450)

Nick Fitzgerald8a1ba5335d18
diff --git a/crates/core/src/slab.rs b/crates/core/src/slab.rs
index 030d6294a2..b55161bda5 100644
--- a/crates/core/src/slab.rs
+++ b/crates/core/src/slab.rs
@@ -156,14 +156,18 @@ impl Id {
u32::try_from(self.0.index()).unwrap()
}
- /// Construct an `Id` from its raw underlying representation.
+ /// Construct an `Id` from a value previously returned by `into_raw`, if
+ /// that value is well-formed.
///
- /// `raw` should be a value that was previously created via
- /// `Id::into_raw`. May panic if given arbitrary values.
+ /// A well-formed `Id` is not necessarily one that any slab has handed out;
+ /// lookups are still checked.
#[inline]
- pub fn from_raw(raw: u32) -> Self {
- let raw = usize::try_from(raw).unwrap();
- Self(EntryIndex::new(raw))
+ pub fn try_from_raw(raw: u32) -> Option<Self> {
+ let raw = usize::try_from(raw).ok()?;
+ if raw > Slab::<()>::MAX_CAPACITY {
+ return None;
+ }
+ Some(Self(EntryIndex::new(raw)))
}
}
diff --git a/crates/environ/src/gc.rs b/crates/environ/src/gc.rs
index a560e7f918..4ed49cda3a 100644
--- a/crates/environ/src/gc.rs
+++ b/crates/environ/src/gc.rs
@@ -516,19 +516,14 @@ impl VMGcKind {
/// Convert the given value into a `VMGcKind` by masking off the unused
/// bottom bits.
+ ///
+ /// Returns `None` if the remaining bits do not name a kind, which most
+ /// callers must be prepared for, since these values come out of the
+ /// untrusted GC heap.
#[inline]
- pub fn from_high_bits_of_u32(val: u32) -> VMGcKind {
+ pub fn from_high_bits_of_u32(val: u32) -> Option<VMGcKind> {
let masked = val & Self::MASK;
- let result = Self::try_from_u32(masked)
- .unwrap_or_else(|| panic!("invalid `VMGcKind`: {masked:#032b}"));
-
- let poison_kind = u32::from_le_bytes([POISON, POISON, POISON, POISON]) & VMGcKind::MASK;
- debug_assert_ne!(
- masked, poison_kind,
- "No valid `VMGcKind` should overlap with the poison pattern"
- );
-
- result
+ Self::try_from_u32(masked)
}
/// Does this kind match the other kind?
@@ -565,7 +560,13 @@ impl VMGcKind {
#[cfg(test)]
mod tests {
use super::VMGcKind::*;
- use crate::prelude::*;
+ use super::*;
+
+ #[test]
+ fn poison_is_not_a_kind() {
+ let poison = u32::from_le_bytes([POISON, POISON, POISON, POISON]);
+ assert!(VMGcKind::from_high_bits_of_u32(poison).is_none());
+ }
#[test]
fn kind_matches() {
diff --git a/crates/wasmtime/src/runtime/externals/tag.rs b/crates/wasmtime/src/runtime/externals/tag.rs
index 3704ea30d8..45463ff238 100644
--- a/crates/wasmtime/src/runtime/externals/tag.rs
+++ b/crates/wasmtime/src/runtime/externals/tag.rs
@@ -9,6 +9,8 @@ use wasmtime_environ::DefinedTagIndex;
#[cfg(feature = "gc")]
use crate::store::InstanceId;
+#[cfg(feature = "gc")]
+use wasmtime_environ::EntityRef;
/// A WebAssembly `tag`.
#[derive(Copy, Clone, Debug)]
@@ -96,27 +98,36 @@ impl Tag {
/// Get the "index coordinates" for this `Tag`: the raw instance
/// ID and defined-tag index within that instance. This can be
- /// used to "serialize" the tag as safe (tamper-proof,
- /// bounds-checked) values, e.g. within the GC store for an
- /// exception object.
+ /// used to "serialize" the tag as a pair of plain integers, e.g.
+ /// within the GC store for an exception object. Nothing keeps those
+ /// integers from being tampered with, so `from_raw_indices`
+ /// re-validates them.
#[cfg(feature = "gc")]
pub(crate) fn to_raw_indices(&self) -> (InstanceId, DefinedTagIndex) {
(self.instance.instance(), self.index)
}
- /// Create a new `Tag` from known raw indices as produced by
- /// `to_raw_indices()`.
- ///
- /// # Panics
+ /// Create a new `Tag` from raw indices as produced by `to_raw_indices()`,
+ /// if those indices are in bounds for the given store.
///
- /// Panics if the indices are out-of-bounds in the given store.
+ /// Returns `None` if either index is out-of-bounds, which can happen when
+ /// they were round-tripped through somewhere untrusted, such as the GC
+ /// heap.
#[cfg(feature = "gc")]
pub(crate) fn from_raw_indices(
store: &StoreOpaque,
instance: InstanceId,
index: DefinedTagIndex,
- ) -> Tag {
+ ) -> Option<Tag> {
+ let num_defined_tags = store
+ .try_instance(instance)?
+ .env_module()
+ .num_defined_tags();
+ if index.index() >= num_defined_tags {
+ return None;
+ }
+
let instance = StoreInstanceId::new(store.id(), instance);
- Tag { instance, index }
+ Some(Tag { instance, index })
}
}
diff --git a/crates/wasmtime/src/runtime/func.rs b/crates/wasmtime/src/runtime/func.rs
index 71b123368e..b1caec85d5 100644
--- a/crates/wasmtime/src/runtime/func.rs
+++ b/crates/wasmtime/src/runtime/func.rs
@@ -878,7 +878,7 @@ impl Func {
/// Note that this is a somewhat expensive method since it requires taking a
/// lock as well as cloning a type.
pub(crate) fn load_ty(&self, store: &StoreOpaque) -> FuncType {
- FuncType::from_shared_type_index(store.engine(), self.type_index(store))
+ FuncType::from_shared_type_index(store.engine(), self.type_index(store)).unwrap()
}
/// Does this function match the given type?
diff --git a/crates/wasmtime/src/runtime/func/typed.rs b/crates/wasmtime/src/runtime/func/typed.rs
index 38c9a3290a..068464c15f 100644
--- a/crates/wasmtime/src/runtime/func/typed.rs
+++ b/crates/wasmtime/src/runtime/func/typed.rs
@@ -224,7 +224,7 @@ where
/// Purely a debug-mode assertion, not actually used in release builds.
fn debug_typecheck(store: &StoreOpaque, func: VMSharedTypeIndex) {
- let ty = FuncType::from_shared_type_index(store.engine(), func);
+ let ty = FuncType::from_shared_type_index(store.engine(), func).unwrap();
Params::typecheck(store.engine(), ty.params(), TypeCheckPosition::Param)
.expect("params should match");
Results::typecheck(store.engine(), ty.results(), TypeCheckPosition::Result)
diff --git a/crates/wasmtime/src/runtime/gc/enabled.rs b/crates/wasmtime/src/runtime/gc/enabled.rs
index 5d74162d53..1e564bac94 100644
--- a/crates/wasmtime/src/runtime/gc/enabled.rs
+++ b/crates/wasmtime/src/runtime/gc/enabled.rs
@@ -18,3 +18,38 @@ pub use externref::*;
pub use i31::*;
pub use rooting::*;
pub use structref::*;
+
+use crate::{Engine, bail_bug, prelude::*};
+use alloc::sync::Arc;
+use wasmtime_environ::{GcArrayLayout, GcLayout, GcStructLayout, VMSharedTypeIndex};
+
+/// Get the GC layout registered for `type_index`.
+///
+/// Type indices generally come out of the untrusted GC heap, so `type_index`
+/// may not name a registered type at all.
+fn gc_layout(engine: &Engine, type_index: VMSharedTypeIndex) -> Result<GcLayout> {
+ match engine.signatures().layout(type_index) {
+ Some(layout) => Ok(layout),
+ None => bail_bug!("no GC layout for {type_index:?}"),
+ }
+}
+
+/// Get the struct layout registered for `type_index`.
+///
+/// See `gc_layout`.
+fn gc_struct_layout(engine: &Engine, type_index: VMSharedTypeIndex) -> Result<Arc<GcStructLayout>> {
+ match gc_layout(engine, type_index)? {
+ GcLayout::Struct(s) => Ok(s),
+ GcLayout::Array(_) => bail_bug!("expected a struct GC layout for {type_index:?}"),
+ }
+}
+
+/// Get the array layout registered for `type_index`.
+///
+/// See `gc_layout`.
+fn gc_array_layout(engine: &Engine, type_index: VMSharedTypeIndex) -> Result<GcArrayLayout> {
+ match gc_layout(engine, type_index)? {
+ GcLayout::Array(a) => Ok(a),
+ GcLayout::Struct(_) => bail_bug!("expected an array GC layout for {type_index:?}"),
+ }
+}
diff --git a/crates/wasmtime/src/runtime/gc/enabled/anyref.rs b/crates/wasmtime/src/runtime/gc/enabled/anyref.rs
index 5e91e1ea8c..fcc017c07e 100644
--- a/crates/wasmtime/src/runtime/gc/enabled/anyref.rs
+++ b/crates/wasmtime/src/runtime/gc/enabled/anyref.rs
@@ -297,15 +297,13 @@ impl AnyRef {
gc_ref.is_i31()
|| store
.unwrap_gc_store()
- .header(&gc_ref)
+ .kind(&gc_ref)
.unwrap()
- .kind()
.matches(VMGcKind::AnyRef)
|| store
.unwrap_gc_store()
- .header(&gc_ref)
+ .kind(&gc_ref)
.unwrap()
- .kind()
.matches(VMGcKind::ExternRef)
);
Rooted::new(store, gc_ref)
@@ -357,29 +355,34 @@ impl AnyRef {
}
let header = store.require_gc_store()?.header(gc_ref)?;
+ let kind = match header.kind() {
+ Some(kind) => kind,
+ None => bail_bug!("invalid `VMGcKind`"),
+ };
- if header.kind().matches(VMGcKind::ExternRef) {
+ if kind.matches(VMGcKind::ExternRef) {
return Ok(HeapType::Any);
}
- debug_assert!(header.kind().matches(VMGcKind::AnyRef));
- debug_assert!(header.kind().matches(VMGcKind::EqRef));
+ debug_assert!(kind.matches(VMGcKind::AnyRef));
+ debug_assert!(kind.matches(VMGcKind::EqRef));
let ty = match header.ty() {
Some(ty) => ty,
None => bail_bug!("ty should be present"),
};
- if header.kind().matches(VMGcKind::StructRef) {
- return Ok(HeapType::ConcreteStruct(
- StructType::from_shared_type_index(store.engine(), ty),
- ));
+ if kind.matches(VMGcKind::StructRef) {
+ return match StructType::from_shared_type_index(store.engine(), ty) {
+ Some(ty) => Ok(HeapType::ConcreteStruct(ty)),
+ None => bail_bug!("invalid struct type index"),
+ };
}
- if header.kind().matches(VMGcKind::ArrayRef) {
- return Ok(HeapType::ConcreteArray(ArrayType::from_shared_type_index(
- store.engine(),
- ty,
- )));
+ if kind.matches(VMGcKind::ArrayRef) {
+ return match ArrayType::from_shared_type_index(store.engine(), ty) {
+ Some(ty) => Ok(HeapType::ConcreteArray(ty)),
+ None => bail_bug!("invalid array type index"),
+ };
}
bail_bug!("no other kinds of `anyref`s")
diff --git a/crates/wasmtime/src/runtime/gc/enabled/arrayref.rs b/crates/wasmtime/src/runtime/gc/enabled/arrayref.rs
index ce21b748fc..4fca492dd9 100644
--- a/crates/wasmtime/src/runtime/gc/enabled/arrayref.rs
+++ b/crates/wasmtime/src/runtime/gc/enabled/arrayref.rs
@@ -8,12 +8,12 @@ use crate::vm::{self, VMArrayRef, VMGcHeader};
use crate::{AnyRef, FieldType};
use crate::{
ArrayType, AsContext, AsContextMut, EqRef, GcHeapOutOfMemory, GcRefImpl, GcRootIndex, HeapType,
- OwnedRooted, RefType, Rooted, Val, ValRaw, ValType, WasmTy,
+ OwnedRooted, RefType, Rooted, Val, ValRaw, ValType, WasmTy, bail_bug,
prelude::*,
store::{AutoAssertNoGc, StoreContextMut, StoreOpaque},
};
use core::mem::{self, MaybeUninit};
-use wasmtime_environ::{GcArrayLayout, GcLayout, VMGcKind, VMSharedTypeIndex};
+use wasmtime_environ::{GcArrayLayout, VMGcKind, VMSharedTypeIndex};
/// An allocator for a particular Wasm GC array type.
///
@@ -769,7 +769,10 @@ impl ArrayRef {
pub(crate) fn _ty(&self, store: &StoreOpaque) -> Result<ArrayType> {
assert!(self.comes_from_same_store(store));
let index = self.type_index(store)?;
- Ok(ArrayType::from_shared_type_index(store.engine(), index))
+ match ArrayType::from_shared_type_index(store.engine(), index) {
+ Some(ty) => Ok(ty),
+ None => bail_bug!("invalid array type index"),
+ }
}
/// Does this `arrayref` match the given type?
@@ -823,7 +826,7 @@ impl ArrayRef {
let gc_ref = self.inner.try_gc_ref(store)?;
debug_assert!({
let header = store.require_gc_store()?.header(gc_ref)?;
- header.kind().matches(VMGcKind::ArrayRef)
+ header.matches_kind(VMGcKind::ArrayRef)
});
let arrayref = gc_ref.as_arrayref_unchecked();
arrayref.len(store)
@@ -857,7 +860,7 @@ impl ArrayRef {
let gc_ref = self.inner.try_gc_ref(&store)?;
let header = store.require_gc_store()?.header(gc_ref)?;
- debug_assert!(header.kind().matches(VMGcKind::ArrayRef));
+ debug_assert!(header.matches_kind(VMGcKind::ArrayRef));
let len = self._len(&store)?;
@@ -915,22 +918,14 @@ impl ArrayRef {
fn arrayref<'a>(&self, store: &'a AutoAssertNoGc<'_>) -> Result<&'a VMArrayRef> {
assert!(self.comes_from_same_store(&store));
let gc_ref = self.inner.try_gc_ref(store)?;
- debug_assert!(self.header(store)?.kind().matches(VMGcKind::ArrayRef));
+ debug_assert!(self.header(store)?.matches_kind(VMGcKind::ArrayRef));
Ok(gc_ref.as_arrayref_unchecked())
}
pub(crate) fn layout(&self, store: &AutoAssertNoGc<'_>) -> Result<GcArrayLayout> {
assert!(self.comes_from_same_store(&store));
let type_index = self.type_index(store)?;
- let layout = store
- .engine()
- .signatures()
- .layout(type_index)
- .expect("array types should have GC layouts");
- match layout {
- GcLayout::Array(a) => Ok(a),
- GcLayout::Struct(_) => unreachable!(),
- }
+ super::gc_array_layout(store.engine(), type_index)
}
fn field_ty(&self, store: &StoreOpaque) -> Result<FieldType> {
@@ -1032,8 +1027,11 @@ impl ArrayRef {
pub(crate) fn type_index(&self, store: &StoreOpaque) -> Result<VMSharedTypeIndex> {
let gc_ref = self.inner.try_gc_ref(store)?;
let header = store.require_gc_store()?.header(gc_ref)?;
- debug_assert!(header.kind().matches(VMGcKind::ArrayRef));
- Ok(header.ty().expect("arrayrefs should have concrete types"))
+ debug_assert!(header.matches_kind(VMGcKind::ArrayRef));
+ match header.ty() {
+ Some(ty) => Ok(ty),
+ None => bail_bug!("arrayrefs should have concrete types"),
+ }
}
/// Create a new `Rooted<ArrayRef>` from the given GC reference.
diff --git a/crates/wasmtime/src/runtime/gc/enabled/eqref.rs b/crates/wasmtime/src/runtime/gc/enabled/eqref.rs
index 0d95bc763d..4127bc7ec5 100644
--- a/crates/wasmtime/src/runtime/gc/enabled/eqref.rs
+++ b/crates/wasmtime/src/runtime/gc/enabled/eqref.rs
@@ -167,9 +167,8 @@ impl EqRef {
gc_ref.is_i31()
|| store
.unwrap_gc_store()
- .header(&gc_ref)
+ .kind(&gc_ref)
.unwrap()
- .kind()
.matches(VMGcKind::EqRef)
);
Rooted::new(store, gc_ref)
@@ -200,22 +199,27 @@ impl EqRef {
}
let header = store.require_gc_store()?.header(gc_ref)?;
+ let kind = match header.kind() {
+ Some(kind) => kind,
+ None => bail_bug!("invalid `VMGcKind`"),
+ };
let ty = match header.ty() {
Some(ty) => ty,
None => bail_bug!("ty should be present"),
};
- if header.kind().matches(VMGcKind::StructRef) {
- return Ok(HeapType::ConcreteStruct(
- StructType::from_shared_type_index(store.engine(), ty),
- ));
+ if kind.matches(VMGcKind::StructRef) {
+ return match StructType::from_shared_type_index(store.engine(), ty) {
+ Some(ty) => Ok(HeapType::ConcreteStruct(ty)),
+ None => bail_bug!("invalid struct type index"),
+ };
}
- if header.kind().matches(VMGcKind::ArrayRef) {
- return Ok(HeapType::ConcreteArray(ArrayType::from_shared_type_index(
- store.engine(),
- ty,
- )));
+ if kind.matches(VMGcKind::ArrayRef) {
+ return match ArrayType::from_shared_type_index(store.engine(), ty) {
+ Some(ty) => Ok(HeapType::ConcreteArray(ty)),
+ None => bail_bug!("invalid array type index"),
+ };
}
bail_bug!("no other kinds of `eqref`s")
diff --git a/crates/wasmtime/src/runtime/gc/enabled/exnref.rs b/crates/wasmtime/src/runtime/gc/enabled/exnref.rs
index a50c3416ba..502fe8f7d0 100644
--- a/crates/wasmtime/src/runtime/gc/enabled/exnref.rs
+++ b/crates/wasmtime/src/runtime/gc/enabled/exnref.rs
@@ -10,11 +10,11 @@ use crate::{
ValRaw, ValType, WasmTy,
store::{AutoAssertNoGc, StoreOpaque},
};
-use crate::{ExnType, FieldType, GcHeapOutOfMemory, StoreContextMut, Tag, prelude::*};
+use crate::{ExnType, FieldType, GcHeapOutOfMemory, StoreContextMut, Tag, bail_bug, prelude::*};
use alloc::sync::Arc;
use core::mem;
use core::mem::MaybeUninit;
-use wasmtime_environ::{GcLayout, GcStructLayout, VMGcKind, VMSharedTypeIndex};
+use wasmtime_environ::{GcStructLayout, VMGcKind, VMSharedTypeIndex};
/// An allocator for a particular Wasm GC exception type.
///
@@ -374,8 +374,11 @@ impl ExnRef {
pub(crate) fn type_index(&self, store: &StoreOpaque) -> Result<VMSharedTypeIndex> {
let gc_ref = self.inner.try_gc_ref(store)?;
let header = store.require_gc_store()?.header(gc_ref)?;
- debug_assert!(header.kind().matches(VMGcKind::ExnRef));
- Ok(header.ty().expect("exnrefs should have concrete types"))
+ debug_assert!(header.matches_kind(VMGcKind::ExnRef));
+ match header.ty() {
+ Some(ty) => Ok(ty),
+ None => bail_bug!("exnrefs should have concrete types"),
+ }
}
/// Create a new `Rooted<ExnRef>` from the given GC reference.
@@ -440,7 +443,10 @@ impl ExnRef {
pub(crate) fn _ty(&self, store: &StoreOpaque) -> Result<ExnType> {
assert!(self.comes_from_same_store(store));
let index = self.type_index(store)?;
- Ok(ExnType::from_shared_type_index(store.engine(), index))
+ match ExnType::from_shared_type_index(store.engine(), index) {
+ Some(ty) => Ok(ty),
+ None => bail_bug!("invalid exception type index"),
+ }
}
/// Does this `exnref` match the given type?
@@ -500,10 +506,16 @@ impl ExnRef {
let gc_ref = self.inner.try_gc_ref(&store)?;
let header = store.require_gc_store()?.header(gc_ref)?;
- debug_assert!(header.kind().matches(VMGcKind::ExnRef));
-
- let index = header.ty().expect("exnrefs should have concrete types");
- let ty = ExnType::from_shared_type_index(store.engine(), index);
+ debug_assert!(header.matches_kind(VMGcKind::ExnRef));
+
+ let index = match header.ty() {
+ Some(index) => index,
+ None => bail_bug!("exnrefs should have concrete types"),
+ };
+ let ty = match ExnType::from_shared_type_index(store.engine(), index) {
+ Some(ty) => ty,
+ None => bail_bug!("invalid exception type index"),
+ };
let len = ty.fields().len();
return Ok(Fields {
@@ -558,22 +570,14 @@ impl ExnRef {
fn exnref<'a>(&self, store: &'a AutoAssertNoGc<'_>) -> Result<&'a VMExnRef> {
assert!(self.comes_from_same_store(&store));
let gc_ref = self.inner.try_gc_ref(store)?;
- debug_assert!(self.header(store)?.kind().matches(VMGcKind::ExnRef));
+ debug_assert!(self.header(store)?.matches_kind(VMGcKind::ExnRef));
Ok(gc_ref.as_exnref_unchecked())
}
fn layout(&self, store: &AutoAssertNoGc<'_>) -> Result<Arc<GcStructLayout>> {
assert!(self.comes_from_same_store(&store));
let type_index = self.type_index(store)?;
- let layout = store
- .engine()
- .signatures()
- .layout(type_index)
- .expect("exn types should have GC layouts");
- match layout {
- GcLayout::Struct(s) => Ok(s),
- GcLayout::Array(_) => unreachable!(),
- }
+ super::gc_struct_layout(store.engine(), type_index)
}
fn field_ty(&self, store: &StoreOpaque, field: usize) -> Result<FieldType> {
@@ -624,7 +628,10 @@ impl ExnRef {
assert!(self.comes_from_same_store(&store));
let exnref = self.exnref(&store)?.unchecked_copy();
let (instance, index) = exnref.tag(&mut store)?;
- Ok(Tag::from_raw_indices(&*store, instance, index))
+ match Tag::from_raw_indices(&*store, instance, index) {
+ Some(tag) => Ok(tag),
+ None => bail_bug!("invalid tag indices in exception object"),
+ }
}
}
diff --git a/crates/wasmtime/src/runtime/gc/enabled/rooting.rs b/crates/wasmtime/src/runtime/gc/enabled/rooting.rs
index 848eebf3be..43955563f2 100644
--- a/crates/wasmtime/src/runtime/gc/enabled/rooting.rs
+++ b/crates/wasmtime/src/runtime/gc/enabled/rooting.rs
@@ -428,7 +428,7 @@ impl PackedIndex {
fn as_owned(&self) -> Option<SlabId> {
if self.is_owned() {
- Some(SlabId::from_raw(self.payload()))
+ Some(SlabId::try_from_raw(self.payload()).unwrap())
} else {
None
}
diff --git a/crates/wasmtime/src/runtime/gc/enabled/structref.rs b/crates/wasmtime/src/runtime/gc/enabled/structref.rs
index dfa09134de..15a946232c 100644
--- a/crates/wasmtime/src/runtime/gc/enabled/structref.rs
+++ b/crates/wasmtime/src/runtime/gc/enabled/structref.rs
@@ -9,13 +9,13 @@ use crate::vm::{self, VMGcHeader, VMStructRef};
use crate::{AnyRef, FieldType};
use crate::{
AsContext, AsContextMut, EqRef, GcHeapOutOfMemory, GcRefImpl, GcRootIndex, HeapType,
- OwnedRooted, RefType, Rooted, StructType, Val, ValRaw, ValType, WasmTy,
+ OwnedRooted, RefType, Rooted, StructType, Val, ValRaw, ValType, WasmTy, bail_bug,
prelude::*,
store::{AutoAssertNoGc, StoreContextMut, StoreOpaque, StoreResourceLimiter},
};
use alloc::sync::Arc;
use core::mem::{self, MaybeUninit};
-use wasmtime_environ::{GcLayout, GcStructLayout, VMGcKind, VMSharedTypeIndex};
+use wasmtime_environ::{GcStructLayout, VMGcKind, VMSharedTypeIndex};
/// An allocator for a particular Wasm GC struct type.
///
@@ -395,7 +395,10 @@ impl StructRef {
pub(crate) fn _ty(&self, store: &StoreOpaque) -> Result<StructType> {
assert!(self.comes_from_same_store(store));
let index = self.type_index(store)?;
- Ok(StructType::from_shared_type_index(store.engine(), index))
+ match StructType::from_shared_type_index(store.engine(), index) {
+ Some(ty) => Ok(ty),
+ None => bail_bug!("invalid struct type index"),
+ }
}
/// Does this `structref` match the given type?
@@ -459,10 +462,16 @@ impl StructRef {
let gc_ref = self.inner.try_gc_ref(&store)?;
let header = store.require_gc_store()?.header(gc_ref)?;
- debug_assert!(header.kind().matches(VMGcKind::StructRef));
-
- let index = header.ty().expect("structrefs should have concrete types");
- let ty = StructType::from_shared_type_index(store.engine(), index);
+ debug_assert!(header.matches_kind(VMGcKind::StructRef));
+
+ let index = match header.ty() {
+ Some(index) => index,
+ None => bail_bug!("structrefs should have concrete types"),
+ };
+ let ty = match StructType::from_shared_type_index(store.engine(), index) {
+ Some(ty) => ty,
+ None => bail_bug!("invalid struct type index"),
+ };
let len = ty.fields().len();
return Ok(Fields {
@@ -517,22 +526,14 @@ impl StructRef {
fn structref<'a>(&self, store: &'a AutoAssertNoGc<'_>) -> Result<&'a VMStructRef> {
assert!(self.comes_from_same_store(&store));
let gc_ref = self.inner.try_gc_ref(store)?;
- debug_assert!(self.header(store)?.kind().matches(VMGcKind::StructRef));
+ debug_assert!(self.header(store)?.matches_kind(VMGcKind::StructRef));
Ok(gc_ref.as_structref_unchecked())
}
fn layout(&self, store: &AutoAssertNoGc<'_>) -> Result<Arc<GcStructLayout>> {
assert!(self.comes_from_same_store(&store));
let type_index = self.type_index(store)?;
- let layout = store
- .engine()
- .signatures()
- .layout(type_index)
- .expect("struct types should have GC layouts");
- match layout {
- GcLayout::Struct(s) => Ok(s),
- GcLayout::Array(_) => unreachable!(),
- }
+ super::gc_struct_layout(store.engine(), type_index)
}
fn field_ty(&self, store: &StoreOpaque, field: usize) -> Result<FieldType> {
@@ -623,8 +624,11 @@ impl StructRef {
pub(crate) fn type_index(&self, store: &StoreOpaque) -> Result<VMSharedTypeIndex> {
let gc_ref = self.inner.try_gc_ref(store)?;
let header = store.require_gc_store()?.header(gc_ref)?;
- debug_assert!(header.kind().matches(VMGcKind::StructRef));
- Ok(header.ty().expect("structrefs should have concrete types"))
+ debug_assert!(header.matches_kind(VMGcKind::StructRef));
+ match header.ty() {
+ Some(ty) => Ok(ty),
+ None => bail_bug!("structrefs should have concrete types"),
+ }
}
/// Create a new `Rooted<StructRef>` from the given GC reference.
diff --git a/crates/wasmtime/src/runtime/store.rs b/crates/wasmtime/src/runtime/store.rs
index c46d3eab56..1a24dbeba3 100644
--- a/crates/wasmtime/src/runtime/store.rs
+++ b/crates/wasmtime/src/runtime/store.rs
@@ -1643,6 +1643,16 @@ impl StoreOpaque {
self.instances[id].handle.get()
}
+ /// Accessor from `InstanceId` to `&vm::Instance`, if `id` is actually an
+ /// instance within this store.
+ ///
+ /// Unlike `instance`, this does not assume `id` has already been validated,
+ /// and so suits ids from an untrusted source.
+ #[inline]
+ pub fn try_instance(&self, id: InstanceId) -> Option<&vm::Instance> {
+ Some(self.instances.get(id)?.handle.get())
+ }
+
/// Accessor from `InstanceId` to `Pin<&mut vm::Instance>`.
///
/// Note that if you have a `StoreInstanceId` you should use
diff --git a/crates/wasmtime/src/runtime/store/gc.rs b/crates/wasmtime/src/runtime/store/gc.rs
index 72492ccbb7..ce98743ab7 100644
--- a/crates/wasmtime/src/runtime/store/gc.rs
+++ b/crates/wasmtime/src/runtime/store/gc.rs
@@ -13,8 +13,8 @@ use crate::vm::{
SendSyncPtr, StoreGcHostAllocTypes, TraceInfo, VMGcRef,
};
use crate::{
- Engine, ExnRef, GcHeapOutOfMemory, Result, Rooted, Store, StoreContextMut, ThrownException,
- bail,
+ Engine, ExnRef, GcHeapOutOfMemory, Result, Rooted, Store, StoreContextMut, Tag,
+ ThrownException, bail,
};
use core::fmt;
use core::mem::ManuallyDrop;
@@ -585,7 +585,15 @@ impl StoreOpaque {
// later. This method is primarily called right now to determine if
// there's a handler for an exception, and by returning `None` here this
// turns into just any old embedder error.
- pending_exnref.into_exnref_unchecked().tag(&mut store).ok()
+ let (instance, index) = pending_exnref
+ .into_exnref_unchecked()
+ .tag(&mut store)
+ .ok()?;
+
+ // Validate the heap-derived indices: handler lookup only compares them
+ // against live tags, so an unvalidated pair can match the wrong
+ // handler, which then decodes the payload at the wrong types.
+ Some(Tag::from_raw_indices(&store, instance, index)?.to_raw_indices())
}
/// Get an owned rooted reference to the pending exception,
diff --git a/crates/wasmtime/src/runtime/type_registry.rs b/crates/wasmtime/src/runtime/type_registry.rs
index 0d98863617..b442818823 100644
--- a/crates/wasmtime/src/runtime/type_registry.rs
+++ b/crates/wasmtime/src/runtime/type_registry.rs
@@ -273,8 +273,16 @@ impl Drop for TypeCollection {
#[inline]
fn shared_type_index_to_slab_id(index: VMSharedTypeIndex) -> SlabId {
- assert!(!index.is_reserved_value());
- SlabId::from_raw(index.bits())
+ try_shared_type_index_to_slab_id(index).unwrap()
+}
+
+/// Like `shared_type_index_to_slab_id`, but for untrusted indices.
+#[inline]
+fn try_shared_type_index_to_slab_id(index: VMSharedTypeIndex) -> Option<SlabId> {
+ if index.is_reserved_value() {
+ return None;
+ }
+ SlabId::try_from_raw(index.bits())
}
#[inline]
@@ -423,19 +431,19 @@ impl RegisteredType {
))
}
- /// Create an owning handle to the given index's associated type.
+ /// Create an owning handle to the given index's associated type, if that
+ /// index names a registered type.
///
/// This will prevent the associated type from being unregistered as long as
- /// the returned `RegisteredType` is kept alive.
- pub fn root(engine: &Engine, index: VMSharedTypeIndex) -> RegisteredType {
- engine.signatures().debug_assert_contains(index);
-
+ /// the returned `RegisteredType` is kept alive. `index` may come from an
+ /// untrusted source, such as the GC heap.
+ pub fn try_root(engine: &Engine, index: VMSharedTypeIndex) -> Option<RegisteredType> {
let (entry, ty, layout) = {
- let id = shared_type_index_to_slab_id(index);
+ let id = try_shared_type_index_to_slab_id(index)?;
let inner = engine.signatures().0.read();
- let ty = inner.types[id].clone().unwrap();
- let entry = inner.type_to_rec_group[index].clone().unwrap();
+ let ty = inner.types.get(id)?.clone()?;
+ let entry = inner.type_to_rec_group.get(index)?.clone()?;
let layout = inner.type_to_gc_layout.get(index).and_then(|l| l.clone());
// NB: make sure to incref while the lock is held to prevent:
@@ -444,12 +452,18 @@ impl RegisteredType {
// * Other thread: drops `RegisteredType` for entry E, decref
// reaches zero, write locks registry, unregisters entry
// * This thread: increfs entry, but it isn't in the registry anymore
- entry.incref("RegisteredType::root");
+ entry.incref("RegisteredType::try_root");
(entry, ty, layout)
};
- RegisteredType::from_parts(engine.clone(), entry, index, ty, layout)
+ Some(RegisteredType::from_parts(
+ engine.clone(),
+ entry,
+ index,
+ ty,
+ layout,
+ ))
}
/// Construct a new `RegisteredType`.
@@ -1677,7 +1691,7 @@ impl TypeRegistry {
/// Looks up a function type from a shared type index.
///
/// This does *NOT* prevent the type from being unregistered while you are
- /// still using the resulting value! Use the `RegisteredType::root`
+ /// still using the resulting value! Use the `RegisteredType::try_root`
/// constructor if you need to ensure that property and you don't have some
/// other mechanism already keeping the type registered.
pub fn borrow(&self, index: VMSharedTypeIndex) -> Option<Arc<WasmSubType>> {
diff --git a/crates/wasmtime/src/runtime/types.rs b/crates/wasmtime/src/runtime/types.rs
index 2a38a02fe0..fc3e313d48 100644
--- a/crates/wasmtime/src/runtime/types.rs
+++ b/crates/wasmtime/src/runtime/types.rs
@@ -1394,13 +1394,13 @@ impl HeapType {
WasmHeapType::Struct => HeapType::Struct,
WasmHeapType::None => HeapType::None,
WasmHeapType::ConcreteFunc(EngineOrModuleTypeIndex::Engine(idx)) => {
- HeapType::ConcreteFunc(FuncType::from_shared_type_index(engine, *idx))
+ HeapType::ConcreteFunc(FuncType::from_shared_type_index(engine, *idx).unwrap())
}
WasmHeapType::ConcreteArray(EngineOrModuleTypeIndex::Engine(idx)) => {
- HeapType::ConcreteArray(ArrayType::from_shared_type_index(engine, *idx))
+ HeapType::ConcreteArray(ArrayType::from_shared_type_index(engine, *idx).unwrap())
}
WasmHeapType::ConcreteStruct(EngineOrModuleTypeIndex::Engine(idx)) => {
- HeapType::ConcreteStruct(StructType::from_shared_type_index(engine, *idx))
+ HeapType::ConcreteStruct(StructType::from_shared_type_index(engine, *idx).unwrap())
}
WasmHeapType::ConcreteFunc(EngineOrModuleTypeIndex::Module(_))
@@ -1418,12 +1418,12 @@ impl HeapType {
WasmHeapType::Cont => HeapType::Cont,
WasmHeapType::NoCont => HeapType::NoCont,
WasmHeapType::ConcreteCont(EngineOrModuleTypeIndex::Engine(idx)) => {
- HeapType::ConcreteCont(ContType::from_shared_type_index(engine, *idx))
+ HeapType::ConcreteCont(ContType::from_shared_type_index(engine, *idx).unwrap())
}
WasmHeapType::Exn => HeapType::Exn,
WasmHeapType::NoExn => HeapType::NoExn,
WasmHeapType::ConcreteExn(EngineOrModuleTypeIndex::Engine(idx)) => {
- HeapType::ConcreteExn(ExnType::from_shared_type_index(engine, *idx))
+ HeapType::ConcreteExn(ExnType::from_shared_type_index(engine, *idx).unwrap())
}
}
}
@@ -1548,7 +1548,7 @@ impl ExternType {
match ty {
EntityType::Function(idx) => match idx {
EngineOrModuleTypeIndex::Engine(e) => {
- FuncType::from_shared_type_index(engine, *e).into()
+ FuncType::from_shared_type_index(engine, *e).unwrap().into()
}
EngineOrModuleTypeIndex::Module(m) => {
let subty = &types[*m];
@@ -2012,9 +2012,9 @@ impl StructType {
/// Get the supertype of this struct type, if any.
pub fn supertype(&self) -> Option<Self> {
- self.registered_type
- .supertype
- .map(|ty| Self::from_shared_type_index(self.engine(), ty.unwrap_engine_type_index()))
+ self.registered_type.supertype.map(|ty| {
+ Self::from_shared_type_index(self.engine(), ty.unwrap_engine_type_index()).unwrap()
+ })
}
/// Get the `i`th field type.
@@ -2133,9 +2133,19 @@ impl StructType {
})
}
- pub(crate) fn from_shared_type_index(engine: &Engine, index: VMSharedTypeIndex) -> StructType {
- let ty = RegisteredType::root(engine, index);
- Self::from_registered_type(ty)
+ /// Get the type registered for `index`.
+ ///
+ /// Returns `None` if `index` does not name a registered type of this
+ /// shape, since indices may come from the untrusted GC heap.
+ pub(crate) fn from_shared_type_index(
+ engine: &Engine,
+ index: VMSharedTypeIndex,
+ ) -> Option<StructType> {
+ let ty = RegisteredType::try_root(engine, index)?;
+ if !ty.is_struct() {
+ return None;
+ }
+ Some(Self::from_registered_type(ty))
}
pub(crate) fn from_registered_type(registered_type: RegisteredType) -> Self {
@@ -2258,9 +2268,9 @@ impl ArrayType {
/// Get the supertype of this array type, if any.
pub fn supertype(&self) -> Option<Self> {
- self.registered_type
- .supertype
- .map(|ty| Self::from_shared_type_index(self.engine(), ty.unwrap_engine_type_index()))
+ self.registered_type.supertype.map(|ty| {
+ Self::from_shared_type_index(self.engine(), ty.unwrap_engine_type_index()).unwrap()
+ })
}
/// Get this array's underlying field type.
@@ -2374,9 +2384,19 @@ impl ArrayType {
})
}
- pub(crate) fn from_shared_type_index(engine: &Engine, index: VMSharedTypeIndex) -> ArrayType {
- let ty = RegisteredType::root(engine, index);
- Self::from_registered_type(ty)
+ /// Get the type registered for `index`.
+ ///
+ /// Returns `None` if `index` does not name a registered type of this
+ /// shape, since indices may come from the untrusted GC heap.
+ pub(crate) fn from_shared_type_index(
+ engine: &Engine,
+ index: VMSharedTypeIndex,
+ ) -> Option<ArrayType> {
+ let ty = RegisteredType::try_root(engine, index)?;
+ if !ty.is_array() {
+ return None;
+ }
+ Some(Self::from_registered_type(ty))
}
pub(crate) fn from_registered_type(registered_type: RegisteredType) -> Self {
@@ -2594,9 +2614,9 @@ impl FuncType {
/// Get the supertype of this function type, if any.
pub fn supertype(&self) -> Option<Self> {
- self.registered_type
- .supertype
- .map(|ty| Self::from_shared_type_index(self.engine(), ty.unwrap_engine_type_index()))
+ self.registered_type.supertype.map(|ty| {
+ Self::from_shared_type_index(self.engine(), ty.unwrap_engine_type_index()).unwrap()
+ })
}
/// Get the `i`th parameter type.
@@ -2747,9 +2767,19 @@ impl FuncType {
})
}
- pub(crate) fn from_shared_type_index(engine: &Engine, index: VMSharedTypeIndex) -> FuncType {
- let ty = RegisteredType::root(engine, index);
- Self::from_registered_type(ty)
+ /// Get the type registered for `index`.
+ ///
+ /// Returns `None` if `index` does not name a registered type of this
+ /// shape, since indices may come from the untrusted GC heap.
+ pub(crate) fn from_shared_type_index(
+ engine: &Engine,
+ index: VMSharedTypeIndex,
+ ) -> Option<FuncType> {
+ let ty = RegisteredType::try_root(engine, index)?;
+ if !ty.is_func() {
+ return None;
+ }
+ Some(Self::from_registered_type(ty))
}
pub(crate) fn from_registered_type(registered_type: RegisteredType) -> Self {
@@ -2812,12 +2842,21 @@ impl ContType {
self.type_index() == other.type_index()
}
- pub(crate) fn from_shared_type_index(engine: &Engine, index: VMSharedTypeIndex) -> ContType {
- let ty = RegisteredType::root(engine, index);
- assert!(ty.is_cont());
- Self {
- registered_type: ty,
+ /// Get the type registered for `index`.
+ ///
+ /// Returns `None` if `index` does not name a registered type of this
+ /// shape, since indices may come from the untrusted GC heap.
+ pub(crate) fn from_shared_type_index(
+ engine: &Engine,
+ index: VMSharedTypeIndex,
+ ) -> Option<ContType> {
+ let ty = RegisteredType::try_root(engine, index)?;
+ if !ty.is_cont() {
+ return None;
}
+ Some(Self {
+ registered_type: ty,
+ })
}
}
@@ -2992,17 +3031,26 @@ impl ExnType {
&self.registered_type
}
- pub(crate) fn from_shared_type_index(engine: &Engine, index: VMSharedTypeIndex) -> ExnType {
- let ty = RegisteredType::root(engine, index);
- assert!(ty.is_exn());
+ /// Get the type registered for `index`.
+ ///
+ /// Returns `None` if `index` does not name a registered type of this
+ /// shape, since indices may come from the untrusted GC heap.
+ pub(crate) fn from_shared_type_index(
+ engine: &Engine,
+ index: VMSharedTypeIndex,
+ ) -> Option<ExnType> {
+ let ty = RegisteredType::try_root(engine, index)?;
+ if !ty.is_exn() {
+ return None;
+ }
let func_ty = FuncType::from_shared_type_index(
engine,
- ty.unwrap_exn().func_ty.unwrap_engine_type_index(),
- );
- Self {
+ ty.unwrap_exn().func_ty.as_engine_type_index()?,
+ )?;
+ Some(Self {
func_ty,
registered_type: ty,
- }
+ })
}
}
@@ -3093,7 +3141,8 @@ impl TagType {
}
pub(crate) fn from_wasmtime_tag(engine: &Engine, tag: &Tag) -> TagType {
- let ty = FuncType::from_shared_type_index(engine, tag.signature.unwrap_engine_type_index());
+ let ty = FuncType::from_shared_type_index(engine, tag.signature.unwrap_engine_type_index())
+ .unwrap();
TagType { ty }
}
diff --git a/crates/wasmtime/src/runtime/vm/gc.rs b/crates/wasmtime/src/runtime/vm/gc.rs
index 28bf087928..0b21ba1f2c 100644
--- a/crates/wasmtime/src/runtime/vm/gc.rs
+++ b/crates/wasmtime/src/runtime/vm/gc.rs
@@ -26,6 +26,7 @@ pub use gc_runtime::*;
pub use host_data::*;
pub use i31::*;
+use crate::bail_bug;
use crate::hash_map::HashMap;
use crate::module::ModuleRegistry;
use crate::prelude::*;
@@ -161,7 +162,10 @@ impl GcStore {
/// Get the kind of the given GC reference.
pub fn kind(&self, gc_ref: &VMGcRef) -> Result<VMGcKind> {
debug_assert!(!gc_ref.is_i31());
- Ok(self.header(gc_ref)?.kind())
+ match self.header(gc_ref)?.kind() {
+ Some(kind) => Ok(kind),
+ None => bail_bug!("invalid `VMGcKind`"),
+ }
}
/// Get the header of the given GC reference.
diff --git a/crates/wasmtime/src/runtime/vm/gc/cont_ref.rs b/crates/wasmtime/src/runtime/vm/gc/cont_ref.rs
index 48c01b4935..e62ac3ef53 100644
--- a/crates/wasmtime/src/runtime/vm/gc/cont_ref.rs
+++ b/crates/wasmtime/src/runtime/vm/gc/cont_ref.rs
@@ -47,8 +47,8 @@ impl ContRefTable {
return Ok(None);
}
- let id = Id::from_raw(raw - 1);
- match self.slab.get(id).copied() {
+ let contobj = Id::try_from_raw(raw - 1).and_then(|id| self.slab.get(id).copied());
+ match contobj {
Some(contobj) => Ok(Some(contobj)),
None => bail_bug!("bad continuation-reference table ID"),
}
diff --git a/crates/wasmtime/src/runtime/vm/gc/enabled/arrayref.rs b/crates/wasmtime/src/runtime/vm/gc/enabled/arrayref.rs
index f7354bd1c3..52976db605 100644
--- a/crates/wasmtime/src/runtime/vm/gc/enabled/arrayref.rs
+++ b/crates/wasmtime/src/runtime/vm/gc/enabled/arrayref.rs
@@ -1,5 +1,5 @@
use crate::{
- StorageType, Val,
+ StorageType, Val, bail_bug,
prelude::*,
runtime::vm::{GcHeap, GcStore, VMGcRef},
store::{AutoAssertNoGc, StoreOpaque},
@@ -41,7 +41,7 @@ impl VMGcRef {
}
match gc_heap.header(&self) {
- Ok(header) => header.kind().matches(VMGcKind::ArrayRef),
+ Ok(header) => header.matches_kind(VMGcKind::ArrayRef),
Err(_) => false,
}
}
@@ -137,7 +137,7 @@ impl VMArrayRef {
/// safe, but will lead to general incorrectness such as panics and wrong
/// results.
///
- /// Panics on out-of-bounds accesses.
+ /// Returns an error on out-of-bounds accesses.
pub fn read_elem(
&self,
store: &mut AutoAssertNoGc,
@@ -145,7 +145,10 @@ impl VMArrayRef {
ty: &StorageType,
index: u32,
) -> Result<Val> {
- let offset = layout.elem_offset(index).unwrap();
+ let offset = match layout.elem_offset(index) {
+ Some(offset) => offset,
+ None => bail_bug!("out-of-bounds array element index"),
+ };
self.as_gc_ref().read_val(store, ty, offset)
}
@@ -159,7 +162,7 @@ impl VMArrayRef {
/// Failure to do so is memory safe, but will lead to general incorrectness
/// such as panics and wrong results.
///
- /// Panics on out-of-bounds accesses.
+ /// Returns an error on out-of-bounds accesses.
pub fn write_elem(
&self,
store: &mut AutoAssertNoGc,
@@ -170,7 +173,10 @@ impl VMArrayRef {
) -> Result<()> {
debug_assert!(val._matches_ty(&store, &ty.unpack())?);
- let offset = layout.elem_offset(index).unwrap();
+ let offset = match layout.elem_offset(index) {
+ Some(offset) => offset,
+ None => bail_bug!("out-of-bounds array element index"),
+ };
self.as_gc_ref().write_val(store, ty, offset, val)
}
@@ -197,7 +203,7 @@ impl VMArrayRef {
/// Returns an error if `val` is a GC reference that has since been
/// unrooted.
///
- /// Panics on out-of-bounds accesses.
+ /// Returns an error on out-of-bounds accesses.
pub fn initialize_elem(
&self,
store: &mut AutoAssertNoGc,
@@ -207,7 +213,10 @@ impl VMArrayRef {
val: Val,
) -> Result<()> {
debug_assert!(val._matches_ty(&store, &ty.unpack())?);
- let offset = layout.elem_offset(index).unwrap();
+ let offset = match layout.elem_offset(index) {
+ Some(offset) => offset,
+ None => bail_bug!("out-of-bounds array element index"),
+ };
self.as_gc_ref().initialize_val(store, ty, offset, val)
}
}
diff --git a/crates/wasmtime/src/runtime/vm/gc/enabled/copying.rs b/crates/wasmtime/src/runtime/vm/gc/enabled/copying.rs
index e8746623cb..9d69157901 100644
--- a/crates/wasmtime/src/runtime/vm/gc/enabled/copying.rs
+++ b/crates/wasmtime/src/runtime/vm/gc/enabled/copying.rs
@@ -144,7 +144,7 @@ struct VMCopyingArrayHeader {
unsafe impl GcHeapObject for VMCopyingArrayHeader {
#[inline]
fn is(header: &VMGcHeader) -> bool {
- header.kind() == VMGcKind::ArrayRef
+ header.kind() == Some(VMGcKind::ArrayRef)
}
}
@@ -155,8 +155,9 @@ struct VMCopyingExternRef {
/// fields aren't overwritten after copying to the new semi-space.
header: VMCopyingHeaderAndForwardingRef,
- /// The ID of this ref's data in the `ExternRefHostDataTable`.
- host_data: ExternRefHostDataId,
+ /// The raw encoding of this ref's `ExternRefHostDataId`; the ID type does
+ /// not accept every bit pattern, and heap bytes are untrusted.
+ host_data: u32,
/// Link to the next `externref` in this semi-space.
next_extern_ref: Option<VMExternRef>,
@@ -165,7 +166,7 @@ struct VMCopyingExternRef {
unsafe impl GcHeapObject for VMCopyingExternRef {
#[inline]
fn is(header: &VMGcHeader) -> bool {
- header.kind() == VMGcKind::ExternRef
+ header.kind() == Some(VMGcKind::ExternRef)
}
}
@@ -564,8 +565,7 @@ survived collection, since the active space is the same size as the idle space",
if self
.index(copying_ref(&to_ref))?
.header
- .kind()
- .matches(VMGcKind::ExternRef)
+ .matches_kind(VMGcKind::ExternRef)
{
let old_head = self.active_extern_ref_set_head.take();
self.index_mut::<VMCopyingExternRef>(to_ref.as_typed_unchecked())?
@@ -625,7 +625,7 @@ survived collection, since the active space is the same size as the idle space",
let Some(ty) = ty else {
bail_bug!("out-of-line trace info but no type index");
};
- match trace_infos.trace_info(&ty, trace_state) {
+ match trace_infos.trace_info(&ty, trace_state)? {
TraceInfo::Struct { gc_ref_offsets } => {
for &offset in gc_ref_offsets {
self.scan_field(object_start, offset)?;
@@ -779,7 +779,7 @@ unsafe impl GcHeap for CopyingHeap {
// Take the old list head before borrowing self mutably through index_mut.
let old_head = self.active_extern_ref_set_head.take();
let externref_obj = self.index_mut::<VMCopyingExternRef>(gc_ref.as_typed_unchecked())?;
- externref_obj.host_data = host_data;
+ externref_obj.host_data = host_data.into_raw();
externref_obj.next_extern_ref = old_head;
let externref = gc_ref.into_externref_unchecked();
self.active_extern_ref_set_head = Some(externref.unchecked_copy());
@@ -788,16 +788,18 @@ unsafe impl GcHeap for CopyingHeap {
fn externref_host_data(&self, externref: &VMExternRef) -> Result<ExternRefHostDataId> {
let typed_ref = externref_to_copying(externref);
- Ok(self.index(typed_ref)?.host_data)
+ match ExternRefHostDataId::from_raw(self.index(typed_ref)?.host_data) {
+ Some(id) => Ok(id),
+ None => bail_bug!("invalid `ExternRefHostDataId`"),
+ }
}
fn header(&self, gc_ref: &VMGcRef) -> Result<&VMGcHeader> {
let header: &VMGcHeader = self.index(gc_ref.as_typed_unchecked())?;
debug_assert!(
- VMGcKind::try_from_u32(header.kind().as_u32()).is_some(),
- "header: invalid VMGcKind {:#010x} at gc_ref {gc_ref:#p}",
- header.kind().as_u32(),
+ header.kind().is_some(),
+ "header: invalid VMGcKind at gc_ref {gc_ref:#p}",
);
Ok(header)
@@ -807,9 +809,8 @@ unsafe impl GcHeap for CopyingHeap {
let header: &mut VMGcHeader = self.index_mut(gc_ref.as_typed_unchecked())?;
debug_assert!(
- VMGcKind::try_from_u32(header.kind().as_u32()).is_some(),
- "header_mut: invalid VMGcKind {:#010x} at gc_ref {gc_ref:#p}",
- header.kind().as_u32(),
+ header.kind().is_some(),
+ "header_mut: invalid VMGcKind at gc_ref {gc_ref:#p}",
);
Ok(header)
@@ -1112,6 +1113,7 @@ impl CopyingCollection<'_, '_> {
/// linked list and deallocating host data for any that were not forwarded.
fn sweep_extern_refs(&mut self) -> Result<()> {
log::trace!("Begin sweeping `externref`s");
+
let mut link = self.heap.idle_extern_ref_set_head.take();
while let Some(externref) = link {
let gc_ref = externref.as_gc_ref();
@@ -1119,8 +1121,14 @@ impl CopyingCollection<'_, '_> {
let header = self.heap.index(copying_ref(gc_ref))?;
if !header.copied() {
let typed: &TypedGcRef<VMCopyingExternRef> = gc_ref.as_typed_unchecked();
- let host_data_id = self.heap.index(typed)?.host_data;
- self.trace_state.host_data_table.dealloc(host_data_id)?;
+ match ExternRefHostDataId::from_raw(self.heap.index(typed)?.host_data) {
+ Some(id) => {
+ self.trace_state.host_data_table.dealloc(id)?;
+ }
+ None => {
+ bail_bug!("invalid `ExternRefHostDataId`");
+ }
+ }
}
link = self
.heap
diff --git a/crates/wasmtime/src/runtime/vm/gc/enabled/drc.rs b/crates/wasmtime/src/runtime/vm/gc/enabled/drc.rs
index 996d8dc5e8..0d2f7428aa 100644
--- a/crates/wasmtime/src/runtime/vm/gc/enabled/drc.rs
+++ b/crates/wasmtime/src/runtime/vm/gc/enabled/drc.rs
@@ -305,7 +305,12 @@ impl DrcHeap {
Some(allocs) => allocs,
None => bail_bug!("allocs missing during tracing"),
};
- let mut undo = Undo::new((self, allocs), |(this, allocs)| {
+ let mut undo = Undo::new((self, allocs), |(this, mut allocs)| {
+ // Unwinding out of a collection leaves these populated, so we must
+ // restore the invariant that they are empty between collections.
+ allocs.large_array_dec_ref_stack.clear();
+ allocs.to_dealloc.clear();
+
debug_assert!(this.tracing_allocs.is_none());
this.tracing_allocs = Some(allocs);
});
@@ -342,7 +347,7 @@ impl DrcHeap {
// Trace: enqueue child GC refs for dec-ref'ing.
if let Some(ty) = ty {
- match this.trace_infos.trace_info(&ty, trace_state) {
+ match this.trace_infos.trace_info(&ty, trace_state)? {
TraceInfo::Struct { gc_ref_offsets } => {
stack.reserve(gc_ref_offsets.len());
let data = this.gc_object_data(&gc_ref)?;
@@ -387,12 +392,16 @@ impl DrcHeap {
// Handle `externref` host data. Only `externref`s have host
// data, and `ty` is `None` only for `externref`s, so we skip
// this for `struct` and `array` objects entirely.
- debug_assert!(drc_header.header.kind().matches(VMGcKind::ExternRef));
+ debug_assert!(drc_header.header.matches_kind(VMGcKind::ExternRef));
let externref = match gc_ref.as_typed::<VMDrcExternRef>(this) {
Some(r) => r,
None => bail_bug!("expected externref"),
};
- let host_data_id = this.index(externref)?.host_data;
+ let host_data_id =
+ match ExternRefHostDataId::from_raw(this.index(externref)?.host_data) {
+ Some(id) => id,
+ None => bail_bug!("invalid `ExternRefHostDataId`"),
+ };
trace_state.host_data_table.dealloc(host_data_id)?;
}
@@ -474,10 +483,9 @@ impl DrcHeap {
// Each entry must have a valid `VMGcKind`.
let header = self.header(&gc_ref)?;
- let kind = header.kind().as_u32();
assert!(
- VMGcKind::try_from_u32(kind).is_some(),
- "over-approx list: entry at heap index {idx} has invalid VMGcKind {kind:#034b}",
+ header.kind().is_some(),
+ "over-approx list: entry at heap index {idx} has an invalid VMGcKind",
);
// Each entry must have its in-list bit set.
@@ -839,7 +847,7 @@ struct VMDrcArrayHeader {
unsafe impl GcHeapObject for VMDrcArrayHeader {
#[inline]
fn is(header: &VMGcHeader) -> bool {
- header.kind() == VMGcKind::ArrayRef
+ header.kind() == Some(VMGcKind::ArrayRef)
}
}
@@ -847,13 +855,15 @@ unsafe impl GcHeapObject for VMDrcArrayHeader {
#[repr(C)]
struct VMDrcExternRef {
header: VMDrcHeader,
- host_data: ExternRefHostDataId,
+ // The raw encoding of an `ExternRefHostDataId`; the ID type does not accept
+ // every bit pattern, and heap bytes are untrusted.
+ host_data: u32,
}
unsafe impl GcHeapObject for VMDrcExternRef {
#[inline]
fn is(header: &VMGcHeader) -> bool {
- header.kind() == VMGcKind::ExternRef
+ header.kind() == Some(VMGcKind::ExternRef)
}
}
@@ -912,9 +922,12 @@ unsafe impl GcHeap for DrcHeap {
debug_assert!(tracing_allocs.is_some());
if let Some(allocs) = tracing_allocs {
+ // Clear, rather than assert empty: an interrupted collection leaves
+ // entries behind, and this runs while the store is being dropped,
+ // where a panic would abort the process.
allocs.dec_ref_stack.clear();
- debug_assert!(allocs.large_array_dec_ref_stack.is_empty());
- debug_assert!(allocs.to_dealloc.is_empty());
+ allocs.large_array_dec_ref_stack.clear();
+ allocs.to_dealloc.clear();
}
memory.take().unwrap()
@@ -1013,22 +1026,24 @@ unsafe impl GcHeap for DrcHeap {
Ok(gc_ref) => gc_ref,
};
self.index_mut::<VMDrcExternRef>(gc_ref.as_typed_unchecked())?
- .host_data = host_data;
+ .host_data = host_data.into_raw();
Ok(Ok(gc_ref.into_externref_unchecked()))
}
fn externref_host_data(&self, externref: &VMExternRef) -> Result<ExternRefHostDataId> {
let typed_ref = externref_to_drc(externref);
- Ok(self.index(typed_ref)?.host_data)
+ match ExternRefHostDataId::from_raw(self.index(typed_ref)?.host_data) {
+ Some(id) => Ok(id),
+ None => bail_bug!("invalid `ExternRefHostDataId`"),
+ }
}
fn header(&self, gc_ref: &VMGcRef) -> Result<&VMGcHeader> {
let header: &VMGcHeader = self.index(gc_ref.as_typed_unchecked())?;
debug_assert!(
- VMGcKind::try_from_u32(header.kind().as_u32()).is_some(),
- "header: invalid VMGcKind {:#010x} at gc_ref {gc_ref:#p}",
- header.kind().as_u32(),
+ header.kind().is_some(),
+ "header: invalid VMGcKind at gc_ref {gc_ref:#p}",
);
Ok(header)
@@ -1038,9 +1053,8 @@ unsafe impl GcHeap for DrcHeap {
let header: &mut VMGcHeader = self.index_mut(gc_ref.as_typed_unchecked())?;
debug_assert!(
- VMGcKind::try_from_u32(header.kind().as_u32()).is_some(),
- "header_mut: invalid VMGcKind {:#010x} at gc_ref {gc_ref:#p}",
- header.kind().as_u32(),
+ header.kind().is_some(),
+ "header_mut: invalid VMGcKind at gc_ref {gc_ref:#p}",
);
Ok(header)
diff --git a/crates/wasmtime/src/runtime/vm/gc/enabled/exnref.rs b/crates/wasmtime/src/runtime/vm/gc/enabled/exnref.rs
index d84f0187fe..16f1e2e580 100644
--- a/crates/wasmtime/src/runtime/vm/gc/enabled/exnref.rs
+++ b/crates/wasmtime/src/runtime/vm/gc/enabled/exnref.rs
@@ -41,7 +41,7 @@ impl VMGcRef {
}
match gc_heap.header(&self) {
- Ok(header) => header.kind().matches(VMGcKind::ExnRef),
+ Ok(header) => header.matches_kind(VMGcKind::ExnRef),
Err(_) => false,
}
}
diff --git a/crates/wasmtime/src/runtime/vm/gc/enabled/externref.rs b/crates/wasmtime/src/runtime/vm/gc/enabled/externref.rs
index f349928177..410989f900 100644
--- a/crates/wasmtime/src/runtime/vm/gc/enabled/externref.rs
+++ b/crates/wasmtime/src/runtime/vm/gc/enabled/externref.rs
@@ -37,7 +37,7 @@ impl VMGcRef {
}
match gc_heap.header(&self) {
- Ok(header) => header.kind() == VMGcKind::ExternRef,
+ Ok(header) => header.kind() == Some(VMGcKind::ExternRef),
Err(_) => false,
}
}
diff --git a/crates/wasmtime/src/runtime/vm/gc/enabled/null.rs b/crates/wasmtime/src/runtime/vm/gc/enabled/null.rs
index 6ad8a79e70..25516f10a9 100644
--- a/crates/wasmtime/src/runtime/vm/gc/enabled/null.rs
+++ b/crates/wasmtime/src/runtime/vm/gc/enabled/null.rs
@@ -6,7 +6,7 @@
use super::*;
use crate::{
- Engine, Trap,
+ Engine, Trap, bail_bug,
prelude::*,
vm::{
ExternRefHostDataId, GarbageCollection, GcHeap, GcHeapObject, GcProgress, GcRootsIter,
@@ -76,7 +76,7 @@ struct VMNullArrayHeader {
unsafe impl GcHeapObject for VMNullArrayHeader {
#[inline]
fn is(header: &VMGcHeader) -> bool {
- header.kind() == VMGcKind::ArrayRef
+ header.kind() == Some(VMGcKind::ArrayRef)
}
}
@@ -95,13 +95,15 @@ impl VMNullArrayHeader {
#[repr(C)]
struct VMNullExternRef {
header: VMGcHeader,
- host_data: ExternRefHostDataId,
+ // The raw encoding of an `ExternRefHostDataId`; the ID type does not accept
+ // every bit pattern, and heap bytes are untrusted.
+ host_data: u32,
}
unsafe impl GcHeapObject for VMNullExternRef {
#[inline]
fn is(header: &VMGcHeader) -> bool {
- header.kind() == VMGcKind::ExternRef
+ header.kind() == Some(VMGcKind::ExternRef)
}
}
@@ -182,7 +184,9 @@ impl NullHeap {
debug_assert_eq!(header.reserved_u26(), 0);
header.set_reserved_u26(size);
- *self.header_mut(&gc_ref)? = header;
+ // NB: not `header_mut`, whose validity assertion would read this
+ // object's still-uninitialized memory.
+ *self.index_mut::<VMGcHeader>(gc_ref.as_typed_unchecked())? = header;
Ok(Ok(gc_ref))
}
@@ -272,13 +276,16 @@ unsafe impl GcHeap for NullHeap {
Err(bytes_needed) => return Ok(Err(bytes_needed)),
};
self.index_mut::<VMNullExternRef>(gc_ref.as_typed_unchecked())?
- .host_data = host_data;
+ .host_data = host_data.into_raw();
Ok(Ok(gc_ref.into_externref_unchecked()))
}
fn externref_host_data(&self, externref: &VMExternRef) -> Result<ExternRefHostDataId> {
let typed_ref = VMNullExternRef::typed_ref(self, externref);
- Ok(self.index(typed_ref)?.host_data)
+ match ExternRefHostDataId::from_raw(self.index(typed_ref)?.host_data) {
+ Some(id) => Ok(id),
+ None => bail_bug!("invalid `ExternRefHostDataId`"),
+ }
}
fn object_size(&self, gc_ref: &VMGcRef) -> Result<usize> {
@@ -287,11 +294,25 @@ unsafe impl GcHeap for NullHeap {
}
fn header(&self, gc_ref: &VMGcRef) -> Result<&VMGcHeader> {
- self.index(gc_ref.as_typed_unchecked())
+ let header: &VMGcHeader = self.index(gc_ref.as_typed_unchecked())?;
+
+ debug_assert!(
+ header.kind().is_some(),
+ "header: invalid VMGcKind at gc_ref {gc_ref:#p}",
+ );
+
+ Ok(header)
}
fn header_mut(&mut self, gc_ref: &VMGcRef) -> Result<&mut VMGcHeader> {
- self.index_mut(gc_ref.as_typed_unchecked())
+ let header: &mut VMGcHeader = self.index_mut(gc_ref.as_typed_unchecked())?;
+
+ debug_assert!(
+ header.kind().is_some(),
+ "header_mut: invalid VMGcKind at gc_ref {gc_ref:#p}",
+ );
+
+ Ok(header)
}
fn alloc_raw(&mut self, header: VMGcHeader, layout: Layout) -> Result<Result<VMGcRef, u64>> {
diff --git a/crates/wasmtime/src/runtime/vm/gc/enabled/structref.rs b/crates/wasmtime/src/runtime/vm/gc/enabled/structref.rs
index 299b138580..e5f346d11f 100644
--- a/crates/wasmtime/src/runtime/vm/gc/enabled/structref.rs
+++ b/crates/wasmtime/src/runtime/vm/gc/enabled/structref.rs
@@ -41,7 +41,7 @@ impl VMGcRef {
}
match gc_heap.header(&self) {
- Ok(header) => header.kind().matches(VMGcKind::StructRef),
+ Ok(header) => header.matches_kind(VMGcKind::StructRef),
Err(_) => false,
}
}
diff --git a/crates/wasmtime/src/runtime/vm/gc/enabled/trace_infos.rs b/crates/wasmtime/src/runtime/vm/gc/enabled/trace_infos.rs
index ae45b0cc06..c0d429353b 100644
--- a/crates/wasmtime/src/runtime/vm/gc/enabled/trace_infos.rs
+++ b/crates/wasmtime/src/runtime/vm/gc/enabled/trace_infos.rs
@@ -7,6 +7,7 @@
use crate::hash_map::{Entry, HashMap};
use crate::module::RegisteredModuleId;
use crate::vm::{GcStoreTraceState, NopHasher, TraceInfo};
+use crate::{bail_bug, prelude::*};
use wasmtime_environ::{ModuleInternedTypeIndex, VMSharedTypeIndex};
#[derive(Clone, Copy)]
@@ -35,14 +36,16 @@ impl TraceInfos {
self.map.clear();
}
- /// Lookup trace information for `ty`, panicking if it can't be found.
+ /// Lookup trace information for `ty`.
pub fn trace_info<'a>(
&mut self,
ty: &VMSharedTypeIndex,
state: &'a GcStoreTraceState<'_>,
- ) -> &'a TraceInfo {
- self.trace_info_(ty, state)
- .unwrap_or_else(|| panic!("failed to find trace information for {ty:?}"))
+ ) -> Result<&'a TraceInfo> {
+ match self.trace_info_(ty, state) {
+ Some(info) => Ok(info),
+ None => bail_bug!("failed to find trace information for {ty:?}"),
+ }
}
fn trace_info_<'a>(
diff --git a/crates/wasmtime/src/runtime/vm/gc/func_ref.rs b/crates/wasmtime/src/runtime/vm/gc/func_ref.rs
index 9276e9cdb1..7a605b2c4d 100644
--- a/crates/wasmtime/src/runtime/vm/gc/func_ref.rs
+++ b/crates/wasmtime/src/runtime/vm/gc/func_ref.rs
@@ -22,18 +22,21 @@ use wasmtime_environ::VMSharedTypeIndex;
/// An identifier into the `FuncRefTable`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
-#[repr(transparent)]
pub struct FuncRefTableId(Id);
impl FuncRefTableId {
- /// Convert this `FuncRefTableId` into its raw `u32` ID.
+ /// Get the raw `u32` to store in the GC heap for this ID.
pub fn into_raw(self) -> u32 {
- self.0.into_raw()
+ self.0.into_raw() + 1
}
- /// Create a `FuncRefTableId` from a raw `u32` ID.
- pub fn from_raw(raw: u32) -> Self {
- Self(Id::from_raw(raw))
+ /// Resolve a raw ID loaded from the GC heap, if it is well-formed.
+ ///
+ /// A well-formed ID is not necessarily one this table has handed out;
+ /// `get_typed` and `get_untyped` still check their lookups.
+ pub fn from_raw(raw: u32) -> Option<Self> {
+ let id = raw.checked_sub(1)?;
+ Some(Self(Id::try_from_raw(id)?))
}
}
diff --git a/crates/wasmtime/src/runtime/vm/gc/gc_ref.rs b/crates/wasmtime/src/runtime/vm/gc/gc_ref.rs
index 17f9d5bcce..e1190466ec 100644
--- a/crates/wasmtime/src/runtime/vm/gc/gc_ref.rs
+++ b/crates/wasmtime/src/runtime/vm/gc/gc_ref.rs
@@ -41,10 +41,21 @@ impl VMGcHeader {
}
/// Get the kind of GC object that this is.
- pub fn kind(&self) -> VMGcKind {
+ ///
+ /// Returns `None` if this header does not name a valid kind, since headers
+ /// come out of the untrusted GC heap.
+ pub fn kind(&self) -> Option<VMGcKind> {
VMGcKind::from_high_bits_of_u32(self.kind)
}
+ /// Is this object's kind valid and a subtype of `kind`?
+ ///
+ /// False for a header whose kind bits do not name a valid kind, since
+ /// headers come out of the untrusted GC heap.
+ pub fn matches_kind(&self, kind: VMGcKind) -> bool {
+ self.kind().is_some_and(|k| k.matches(kind))
+ }
+
/// Get the reserved 26 bits in this header.
///
/// These are bits are reserved for `GcRuntime` implementations to make use
@@ -381,7 +392,7 @@ impl VMGcRef {
#[inline]
pub fn is_extern_ref(&self, gc_heap: &(impl GcHeap + ?Sized)) -> bool {
self.gc_header(gc_heap)
- .map_or(false, |h| h.kind().matches(VMGcKind::ExternRef))
+ .map_or(false, |h| h.matches_kind(VMGcKind::ExternRef))
}
/// Is this `VMGcRef` an `anyref`?
@@ -390,7 +401,7 @@ impl VMGcRef {
self.is_i31()
|| self
.gc_header(gc_heap)
- .map_or(false, |h| h.kind().matches(VMGcKind::AnyRef))
+ .map_or(false, |h| h.matches_kind(VMGcKind::AnyRef))
}
pub fn read_val(
@@ -423,7 +434,10 @@ impl VMGcRef {
}
HeapTopType::Func => {
let func_ref_id = data.read_u32(offset)?;
- let func_ref_id = FuncRefTableId::from_raw(func_ref_id);
+ let func_ref_id = match FuncRefTableId::from_raw(func_ref_id) {
+ Some(id) => id,
+ None => bail_bug!("bad FuncRefTableId"),
+ };
let func_ref = store
.unwrap_gc_store()
.func_ref_table
@@ -677,23 +691,23 @@ mod tests {
let mut header = VMGcHeader::from_kind_and_index(kind, ty);
assert_eq!(header.reserved_u26(), 0);
- assert_eq!(header.kind(), kind);
+ assert_eq!(header.kind(), Some(kind));
assert_eq!(header.ty(), Some(ty));
header.set_reserved_u26(36);
assert_eq!(header.reserved_u26(), 36);
- assert_eq!(header.kind(), kind);
+ assert_eq!(header.kind(), Some(kind));
assert_eq!(header.ty(), Some(ty));
let max = (1 << 26) - 1;
header.set_reserved_u26(max);
assert_eq!(header.reserved_u26(), max);
- assert_eq!(header.kind(), kind);
+ assert_eq!(header.kind(), Some(kind));
assert_eq!(header.ty(), Some(ty));
header.set_reserved_u26(0);
assert_eq!(header.reserved_u26(), 0);
- assert_eq!(header.kind(), kind);
+ assert_eq!(header.kind(), Some(kind));
assert_eq!(header.ty(), Some(ty));
let result = std::panic::catch_unwind(move || header.set_reserved_u26(max + 1));
diff --git a/crates/wasmtime/src/runtime/vm/gc/gc_runtime.rs b/crates/wasmtime/src/runtime/vm/gc/gc_runtime.rs
index 20fb2cf287..34e1dda408 100644
--- a/crates/wasmtime/src/runtime/vm/gc/gc_runtime.rs
+++ b/crates/wasmtime/src/runtime/vm/gc/gc_runtime.rs
@@ -235,9 +235,15 @@ pub unsafe trait GcHeap: 'static + Send + Sync {
// Struct, array, and general GC object methods
/// Get the header of the object that `gc_ref` points to.
+ ///
+ /// Implementations may assert that the header's kind is valid, so
+ /// allocation paths that have not written the header yet must reach for the
+ /// raw object data instead of these accessors.
fn header(&self, gc_ref: &VMGcRef) -> Result<&VMGcHeader>;
/// Get the header of the object that `gc_ref` points to.
+ ///
+ /// See `header` for the restriction on uninitialized objects.
fn header_mut(&mut self, gc_ref: &VMGcRef) -> Result<&mut VMGcHeader>;
/// Get the size (in bytes) of the object referenced by `gc_ref`.
diff --git a/crates/wasmtime/src/runtime/vm/gc/host_data.rs b/crates/wasmtime/src/runtime/vm/gc/host_data.rs
index ae097ed691..586001c291 100644
--- a/crates/wasmtime/src/runtime/vm/gc/host_data.rs
+++ b/crates/wasmtime/src/runtime/vm/gc/host_data.rs
@@ -28,10 +28,31 @@ pub struct ExternRefHostDataTable {
}
/// ID into the `externref` host data table.
+///
+/// Not every bit pattern is a valid ID, so this must never be a field of a
+/// type reinterpreted from GC heap bytes; use `into_raw` and `from_raw`
+/// instead.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
-#[repr(transparent)]
pub struct ExternRefHostDataId(Id);
+impl ExternRefHostDataId {
+ /// Get the raw `u32` to store in the GC heap for this ID.
+ ///
+ /// Biased by one so that zero is never a valid encoding.
+ pub fn into_raw(self) -> u32 {
+ self.0.into_raw() + 1
+ }
+
+ /// Resolve a raw ID loaded from the GC heap, if it is well-formed.
+ ///
+ /// A well-formed ID is not necessarily a live one; lookups are still
+ /// checked.
+ pub fn from_raw(raw: u32) -> Option<Self> {
+ let id = raw.checked_sub(1)?;
+ Some(ExternRefHostDataId(Id::try_from_raw(id)?))
+ }
+}
+
fn deref_box<T: ?Sized>(b: &Box<T>) -> &T {
&**b
}
diff --git a/crates/wasmtime/src/runtime/vm/libcalls.rs b/crates/wasmtime/src/runtime/vm/libcalls.rs
index b5e43da3de..9caf42d7ae 100644
--- a/crates/wasmtime/src/runtime/vm/libcalls.rs
+++ b/crates/wasmtime/src/runtime/vm/libcalls.rs
@@ -502,7 +502,11 @@ fn gc_alloc_raw(
use core::alloc::Layout;
use wasmtime_environ::{VMGcKind, VMSharedTypeIndex};
- let kind = VMGcKind::from_high_bits_of_u32(kind_and_reserved);
+ // NB: unlike most `VMGcKind`s, this one is a constant baked into compiled
+ // code by our own code generator, not a value out of the GC heap.
+ let Some(kind) = VMGcKind::from_high_bits_of_u32(kind_and_reserved) else {
+ bail_bug!("compiler emitted an invalid `VMGcKind`")
+ };
log::trace!("gc_alloc_raw(kind={kind:?}, size={size}, align={align})");
let shared_type_index = VMSharedTypeIndex::from_u32(shared_type_index);
@@ -586,7 +590,10 @@ fn get_interned_func_ref(
let store = AutoAssertNoGc::new(store.store_opaque_mut());
- let func_ref_id = FuncRefTableId::from_raw(func_ref_id);
+ let func_ref_id = match FuncRefTableId::from_raw(func_ref_id) {
+ Some(id) => id,
+ None => bail_bug!("bad FuncRefTableId"),
+ };
let module_interned_type_index = ModuleInternedTypeIndex::from_bits(module_interned_type_index);
let func_ref = if module_interned_type_index.is_reserved_value() {