From 37bb7af454dc7f25a18824ec8b2da5c006aee9eb Mon Sep 17 00:00:00 2001 From: Peter Huene Date: Fri, 2 Apr 2021 16:12:19 -0700 Subject: [PATCH] Fix incorrect range in `ininitialize_instance`. This commit fixes a bug where the wrong destination range was used when copying data from the module's memory initialization upon instance initialization. This affects the on-demand allocator only when using the `uffd` feature on Linux and when the Wasm page being initialized is not the last in the module's initial pages. Fixes #2784. --- crates/runtime/src/instance/allocator.rs | 4 +++- tests/all/instance.rs | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/runtime/src/instance/allocator.rs b/crates/runtime/src/instance/allocator.rs index e8e1e654af67..611b069f6178 100644 --- a/crates/runtime/src/instance/allocator.rs +++ b/crates/runtime/src/instance/allocator.rs @@ -379,7 +379,9 @@ fn initialize_instance( for (page_index, page) in pages.iter().enumerate() { if let Some(data) = page { debug_assert_eq!(data.len(), WASM_PAGE_SIZE as usize); - slice[page_index * WASM_PAGE_SIZE as usize..].copy_from_slice(data); + let start = page_index * WASM_PAGE_SIZE as usize; + let end = start + WASM_PAGE_SIZE as usize; + slice[start..end].copy_from_slice(data); } } } diff --git a/tests/all/instance.rs b/tests/all/instance.rs index 83ee52b22744..3d8046110ce3 100644 --- a/tests/all/instance.rs +++ b/tests/all/instance.rs @@ -11,3 +11,23 @@ fn wrong_import_numbers() -> Result<()> { assert!(Instance::new(&store, &module, &[func.clone().into(), func.into()]).is_err()); Ok(()) } + +#[test] +fn initializes_linear_memory() -> Result<()> { + // Test for https://github.com/bytecodealliance/wasmtime/issues/2784 + let wat = r#" + (module + (memory (export "memory") 2) + (data (i32.const 0) "Hello World!") + )"#; + let module = Module::new(&Engine::default(), wat)?; + + let store = Store::new(module.engine()); + let instance = Instance::new(&store, &module, &[])?; + let memory = instance.get_memory("memory").unwrap(); + + let mut bytes = [0; 12]; + memory.read(0, &mut bytes)?; + assert_eq!(bytes, "Hello World!".as_bytes()); + Ok(()) +}