A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
fix: avoid CoW memory init before trapping table segments (#14780)
Shray Jaiswal5154f1c467af
diff --git a/crates/environ/src/compile/module_environ.rs b/crates/environ/src/compile/module_environ.rsindex 27003f4123..937cf27e7b 100644--- a/crates/environ/src/compile/module_environ.rs+++ b/crates/environ/src/compile/module_environ.rs@@ -1217,7 +1217,11 @@ impl ModuleTranslation<'_> {max_image_size_always_allowed: u64,types: &mut ModuleTypesBuilder,) {- if tunables.memory_init_cow {+ // Memory images are installed before the module's startup function+ // runs. If a table initializer can trap, using a memory image would+ // initialize memory even though the startup function should trap+ // before reaching the memory initializers.+ if tunables.memory_init_cow && !self.table_initialization_may_trap() {self.try_static_init(page_size, max_image_size_always_allowed);}@@ -1272,6 +1276,29 @@ impl ModuleTranslation<'_> {}}+ /// Returns whether an active table initializer may trap during startup.+ ///+ /// Memory images are installed while allocating an instance, before the+ /// startup function executes. Therefore a memory image cannot be used when+ /// a table initializer might trap: doing so would make the memory+ /// observable even though execution should stop before reaching the memory+ /// initializers.+ fn table_initialization_may_trap(&self) -> bool {+ self.table_initialization.segments.iter().any(|segment| {+ let offset = match segment.offset.ops() {+ &[ConstOp::I32Const(offset)] => u64::from(offset.cast_unsigned()),+ &[ConstOp::I64Const(offset)] => offset.cast_unsigned(),+ // A dynamic offset cannot be proven to be in bounds here.+ _ => return true,+ };+ let top = match offset.checked_add(segment.elements.len()) {+ Some(top) => top,+ None => return true,+ };+ top > self.module.tables[segment.table_index].limits.min+ })+ }+/// Attempts to convert segmented memory initialization into static/// initialization for the module that this translation represents.///diff --git a/tests/misc_testsuite/cow-order.wast b/tests/misc_testsuite/cow-order.wastnew file mode 100644index 0000000000..2b516128f3--- /dev/null+++ b/tests/misc_testsuite/cow-order.wast@@ -0,0 +1,18 @@+(module $M+ (type $t (func (result i32)))+ (table (export "t") 2 funcref)+ (func (export "call") (param i32) (result i32)+ (call_indirect (type $t) (local.get 0))))+(register "M" $M)++(assert_trap+ (module+ (import "M" "t" (table 2 funcref))+ (memory 1)+ (func $f (result i32) (i32.load8_u (i32.const 0)))+ (elem (table 0) (i32.const 0) func $f)+ (elem (table 0) (i32.const 2) func $f)+ (data (i32.const 0) "\2a"))+ "out of bounds table access")++(assert_return (invoke $M "call" (i32.const 0)) (i32.const 0))