A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Refactor the `TypeRegistry` to partially handle OOM (#12500)
Nick Fitzgerald9e3b5ee5f1dd
diff --git a/crates/environ/src/types.rs b/crates/environ/src/types.rsindex 73766d4e6a..89c0e122d2 100644--- a/crates/environ/src/types.rs+++ b/crates/environ/src/types.rs@@ -1430,7 +1430,7 @@ impl TypeTrace for WasmSubType {/// (rec (type (func $f (result (ref null $g))))/// (type (func $g (result (ref null $f)))))/// ```-#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]+#[derive(Debug, Default, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]pub struct WasmRecGroup {/// The types inside of this recgroup.pub types: Box<[WasmSubType]>,diff --git a/crates/wasmtime/src/runtime/component/component.rs b/crates/wasmtime/src/runtime/component/component.rsindex 45f1e03821..e2d4b2fba6 100644--- a/crates/wasmtime/src/runtime/component/component.rs+++ b/crates/wasmtime/src/runtime/component/component.rs@@ -427,7 +427,7 @@ impl Component {let signatures = engine.register_and_canonicalize_types(types.module_types_mut(),static_modules.iter_mut().map(|(_, m)| &mut m.module),- );+ )?;types.canonicalize_for_runtime_usage(&mut |idx| signatures.shared_type(idx).unwrap());// Assemble the `EngineCode` artifact which is shared by all core wasmdiff --git a/crates/wasmtime/src/runtime/module.rs b/crates/wasmtime/src/runtime/module.rsindex dbca042d1f..d3bc42cb66 100644--- a/crates/wasmtime/src/runtime/module.rs+++ b/crates/wasmtime/src/runtime/module.rs@@ -515,8 +515,8 @@ impl Module {// Note that the unsafety here should be ok since the `trampolines`// field should only point to valid trampoline function pointers// within the text section.- let signatures =- engine.register_and_canonicalize_types(&mut types, core::iter::once(&mut info.module));+ let signatures = engine+ .register_and_canonicalize_types(&mut types, core::iter::once(&mut info.module))?;// Package up all our data into an `EngineCode` and delegate to the final// step of module compilation.diff --git a/crates/wasmtime/src/runtime/type_registry.rs b/crates/wasmtime/src/runtime/type_registry.rsindex d0cd39d552..a06322352b 100644--- a/crates/wasmtime/src/runtime/type_registry.rs+++ b/crates/wasmtime/src/runtime/type_registry.rs@@ -4,12 +4,14 @@//! downcasting, and etc...use crate::Engine;+use crate::error::OutOfMemory;use crate::hash_set::HashSet;use crate::prelude::*;use crate::sync::RwLock;use crate::vm::GcRuntime;use alloc::borrow::Cow;use alloc::sync::Arc;+use core::cell::Cell;use core::iter;use core::{borrow::Borrow,@@ -21,11 +23,15 @@ use core::{Ordering::{AcqRel, Acquire, Release},},};-use wasmtime_core::alloc::PanicOnOom;+use wasmtime_core::alloc::{+ boxed_slice_write_iter, new_boxed_slice_from_iter_with_len, new_uninit_boxed_slice,+};use wasmtime_core::slab::{Id as SlabId, Slab};use wasmtime_environ::{- EngineOrModuleTypeIndex, GcLayout, ModuleInternedTypeIndex, ModuleTypes, PrimaryMap,- SecondaryMap, TypeTrace, VMSharedTypeIndex, WasmRecGroup, WasmSubType, iter_entity_range,+ EngineOrModuleTypeIndex, EntityRef, GcLayout, ModuleInternedTypeIndex, ModuleTypes, TypeTrace,+ Undo, VMSharedTypeIndex, WasmRecGroup, WasmSubType,+ collections::{PrimaryMap, SecondaryMap, Vec},+ iter_entity_range,packed_option::{PackedOption, ReservedValue},};@@ -116,7 +122,7 @@ impl Engine {&self,module_types: &mut ModuleTypes,env_modules: I,- ) -> TypeCollection+ ) -> Result<TypeCollection, OutOfMemory>whereI: IntoIterator<Item = &'a mut wasmtime_environ::Module>,I::IntoIter: ExactSizeIterator,@@ -140,18 +146,20 @@ impl Engine {let (rec_groups, types) = registry.0.write()- .register_module_types(gc_runtime, module_types);+ .register_module_types(gc_runtime, module_types)?;// Then build our map from each function type's engine index to the// module-index of its trampoline. Trampoline functions are queried by// module-index in a compiled module, and doing this engine-to-module// resolution now means we don't need to do it on the function call hot// path.- let mut trampolines = SecondaryMap::with_capacity(types.len());+ let mut trampolines = SecondaryMap::with_capacity(types.len())?;for (module_ty, module_trampoline_ty) in module_types.trampoline_types() {let shared_ty = types[module_ty];let trampoline_shared_ty = registry.trampoline_type(shared_ty);- trampolines[trampoline_shared_ty] = Some(module_trampoline_ty).into();+ trampolines+ .insert(trampoline_shared_ty, Some(module_trampoline_ty).into())+ .expect("reserved space");}// Finally, to ensure that no matter which API from which layer@@ -166,12 +174,12 @@ impl Engine {module.canonicalize_for_runtime_usage(&mut |idx| types[idx]);}- TypeCollection {+ Ok(TypeCollection {engine,rec_groups,types,trampolines,- }+ })}}@@ -333,7 +341,7 @@ impl Hash for RegisteredType {impl RegisteredType {/// Constructs a new `RegisteredType`, registering the given type with the/// engine's `TypeRegistry`.- pub fn new(engine: &Engine, ty: WasmSubType) -> RegisteredType {+ pub fn new(engine: &Engine, ty: WasmSubType) -> Result<RegisteredType, OutOfMemory> {let (entry, index, ty, layout) = {log::trace!("RegisteredType::new({ty:?})");@@ -348,7 +356,7 @@ impl RegisteredType {// engine mismatch; those should be caught earlier.inner.assert_canonicalized_for_runtime_usage_in_this_registry(&ty);- let entry = inner.register_singleton_rec_group(gc_runtime, ty);+ let entry = inner.register_singleton_rec_group(gc_runtime, ty)?;let index = entry.0.shared_type_indices[0];let id = shared_type_index_to_slab_id(index);@@ -358,7 +366,13 @@ impl RegisteredType {(entry, index, ty, layout)};- RegisteredType::from_parts(engine.clone(), entry, index, ty, layout)+ Ok(RegisteredType::from_parts(+ engine.clone(),+ entry,+ index,+ ty,+ layout,+ ))}/// Create an owning handle to the given index's associated type.@@ -508,6 +522,43 @@ impl Borrow<WasmRecGroup> for RecGroupEntry {}impl RecGroupEntry {+ /// Allocate a new, default `RecGroupEntryInner`.+ ///+ /// The resulting value should be initialized via `RecGroupEntry::init`.+ fn new_inner() -> Result<Arc<RecGroupEntryInner>, OutOfMemory> {+ try_new(RecGroupEntryInner {+ hash_consing_key: Default::default(),+ shared_type_indices: Default::default(),+ registrations: AtomicUsize::new(0),+ unregistered: AtomicBool::new(false),+ })+ }++ /// Initialize a `Arc<RecGroupEntryInner>` (as created by+ /// `RecGroupEntry::new_inner`) and wrap it into a `RecGroupEntry`.+ fn init(+ mut inner: Arc<RecGroupEntryInner>,+ key: WasmRecGroup,+ shared_types: Box<[VMSharedTypeIndex]>,+ ) -> Self {+ debug_assert!(key.is_canonicalized_for_hash_consing());++ let RecGroupEntryInner {+ hash_consing_key,+ shared_type_indices,+ registrations: _,+ unregistered: _,+ } = Arc::get_mut(&mut inner).expect("must have the only handle to this inner entry");++ debug_assert!(shared_type_indices.is_empty());+ *shared_type_indices = shared_types;++ debug_assert!(hash_consing_key.types.is_empty());+ *hash_consing_key = key;++ RecGroupEntry(inner)+ }+/// Increment the registration count.fn incref(&self, why: &str) {let old_count = self.0.registrations.fetch_add(1, AcqRel);@@ -609,10 +660,10 @@ impl TypeRegistryInner {#[inline]#[track_caller]- fn debug_assert_all_registered(&self, indices: impl IntoIterator<Item = VMSharedTypeIndex>) {+ fn debug_assert_all_registered(&self, entry: &RecGroupEntry) {if cfg!(debug_assertions) {- for index in indices {- self.debug_assert_registered(index);+ for &ty in &entry.0.shared_type_indices {+ self.debug_assert_registered(ty);}}}@@ -621,20 +672,23 @@ impl TypeRegistryInner {&mut self,gc_runtime: Option<&dyn GcRuntime>,types: &ModuleTypes,- ) -> (- Vec<RecGroupEntry>,- PrimaryMap<ModuleInternedTypeIndex, VMSharedTypeIndex>,- ) {+ ) -> Result<+ (+ Vec<RecGroupEntry>,+ PrimaryMap<ModuleInternedTypeIndex, VMSharedTypeIndex>,+ ),+ OutOfMemory,+ > {log::trace!("Start registering module types");// The engine's type registry entries for these module types.- let mut entries = Vec::with_capacity(types.rec_groups().len());+ let mut entries = Vec::with_capacity(types.rec_groups().len())?;// The map from a module type index to an engine type index for these// module types.let mut map = PrimaryMap::<ModuleInternedTypeIndex, VMSharedTypeIndex>::with_capacity(types.wasm_types().len(),- );+ )?;for (_rec_group_index, module_group) in types.rec_groups() {let entry = self.register_rec_group(@@ -642,23 +696,23 @@ impl TypeRegistryInner {&map,module_group.clone(),iter_entity_range(module_group.clone()).map(|ty| types[ty].clone()),- );+ )?;// Update the module-to-engine map with this rec group's// newly-registered types.for (module_ty, engine_ty) initer_entity_range(module_group).zip(entry.0.shared_type_indices.iter()){- let module_ty2 = map.push(*engine_ty);+ let module_ty2 = map.push(*engine_ty).expect("reserved capacity");assert_eq!(module_ty, module_ty2);}- entries.push(entry);+ entries.push(entry).expect("reserved capacity");}log::trace!("End registering module types");- (entries, map)+ Ok((entries, map))}/// Register a rec group in this registry.@@ -693,7 +747,7 @@ impl TypeRegistryInner {map: &PrimaryMap<ModuleInternedTypeIndex, VMSharedTypeIndex>,range: Range<ModuleInternedTypeIndex>,types: impl ExactSizeIterator<Item = WasmSubType>,- ) -> RecGroupEntry {+ ) -> Result<RecGroupEntry, OutOfMemory> {log::trace!("registering rec group of length {}", types.len());debug_assert_eq!(iter_entity_range(range.clone()).len(), types.len());@@ -705,19 +759,24 @@ impl TypeRegistryInner {// canonicalize for runtime usage in this engine, we must still eagerly// clone and set aside the original, non-canonicalized types for that// potential engine canonicalization eventuality.- let mut non_canon_types = Vec::with_capacity(types.len());+ let mut non_canon_types = Vec::with_capacity(types.len())?;let hash_consing_key = WasmRecGroup {- types: types- .zip(iter_entity_range(range.clone()))- .map(|(mut ty, module_index)| {- non_canon_types.push((module_index, ty.clone()));- ty.canonicalize_for_hash_consing(range.clone(), &mut |idx| {- debug_assert!(idx < range.clone().start);- map[idx]- });- ty- })- .collect::<Box<[_]>>(),+ types: new_boxed_slice_from_iter_with_len(+ types.len(),+ types+ .zip(iter_entity_range(range.clone()))+ .map(|(mut ty, module_index)| {+ non_canon_types+ .push((module_index, ty.clone()))+ .expect("reserved capacity");+ ty.canonicalize_for_hash_consing(range.clone(), &mut |idx| {+ debug_assert!(idx < range.clone().start);+ map[idx]+ });+ ty+ }),+ )+ .map_err(|e| e.unwrap_oom())?,};// Any references in the hash-consing key to types outside of this rec@@ -732,166 +791,517 @@ impl TypeRegistryInner {if let Some(entry) = self.hash_consing_map.get(&hash_consing_key) {log::trace!("hash-consing map hit: reusing {entry:?}");assert_eq!(entry.0.unregistered.load(Acquire), false);- self.debug_assert_all_registered(entry.0.shared_type_indices.iter().copied());+ self.debug_assert_all_registered(entry);entry.incref("hash-consing map hit");- return entry.clone();+ Ok(entry.clone())+ } else {+ log::trace!("hash-consing map miss: making new registration");+ self.register_new_rec_group(gc_runtime, map, range, hash_consing_key, non_canon_types)}+ }- log::trace!("hash-consing map miss: making new registration");+ /// Register a new rec group that is not already in this registry.+ fn register_new_rec_group(+ &mut self,+ gc_runtime: Option<&(dyn GcRuntime + 'static)>,+ map: &PrimaryMap<ModuleInternedTypeIndex, VMSharedTypeIndex>,+ range: Range<ModuleInternedTypeIndex>,+ hash_consing_key: WasmRecGroup,+ mut non_canon_types: Vec<(ModuleInternedTypeIndex, WasmSubType)>,+ ) -> Result<RecGroupEntry, OutOfMemory> {+ debug_assert!(hash_consing_key.is_canonicalized_for_hash_consing());+ debug_assert_eq!(self.hash_consing_map.contains(&hash_consing_key), false);++ // XXX: Do not write new entries to `self` or its arenas in this block+ // of code, as we will not rollback those changes on OOM.+ let entry = {+ // First, pre-allocate capacity in our arenas for this rec group, as+ // much as possible.+ let num_types = non_canon_types.len();+ self.reserve_capacity_for_rec_group(num_types)?;+ let shared_type_indices = new_uninit_boxed_slice(num_types)?;+ let entry_inner = RecGroupEntry::new_inner()?;++ // Assign a `VMSharedTypeIndex` to each type.+ let shared_type_indices =+ self.assign_shared_type_indices(&non_canon_types, shared_type_indices);++ // Initialize the rec group entry, now that we have all its parts.+ RecGroupEntry::init(entry_inner, hash_consing_key, shared_type_indices)+ };- // Reserve capacity before making any side effects (like incrementing- // other rec groups ref counts). We do not want to panic or- // `?`-propagate an error when we have applied partial side effects.- //- // TODO(#12069): handle allocation failure here.- self.types.reserve(non_canon_types.len()).panic_on_oom();+ // XXX: From the creation of the `Undo` and afterwards, we can write to+ // `self` and its arenas. We must, however, always ensure that the+ // `Undo` fully rolls back the changes made below, so keep this in mind+ // if adding/removing/changing the arenas in `self`.+ let did_incref = Cell::new(false);+ let entry2 = entry.clone();+ let mut registry = Undo::new(self, |registry| {+ registry.remove_entry_impl(&entry2, did_incref.get());+ registry.drain_drop_stack();+ });++ registry.canonicalize_entry_types_for_runtime_usage(+ map,+ &entry,+ non_canon_types.iter_mut().map(|(_, ty)| ty),+ range.clone(),+ );// Inter-group edges: increment the referenced group's ref// count, because these other rec groups shouldn't be dropped- // while this rec group is still alive.- hash_consing_key- .trace_engine_indices::<_, ()>(&mut |index| {- self.debug_assert_registered(index);- let other_entry = self.type_to_rec_group[index].as_ref().unwrap();- assert_eq!(other_entry.0.unregistered.load(Acquire), false);- other_entry.incref("new rec group's type references");- Ok(())- })- .unwrap();+ // while this new rec group is still alive.+ registry.incref_outgoing_edges(&entry);+ did_incref.set(true);- // Register the individual types.- //- // Note that we can't update the reverse type-to-rec-group map until- // after we've constructed the `RecGroupEntry`, since that map needs the- // fully-constructed entry for its values.- let module_rec_group_start = range.start;- let shared_type_indices: Box<[_]> = non_canon_types- .iter()- .map(|(module_index, ty)| {- let engine_index = slab_id_to_shared_type_index(- self.types.alloc(None).expect("reserved capacity"),- );- log::trace!(- "reserved {engine_index:?} for {module_index:?} = non-canonical {ty:?}"- );- engine_index- })- .collect();- for (engine_index, (module_index, mut ty)) in- shared_type_indices.iter().copied().zip(non_canon_types)- {- log::trace!("canonicalizing {engine_index:?} for runtime usage");- ty.canonicalize_for_runtime_usage(&mut |module_index| {- if module_index < module_rec_group_start {- let engine_index = map[module_index];- log::trace!(" cross-group {module_index:?} becomes {engine_index:?}");- self.debug_assert_registered(engine_index);- engine_index- } else {- assert!(module_index < range.end);- let rec_group_offset = module_index.as_u32() - module_rec_group_start.as_u32();- let rec_group_offset = usize::try_from(rec_group_offset).unwrap();- let engine_index = shared_type_indices[rec_group_offset];- log::trace!(" intra-group {module_index:?} becomes {engine_index:?}");- assert!(!engine_index.is_reserved_value());- assert!(- self.types- .contains(shared_type_index_to_slab_id(engine_index))- );- engine_index+ registry.insert_entry_types(&entry, non_canon_types.into_iter().map(|(_, ty)| ty))?;+ registry.insert_entry_rec_groups(&entry);+ registry.insert_entry_supertypes(&entry)?;+ registry.insert_entry_trampolines(gc_runtime, &entry)?;+ registry.insert_entry_gc_layouts(gc_runtime, &entry)?;++ let is_new_entry = registry.hash_consing_map.insert(entry.clone());+ debug_assert!(is_new_entry);++ // We successfully registered the rec group! Commit our changes,+ // increment the rec group's registration count to one, and return it.+ registry.debug_assert_all_registered(&entry);+ Undo::commit(registry);+ entry.incref("creation");+ Ok(entry)+ }++ /// Implementation of removing a rec group entry.+ ///+ /// Shared by both unregistering a rec group and rolling back changes when+ /// we OOM in `register_new_rec_group`.+ ///+ /// The order of removals should be the reverse of the insertions in+ /// `register_new_rec_group`.+ fn remove_entry_impl(&mut self, entry: &RecGroupEntry, should_decref: bool) {+ // All entries we are removing should *really* be ready for+ // unregistration.+ assert_eq!(entry.0.registrations.load(Acquire), 0);+ assert_eq!(entry.0.unregistered.load(Acquire), false);++ // We are taking responsibility for unregistering this entry, so prevent+ // anyone else from attempting to do it again. See race (2) in the+ // comment in `unregister_entry`.+ entry.0.unregistered.store(true, Release);++ // Perform the removals in the opposite order as the insertions in+ // `register_new_rec_group`.+ self.hash_consing_map.remove(&entry.0.hash_consing_key);+ self.remove_entry_gc_layouts(&entry);+ self.remove_entry_trampolines(&entry);+ self.remove_entry_supertypes(&entry);+ self.remove_entry_rec_groups(&entry);+ self.remove_entry_types(&entry);+ if should_decref {+ self.decref_outgoing_edges(&entry);+ }+ }++ /// Insert the rec group entry's types into the `self.types` arena.+ fn insert_entry_types(+ &mut self,+ entry: &RecGroupEntry,+ sub_types: impl ExactSizeIterator<Item = WasmSubType>,+ ) -> Result<(), OutOfMemory> {+ debug_assert_eq!(entry.0.shared_type_indices.len(), sub_types.len());+ for (ty_idx, sub_ty) in entry.0.shared_type_indices.iter().copied().zip(sub_types) {+ // NB: Do not use+ // `assert_canonicalized_for_runtime_usage_in_this_registry` because+ // the types this type references may not be fully registered yet,+ // as we are in the middle of a rec group's registration.+ debug_assert!(sub_ty.is_canonicalized_for_runtime_usage());++ let id = shared_type_index_to_slab_id(ty_idx);+ debug_assert!(self.types.contains(id));+ debug_assert!(self.types[id].is_none());+ self.types[id] = Some(try_new(sub_ty)?);+ }+ Ok(())+ }++ /// Remove the rec group entry's types into the `self.types` arena.+ fn remove_entry_types(&mut self, entry: &RecGroupEntry) {+ for &ty in &entry.0.shared_type_indices {+ let id = shared_type_index_to_slab_id(ty);+ debug_assert!(self.types.contains(id));+ self.types.dealloc(id);+ }+ }++ /// Insert the rec group backlink for each type in this rec group.+ fn insert_entry_rec_groups(&mut self, entry: &RecGroupEntry) {+ debug_assert!(self.type_to_rec_group.capacity() >= self.types.len());+ for &ty in &entry.0.shared_type_indices {+ debug_assert!(self.type_to_rec_group[ty].is_none());+ debug_assert!(ty.index() < self.type_to_rec_group.capacity());+ self.type_to_rec_group+ .insert(ty, Some(entry.clone()))+ .expect("reserved capacity");+ }+ }++ /// Remove the rec group's type's backlinks to the rec group.+ fn remove_entry_rec_groups(&mut self, entry: &RecGroupEntry) {+ for &ty in &entry.0.shared_type_indices {+ debug_assert!(ty.index() < self.type_to_rec_group.capacity());+ self.type_to_rec_group.remove(ty);+ }+ }++ /// Insert the supertype information for this rec group's types.+ fn insert_entry_supertypes(&mut self, entry: &RecGroupEntry) -> Result<(), OutOfMemory> {+ for &ty in &entry.0.shared_type_indices {+ let id = shared_type_index_to_slab_id(ty);+ if let Some(supertype) = self.types[id].as_ref().unwrap().supertype {+ debug_assert!(self.type_to_supertypes.capacity() <= self.types.capacity());+ if self.type_to_supertypes.capacity() < self.types.capacity() {+ log::trace!("type_to_supertypes.resize({})", self.types.capacity());+ self.type_to_supertypes.resize(self.types.capacity())?;}- });- self.insert_one_type_from_rec_group(gc_runtime, module_index, engine_index, ty);++ let supertype = supertype.unwrap_engine_type_index();+ let supers_supertypes = self.supertypes(supertype);+ let supertypes = new_boxed_slice_from_iter_with_len(+ supers_supertypes.len() + 1,+ supers_supertypes+ .iter()+ .copied()+ .chain(iter::once(supertype)),+ )+ .map_err(|e| e.unwrap_oom())?;++ self.type_to_supertypes+ .insert(ty, Some(supertypes))+ .expect("reserved capacity");+ }}+ Ok(())+ }- // Although we haven't finished registering all their metadata, the- // types themselves should all be filled in now.- if cfg!(debug_assertions) {- for index in &shared_type_indices {- let id = shared_type_index_to_slab_id(*index);- debug_assert!(self.types.contains(id));- debug_assert!(self.types[id].is_some());+ /// Remove the rec group's associated supertype information.+ fn remove_entry_supertypes(&mut self, entry: &RecGroupEntry) {+ // We delay allocating space for this arena until we actually see a type+ // with a supertype, so early exit if we never allocated any space.+ if self.type_to_supertypes.capacity() == 0 {+ return;+ }++ for &ty in &entry.0.shared_type_indices {+ self.type_to_supertypes.remove(ty);+ }+ }++ /// Insert the trampoline information for this rec group's types.+ fn insert_entry_trampolines(+ &mut self,+ gc_runtime: Option<&(dyn GcRuntime + 'static)>,+ entry: &RecGroupEntry,+ ) -> Result<(), OutOfMemory> {+ for &ty_idx in &entry.0.shared_type_indices {+ let id = shared_type_index_to_slab_id(ty_idx);+ debug_assert!(self.types.contains(id));+ debug_assert!(self.types[id].is_some());+ let sub_ty = self.types[id].as_ref().unwrap();++ let Some(func_ty) = sub_ty.as_func() else {+ continue;+ };++ let trampoline_ty = func_ty.trampoline_type();++ if let Cow::Borrowed(_) = &trampoline_ty+ && sub_ty.is_final+ && sub_ty.supertype.is_none()+ {+ // The function type is its own trampoline type. Leave its entry+ // in `type_to_trampoline` empty to signal this.+ log::trace!("trampoline_type({ty_idx:?}) = {ty_idx:?}");+ continue;}++ debug_assert!(self.type_to_trampoline.capacity() <= self.types.capacity());+ if self.type_to_trampoline.capacity() < self.types.capacity() {+ log::trace!("type_to_trampoline.resize({})", self.types.capacity());+ self.type_to_trampoline.resize(self.types.capacity())?;+ }++ // This will recursively call into rec group registration, but at+ // most once since trampoline function types are their own+ // trampoline type.+ let trampoline_sub_ty = WasmSubType {+ is_final: true,+ supertype: None,+ composite_type: wasmtime_environ::WasmCompositeType {+ shared: sub_ty.composite_type.shared,+ inner: wasmtime_environ::WasmCompositeInnerType::Func(+ // TODO(#12069): handle OOM here.+ trampoline_ty.into_owned(),+ ),+ },+ };++ let trampoline_entry =+ self.register_singleton_rec_group(gc_runtime, trampoline_sub_ty)?;+ assert_eq!(trampoline_entry.0.shared_type_indices.len(), 1);+ let trampoline_index = trampoline_entry.0.shared_type_indices[0];+ self.debug_assert_registered(trampoline_index);+ debug_assert_ne!(ty_idx, trampoline_index);++ self.type_to_trampoline+ .insert(ty_idx, Some(trampoline_index).into())+ .expect("reserved capacity");++ log::trace!("trampoline_type({ty_idx:?}) = {trampoline_index:?}");}- debug_assert_eq!(- shared_type_indices.len(),- shared_type_indices- .iter()- .copied()- .collect::<crate::hash_set::HashSet<_>>()- .len(),- "should not have any duplicate type indices",- );- let entry = RecGroupEntry(Arc::new(RecGroupEntryInner {- hash_consing_key,- shared_type_indices,- registrations: AtomicUsize::new(1),- unregistered: AtomicBool::new(false),- }));- log::trace!("new {entry:?} -> count 1");+ Ok(())+ }- let is_new_entry = self.hash_consing_map.insert(entry.clone());- debug_assert!(is_new_entry);+ /// Remove the rec group's associated trampoline information.+ fn remove_entry_trampolines(&mut self, entry: &RecGroupEntry) {+ // We delay allocating space for this arena until we actually see a+ // function type that is not its own trampoline type, so early exit if+ // we never allocated any space.+ if self.type_to_trampoline.capacity() == 0 {+ return;+ }- // Now that we've constructed the entry, we can update the reverse- // type-to-rec-group map.- for ty in entry.0.shared_type_indices.iter().copied() {- debug_assert!(self.type_to_rec_group[ty].is_none());- self.type_to_rec_group[ty] = Some(entry.clone());+ for &ty in &entry.0.shared_type_indices {+ if let Some(tramp_ty) = self.type_to_trampoline.remove(ty).and_then(|x| x.expand()) {+ self.debug_assert_registered(tramp_ty);+ let tramp_entry = self.type_to_rec_group[tramp_ty].as_ref().unwrap();+ if tramp_entry.decref("dropping rec group's trampoline-type references") {+ self.push_to_drop_stack(tramp_entry.clone());+ }+ }}- self.debug_assert_all_registered(entry.0.shared_type_indices.iter().copied());-- // Finally, make sure to register the trampoline type for each function- // type in the rec group.- for shared_type_index in entry.0.shared_type_indices.iter().copied() {- let slab_id = shared_type_index_to_slab_id(shared_type_index);- let sub_ty = self.types[slab_id].as_ref().unwrap();- if let Some(f) = sub_ty.as_func() {- let trampoline = f.trampoline_type();- match &trampoline {- Cow::Borrowed(_) if sub_ty.is_final && sub_ty.supertype.is_none() => {- // The function type is its own trampoline type. Leave- // its entry in `type_to_trampoline` empty to signal- // this.- log::trace!(- "trampoline_type({shared_type_index:?}) = {shared_type_index:?}",- );- }- Cow::Borrowed(_) | Cow::Owned(_) => {- // This will recursively call into rec group- // registration, but at most once since trampoline- // function types are their own trampoline type.- let trampoline_entry = self.register_singleton_rec_group(- gc_runtime,- WasmSubType {- is_final: true,- supertype: None,- composite_type: wasmtime_environ::WasmCompositeType {- shared: sub_ty.composite_type.shared,- inner: wasmtime_environ::WasmCompositeInnerType::Func(- trampoline.into_owned(),- ),- },- },- );- assert_eq!(trampoline_entry.0.shared_type_indices.len(), 1);- let trampoline_index = trampoline_entry.0.shared_type_indices[0];- log::trace!(- "trampoline_type({shared_type_index:?}) = {trampoline_index:?}",- );- self.debug_assert_registered(trampoline_index);- debug_assert_ne!(shared_type_index, trampoline_index);- self.type_to_trampoline[shared_type_index] = Some(trampoline_index).into();- }++ self.drain_drop_stack();+ }++ /// Insert the GC layout information for this rec group's types.+ fn insert_entry_gc_layouts(+ &mut self,+ gc_runtime: Option<&(dyn GcRuntime + 'static)>,+ entry: &RecGroupEntry,+ ) -> Result<(), OutOfMemory> {+ let Some(gc_runtime) = gc_runtime else {+ // If we don't have a GC runtime, then we won't have any GC types+ // and don't have to remember any GC layouts.+ debug_assert!(entry.0.shared_type_indices.iter().all(|ty| {+ let id = shared_type_index_to_slab_id(*ty);+ let sub_ty = self.types[id].as_ref().unwrap();+ assert!(!sub_ty.composite_type.shared);+ matches!(+ &sub_ty.composite_type.inner,+ wasmtime_environ::WasmCompositeInnerType::Func(_)+ )+ }));+ return Ok(());+ };++ for &ty_idx in &entry.0.shared_type_indices {+ let id = shared_type_index_to_slab_id(ty_idx);+ let sub_ty = self.types[id].as_ref().unwrap();+ assert!(!sub_ty.composite_type.shared);++ let gc_layout = match &sub_ty.composite_type.inner {+ wasmtime_environ::WasmCompositeInnerType::Func(_) => continue,+ wasmtime_environ::WasmCompositeInnerType::Array(a) => {+ gc_runtime.layouts().array_layout(a).into()}+ wasmtime_environ::WasmCompositeInnerType::Struct(s) => {+ gc_runtime.layouts().struct_layout(s).into()+ }+ wasmtime_environ::WasmCompositeInnerType::Exn(e) => {+ gc_runtime.layouts().exn_layout(e).into()+ }+ wasmtime_environ::WasmCompositeInnerType::Cont(_) => continue, // FIXME: #10248 stack switching support.+ };++ debug_assert!(self.type_to_gc_layout.capacity() <= self.types.capacity());+ if self.type_to_gc_layout.capacity() < self.types.capacity() {+ log::trace!("type_to_gc_layout.resize({})", self.types.capacity());+ self.type_to_gc_layout.resize(self.types.capacity())?;}++ self.type_to_gc_layout+ .insert(ty_idx, Some(gc_layout))+ .expect("reserved capacity");}- entry+ Ok(())}- /// Is the given type canonicalized for runtime usage this registry?+ /// Remove the rec group's associated GC layout information.+ fn remove_entry_gc_layouts(&mut self, entry: &RecGroupEntry) {+ // We delay allocating space for this arena until we actually see a GC+ // type, so early exit if we never allocated any space.+ if self.type_to_gc_layout.capacity() == 0 {+ return;+ }++ for ty in &entry.0.shared_type_indices {+ self.type_to_gc_layout.remove(*ty);+ }+ }++ /// Assign a `VMSharedTypeIndex` to each type in a rec group.+ fn assign_shared_type_indices(+ &mut self,+ non_canon_types: &[(ModuleInternedTypeIndex, WasmSubType)],+ shared_type_indices: Box<[core::mem::MaybeUninit<VMSharedTypeIndex>]>,+ ) -> Box<[VMSharedTypeIndex]> {+ debug_assert_eq!(non_canon_types.len(), shared_type_indices.len());+ debug_assert!(+ self.types.capacity() - self.types.len() >= non_canon_types.len(),+ "should have reserved capacity"+ );+ boxed_slice_write_iter(+ shared_type_indices,+ non_canon_types.iter().map(|(module_index, ty)| {+ let engine_index =+ slab_id_to_shared_type_index(self.types.alloc(None).expect("have capacity"));+ log::trace!(+ "reserved {engine_index:?} for {module_index:?} = non-canonical {ty:?}"+ );+ engine_index+ }),+ )+ .expect("iterator is same length as slice")+ }++ /// For each cross-rec group type reference inside `entry`, increment the+ /// referenced rec group's registration count.+ fn incref_outgoing_edges(&mut self, entry: &RecGroupEntry) {+ let key = &entry.0.hash_consing_key;+ debug_assert!(key.is_canonicalized_for_hash_consing());+ key.trace_engine_indices::<_, ()>(&mut |index| {+ self.debug_assert_registered(index);+ let other_entry = self.type_to_rec_group[index].as_ref().unwrap();+ assert_eq!(other_entry.0.unregistered.load(Acquire), false);+ other_entry.incref("new rec group's type references");+ Ok(())+ })+ .unwrap();+ }++ /// For each cross-rec group type reference inside `entry`, decrement the+ /// referenced rec group's registration count.+ fn decref_outgoing_edges(&mut self, entry: &RecGroupEntry) {+ let key = &entry.0.hash_consing_key;+ debug_assert!(key.is_canonicalized_for_hash_consing());+ key.trace_engine_indices::<_, ()>(&mut |other_index| {+ self.debug_assert_registered(other_index);+ let other_entry = self.type_to_rec_group[other_index].as_ref().unwrap();+ assert_eq!(other_entry.0.unregistered.load(Acquire), false);+ if other_entry.decref("dropping rec group's type references") {+ self.push_to_drop_stack(other_entry.clone());+ }+ Ok(())+ })+ .unwrap();+ self.drain_drop_stack();+ }++ /// Pre-allocate capacity for a rec group of size `num_types` in our various+ /// arenas.+ fn reserve_capacity_for_rec_group(&mut self, num_types: usize) -> Result<(), OutOfMemory> {+ log::trace!("Reserving capacity for rec group of {num_types} types");++ // NB: Destructure to make sure we are considering every field in+ // `self`.+ let TypeRegistryInner {+ hash_consing_map,+ types,+ type_to_rec_group,+ drop_stack,++ // We only insert entries into these `SecondaryMap`s if/when we+ // encounter GC types (which is rare, even when GC types are+ // enabled).+ type_to_supertypes: _,+ type_to_trampoline: _,+ type_to_gc_layout: _,+ } = self;++ // This map contains rec groups, not types, so only reserve space for+ // one additional entry.+ //+ // TODO(#12069): handle OOM here.+ log::trace!(" hash_consing_map.reserve(1)");+ hash_consing_map.reserve(1);++ log::trace!(" types.reserve({num_types})");+ types.reserve(num_types)?;+ let types_capacity = types.capacity();++ log::trace!(" type_to_rec_group.resize({types_capacity})");+ type_to_rec_group.resize(types_capacity)?;++ log::trace!(" type_to_rec_group.reserve({types_capacity})");+ debug_assert!(drop_stack.is_empty());+ drop_stack.reserve(types_capacity)?;++ Ok(())+ }++ /// Canonicalize all the types inside a rec group for runtime usage within+ /// this registry.+ fn canonicalize_entry_types_for_runtime_usage<'a>(+ &self,+ map: &PrimaryMap<ModuleInternedTypeIndex, VMSharedTypeIndex>,+ entry: &RecGroupEntry,+ sub_tys: impl ExactSizeIterator<Item = &'a mut WasmSubType>,+ range: Range<ModuleInternedTypeIndex>,+ ) {+ debug_assert_eq!(sub_tys.len(), entry.0.shared_type_indices.len());+ for (engine_index, ty) in entry.0.shared_type_indices.iter().copied().zip(sub_tys) {+ self.canonicalize_type_for_runtime_usage(map, &entry, engine_index, ty, range.clone());+ }+ }++ /// Canonicalize one type for runtime usage within this registry.+ fn canonicalize_type_for_runtime_usage(+ &self,+ map: &PrimaryMap<ModuleInternedTypeIndex, VMSharedTypeIndex>,+ entry: &RecGroupEntry,+ engine_index: VMSharedTypeIndex,+ ty: &mut WasmSubType,+ range: Range<ModuleInternedTypeIndex>,+ ) {+ log::trace!("canonicalizing {engine_index:?} for runtime usage");+ ty.canonicalize_for_runtime_usage(&mut |module_index| {+ if module_index < range.start {+ let engine_index = map[module_index];+ log::trace!(" cross-group {module_index:?} becomes {engine_index:?}");+ self.debug_assert_registered(engine_index);+ engine_index+ } else {+ assert!(module_index < range.end);+ let rec_group_offset = module_index.as_u32() - range.start.as_u32();+ let rec_group_offset = usize::try_from(rec_group_offset).unwrap();+ let engine_index = entry.0.shared_type_indices[rec_group_offset];+ log::trace!(" intra-group {module_index:?} becomes {engine_index:?}");+ assert!(!engine_index.is_reserved_value());+ assert!(+ self.types+ .contains(shared_type_index_to_slab_id(engine_index))+ );+ engine_index+ }+ });+ }++ /// Assert that the given type is canonicalized for runtime usage this+ /// registry, and that every type it references is also registered in this+ /// registry.+ #[track_caller]fn assert_canonicalized_for_runtime_usage_in_this_registry(&self, ty: &WasmSubType) {ty.trace::<_, ()>(&mut |index| match index {EngineOrModuleTypeIndex::RecGroup(_) | EngineOrModuleTypeIndex::Module(_) => {@@ -905,89 +1315,6 @@ impl TypeRegistryInner {.unwrap();}- /// Insert a new type as part of registering a new rec group.- ///- /// The type must be canonicalized for runtime usage in this registry and- /// its rec group must be a new one that we are currently registering, not- /// an already-registered rec group.- fn insert_one_type_from_rec_group(- &mut self,- gc_runtime: Option<&dyn GcRuntime>,- module_index: ModuleInternedTypeIndex,- engine_index: VMSharedTypeIndex,- ty: WasmSubType,- ) {- // Despite being canonicalized for runtime usage, this type may still- // have forward references to other types in the rec group we haven't- // yet registered. Therefore, we can't use our usual- // `assert_canonicalized_for_runtime_usage_in_this_registry` helper here- // as that will see the forward references and think they must be- // references to types in other registries.- assert!(- ty.is_canonicalized_for_runtime_usage(),- "type is not canonicalized for runtime usage: {ty:?}"- );-- assert!(!ty.composite_type.shared);- let gc_layout = match &ty.composite_type.inner {- wasmtime_environ::WasmCompositeInnerType::Func(_) => None,- wasmtime_environ::WasmCompositeInnerType::Array(a) => Some(- gc_runtime- .expect("must have a GC runtime to register array types")- .layouts()- .array_layout(a)- .into(),- ),- wasmtime_environ::WasmCompositeInnerType::Struct(s) => Some(- gc_runtime- .expect("must have a GC runtime to register struct types")- .layouts()- .struct_layout(s)- .into(),- ),- wasmtime_environ::WasmCompositeInnerType::Exn(e) => Some(- gc_runtime- .expect("must have a GC runtime to register exception types")- .layouts()- .exn_layout(e)- .into(),- ),- wasmtime_environ::WasmCompositeInnerType::Cont(_) => None, // FIXME: #10248 stack switching support.- };-- // Add the type to our slab.- let id = shared_type_index_to_slab_id(engine_index);- assert!(self.types.contains(id));- assert!(self.types[id].is_none());- self.types[id] = Some(Arc::new(ty));-- // Create the supertypes list for this type.- if let Some(supertype) = self.types[id].as_ref().unwrap().supertype {- let supertype = supertype.unwrap_engine_type_index();- let supers_supertypes = self.supertypes(supertype);- let mut supertypes = Vec::with_capacity(supers_supertypes.len() + 1);- supertypes.extend(- supers_supertypes- .iter()- .copied()- .chain(iter::once(supertype)),- );- self.type_to_supertypes[engine_index] = Some(supertypes.into_boxed_slice());- }-- // Only write the type-to-gc-layout entry if we have a GC layout, so- // that the map can avoid any heap allocation for backing storage in the- // case where Wasm GC is disabled.- if let Some(layout) = gc_layout {- self.type_to_gc_layout[engine_index] = Some(layout);- }-- log::trace!(- "finished registering type {module_index:?} as {engine_index:?} = runtime-canonical {:?}",- self.types[id].as_ref().unwrap()- );- }-/// Get the supertypes list for the given type.////// The supertypes are listed in super-to-sub order. `ty` itself is not@@ -1010,7 +1337,7 @@ impl TypeRegistryInner {&mut self,gc_runtime: Option<&dyn GcRuntime>,ty: WasmSubType,- ) -> RecGroupEntry {+ ) -> Result<RecGroupEntry, OutOfMemory> {self.assert_canonicalized_for_runtime_usage_in_this_registry(&ty);// This type doesn't have any module-level type references, since it is@@ -1031,7 +1358,7 @@ impl TypeRegistryInner {fn unregister_type_collection(&mut self, collection: &TypeCollection) {log::trace!("Begin unregistering `TypeCollection`");for entry in &collection.rec_groups {- self.debug_assert_all_registered(entry.0.shared_type_indices.iter().copied());+ self.debug_assert_all_registered(entry);if entry.decref("TypeRegistryInner::unregister_type_collection") {self.unregister_entry(entry.clone());}@@ -1154,106 +1481,36 @@ impl TypeRegistryInner {// Okay, we are really going to unregister this entry. Enqueue it on the// drop stack.- self.drop_stack.push(entry);-- // Keep unregistering entries until the drop stack is empty. This is- // logically a recursive process where if we unregister a type that was- // the only thing keeping another type alive, we then recursively- // unregister that other type as well. However, we use this explicit- // drop stack to avoid recursion and the potential stack overflows that- // recursion implies.- while let Some(entry) = self.drop_stack.pop() {- log::trace!("Begin unregistering {entry:?}");- self.debug_assert_all_registered(entry.0.shared_type_indices.iter().copied());-- // All entries on the drop stack should *really* be ready for- // unregistration, since no one can resurrect entries once we've- // locked the registry.- assert_eq!(entry.0.registrations.load(Acquire), 0);- assert_eq!(entry.0.unregistered.load(Acquire), false);-- // We are taking responsibility for unregistering this entry, so- // prevent anyone else from attempting to do it again.- entry.0.unregistered.store(true, Release);-- // Decrement any other types that this type was shallowly- // (i.e. non-transitively) referencing and keeping alive. If this- // was the last thing keeping them registered, its okay to- // unregister them as well now.- debug_assert!(entry.0.hash_consing_key.is_canonicalized_for_hash_consing());- entry- .0- .hash_consing_key- .trace_engine_indices::<_, ()>(&mut |other_index| {- self.debug_assert_registered(other_index);- let other_entry = self.type_to_rec_group[other_index].as_ref().unwrap();- if other_entry.decref("dropping rec group's type references") {- self.drop_stack.push(other_entry.clone());- }- Ok(())- })- .unwrap();-- // Remove the entry from the hash-consing map. If we register a- // duplicate definition of this rec group again in the future, it- // will be as if it is the first time it has ever been registered,- // and it will be inserted into the hash-consing map again at that- // time.- let was_in_map = self.hash_consing_map.remove(&entry);- debug_assert!(was_in_map);-- // Similarly, remove the rec group's types from the registry, as- // well as their entries from the reverse type-to-rec-group- // map. Additionally, stop holding a strong reference from each- // function type in the rec group to that function type's trampoline- // type.- debug_assert_eq!(- entry.0.shared_type_indices.len(),- entry- .0- .shared_type_indices- .iter()- .copied()- .collect::<crate::hash_set::HashSet<_>>()- .len(),- "should not have any duplicate type indices",- );- for ty in entry.0.shared_type_indices.iter().copied() {- log::trace!("removing {ty:?} from registry");-- let removed_entry = self.type_to_rec_group[ty].take();- debug_assert_eq!(removed_entry.unwrap(), entry);-- // Remove the associated trampoline type, if any.- if let Some(trampoline_ty) =- self.type_to_trampoline.get(ty).and_then(|x| x.expand())- {- self.debug_assert_registered(trampoline_ty);- self.type_to_trampoline[ty] = None.into();- let trampoline_entry = self.type_to_rec_group[trampoline_ty].as_ref().unwrap();- if trampoline_entry.decref("dropping rec group's trampoline-type references") {- self.drop_stack.push(trampoline_entry.clone());- }- }-- // Remove the type's supertypes list, if any. Take care to guard- // this assignment so that we don't accidentally force the- // secondary map to allocate even when we never actually use- // Wasm GC.- if self.type_to_supertypes.get(ty).is_some() {- self.type_to_supertypes[ty] = None;- }-- // Same as above, but for the type's GC layout.- if self.type_to_gc_layout.get(ty).is_some() {- self.type_to_gc_layout[ty] = None;- }+ debug_assert!(self.drop_stack.capacity() >= self.types.capacity());+ self.push_to_drop_stack(entry);+ self.drain_drop_stack();+ }- let id = shared_type_index_to_slab_id(ty);- let deallocated_ty = self.types.dealloc(id);- assert!(deallocated_ty.is_some());- }+ /// Enqueue an entry for dropping.+ ///+ /// Should always be followed by some call to `drain_drop_stack()`, although+ /// it is fine to associate many `push_to_drop_stack()` calls with one final+ /// `drain_drop_stack()` call.+ fn push_to_drop_stack(&mut self, entry: RecGroupEntry) {+ log::trace!("Pushing entry to drop stack: {entry:?}");+ self.drop_stack+ .push(entry)+ .expect("always have space in `drop_stack` for all types");+ }+ /// Keep unregistering entries until the drop stack is empty.+ ///+ /// This is logically a recursive process where if we unregister a type that+ /// was the only thing keeping another type alive, we then recursively+ /// unregister that other type as well. However, we use an explicit drop+ /// stack to avoid recursion and the potential stack overflows that+ /// recursion implies.+ fn drain_drop_stack(&mut self) {+ log::trace!("Draining drop stack");+ while let Some(entry) = self.drop_stack.pop() {+ log::trace!("Begin unregistering {entry:?}");+ self.debug_assert_all_registered(&entry);+ self.remove_entry_impl(&entry, true);log::trace!("End unregistering {entry:?}");}}diff --git a/crates/wasmtime/src/runtime/types.rs b/crates/wasmtime/src/runtime/types.rsindex 82a0e56655..2b61d381f3 100644--- a/crates/wasmtime/src/runtime/types.rs+++ b/crates/wasmtime/src/runtime/types.rs@@ -7,10 +7,10 @@ use crate::{Engine, type_registry::RegisteredType};use core::fmt::{self, Display, Write};use wasmtime_environ::WasmExnType;use wasmtime_environ::{- EngineOrModuleTypeIndex, EntityType, Global, IndexType, Limits, Memory, ModuleTypes, Table,- Tag, TypeTrace, VMSharedTypeIndex, WasmArrayType, WasmCompositeInnerType, WasmCompositeType,- WasmFieldType, WasmFuncType, WasmHeapType, WasmRefType, WasmStorageType, WasmStructType,- WasmSubType, WasmValType,+ EngineOrModuleTypeIndex, EntityType, Global, IndexType, Limits, Memory, ModuleTypes,+ PanicOnOom as _, Table, Tag, TypeTrace, VMSharedTypeIndex, WasmArrayType,+ WasmCompositeInnerType, WasmCompositeType, WasmFieldType, WasmFuncType, WasmHeapType,+ WasmRefType, WasmStorageType, WasmStructType, WasmSubType, WasmValType,};pub(crate) mod matching;@@ -2091,7 +2091,7 @@ impl StructType {inner: WasmCompositeInnerType::Struct(ty),},},- );+ )?;Ok(Self {registered_type: ty,})@@ -2332,7 +2332,8 @@ impl ArrayType {inner: WasmCompositeInnerType::Array(ty),},},- );+ )+ .panic_on_oom();Self {registered_type: ty,}@@ -2684,7 +2685,8 @@ impl FuncType {inner: WasmCompositeInnerType::Func(ty),},},- );+ )+ .panic_on_oom();Self {registered_type: ty,}@@ -2860,7 +2862,8 @@ impl ExnType {}),},},- );+ )+ .panic_on_oom();Self {func_ty,