A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Add `wasmtime::FuncType::try_new`, which propagates allocation failure (#12530)
Nick Fitzgeraldb236888c9ff1
diff --git a/crates/fuzzing/src/oom.rs b/crates/fuzzing/src/oom.rsindex cb145506b7..dff622728e 100644--- a/crates/fuzzing/src/oom.rs+++ b/crates/fuzzing/src/oom.rs@@ -74,21 +74,42 @@ unsafe impl GlobalAlloc for OomTestAllocator {let new_state;let ptr;- {++ 'outside_oom_test: {// NB: It's okay to log/backtrace/etc... in this block because the// current state is `OutsideOomTest`, so any re-entrant allocations// will be passed through to the system allocator.+ // Don't panic on allocation-after-OOM attempts if we+ // are already in the middle of panicking. That will+ // cause an abort and we won't get as good of an error+ // message for the original panic, which is most likely+ // some kind of test failure.+ if old_state == OomState::OutsideOomTest || std::thread::panicking() {+ new_state = old_state;+ ptr = unsafe { std::alloc::System.alloc(layout) };+ break 'outside_oom_test;+ }++ let bt = Backtrace::new();+ let bt = format!("{bt:?}");++ // XXX: `env_logger` internally buffers writes in a `Vec` which+ // means our OOM tests might sporadically fail when you enable+ // logging to debug stuff, so simply let the allocation through if+ // `env_logger` is on the stack.+ if bt.contains("env_logger") {+ new_state = old_state;+ ptr = unsafe { std::alloc::System.alloc(layout) };+ break 'outside_oom_test;+ }+match old_state {- OomState::OutsideOomTest => {- new_state = OomState::OutsideOomTest;- ptr = unsafe { std::alloc::System.alloc(layout) };- }+ OomState::OutsideOomTest => unreachable!("handled above"),OomState::OomOnAlloc(0) => {log::trace!(- "injecting OOM for allocation: {layout:?}\nAllocation backtrace:\n{:?}",- Backtrace::new(),+ "injecting OOM for allocation: {layout:?}\nAllocation backtrace:\n{bt}");new_state = OomState::DidOom;ptr = ptr::null_mut();@@ -99,25 +120,8 @@ unsafe impl GlobalAlloc for OomTestAllocator {ptr = unsafe { std::alloc::System.alloc(layout) };}- // Don't panic on allocation-after-OOM attempts if we- // are already in the middle of panicking. That will- // cause an abort and we won't get as good of an error- // message for the original panic, which is most likely- // some kind of test failure.- OomState::DidOom if std::thread::panicking() => {- log::trace!(- "Ignoring attempt to allocate {layout:?} after OOM while panicking:\n{:?}",- Backtrace::new(),- );- new_state = OomState::DidOom;- ptr = unsafe { std::alloc::System.alloc(layout) };- }-OomState::DidOom => {- log::trace!(- "Attempt to allocate {layout:?} after OOM:\n{:?}",- Backtrace::new(),- );+ log::trace!("Attempt to allocate {layout:?} after OOM:\n{bt}");panic!("OOM test attempted to allocate after OOM: {layout:?}")}}diff --git a/crates/fuzzing/tests/oom.rs b/crates/fuzzing/tests/oom.rsindex 68308a425b..43fb320a54 100644--- a/crates/fuzzing/tests/oom.rs+++ b/crates/fuzzing/tests/oom.rs@@ -230,6 +230,49 @@ fn engine_new() -> Result<()> {})}+#[test]+#[cfg(arc_try_new)]+fn func_type_try_new() -> Result<()> {+ let mut config = Config::new();+ config.enable_compiler(false);+ let engine = Engine::new(&config)?;++ // Run this OOM test a few times to make sure that we leave the engine's+ // type registry in a good state when failing to register new types.+ for i in 1..6 {+ OomTest::new().test(|| {+ let ty1 = FuncType::try_new(+ &engine,+ std::iter::repeat(ValType::ANYREF).take(i),+ std::iter::repeat(ValType::ANYREF).take(i),+ )?;+ assert_eq!(ty1.params().len(), i);+ assert_eq!(ty1.results().len(), i);++ let ty2 = FuncType::try_new(+ &engine,+ std::iter::repeat(ValType::ANYREF).take(i),+ std::iter::repeat(ValType::ANYREF).take(i),+ )?;+ assert_eq!(ty2.params().len(), i);+ assert_eq!(ty2.results().len(), i);++ let ty3 = FuncType::try_new(&engine, [], [])?;+ assert_eq!(ty3.params().len(), 0);+ assert_eq!(ty3.results().len(), 0);++ assert!(+ !FuncType::eq(&ty2, &ty3),+ "{ty2:?} should not be equal to {ty3:?}"+ );++ Ok(())+ })?;+ }++ Ok(())+}+#[test]#[cfg(arc_try_new)]fn linker_new() -> Result<()> {diff --git a/crates/wasmtime/src/runtime/component/types.rs b/crates/wasmtime/src/runtime/component/types.rsindex 63aff29672..8e4875aadc 100644--- a/crates/wasmtime/src/runtime/component/types.rs+++ b/crates/wasmtime/src/runtime/component/types.rs@@ -7,7 +7,6 @@ use crate::{Engine, ExternType, FuncType};use alloc::sync::Arc;use core::fmt;use core::ops::Deref;-use wasmtime_environ::PrimaryMap;use wasmtime_environ::component::{ComponentTypes, Export, InterfaceType, ResourceIndex, TypeComponentIndex,TypeComponentInstanceIndex, TypeDef, TypeEnumIndex, TypeFlagsIndex, TypeFuncIndex,@@ -15,6 +14,7 @@ use wasmtime_environ::component::{TypeRecordIndex, TypeResourceTable, TypeResourceTableIndex, TypeResultIndex, TypeStreamIndex,TypeStreamTableIndex, TypeTupleIndex, TypeVariantIndex,};+use wasmtime_environ::{PanicOnOom, PrimaryMap};pub use crate::component::resources::ResourceType;@@ -1099,12 +1099,15 @@ impl ComponentItem {TypeDef::Module(idx) => Self::Module(Module::from(*idx, ty)),TypeDef::CoreFunc(idx) => {let subty = &ty.types[*idx];- Self::CoreFunc(FuncType::from_wasm_func_type(- engine,- subty.is_final,- subty.supertype,- subty.unwrap_func().clone(),- ))+ Self::CoreFunc(+ FuncType::from_wasm_func_type(+ engine,+ subty.is_final,+ subty.supertype,+ subty.unwrap_func().clone(),+ )+ .panic_on_oom(),+ )}TypeDef::Resource(idx) => match ty.types[*idx] {TypeResourceTable::Concrete {diff --git a/crates/wasmtime/src/runtime/types.rs b/crates/wasmtime/src/runtime/types.rsindex 2b61d381f3..e37f333d2e 100644--- a/crates/wasmtime/src/runtime/types.rs+++ b/crates/wasmtime/src/runtime/types.rs@@ -1,3 +1,4 @@+use crate::error::OutOfMemory;use crate::prelude::*;use crate::runtime::externals::Global as RuntimeGlobal;use crate::runtime::externals::Table as RuntimeTable;@@ -11,6 +12,7 @@ use wasmtime_environ::{PanicOnOom as _, Table, Tag, TypeTrace, VMSharedTypeIndex, WasmArrayType,WasmCompositeInnerType, WasmCompositeType, WasmFieldType, WasmFuncType, WasmHeapType,WasmRefType, WasmStorageType, WasmStructType, WasmSubType, WasmValType,+ collections::Vec as FallibleVec,};pub(crate) mod matching;@@ -1509,6 +1511,7 @@ impl ExternType {subty.supertype,subty.unwrap_func().clone(),)+ .panic_on_oom().into()}EngineOrModuleTypeIndex::RecGroup(_) => unreachable!(),@@ -2410,6 +2413,21 @@ impl FuncType {.expect("cannot fail without a supertype")}+ /// Like [`FuncType::new`] but returns an+ /// [`OutOfMemory`][crate::error::OutOfMemory] error on allocation failure.+ pub fn try_new(+ engine: &Engine,+ params: impl IntoIterator<Item = ValType>,+ results: impl IntoIterator<Item = ValType>,+ ) -> Result<FuncType, OutOfMemory> {+ Self::with_finality_and_supertype(engine, Finality::Final, None, params, results).map_err(+ |e| {+ e.downcast::<OutOfMemory>()+ .expect("cannot fail without a supertype, other than OOM")+ },+ )+ }+/// Create a new function type with the given finality, supertype, parameter/// types, and result types.///@@ -2430,52 +2448,52 @@ impl FuncType {let params = params.into_iter();let results = results.into_iter();- let mut wasmtime_params = Vec::with_capacity({+ let mut wasmtime_params = FallibleVec::with_capacity({let size_hint = params.size_hint();let cap = size_hint.1.unwrap_or(size_hint.0);// Only reserve space if we have a supertype, as that is the only time// that this vec is used.supertype.is_some() as usize * cap- });+ })?;- let mut wasmtime_results = Vec::with_capacity({+ let mut wasmtime_results = FallibleVec::with_capacity({let size_hint = results.size_hint();let cap = size_hint.1.unwrap_or(size_hint.0);// Same as above.supertype.is_some() as usize * cap- });+ })?;// Keep any of our parameters' and results' `RegisteredType`s alive// across `Self::from_wasm_func_type`. If one of our given `ValType`s is// the only thing keeping a type in the registry, we don't want to// unregister it when we convert the `ValType` into a `WasmValType` just// before we register our new `WasmFuncType` that will reference it.- let mut registrations = smallvec::SmallVec::<[_; 4]>::new();+ let mut registrations = FallibleVec::new();- let mut to_wasm_type = |ty: ValType, vec: &mut Vec<_>| {- assert!(ty.comes_from_same_engine(engine));+ let mut to_wasm_type =+ |ty: ValType, vec: &mut FallibleVec<_>| -> Result<WasmValType, OutOfMemory> {+ assert!(ty.comes_from_same_engine(engine));- if supertype.is_some() {- vec.push(ty.clone());- }+ if supertype.is_some() {+ vec.push(ty.clone())?;+ }- if let Some(r) = ty.as_ref() {- if let Some(r) = r.heap_type().as_registered_type() {- registrations.push(r.clone());+ if let Some(r) = ty.as_ref() {+ if let Some(r) = r.heap_type().as_registered_type() {+ registrations.push(r.clone())?;+ }}- }- ty.to_wasm_type()- };+ Ok(ty.to_wasm_type())+ };- let wasm_func_ty = WasmFuncType::new(- params- .map(|p| to_wasm_type(p, &mut wasmtime_params))- .collect(),- results- .map(|r| to_wasm_type(r, &mut wasmtime_results))- .collect(),- );+ let params: Box<[_]> = params+ .map(|p| to_wasm_type(p, &mut wasmtime_params))+ .try_collect()?;+ let results: Box<[_]> = results+ .map(|p| to_wasm_type(p, &mut wasmtime_results))+ .try_collect()?;+ let wasm_func_ty = WasmFuncType::new(params, results);if let Some(supertype) = supertype {assert!(supertype.comes_from_same_engine(engine));@@ -2520,7 +2538,7 @@ impl FuncType {finality.is_final(),supertype.map(|ty| ty.type_index().into()),wasm_func_ty,- ))+ )?)}/// Get the engine that this function type is associated with.@@ -2674,7 +2692,7 @@ impl FuncType {is_final: bool,supertype: Option<EngineOrModuleTypeIndex>,ty: WasmFuncType,- ) -> FuncType {+ ) -> Result<FuncType, OutOfMemory> {let ty = RegisteredType::new(engine,WasmSubType {@@ -2685,11 +2703,10 @@ impl FuncType {inner: WasmCompositeInnerType::Func(ty),},},- )- .panic_on_oom();- Self {+ )?;+ Ok(Self {registered_type: ty,- }+ })}pub(crate) fn from_shared_type_index(engine: &Engine, index: VMSharedTypeIndex) -> FuncType {