A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Test reusing the shared `Store`/`Engine`/`Linker` state after OOM (#14969)
Nick Fitzgeraldce4a986fc1b0
diff --git a/crates/fuzzing/tests/oom/caller.rs b/crates/fuzzing/tests/oom/caller.rsindex 8198b713ba..5e86d9afa7 100644--- a/crates/fuzzing/tests/oom/caller.rs+++ b/crates/fuzzing/tests/oom/caller.rs@@ -1,6 +1,8 @@#![cfg(arc_try_new)]-use wasmtime::{Config, Engine, Func, FuncType, Module, Result, Store};+use wasmtime::{+ Config, Engine, Func, FuncType, Instance, Linker, Module, Ref, Result, Store, Table, Val,+};use wasmtime_fuzzing::oom::OomTest;#[test]@@ -94,3 +96,130 @@ fn caller_engine() -> Result<()> {Ok(())})}++/// Check that an OOM during a call, or while mutating an instance's VM+/// state, leaves the store usable.+///+/// The scratch buffers (`wasm_val_raw_storage`, `hostcall_val_storage`) are+/// `mem::take`n at the start of a call and saved back at the end, so a call+/// that errors in between leaves them for the next one.+#[tokio::test]+async fn call_scratch_and_vm_state_reuse_store() -> Result<()> {+ let mut config = Config::new();+ config.concurrency_support(false);+ // No room to grow in place, so `memory.grow` must relocate the base that+ // compiled code reads.+ config.memory_reservation(1 << 16);+ config.memory_reservation_for_growth(0);+ let engine = Engine::new(&config)?;++ let module = Module::new(+ &engine,+ r#"+ (module+ (import "" "host" (func $host (param i32) (result i32)))++ (memory (export "mem") 1)+ (table (export "tab") 4 funcref)+ (global (export "g") (mut i32) (i32.const 0))++ (func $forty_two (result i32) (i32.const 42))+ (elem (i32.const 0) func $forty_two)++ ;; Calls back out to the host and back in, so a call exercises+ ;; both scratch buffers.+ (func (export "round_trip") (param i32) (result i32)+ (call $host (local.get 0)))++ ;; Grows memory, relocating its base.+ (func (export "grow") (param i32) (result i32)+ (memory.grow (local.get 0)))++ (func (export "indirect") (param i32) (result i32)+ (call_indirect (type 1) (local.get 0)))+ )+ "#,+ )?;++ let mut linker = Linker::<()>::new(&engine);+ linker.func_wrap("", "host", |x: i32| x * 2)?;+ let instance_pre = linker.instantiate_pre(&module)?;++ /// Exercise the call paths and in-place VM state mutations.+ async fn exercise(store: &mut Store<()>, instance: Instance) -> Result<()> {+ // Each of these takes and restores the scratch buffers.+ let round_trip = instance.get_func(&mut *store, "round_trip").unwrap();+ let mut results = [Val::I32(0)];+ round_trip.call(&mut *store, &[Val::I32(21)], &mut results)?;+ assert_eq!(results[0].unwrap_i32(), 42);+ round_trip+ .call_async(&mut *store, &[Val::I32(21)], &mut results)+ .await?;+ assert_eq!(results[0].unwrap_i32(), 42);++ let typed = round_trip.typed::<i32, i32>(&*store)?;+ assert_eq!(typed.call(&mut *store, 21)?, 42);+ assert_eq!(typed.call_async(&mut *store, 21).await?, 42);++ // `Table::get` lazily initializes elements in place.+ let table = instance.get_table(&mut *store, "tab").unwrap();+ assert!(table.get(&mut *store, 0).is_some());+ let indirect = instance.get_typed_func::<i32, i32>(&mut *store, "indirect")?;+ assert_eq!(indirect.call(&mut *store, 0)?, 42);++ let old_size = table.grow(&mut *store, 2, Ref::Func(None))?;+ assert_eq!(old_size, 4);+ table.fill(&mut *store, 4, Ref::Func(None), 2)?;+ table.set(&mut *store, 5, Ref::Func(None))?;+ Table::copy(&mut *store, &table, 2, &table, 0, 2)?;++ let memory = instance.get_memory(&mut *store, "mem").unwrap();+ memory.write(&mut *store, 0, &[1, 2, 3, 4])?;+ memory.data_mut(&mut *store)[4] = 5;+ let old_pages = memory.grow(&mut *store, 1)?;+ assert_eq!(old_pages, 1);++ let mut buf = [0u8; 5];+ memory.read(&*store, 0, &mut buf)?;+ assert_eq!(buf, [1, 2, 3, 4, 5]);++ // `memory.grow` reports failure in-band as -1, and whether there is+ // room depends on the host, so only require that it agrees with the+ // embedder API.+ let grow = instance.get_typed_func::<i32, i32>(&mut *store, "grow")?;+ let grown = grow.call(&mut *store, 1)?;+ if grown != -1 {+ assert_eq!(grown, 2);+ assert_eq!(memory.size(&*store), 3);+ } else {+ assert_eq!(memory.size(&*store), 2);+ }++ let global = instance.get_global(&mut *store, "g").unwrap();+ global.set(&mut *store, Val::I32(7))?;+ assert_eq!(global.get(&mut *store).unwrap_i32(), 7);++ Ok(())+ }++ OomTest::new()+ .allow_alloc_after_oom(true)+ .alloc_succeeds_after_oom(true)+ // `memory.grow` reports failure in-band, so a run can finish without+ // surfacing the injected OOM.+ .allow_missed_oom_errors(true)+ .test_with_reuse_async(+ async || Store::try_new(&engine, ()),+ async |store: &mut Store<()>| {+ let instance = instance_pre.instantiate_async(&mut *store).await?;+ exercise(store, instance).await+ },+ async |mut store: Store<()>| {+ // A fresh instance must run every path again on the+ // inherited buffers and VM state.+ let instance = instance_pre.instantiate_async(&mut store).await?;+ exercise(&mut store, instance).await+ },+ )+ .await+}diff --git a/crates/fuzzing/tests/oom/component_linker.rs b/crates/fuzzing/tests/oom/component_linker.rsindex 1d65d852f4..4d8a563432 100644--- a/crates/fuzzing/tests/oom/component_linker.rs+++ b/crates/fuzzing/tests/oom/component_linker.rs@@ -206,3 +206,91 @@ fn component_linker_instance_resource() -> Result<()> {Ok(())})}++/// Check that an OOM partway through defining items leaves a component+/// `Linker`'s string pool and map consistent.+///+/// `define_unknown_imports_as_traps` is the worst case: a loop with no+/// rollback.+#[test]+fn component_linker_state_reuse_linker() -> Result<()> {+ let mut config = Config::new();+ config.concurrency_support(false);+ let engine = Engine::new(&config)?;+ let module = Module::new(&engine, "(module)")?;++ // Several imports, so the loop is long enough for an OOM to land mid-way.+ let unknown_imports = Component::new(+ &engine,+ r#"+ (component+ (import "a" (func))+ (import "b" (func (param "x" u32)))+ (import "c" (func (result u32)))+ (import "d" (func (param "x" string) (result u32)))+ )+ "#,+ )?;++ let component = Component::new(+ &engine,+ r#"+ (component+ (import "post-wrapped" (func $f))+ (core func $f (canon lower (func $f)))+ (core module $m+ (import "" "f" (func))+ (func (export "run") (call 0))+ )+ (core instance $i (instantiate $m+ (with "" (instance (export "f" (func $f))))+ ))+ (func (export "run") (canon lift (core func $i "run")))+ )+ "#,+ )?;++ OomTest::new()+ // Error propagation via anyhow allocates after OOM.+ .allow_alloc_after_oom(true)+ .test_with_reuse(+ || Ok(Linker::<()>::new(&engine)),+ |linker: &mut Linker<()>| {+ // Every API that interns into the pool and inserts into the+ // map.+ let mut root = linker.root();+ root.func_wrap(+ "wrapped",+ |_cx: wasmtime::StoreContextMut<'_, ()>, (): ()| Ok(()),+ )?;+ root.func_new("new", |_cx, _func_ty, _params, _results| Ok(()))?;+ root.module("m", &module)?;+ root.resource("r", ResourceType::host::<()>(), |_, _| Ok(()))?;++ linker.define_unknown_imports_as_traps(&unknown_imports)?;++ Ok(())+ },+ |mut linker: Linker<()>| {+ let mut root = linker.root();+ root.func_wrap(+ "post-wrapped",+ |_cx: wasmtime::StoreContextMut<'_, ()>, (): ()| Ok(()),+ )?;+ root.func_new("post-new", |_cx, _func_ty, _params, _results| Ok(()))?;+ root.module("post-m", &module)?;+ root.resource("post-r", ResourceType::host::<()>(), |_, _| Ok(()))?;++ // Instantiating only succeeds if *every* import got defined.+ linker.define_unknown_imports_as_traps(&unknown_imports)?;+ let mut store = Store::try_new(&engine, ())?;+ let _ = linker.instantiate(&mut store, &unknown_imports)?;++ let instance = linker.instantiate(&mut store, &component)?;+ let run = instance.get_typed_func::<(), ()>(&mut store, "run")?;+ run.call(&mut store, ())?;++ Ok(())+ },+ )+}diff --git a/crates/fuzzing/tests/oom/component_resource.rs b/crates/fuzzing/tests/oom/component_resource.rsindex 126fdca18e..2ffbd8ae44 100644--- a/crates/fuzzing/tests/oom/component_resource.rs+++ b/crates/fuzzing/tests/oom/component_resource.rs@@ -153,3 +153,117 @@ fn component_resource_lift_borrow() -> Result<()> {Ok(())})}++/// Check that an OOM partway through mutating a store's+/// `ComponentStoreData` leaves it consistent: the instance arena, handle+/// counter, host resource table, and generation metadata.+///+/// The test function deliberately does not call into the component: any+/// error from a call poisons the store via `set_trapped`, making every later+/// entry trap with `CannotEnterComponent` by design.+#[tokio::test]+async fn component_store_data_reuse_store() -> Result<()> {+ let mut config = Config::new();+ config.concurrency_support(false);+ let engine = Engine::new(&config)?;++ // Own resources and a host borrow exercise both resource tables.+ let component = Component::new(+ &engine,+ r#"+ (component+ (import "r" (type $hr (sub resource)))+ (core func $hdrop (canon resource.drop $hr))++ (type $t' (resource (rep i32)))+ (export $t "t" (type $t'))+ (core func $new (canon resource.new $t))++ (core module $m+ (import "" "hdrop" (func $hdrop (param i32)))+ (import "" "new" (func $new (param i32) (result i32)))+ (func (export "mk") (param i32) (result i32)+ (call $new (local.get 0)))+ (func (export "take") (param i32)+ (call $hdrop (local.get 0)))+ )+ (core instance $i (instantiate $m+ (with "" (instance+ (export "hdrop" (func $hdrop))+ (export "new" (func $new))+ ))+ ))++ (func (export "mk") (param "r" u32) (result (own $t))+ (canon lift (core func $i "mk")))+ (func (export "take") (param "r" (borrow $hr))+ (canon lift (core func $i "take")))+ )+ "#,+ )?;+ let mut linker = Linker::<()>::new(&engine);+ linker+ .root()+ .resource("r", ResourceType::host::<MyResource>(), |_, _| Ok(()))?;+ let instance_pre = linker.instantiate_pre(&component)?;++ OomTest::new()+ .allow_alloc_after_oom(true)+ .test_with_reuse_async(+ async || Store::try_new(&engine, ()),+ async |store: &mut Store<()>| {+ // Arena registration, plus the two-step table insert.+ let _ = instance_pre.instantiate(&mut *store)?;+ let _ = instance_pre.instantiate_async(&mut *store).await?;++ let any = ResourceAny::try_from_resource(+ Resource::<MyResource>::new_own(9),+ &mut *store,+ )?;+ let _typed: Resource<MyResource> = any.try_into_resource(&mut *store)?;++ let any = ResourceAny::try_from_resource(+ Resource::<MyResource>::new_own(11),+ &mut *store,+ )?;+ any.resource_drop_async(&mut *store).await?;++ Ok(())+ },+ async |mut store: Store<()>| {+ let instance = instance_pre.instantiate_async(&mut store).await?;++ // Bumps the handle counter and the instance's table.+ let mk = instance.get_typed_func::<(u32,), (ResourceAny,)>(&mut store, "mk")?;+ let (resource,) = mk.call_async(&mut store, (42,)).await?;+ resource.resource_drop_async(&mut store).await?;++ // Goes through the host table and generation metadata.+ let take =+ instance.get_typed_func::<(Resource<MyResource>,), ()>(&mut store, "take")?;+ take.call_async(&mut store, (Resource::new_own(7),)).await?;++ // A dropped handle must be rejected, not resolved to some+ // other resource.+ let any = ResourceAny::try_from_resource(+ Resource::<MyResource>::new_own(11),+ &mut store,+ )?;+ any.resource_drop_async(&mut store).await?;+ assert!(+ any.try_into_resource::<MyResource>(&mut store).is_err(),+ "a dropped resource handle should no longer be valid"+ );++ let any = ResourceAny::try_from_resource(+ Resource::<MyResource>::new_own(13),+ &mut store,+ )?;+ let typed: Resource<MyResource> = any.try_into_resource(&mut store)?;+ assert_eq!(typed.rep(), 13);++ Ok(())+ },+ )+ .await+}diff --git a/crates/fuzzing/tests/oom/func_type.rs b/crates/fuzzing/tests/oom/func_type.rsindex 960f3047a5..707951ad5a 100644--- a/crates/fuzzing/tests/oom/func_type.rs+++ b/crates/fuzzing/tests/oom/func_type.rs@@ -1,7 +1,11 @@#![cfg(arc_try_new)]use std::iter;-use wasmtime::{Config, Engine, FuncType, Result, ValType};+use wasmtime::component::{Component, Linker};+use wasmtime::{+ Config, Engine, Finality, Func, FuncType, Module, Result, Store, Tag, TagType, ValType,+ WasmBacktrace,+};use wasmtime_fuzzing::oom::OomTest;#[test]@@ -45,3 +49,197 @@ fn func_type_try_new() -> Result<()> {Ok(())}++/// Check that an OOM partway through registering types leaves the engine's+/// type registry consistent.+///+/// This covers every way the registry is mutated: the `FuncType`+/// constructors, `Tag::new`, host functions, and the bulk registration that+/// `Module::deserialize` and `Component::deserialize` perform.+/// `Component::deserialize` also populates the global code registry.+#[test]+fn type_registry_reuse_engine() -> Result<()> {+ // A rec group registers a cycle of types in one go.+ let module_bytes = {+ let mut config = Config::new();+ config.concurrency_support(false);+ let engine = Engine::new(&config)?;+ Module::new(+ &engine,+ r#"+ (module+ (rec+ (type $a (func (param (ref null $b)) (result i32)))+ (type $b (func (param (ref null $a))))+ )+ (type $c (func (param i32 i32) (result i64)))+ (func (export "c") (type $c) (i64.const 0))+ (func (export "b") (type $b))+ )+ "#,+ )?+ .serialize()?+ };++ // The realloc-using lift forces a second, separate registration.+ let component_bytes = {+ let mut config = Config::new();+ config.concurrency_support(false);+ let engine = Engine::new(&config)?;+ Component::new(+ &engine,+ r#"+ (component+ (core module $libc+ (memory (export "memory") 1)+ (func (export "realloc") (param i32 i32 i32 i32) (result i32)+ (i32.const 8)+ )+ )+ (core instance $libc (instantiate $libc))+ (core module $m+ (func (export "id") (param i32) (result i32) (local.get 0))+ (func (export "boom") unreachable)+ )+ (core instance $i (instantiate $m))+ (func (export "id") (param "x" s32) (result s32)+ (canon lift (core func $i "id"))+ )+ (func (export "boom")+ (canon lift (core func $i "boom")+ (memory (core memory $libc "memory"))+ (realloc (core func $libc "realloc")))+ )+ )+ "#,+ )?+ .serialize()?+ };++ OomTest::new()+ // Error propagation via anyhow allocates after OOM.+ .allow_alloc_after_oom(true)+ .test_with_reuse(+ || {+ let mut config = Config::new();+ config.enable_compiler(false);+ config.concurrency_support(false);+ config.wasm_exceptions(true);+ Engine::new(&config)+ },+ |engine: &mut Engine| {+ let mut store = Store::try_new(&*engine, ())?;++ // Subtyping forces a check against a just-registered entry.+ let super_ty = FuncType::with_finality_and_supertype(+ engine,+ Finality::NonFinal,+ None,+ [ValType::I32],+ [ValType::I64],+ )?;+ let _sub_ty = FuncType::with_finality_and_supertype(+ engine,+ Finality::Final,+ Some(&super_ty),+ [ValType::I32],+ [ValType::I64],+ )?;++ // `Tag::new` registers an exception type too; an OOM+ // between the two must unwind the first.+ let tag_ty = TagType::new(FuncType::try_new(engine, [ValType::F32], [])?);+ let _tag = Tag::new(&mut store, &tag_ty)?;++ // A host function registers its signature in the engine too,+ // claiming a type index ahead of the module's and component's+ // own types and so shifting those past the end of the space+ // reserved for their trampolines.+ let _func = Func::try_wrap(&mut store, |x: i32| x * 2)?;++ // Bulk registration of a whole module's and component's types.+ unsafe {+ let _ = Module::deserialize(&*engine, &module_bytes)?;+ let _ = Component::deserialize(&*engine, &component_bytes)?;+ }++ Ok(())+ },+ |engine: Engine| {+ let mut store = Store::try_new(&engine, ())?;++ let a = FuncType::try_new(&engine, [ValType::I32], [ValType::I64])?;+ let b = FuncType::try_new(&engine, [ValType::I32], [ValType::I64])?;+ let c = FuncType::try_new(&engine, [ValType::F32], [])?;+ assert!(FuncType::eq(&a, &b), "{a:?} should be equal to {b:?}");+ assert!(!FuncType::eq(&a, &c), "{a:?} should not be equal to {c:?}");++ let super_ty = FuncType::with_finality_and_supertype(+ &engine,+ Finality::NonFinal,+ None,+ [ValType::I32],+ [ValType::I64],+ )?;+ let sub_ty = FuncType::with_finality_and_supertype(+ &engine,+ Finality::Final,+ Some(&super_ty),+ [ValType::I32],+ [ValType::I64],+ )?;+ assert!(+ sub_ty.matches(&super_ty),+ "{sub_ty:?} should match {super_ty:?}"+ );++ let tag_ty = TagType::new(c.clone());+ let tag1 = Tag::new(&mut store, &tag_ty)?;+ let tag2 = Tag::new(&mut store, &tag_ty)?;+ assert!(FuncType::eq(tag1.ty(&store).ty(), &c));+ assert!(Tag::eq(&tag1, &tag1, &store));+ assert!(!Tag::eq(&tag1, &tag2, &store));++ let func = Func::try_wrap(&mut store, |x: i32| x * 2)?;+ let func_ty = func.ty(&store);+ assert_eq!(func_ty.params().len(), 1);+ assert_eq!(func_ty.results().len(), 1);+ assert!(FuncType::eq(+ &func_ty,+ &FuncType::try_new(&engine, [ValType::I32], [ValType::I32])?+ ));+ let _typed = func.typed::<i32, i32>(&store)?;++ // The module's types must survive re-registration intact.+ let module = unsafe { Module::deserialize(&engine, &module_bytes)? };+ let c_ty = module.get_export("c").unwrap().unwrap_func().clone();+ assert_eq!(c_ty.params().len(), 2);+ assert_eq!(c_ty.results().len(), 1);+ let c_ty2 =+ FuncType::try_new(&engine, [ValType::I32, ValType::I32], [ValType::I64])?;+ assert!(+ FuncType::eq(&c_ty, &c_ty2),+ "{c_ty:?} should be equal to {c_ty2:?}"+ );++ let component = unsafe { Component::deserialize(&engine, &component_bytes)? };+ let linker = Linker::<()>::new(&engine);+ let instance = linker.instantiate(&mut store, &component)?;+ let id = instance.get_typed_func::<(i32,), (i32,)>(&mut store, "id")?;+ assert_eq!(id.call(&mut store, (42,))?, (42,));++ // Symbolication reads the global code registry.+ let boom = instance.get_typed_func::<(), ()>(&mut store, "boom")?;+ let err = boom.call(&mut store, ()).unwrap_err();+ let trace = err+ .downcast_ref::<WasmBacktrace>()+ .expect("trap should have a wasm backtrace");+ assert!(+ !trace.frames().is_empty(),+ "backtrace should have at least one frame"+ );++ Ok(())+ },+ )+}diff --git a/crates/fuzzing/tests/oom/instance.rs b/crates/fuzzing/tests/oom/instance.rsindex db68f5dedc..96c2e7f402 100644--- a/crates/fuzzing/tests/oom/instance.rs+++ b/crates/fuzzing/tests/oom/instance.rs@@ -2,7 +2,7 @@use wasmtime::{Config, Engine, Func, Global, GlobalType, Instance, InstanceAllocationStrategy, Linker, Module,- Mutability, PoolingAllocationConfig, Result, Store, Val, ValType,+ Mutability, PoolingAllocationConfig, Result, Store, Val, ValType, WasmBacktrace,};use wasmtime_fuzzing::oom::OomTest;@@ -361,3 +361,231 @@ async fn instance_new_async_reuse_engine() -> Result<()> {).await}++/// Check that an OOM partway through registering a module leaves the store's+/// `ModuleRegistry` consistent.+///+/// Registration patches the `wasm_call` hole in host funcrefs created+/// *earlier*, hence the context's host function is made before the OOM.+#[tokio::test]+async fn module_registry_reuse_store() -> Result<()> {+ let mut config = Config::new();+ config.concurrency_support(false);+ let engine = Engine::new(&config)?;++ // One per instantiation API, so each registration is a fresh insertion+ // rather than a hit on the memoized `store_code` entry.+ let module = |n: u32| -> Result<Module> {+ Module::new(+ &engine,+ &format!(+ r#"+ (module+ (import "host" "f" (func $f (result i32)))+ (func (export "call_host") (result i32)+ (i32.add (call $f) (i32.const {n}))+ )+ (func (export "boom") unreachable)+ )+ "#+ ),+ )+ };+ let modules: [Module; 5] = std::array::from_fn(|n| module(n as u32).unwrap());++ let mut linker = Linker::<()>::new(&engine);+ linker.func_wrap("host", "f", || 100i32)?;+ let instance_pre = linker.instantiate_pre(&modules[1])?;++ struct Context {+ store: Store<()>,+ host_func: Func,+ module_linker: Linker<()>,+ }++ let make_context = async || -> Result<Context> {+ let mut store = Store::try_new(&engine, ())?;+ let host_func = Func::try_wrap(&mut store, || 100i32)?;+ let mut module_linker = Linker::<()>::new(&engine);+ module_linker.func_wrap("host", "f", || 100i32)?;+ Ok(Context {+ store,+ host_func,+ module_linker,+ })+ };++ /// Check that the imported host function is callable from wasm.+ async fn check_instance(store: &mut Store<()>, instance: Instance, n: i32) -> Result<()> {+ let f = instance.get_typed_func::<(), i32>(&mut *store, "call_host")?;+ assert_eq!(f.call_async(&mut *store, ()).await?, 100 + n);+ Ok(())+ }++ OomTest::new()+ .allow_alloc_after_oom(true)+ .test_with_reuse_async(+ async || make_context().await,+ async |cx: &mut Context| {+ let imports = [cx.host_func.into()];++ // Every API that registers code in the `ModuleRegistry`.+ let _ = Instance::new(&mut cx.store, &modules[0], &imports)?;+ let _ = Instance::new_async(&mut cx.store, &modules[1], &imports).await?;+ let _ = instance_pre.instantiate(&mut cx.store)?;+ let _ = instance_pre.instantiate_async(&mut cx.store).await?;+ let _ = linker.instantiate(&mut cx.store, &modules[2])?;+ let _ = linker.instantiate_async(&mut cx.store, &modules[3]).await?;++ cx.module_linker+ .module_async(&mut cx.store, "m", &modules[4])+ .await?;++ Ok(())+ },+ async |mut cx: Context| {+ // The host function must have had its hole filled.+ let imports = [cx.host_func.into()];++ let instance = Instance::new(&mut cx.store, &modules[0], &imports)?;+ check_instance(&mut cx.store, instance, 0).await?;++ let instance = Instance::new_async(&mut cx.store, &modules[1], &imports).await?;+ check_instance(&mut cx.store, instance, 1).await?;++ let instance = instance_pre.instantiate(&mut cx.store)?;+ check_instance(&mut cx.store, instance, 1).await?;++ let instance = instance_pre.instantiate_async(&mut cx.store).await?;+ check_instance(&mut cx.store, instance, 1).await?;++ let instance = linker.instantiate(&mut cx.store, &modules[2])?;+ check_instance(&mut cx.store, instance, 2).await?;++ let instance = linker.instantiate_async(&mut cx.store, &modules[3]).await?;+ check_instance(&mut cx.store, instance, 3).await?;++ // Fresh, since the above may already have defined "m".+ let mut module_linker = Linker::<()>::new(&engine);+ module_linker.func_wrap("host", "f", || 100i32)?;+ module_linker+ .module_async(&mut cx.store, "m", &modules[4])+ .await?;+ let f = module_linker+ .get(&mut cx.store, "m", "call_host")+ .unwrap()+ .into_func()+ .unwrap()+ .typed::<(), i32>(&cx.store)?;+ assert_eq!(f.call_async(&mut cx.store, ()).await?, 104);++ // Frame-info lookup reads the store's registry.+ let boom = instance.get_typed_func::<(), ()>(&mut cx.store, "boom")?;+ let err = boom.call_async(&mut cx.store, ()).await.unwrap_err();+ let trace = err+ .downcast_ref::<WasmBacktrace>()+ .expect("trap should have a wasm backtrace");+ assert!(+ !trace.frames().is_empty(),+ "backtrace should have at least one frame"+ );++ Ok(())+ },+ )+ .await+}++/// Check that an OOM partway through a pooling allocation returns every slot+/// it took.+///+/// The pools hold exactly one of everything, so a leaked slot fails the+/// post-OOM instantiation.+#[tokio::test]+async fn pooling_allocator_reuse_engine() -> Result<()> {+ let module_bytes = {+ let mut config = Config::new();+ config.concurrency_support(false);+ let engine = Engine::new(&config)?;+ Module::new(+ &engine,+ r#"+ (module+ (memory (export "m") 1)+ (table (export "t") 1 funcref)+ (func (export "f") (result i32) (i32.const 42))+ )+ "#,+ )?+ .serialize()?+ };++ struct Context {+ engine: Engine,+ module: Module,+ }++ let make_context = async || -> Result<Context> {+ let mut pool = PoolingAllocationConfig::default();+ pool.total_memories(1);+ pool.total_tables(1);+ pool.total_core_instances(1);+ pool.total_stacks(1);++ let mut config = Config::new();+ config.enable_compiler(false);+ config.concurrency_support(false);+ config.allocation_strategy(InstanceAllocationStrategy::Pooling(pool));+ let engine = Engine::new(&config)?;+ let module = unsafe { Module::deserialize(&engine, &module_bytes)? };++ // Warm every pool outside the OOM region: on macOS a+ // `std::sync::Mutex` infallibly box-allocates its pthread mutex on+ // first lock, which would abort under an injected OOM.+ let mut store = Store::try_new(&engine, ())?;+ let instance = Instance::new_async(&mut store, &module, &[]).await?;+ let f = instance.get_typed_func::<(), i32>(&mut store, "f")?;+ assert_eq!(f.call_async(&mut store, ()).await?, 42);+ drop(store);++ Ok(Context { engine, module })+ };++ OomTest::new()+ .allow_alloc_after_oom(true)+ .test_with_reuse_async(+ async || make_context().await,+ async |cx: &mut Context| {+ // Every slot taken here must come back on drop.+ let mut store = Store::try_new(&cx.engine, ())?;+ let instance = Instance::new_async(&mut store, &cx.module, &[]).await?;+ let f = instance.get_typed_func::<(), i32>(&mut store, "f")?;+ assert_eq!(f.call_async(&mut store, ()).await?, 42);+ drop(store);++ // Re-allocate the slots just returned.+ let mut store = Store::try_new(&cx.engine, ())?;+ let instance = Instance::new_async(&mut store, &cx.module, &[]).await?;+ let f = instance.get_typed_func::<(), i32>(&mut store, "f")?;+ assert_eq!(f.call_async(&mut store, ()).await?, 42);++ Ok(())+ },+ async |cx: Context| {+ // With room for exactly one of each, this only succeeds if+ // nothing was leaked.+ let mut store = Store::try_new(&cx.engine, ())?;+ let instance = Instance::new_async(&mut store, &cx.module, &[]).await?;+ let f = instance.get_typed_func::<(), i32>(&mut store, "f")?;+ assert_eq!(f.call_async(&mut store, ()).await?, 42);++ let memory = instance.get_memory(&mut store, "m").unwrap();+ assert_eq!(memory.size(&store), 1);+ let table = instance.get_table(&mut store, "t").unwrap();+ assert_eq!(table.size(&store), 1);++ Ok(())+ },+ )+ .await+}diff --git a/crates/fuzzing/tests/oom/linker.rs b/crates/fuzzing/tests/oom/linker.rsindex 8f70b86145..4d06d2bdda 100644--- a/crates/fuzzing/tests/oom/linker.rs+++ b/crates/fuzzing/tests/oom/linker.rs@@ -1,6 +1,8 @@#![cfg(arc_try_new)]-use wasmtime::{Config, Engine, Func, FuncType, Instance, Linker, Module, Result, Store};+use wasmtime::{+ Config, Engine, Func, FuncType, Instance, Linker, Module, Result, Store, error::Context as _,+};use wasmtime_fuzzing::oom::OomTest;#[test]@@ -291,3 +293,193 @@ fn linker_alias_module() -> Result<()> {Ok(())})}++/// Check that an OOM partway through pushing host functions leaves the+/// store's `FuncRefs` arena consistent.+///+/// The `Linker` getters look like reads but mutate the store, and a funcref+/// whose `wasm_call` hole never gets filled only shows up when wasm calls it.+#[tokio::test]+async fn func_refs_reuse_store() -> Result<()> {+ let mut config = Config::new();+ config.concurrency_support(false);+ let engine = Engine::new(&config)?;++ let module = Module::new(+ &engine,+ r#"+ (module+ (import "mod" "func" (func $f (result i32)))+ (func (export "_start") (result i32) (call $f))+ )+ "#,+ )?;++ let mut linker = Linker::<()>::new(&engine);+ linker.func_wrap("mod", "func", || 42i32)?;+ let instance_pre = linker.instantiate_pre(&module)?;+ let import = module.imports().next().unwrap();++ OomTest::new()+ .allow_alloc_after_oom(true)+ .test_with_reuse_async(+ async || Store::try_new(&engine, ()),+ async |store: &mut Store<()>| {+ // Every API that pushes into the `FuncRefs` arena.+ let _ = Func::try_wrap(&mut *store, || 42i32)?;+ let _ = linker.get(&mut *store, "mod", "func")?;+ let _ = linker.try_get_by_import(&mut *store, &import)?;+ let _ = instance_pre.instantiate(&mut *store)?;+ let _ = instance_pre.instantiate_async(&mut *store).await?;+ Ok(())+ },+ async |mut store: Store<()>| {+ // Every funcref must be callable from wasm.+ let func = Func::try_wrap(&mut store, || 42i32)?;+ let instance = Instance::new(&mut store, &module, &[func.into()])?;+ let start = instance.get_typed_func::<(), i32>(&mut store, "_start")?;+ assert_eq!(start.call(&mut store, ())?, 42);++ let got = linker+ .get(&mut store, "mod", "func")+ .unwrap()+ .into_func()+ .unwrap();+ let instance = Instance::new(&mut store, &module, &[got.into()])?;+ let start = instance.get_typed_func::<(), i32>(&mut store, "_start")?;+ assert_eq!(start.call(&mut store, ())?, 42);++ let by_import = linker+ .try_get_by_import(&mut store, &import)?+ .expect("import should be satisfied")+ .into_func()+ .unwrap();+ assert_eq!(+ by_import.typed::<(), i32>(&store)?.call(&mut store, ())?,+ 42+ );++ let instance = instance_pre.instantiate(&mut store)?;+ let start = instance.get_typed_func::<(), i32>(&mut store, "_start")?;+ assert_eq!(start.call(&mut store, ())?, 42);++ let instance = instance_pre.instantiate_async(&mut store).await?;+ let start = instance.get_typed_func::<(), i32>(&mut store, "_start")?;+ assert_eq!(start.call_async(&mut store, ()).await?, 42);++ // `get_default` reads the arena too, via `get`.+ let mut linker = Linker::<()>::new(&engine);+ linker.instance(&mut store, "inst", instance)?;+ let default = linker.get_default(&mut store, "inst")?;+ assert_eq!(default.typed::<(), i32>(&store)?.call(&mut store, ())?, 42);++ Ok(())+ },+ )+ .await+}++/// Check that an OOM partway through defining items leaves a `Linker`'s+/// string pool and map consistent.+///+/// `import_key` interns into the pool *before* `insert` touches the map, so+/// an OOM between them orphans an atom.+#[tokio::test]+async fn linker_state_reuse_linker() -> Result<()> {+ let mut config = Config::new();+ config.concurrency_support(false);+ let engine = Engine::new(&config)?;++ let module = Module::new(+ &engine,+ r#"(module (func (export "f") (result i32) (i32.const 42)) (memory (export "m") 1))"#,+ )?;+ let importing_module = Module::new(+ &engine,+ r#"+ (module+ (import "post" "wrapped" (func $f (result i32)))+ (func (export "_start") (result i32) (call $f))+ )+ "#,+ )?;+ let import = importing_module.imports().next().unwrap();++ // `Linker::instance` requires an instance from the store it is given.+ let instance_pre = Linker::<()>::new(&engine).instantiate_pre(&module)?;++ OomTest::new()+ .allow_alloc_after_oom(true)+ .test_with_reuse_async(+ async || Ok(Linker::<()>::new(&engine)),+ async |linker: &mut Linker<()>| {+ // Every API that interns into the pool and inserts into the+ // map.+ linker.func_wrap("mod", "wrapped", || 42i32)?;+ linker.func_new(+ "mod",+ "new",+ FuncType::try_new(&engine, [], [])?,+ |_caller, _params, _results| Ok(()),+ )?;++ let mut store = Store::try_new(&engine, ())?;+ let func = Func::try_wrap(&mut store, || {})?;+ linker.define(&store, "mod", "defined", func)?;+ let instance = instance_pre.instantiate(&mut store)?;+ linker.instance(&mut store, "inst", instance)?;+ linker.module_async(&mut store, "m", &module).await?;++ linker.alias("mod", "wrapped", "mod2", "aliased")?;+ linker.alias_module("mod", "mod3")?;++ Ok(())+ },+ async |mut linker: Linker<()>| {+ let mut store = Store::try_new(&engine, ())?;++ // A fresh namespace: the test function may already have+ // defined these.+ linker.func_wrap("post", "wrapped", || 42i32)?;+ linker.alias("post", "wrapped", "post2", "aliased")?;+ linker.alias_module("post", "post3")?;++ for (module, name) in [+ ("post", "wrapped"),+ ("post2", "aliased"),+ ("post3", "wrapped"),+ ] {+ let func = linker+ .get(&mut store, module, name)+ .with_context(|| format!("{module}::{name} should be defined"))?+ .into_func()+ .unwrap();+ assert_eq!(func.typed::<(), i32>(&store)?.call(&mut store, ())?, 42);+ }++ let instance = instance_pre.instantiate(&mut store)?;+ linker.instance(&mut store, "post_inst", instance)?;+ let f = linker+ .get(&mut store, "post_inst", "f")?+ .into_func()+ .unwrap();+ assert_eq!(f.typed::<(), i32>(&store)?.call(&mut store, ())?, 42);++ linker.module_async(&mut store, "post_m", &module).await?;+ let f = linker.get(&mut store, "post_m", "f")?.into_func().unwrap();+ assert_eq!(f.typed::<(), i32>(&store)?.call(&mut store, ())?, 42);++ let ext = linker+ .try_get_by_import(&mut store, &import)?+ .expect("import should be satisfied");+ assert!(ext.into_func().is_some());++ let instance = linker.instantiate(&mut store, &importing_module)?;+ let start = instance.get_typed_func::<(), i32>(&mut store, "_start")?;+ assert_eq!(start.call(&mut store, ())?, 42);++ Ok(())+ },+ )+ .await+}diff --git a/crates/fuzzing/tests/oom/module.rs b/crates/fuzzing/tests/oom/module.rsindex 9db2693b53..60a0afb0fd 100644--- a/crates/fuzzing/tests/oom/module.rs+++ b/crates/fuzzing/tests/oom/module.rs@@ -1,6 +1,6 @@#![cfg(arc_try_new)]-use wasmtime::{Config, Engine, FuncType, Module, Result, ValType, WasmBacktraceDetails};+use wasmtime::{Config, Engine, Module, Result, WasmBacktraceDetails};use wasmtime_fuzzing::oom::OomTest;#[test]@@ -86,60 +86,3 @@ fn module_deserialize_multiple_rec_groups() -> Result<()> {Ok(())})}--/// Check that failing to register a module's types partway through leaves the-/// engine's type registry in a good state, by reusing the engine afterwards.-#[test]-fn module_deserialize_reuse_engine() -> Result<()> {- let module_bytes = {- let mut config = Config::new();- config.concurrency_support(false);- let engine = Engine::new(&config)?;- Module::new(- &engine,- r#"- (module- (rec- (type $a (func (param (ref null $b)) (result i32)))- (type $b (func (param (ref null $a))))- )- (type $c (func (param i32 i32) (result i64)))- (func (export "c") (type $c) (i64.const 0))- (func (export "b") (type $b))- )- "#,- )?- .serialize()?- };-- OomTest::new()- // See the note on `module_deserialize` above.- .allow_alloc_after_oom(true)- .test_with_reuse(- || {- let mut config = Config::new();- config.enable_compiler(false);- config.concurrency_support(false);- Engine::new(&config)- },- |engine: &mut Engine| unsafe {- let _ = Module::deserialize(engine, &module_bytes)?;- Ok(())- },- |engine: Engine| unsafe {- // Whether or not we hit an OOM above, the engine must remain- // usable and its type registry must not have any of the- // module's types left half-registered within it.- let module = Module::deserialize(&engine, &module_bytes)?;-- // The module's types must be as expected.- let c = module.get_export("c").unwrap().unwrap_func().clone();- assert_eq!(c.params().len(), 2);- assert_eq!(c.results().len(), 1);- let c2 = FuncType::try_new(&engine, [ValType::I32, ValType::I32], [ValType::I64])?;- assert!(FuncType::eq(&c, &c2), "{c:?} should be equal to {c2:?}");-- Ok(())- },- )-}diff --git a/crates/fuzzing/tests/oom/store.rs b/crates/fuzzing/tests/oom/store.rsindex f4805a06d7..8f3838800a 100644--- a/crates/fuzzing/tests/oom/store.rs+++ b/crates/fuzzing/tests/oom/store.rs@@ -1,6 +1,10 @@#![cfg(arc_try_new)]-use wasmtime::{Config, Engine, Result, Store, StoreLimitsBuilder};+use wasmtime::{+ Config, Engine, Extern, Func, FuncType, Global, GlobalType, Instance, Memory, MemoryType,+ Module, Mutability, Ref, RefType, Result, Store, StoreLimitsBuilder, Table, TableType, Tag,+ TagType, Val, ValType,+};use wasmtime_fuzzing::oom::OomTest;#[test]@@ -97,3 +101,118 @@ fn store_epoch_deadline() -> Result<()> {Ok(())})}++/// Check that an OOM partway through creating a host object leaves the+/// store's arenas consistent: the instance arena and its resource counts,+/// the `FuncRefs` arena, and `host_globals`.+///+/// The counters are bumped before allocating, so an OOM can leave one high.+#[tokio::test]+async fn store_arenas_reuse_store() -> Result<()> {+ let mut config = Config::new();+ config.concurrency_support(false);+ config.wasm_exceptions(true);+ let engine = Engine::new(&config)?;++ // Importing one of each kind reads every arena back.+ let module = Module::new(+ &engine,+ r#"+ (module+ (import "" "f" (func $f (result i32)))+ (import "" "g" (global $g (mut i32)))+ (import "" "m" (memory 1))+ (import "" "t" (table 1 funcref))+ (func (export "run") (result i32)+ (i32.add (call $f) (global.get $g))+ )+ )+ "#,+ )?;++ /// One of every host object that pushes into a store arena.+ fn make_host_objects(store: &mut Store<()>) -> Result<[Extern; 4]> {+ let func = Func::try_wrap(&mut *store, || 7i32)?;+ let global = Global::new(+ &mut *store,+ GlobalType::new(ValType::I32, Mutability::Var),+ Val::I32(35),+ )?;+ let memory = Memory::new(&mut *store, MemoryType::new(1, None)?)?;+ let table = Table::new(+ &mut *store,+ TableType::new(RefType::FUNCREF, 1, None)?,+ Ref::Func(None),+ )?;+ Ok([func.into(), global.into(), memory.into(), table.into()])+ }++ OomTest::new()+ // `IndexMap::reserve` will try to allocate double space, but if that+ // fails, will attempt to allocate the minimal space necessary.+ .allow_alloc_after_oom(true)+ .test_with_reuse_async(+ async || Store::try_new(&engine, ()),+ async |store: &mut Store<()>| {+ // Every API that pushes into a store arena.+ let _ = Func::try_new(+ &mut *store,+ FuncType::try_new(&engine, [ValType::I32], [ValType::I32])?,+ |_caller, params, results| {+ results[0] = params[0].clone();+ Ok(())+ },+ )?;+ let _ = make_host_objects(store)?;+ let _ = Memory::new_async(&mut *store, MemoryType::new(1, None)?).await?;+ let _ = Table::new_async(+ &mut *store,+ TableType::new(RefType::FUNCREF, 1, None)?,+ Ref::Func(None),+ )+ .await?;+ let _ = Tag::new(+ &mut *store,+ &TagType::new(FuncType::try_new(&engine, [ValType::I32], [])?),+ )?;+ Ok(())+ },+ async |mut store: Store<()>| {+ let imports = make_host_objects(&mut store)?;++ let global = imports[1].clone().into_global().unwrap();+ assert_eq!(global.get(&mut store).unwrap_i32(), 35);+ global.set(&mut store, Val::I32(99))?;+ assert_eq!(global.get(&mut store).unwrap_i32(), 99);+ global.set(&mut store, Val::I32(35))?;+ assert!(global.ty(&store).content().is_i32());++ let memory = imports[2].clone().into_memory().unwrap();+ assert_eq!(memory.size(&store), 1);+ memory.write(&mut store, 0, &[1, 2, 3, 4])?;+ let mut buf = [0u8; 4];+ memory.read(&store, 0, &mut buf)?;+ assert_eq!(buf, [1, 2, 3, 4]);+ assert_eq!(memory.grow(&mut store, 1)?, 1);++ let table = imports[3].clone().into_table().unwrap();+ assert_eq!(table.size(&store), 1);+ assert!(table.get(&mut store, 0).is_some());+ assert_eq!(table.grow(&mut store, 1, Ref::Func(None))?, 1);++ let tag_ty = TagType::new(FuncType::try_new(&engine, [ValType::I32], [])?);+ let tag1 = Tag::new(&mut store, &tag_ty)?;+ let tag2 = Tag::new(&mut store, &tag_ty)?;+ assert!(Tag::eq(&tag1, &tag1, &store));+ assert!(!Tag::eq(&tag1, &tag2, &store));++ // Checks that the host funcref was initialized.+ let instance = Instance::new_async(&mut store, &module, &imports).await?;+ let run = instance.get_typed_func::<(), i32>(&mut store, "run")?;+ assert_eq!(run.call_async(&mut store, ()).await?, 42);++ Ok(())+ },+ )+ .await+}diff --git a/crates/wasmtime/src/runtime/type_registry.rs b/crates/wasmtime/src/runtime/type_registry.rsindex f5d45a9135..045dab0e52 100644--- a/crates/wasmtime/src/runtime/type_registry.rs+++ b/crates/wasmtime/src/runtime/type_registry.rs@@ -179,9 +179,7 @@ impl Engine {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- .insert(trampoline_shared_ty, Some(module_trampoline_ty).into())- .expect("reserved space");+ trampolines.insert(trampoline_shared_ty, Some(module_trampoline_ty).into())?;}// Finally, to ensure that no matter which API from which layer