Skip to content

Commit 2254f91

Browse files
authored
Fix module instantiation bug: out of bounds memory access (#1531)
* add regression test * fix instantiation bug * apply rustfmt * apply clippy suggestion
1 parent 62cd056 commit 2254f91

File tree

3 files changed

+23
-4
lines changed

3 files changed

+23
-4
lines changed

crates/wasmi/src/module/instantiate/mod.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ mod tests;
77
pub use self::{error::InstantiationError, pre::InstancePre};
88
use super::{element::ElementSegmentKind, export, ConstExpr, InitDataSegment, Module};
99
use crate::{
10-
core::UntypedVal,
10+
core::{MemoryError, UntypedVal},
1111
error::ErrorKind,
1212
func::WasmFuncEntity,
1313
memory::DataSegment,
@@ -368,10 +368,12 @@ impl Module {
368368
offset,
369369
bytes,
370370
} => {
371-
let offset =
372-
u32::from(Self::eval_init_expr(context.as_context(), builder, offset))
373-
as usize;
374371
let memory = builder.get_memory(memory_index.into_u32());
372+
let offset = Self::eval_init_expr(context.as_context(), builder, offset);
373+
let offset = match usize::try_from(u64::from(offset)) {
374+
Ok(offset) => offset,
375+
Err(_) => return Err(Error::from(MemoryError::OutOfBoundsAccess)),
376+
};
375377
memory.write(context.as_context_mut(), offset, bytes)?;
376378
DataSegment::new_active(context.as_context_mut())
377379
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
use wasmi::{Engine, Instance, Module, Store};
2+
3+
#[test]
4+
fn instantiate_out_of_memory() {
5+
let wasm = r#"
6+
(module
7+
(memory (;0;) i64 1 1)
8+
(func (export ""))
9+
(data (i64.const -1095216660480) "\ff")
10+
)
11+
"#;
12+
let engine = Engine::default();
13+
let module = Module::new(&engine, wasm).unwrap();
14+
let mut store = Store::new(&engine, ());
15+
Instance::new(&mut store, &module, &[]).unwrap_err();
16+
}

crates/wasmi/tests/integration/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,6 @@ mod func;
55
mod host_call_compilation;
66
mod host_call_instantiation;
77
mod host_calls_wasm;
8+
mod instantitation;
89
mod resource_limiter;
910
mod resumable_call;

0 commit comments

Comments
 (0)