A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Handle OOM when getting a function type's trampoline type (#12524)
Nick Fitzgeraldb96811d8cf8e
diff --git a/crates/environ/src/compile/module_types.rs b/crates/environ/src/compile/module_types.rsindex 59b018c573..ed9e789431 100644--- a/crates/environ/src/compile/module_types.rs+++ b/crates/environ/src/compile/module_types.rs@@ -10,6 +10,7 @@ use std::{ops::Index,};use wasmparser::{UnpackedIndex, Validator, ValidatorId};+use wasmtime_core::alloc::PanicOnOom as _;/// A type marking the start of a recursion group's definition.///@@ -153,7 +154,7 @@ impl ModuleTypesBuilder {for_func_ty: ModuleInternedTypeIndex,) -> ModuleInternedTypeIndex {let sub_ty = &self.types[for_func_ty];- let trampoline = sub_ty.unwrap_func().trampoline_type();+ let trampoline = sub_ty.unwrap_func().trampoline_type().panic_on_oom();if let Some(idx) = self.trampoline_types.get(&trampoline) {// We've already interned this trampoline type; reuse it.diff --git a/crates/environ/src/types.rs b/crates/environ/src/types.rsindex 89c0e122d2..24da68d079 100644--- a/crates/environ/src/types.rs+++ b/crates/environ/src/types.rs@@ -1,10 +1,11 @@-use crate::{Tunables, WasmResult, wasm_unsupported};+use crate::{Tunables, WasmResult, error::OutOfMemory, wasm_unsupported};use alloc::borrow::Cow;use alloc::boxed::Box;use core::{fmt, ops::Range};use cranelift_entity::entity_impl;use serde_derive::{Deserialize, Serialize};use smallvec::SmallVec;+use wasmtime_core::alloc::{TryClone, TryCollect as _};/// A trait for things that can trace all type-to-type edges, aka all type/// indices within this thing.@@ -142,6 +143,12 @@ pub enum WasmValType {Ref(WasmRefType),}+impl TryClone for WasmValType {+ fn try_clone(&self) -> Result<Self, OutOfMemory> {+ Ok(*self)+ }+}+impl fmt::Display for WasmValType {fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {match self {@@ -685,6 +692,17 @@ pub struct WasmFuncType {non_i31_gc_ref_returns_count: usize,}+impl TryClone for WasmFuncType {+ fn try_clone(&self) -> Result<Self, OutOfMemory> {+ Ok(WasmFuncType {+ params: TryClone::try_clone(&self.params)?,+ non_i31_gc_ref_params_count: self.non_i31_gc_ref_params_count,+ returns: TryClone::try_clone(&self.returns)?,+ non_i31_gc_ref_returns_count: self.non_i31_gc_ref_returns_count,+ })+ }+}+impl fmt::Display for WasmFuncType {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {write!(f, "(func")?;@@ -809,15 +827,21 @@ impl WasmFuncType {/// references themselves (unless the trampolines start doing explicit,/// fallible downcasts, but if we ever need that, then we might want to/// redesign this stuff).- pub fn trampoline_type(&self) -> Cow<'_, Self> {+ pub fn trampoline_type(&self) -> Result<Cow<'_, Self>, OutOfMemory> {if self.is_trampoline_type() {- return Cow::Borrowed(self);+ return Ok(Cow::Borrowed(self));}- Cow::Owned(Self::new(- self.params().iter().map(|p| p.trampoline_type()).collect(),- self.returns().iter().map(|r| r.trampoline_type()).collect(),- ))+ Ok(Cow::Owned(Self::new(+ self.params()+ .iter()+ .map(|p| p.trampoline_type())+ .try_collect()?,+ self.returns()+ .iter()+ .map(|r| r.trampoline_type())+ .try_collect()?,+ )))}}diff --git a/crates/wasmtime/src/runtime/type_registry.rs b/crates/wasmtime/src/runtime/type_registry.rsindex c85744013d..058fd75414 100644--- a/crates/wasmtime/src/runtime/type_registry.rs+++ b/crates/wasmtime/src/runtime/type_registry.rs@@ -26,7 +26,7 @@ use wasmtime_core::slab::{Id as SlabId, Slab};use wasmtime_environ::{EngineOrModuleTypeIndex, EntityRef, GcLayout, ModuleInternedTypeIndex, ModuleTypes, TypeTrace,Undo, VMSharedTypeIndex, WasmRecGroup, WasmSubType,- collections::{HashSet, PrimaryMap, SecondaryMap, Vec},+ collections::{HashSet, PrimaryMap, SecondaryMap, TryClone as _, Vec},iter_entity_range,packed_option::{PackedOption, ReservedValue},};@@ -1003,17 +1003,19 @@ impl TypeRegistryInner {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;- }+ let trampoline_ty = match func_ty.trampoline_type()? {+ Cow::Owned(ty) => ty,+ Cow::Borrowed(ty) if !sub_ty.is_final || sub_ty.supertype.is_some() => {+ ty.try_clone()?+ }+ Cow::Borrowed(_) => {+ // The function type is its own trampoline type. Leave its entry+ // in `type_to_trampoline` empty to signal this.+ debug_assert!(func_ty.is_trampoline_type());+ 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() {@@ -1021,23 +1023,21 @@ impl TypeRegistryInner {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(),- ),+ inner: wasmtime_environ::WasmCompositeInnerType::Func(trampoline_ty),},};+ // 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, 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);@@ -1497,6 +1497,9 @@ impl TypeRegistryInner {/// stack to avoid recursion and the potential stack overflows that/// recursion implies.fn drain_drop_stack(&mut self) {+ if self.drop_stack.is_empty() {+ return;+ }log::trace!("Draining drop stack");while let Some(entry) = self.drop_stack.pop() {log::trace!("Begin unregistering {entry:?}");