Skip to content

Commit

Permalink
Fix memory initialization when offset is negative
Browse files Browse the repository at this point in the history
This commit fixes a bug in initializing memory segments of 32-bit
memories where if the offset was negative when viewed as a signed
integer the offset was incorrectly sign-extended to a 64-bit value
instead of zero-extended. This commit replaces an `i32`-to-`u64` cast
with an `i32`-to-`u32` cast followed by a `u32`-to-`u64` cast which
performs the zero extend.

Closes bytecodealliance#7558
  • Loading branch information
alexcrichton committed Nov 20, 2023
1 parent 877059f commit 18679a5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
2 changes: 1 addition & 1 deletion crates/environ/src/module_environ.rs
Original file line number Diff line number Diff line change
Expand Up @@ -607,7 +607,7 @@ impl<'a, 'data> ModuleEnvironment<'a, 'data> {
let memory_index = MemoryIndex::from_u32(memory_index);
let mut offset_expr_reader = offset_expr.get_binary_reader();
let (base, offset) = match offset_expr_reader.read_operator()? {
Operator::I32Const { value } => (None, value as u64),
Operator::I32Const { value } => (None, (value as u32).into()),
Operator::I64Const { value } => (None, value as u64),
Operator::GlobalGet { global_index } => {
(Some(GlobalIndex::from_u32(global_index)), 0)
Expand Down
18 changes: 18 additions & 0 deletions tests/all/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -642,3 +642,21 @@ fn shared_memory_wait_notify() -> Result<()> {

Ok(())
}

#[test]
#[cfg_attr(miri, ignore)]
fn init_with_negative_segment() -> Result<()> {
let engine = Engine::default();
let module = Module::new(
&engine,
r#"
(module
(memory 65536)
(data (i32.const 0x8000_0000) "x")
)
"#,
)?;
let mut store = Store::new(&engine, ());
Instance::new(&mut store, &module, &[])?;
Ok(())
}

0 comments on commit 18679a5

Please sign in to comment.