Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Evaluate trapping active element segments before table writes (#15130)

pothihai selvan17fe5e6c78a9
diff --git a/crates/cranelift/src/func_environ.rs b/crates/cranelift/src/func_environ.rs
index 4403277182..30123dbcae 100644
--- a/crates/cranelift/src/func_environ.rs
+++ b/crates/cranelift/src/func_environ.rs
@@ -40,7 +40,7 @@ use wasmtime_environ::{
IndexType, KnownFunc, KnownGlobal, Memory, MemoryIndex, MemoryInit, MemorySegmentOffset,
MemoryTunables, Module, ModuleInternedTypeIndex, ModuleTranslation, ModuleTypesBuilder,
PassiveElemIndex, RuntimeDataIndex, Table, TableIndex, TableInitialValue, TableSegment,
- TableSegmentElements, TagIndex, Tunables, TypeConvert, TypeIndex, VMOffsets,
+ TableSegmentElements, TableSegmentInit, TagIndex, Tunables, TypeConvert, TypeIndex, VMOffsets,
WasmCompositeInnerType, WasmFuncType, WasmHeapTopType, WasmHeapType, WasmRefType, WasmResult,
WasmStorageType, WasmValType,
};
@@ -3304,7 +3304,7 @@ impl FuncEnvironment<'_> {
self,
builder,
array_type_index,
- CheckedEntity::Elem(elem_index),
+ CheckedEntity::Elem(self.translation.passive_elem_map[elem_index]),
elem_offset,
len,
cost,
@@ -3439,7 +3439,7 @@ impl FuncEnvironment<'_> {
ty,
initialized: true,
},
- CheckedEntity::Elem(elem_index),
+ CheckedEntity::Elem(self.translation.passive_elem_map[elem_index]),
dst_index,
elem_offset,
len,
@@ -4573,7 +4573,7 @@ impl FuncEnvironment<'_> {
None => builder.ins().iconst(pointer_type, 0),
},
CheckedEntity::RuntimeData(i) => self.load_runtime_data_length_as_pointer(builder, i),
- CheckedEntity::Elem(i) => match self.translation.passive_elem_map[i] {
+ CheckedEntity::Elem(i) => match i {
Some(passive_index) => {
let vmctx = self.vmctx_val(&mut builder.cursor());
let libcall = self
@@ -4660,7 +4660,7 @@ impl FuncEnvironment<'_> {
},
CheckedEntity::RuntimeData(i) => self.load_runtime_data_base(builder, i),
// Element segments are quite similar to data segments just above.
- CheckedEntity::Elem(i) => match self.translation.passive_elem_map[i] {
+ CheckedEntity::Elem(i) => match i {
Some(passive_index) => {
let vmctx = self.vmctx_val(&mut builder.cursor());
let libcall = self
@@ -5345,7 +5345,7 @@ impl FuncEnvironment<'_> {
table: table_index,
initialized: true,
},
- CheckedEntity::Elem(ElemIndex::from_u32(seg_index)),
+ CheckedEntity::Elem(self.translation.passive_elem_map[ElemIndex::from_u32(seg_index)]),
dst,
src,
len,
@@ -6477,7 +6477,7 @@ impl FuncEnvironment<'_> {
let offset = self.translate_const_expr(builder, &segment.offset)?;
let segment_len = builder.ins().iconst(
index_type_to_ir_type(self.module.tables[segment.table_index].idx_type),
- i64::try_from(segment.elements.len()).unwrap(),
+ i64::try_from(segment.init.len()).unwrap(),
);
// Check the bounds first before mutating anything.
@@ -6497,10 +6497,45 @@ impl FuncEnvironment<'_> {
.table_init_per_element;
let fuel = self.pre_translate_bulk_op(builder, segment_len, cost);
+ let elements = match &segment.init {
+ TableSegmentInit::Direct(elements) => elements,
+
+ // If this segment's elements were already evaluated into passive
+ // storage then copy them into the table from there, like
+ // `table.init`, and then free that storage like `elem.drop`.
+ TableSegmentInit::Staged { index, len } => {
+ let passive_index = *index;
+ // Like `table.init`, the source and length are always 32-bit
+ // since element segments are, even for 64-bit tables.
+ let src = builder.ins().iconst(I32, 0);
+ let len = builder
+ .ins()
+ .iconst(I32, i64::from(u32::try_from(*len).unwrap()));
+ self.translate_entity_copy(
+ builder,
+ CheckedEntity::Table {
+ table: segment.table_index,
+ initialized: true,
+ },
+ CheckedEntity::Elem(Some(passive_index)),
+ offset,
+ src,
+ len,
+ )?;
+ let vmctx = self.vmctx_val(&mut builder.cursor());
+ let libcall = self
+ .builtin_functions
+ .passive_elem_segment_drop(builder.func);
+ let idx = builder.ins().iconst(I32, i64::from(passive_index.as_u32()));
+ builder.ins().call(libcall, &[vmctx, idx]);
+ return self.post_translate_bulk_op(builder, fuel);
+ }
+ };
+
// Re-use the `table.set` translation for making this a simple function
// to define. That re-executes the bounds check which is a bit
// inefficient, but can be optimized in the future.
- match &segment.elements {
+ match elements {
TableSegmentElements::Functions(indices) => {
for (i, func) in indices.iter().enumerate() {
let func = self.translate_ref_func(builder.cursor(), *func)?;
@@ -6822,8 +6857,11 @@ enum CheckedEntity {
/// This isn't reachable from core wasm but is used during module
/// startup.
RuntimeData(RuntimeDataIndex),
- /// A WebAssembly passive element segment.
- Elem(ElemIndex),
+ /// A WebAssembly element segment, resolved to its passive storage.
+ ///
+ /// This is `None` for active and declared segments, which behave as if
+ /// they have zero length when accessed from wasm.
+ Elem(Option<PassiveElemIndex>),
/// An `arrayref` with the specified type.
Array {
/// The type of this array.
diff --git a/crates/environ/src/compile/module_environ.rs b/crates/environ/src/compile/module_environ.rs
index d84d40c1fa..9955980a7e 100644
--- a/crates/environ/src/compile/module_environ.rs
+++ b/crates/environ/src/compile/module_environ.rs
@@ -1,6 +1,7 @@
use crate::error::{OutOfMemory, Result, bail};
use crate::module::{
FuncRefIndex, Initializer, MemoryInitialization, Module, TableSegment, TableSegmentElements,
+ TableSegmentInit,
};
use crate::prelude::*;
use crate::{
@@ -743,6 +744,11 @@ impl<'a, 'data> ModuleEnvironment<'a, 'data> {
Payload::ElementSection(elements) => {
self.validator.element_section(&elements)?;
+ // Whether writes to tables made so far during instantiation
+ // could be observed outside of this instance, which becomes
+ // true once an active segment applies to an imported table.
+ let mut side_effects_visible = false;
+
for (index, entry) in elements.into_iter().enumerate() {
let wasmparser::Element {
kind,
@@ -793,13 +799,45 @@ impl<'a, 'data> ModuleEnvironment<'a, 'data> {
let (offset, escaped) = ConstExpr::from_wasmparser(self, offset_expr)?;
debug_assert!(escaped.is_empty());
+ // The spec's instantiation evaluates the
+ // expressions of all element segments before
+ // executing any active segment's `table.init`
+ // (https://webassembly.github.io/spec/core/exec/modules.html#exec-instantiation).
+ // So if any element expression may trap, and an
+ // earlier write (including from this segment)
+ // could be observed, then stage its evaluation
+ // into a passive element segment, which is
+ // evaluated before any active segment is applied.
+ // Note that this passive segment isn't registered
+ // in `passive_elem_map` so it's not reachable from
+ // wasm itself.
+ //
+ // If no imported table has been written yet then a
+ // trap is unobservable, so evaluating in place is
+ // fine and avoids the extra copy.
+ side_effects_visible |=
+ self.result.module.is_imported_table(table_index);
+ let init = if side_effects_visible && elements_may_trap(&elements) {
+ let len = elements.len();
+ let index = self
+ .result
+ .module
+ .passive_elements
+ .push((elements.ty(), len))?;
+ self.result.passive_elements.push(elements);
+ self.require_startup_func();
+ TableSegmentInit::Staged { index, len }
+ } else {
+ TableSegmentInit::Direct(elements)
+ };
+
self.result
.table_initialization
.segments
.push(TableSegment {
table_index,
offset,
- elements,
+ init,
})?;
None
}
@@ -1292,18 +1330,16 @@ impl ModuleTranslation<'_> {
// A dynamic offset cannot be proven to be in bounds here.
_ => return true,
};
- let top = match offset.checked_add(segment.elements.len()) {
+ let top = match offset.checked_add(segment.init.len()) {
Some(top) => top,
None => return true,
};
if top > self.module.tables[segment.table_index].limits.min {
return true;
}
- match &segment.elements {
- TableSegmentElements::Functions(_) => false,
- TableSegmentElements::Expressions { exprs, .. } => exprs
- .iter()
- .any(|expr| expr.ops().iter().any(|op| op.may_trap())),
+ match &segment.init {
+ TableSegmentInit::Direct(elements) => elements_may_trap(elements),
+ TableSegmentInit::Staged { .. } => true,
}
})
}
@@ -1645,7 +1681,7 @@ impl ModuleTranslation<'_> {
// Get the end of this segment. If out-of-bounds, or too
// large for our dense table representation, then skip the
// segment.
- let top = match offset.checked_add(segment.elements.len()) {
+ let top = match offset.checked_add(segment.init.len()) {
Some(top) => top,
None => break,
};
@@ -1673,9 +1709,10 @@ impl ModuleTranslation<'_> {
// Function indices can be optimized here, but fully general
// expressions are deferred to get evaluated at runtime.
- let function_elements = match &segment.elements {
- TableSegmentElements::Functions(indices) => indices,
- TableSegmentElements::Expressions { .. } => break,
+ let function_elements = match &segment.init {
+ TableSegmentInit::Direct(TableSegmentElements::Functions(indices)) => indices,
+ TableSegmentInit::Direct(TableSegmentElements::Expressions { .. })
+ | TableSegmentInit::Staged { .. } => break,
};
match &self.table_initialization.initial_values[defined_index] {
@@ -1731,3 +1768,13 @@ impl ModuleTranslation<'_> {
self.module.startup = ModuleStartup::IfMemoriesNeedInit(ty);
}
}
+
+/// Returns whether evaluating any element of `elements` may trap.
+fn elements_may_trap(elements: &TableSegmentElements) -> bool {
+ match elements {
+ TableSegmentElements::Functions(_) => false,
+ TableSegmentElements::Expressions { exprs, .. } => exprs
+ .iter()
+ .any(|expr| expr.ops().iter().any(|op| op.may_trap())),
+ }
+}
diff --git a/crates/environ/src/module.rs b/crates/environ/src/module.rs
index 7e9e80e422..cb6744b268 100644
--- a/crates/environ/src/module.rs
+++ b/crates/environ/src/module.rs
@@ -130,7 +130,42 @@ pub struct TableSegment {
/// The base offset to start this segment at.
pub offset: ConstExpr,
/// The values to write into the table elements.
- pub elements: TableSegmentElements,
+ pub init: TableSegmentInit,
+}
+
+/// How the values of an active table segment are produced.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub enum TableSegmentInit {
+ /// The elements are evaluated and written directly to the table in
+ /// segment order. These never appear in `vm::Instance`.
+ ///
+ /// This is used when the elements cannot trap, or when a trap could not
+ /// be observed because no imported table has been written to yet.
+ Direct(TableSegmentElements),
+ /// The elements may trap during evaluation, so they are instead evaluated
+ /// up-front into this passive element segment's storage alongside all
+ /// other passive element segments. The segment is then copied into the
+ /// table in segment order and dropped.
+ ///
+ /// Instantiation evaluates all element segment expressions before any
+ /// active segment is written to a table, so a trapping expression must not
+ /// leave earlier segments' writes visible in imported tables.
+ Staged {
+ /// The passive element segment holding the evaluated elements.
+ index: PassiveElemIndex,
+ /// The number of elements in this segment.
+ len: u64,
+ },
+}
+
+impl TableSegmentInit {
+ /// Returns the number of elements in this segment.
+ pub fn len(&self) -> u64 {
+ match self {
+ Self::Direct(elements) => elements.len(),
+ Self::Staged { len, .. } => *len,
+ }
+ }
}
/// Elements of a table segment, either a list of functions or list of arbitrary
diff --git a/tests/misc_testsuite/gc/cow-order-trapping-elem-expr.wast b/tests/misc_testsuite/gc/cow-order-trapping-elem-expr.wast
index 21f92b0fcc..a0be6a2096 100644
--- a/tests/misc_testsuite/gc/cow-order-trapping-elem-expr.wast
+++ b/tests/misc_testsuite/gc/cow-order-trapping-elem-expr.wast
@@ -21,4 +21,6 @@
(data (i32.const 0) "\2a"))
"allocation size too large")
-(assert_return (invoke $M "call" (i32.const 0)) (i32.const 0))
+;; All element expressions are evaluated before any table is written, so the
+;; trap also means that `$f` is never written to the imported table (#15036).
+(assert_trap (invoke $M "call" (i32.const 0)) "uninitialized element")
diff --git a/tests/misc_testsuite/gc/issue15036.wast b/tests/misc_testsuite/gc/issue15036.wast
new file mode 100644
index 0000000000..109ca9c8c3
--- /dev/null
+++ b/tests/misc_testsuite/gc/issue15036.wast
@@ -0,0 +1,133 @@
+;;! gc = true
+;;! bulk_memory = true
+;;! memory64 = true
+
+;; All element segment expressions are evaluated before any active element
+;; segment is written to a table, so a trapping expression must leave imported
+;; tables untouched. See #15036.
+
+(module $M
+ (type $t (func (result i32)))
+ (table (export "t") 2 funcref)
+ (table (export "a") 2 anyref)
+ (func (export "call") (param i32) (result i32)
+ (call_indirect (type $t) (local.get 0)))
+ (func (export "a-is-null") (param i32) (result i32)
+ (ref.is_null (table.get 1 (local.get 0))))
+ (func (export "get-a") (param i32) (result i32)
+ (i31.get_s (ref.cast (ref i31) (table.get 1 (local.get 0))))))
+(register "M" $M)
+
+;; A trap in a later segment must not leave an earlier segment's writes behind.
+(assert_trap
+ (module
+ (type $a (array (mut i64)))
+ (import "M" "t" (table 2 funcref))
+ (table $t2 1 anyref)
+ (func $f (result i32) (i32.const 7))
+ (elem (table 0) (i32.const 0) func $f)
+ (elem (table $t2) (i32.const 0) anyref
+ (array.new_default $a (i32.const 0x7fffffff))))
+ "allocation size too large")
+(assert_trap (invoke $M "call" (i32.const 0)) "uninitialized element")
+
+;; A trap in a later element must not leave an earlier element of the same
+;; segment behind.
+(assert_trap
+ (module
+ (type $a (array (mut i64)))
+ (import "M" "a" (table 2 anyref))
+ (elem (table 0) (i32.const 0) anyref
+ (ref.i31 (i32.const 5))
+ (array.new_default $a (i32.const 0x7fffffff))))
+ "allocation size too large")
+(assert_return (invoke $M "a-is-null" (i32.const 0)) (i32.const 1))
+
+;; A trap in a passive segment also comes before any active segment write.
+(assert_trap
+ (module
+ (type $a (array (mut i64)))
+ (import "M" "a" (table 2 anyref))
+ (elem (table 0) (i32.const 0) anyref
+ (ref.i31 (i32.const 5))
+ (array.new_default $a (i32.const 1)))
+ (elem anyref (array.new_default $a (i32.const 0x7fffffff))))
+ "allocation size too large")
+(assert_return (invoke $M "a-is-null" (i32.const 0)) (i32.const 1))
+
+;; A trapping segment before any write to an imported table is evaluated in
+;; place, and still traps before the later segment writes the imported table.
+(assert_trap
+ (module
+ (type $a (array (mut i64)))
+ (import "M" "a" (table 2 anyref))
+ (table $l 1 anyref)
+ (elem (table $l) (i32.const 0) anyref
+ (array.new_default $a (i32.const 0x7fffffff)))
+ (elem (table 0) (i32.const 0) anyref (ref.i31 (i32.const 5))))
+ "allocation size too large")
+(assert_return (invoke $M "a-is-null" (i32.const 0)) (i32.const 1))
+
+;; Out-of-bounds active segments still trap in order: earlier segments stay
+;; written.
+(assert_trap
+ (module
+ (type $a (array (mut i64)))
+ (import "M" "a" (table 2 anyref))
+ (elem (table 0) (i32.const 0) anyref (ref.i31 (i32.const 9)))
+ (elem (table 0) (i32.const 1) anyref
+ (array.new_default $a (i32.const 1))
+ (array.new_default $a (i32.const 1))))
+ "out of bounds table access")
+(assert_return (invoke $M "get-a" (i32.const 0)) (i32.const 9))
+(assert_return (invoke $M "a-is-null" (i32.const 1)) (i32.const 1))
+
+;; When nothing traps, staged segments are written to the table as normal.
+(module $N
+ (type $a (array (mut i64)))
+ (table $t 4 anyref)
+ (elem (table $t) (i32.const 1) anyref
+ (ref.i31 (i32.const 3))
+ (array.new $a (i64.const 42) (i32.const 2))
+ (ref.null any))
+ (func (export "i31") (param i32) (result i32)
+ (i31.get_s (ref.cast (ref i31) (table.get $t (local.get 0)))))
+ (func (export "arr") (param i32) (result i64)
+ (array.get $a (ref.cast (ref $a) (table.get $t (local.get 0))) (i32.const 1)))
+ (func (export "is-null") (param i32) (result i32)
+ (ref.is_null (table.get $t (local.get 0))))
+ ;; Active segments are dropped after instantiation, so they behave like
+ ;; empty segments for `table.init`.
+ (func (export "init") (param i32)
+ (table.init $t 0 (i32.const 0) (i32.const 0) (local.get 0))))
+(assert_return (invoke $N "is-null" (i32.const 0)) (i32.const 1))
+(assert_return (invoke $N "i31" (i32.const 1)) (i32.const 3))
+(assert_return (invoke $N "arr" (i32.const 2)) (i64.const 42))
+(assert_return (invoke $N "is-null" (i32.const 3)) (i32.const 1))
+(assert_return (invoke $N "init" (i32.const 0)))
+(assert_trap (invoke $N "init" (i32.const 1)) "out of bounds table access")
+
+;; Staged segments also work with 64-bit tables, where the copy from the
+;; 32-bit element segment uses a 32-bit length like `table.init`.
+(module $T64
+ (type $s (struct (field i32)))
+ (table $t i64 3 anyref)
+ (elem (table $t) (i64.const 1) anyref
+ (struct.new $s (i32.const 11))
+ (struct.new $s (i32.const 12)))
+ (func (export "get") (param i64) (result i32)
+ (struct.get $s 0 (ref.cast (ref $s) (table.get $t (local.get 0)))))
+ (func (export "is-null") (param i64) (result i32)
+ (ref.is_null (table.get $t (local.get 0)))))
+(assert_return (invoke $T64 "is-null" (i64.const 0)) (i32.const 1))
+(assert_return (invoke $T64 "get" (i64.const 1)) (i32.const 11))
+(assert_return (invoke $T64 "get" (i64.const 2)) (i32.const 12))
+
+;; An out-of-bounds 64-bit offset still traps.
+(assert_trap
+ (module
+ (type $s (struct (field i32)))
+ (table $t i64 3 anyref)
+ (elem (table $t) (i64.const 0xffffffffffffffff) anyref
+ (struct.new $s (i32.const 1))))
+ "out of bounds table access")