From 47f8baa6dcdfb255de5d6d0117122a1e84c2e876 Mon Sep 17 00:00:00 2001 From: Till Schneidereit Date: Tue, 10 Nov 2026 23:29:03 +0100 Subject: [PATCH 1/5] Frontend: move element item parsing into a helper. The items of an element segment are parsed into a list of `Func`s inline in the active-segment case. Move that code into `parse_element_items` so that passive and declarative segments can use it as well. No functional change. --- src/frontend.rs | 72 ++++++++++++++++++++++++++----------------------- 1 file changed, 39 insertions(+), 33 deletions(-) diff --git a/src/frontend.rs b/src/frontend.rs index 5be0944..bd11b59 100644 --- a/src/frontend.rs +++ b/src/frontend.rs @@ -89,6 +89,44 @@ fn parse_init_expr<'a>(init_expr: &wasmparser::ConstExpr<'a>) -> Result Result> { + Ok(match items { + wasmparser::ElementItems::Functions(items) => { + let mut funcs = vec![]; + for item in items { + let item = item?; + let func = Func::from(item); + funcs.push(func); + } + funcs + } + wasmparser::ElementItems::Expressions(_, const_exprs) => { + let mut funcs = vec![]; + for const_expr in const_exprs { + let const_expr = const_expr?; + let mut func = None; + for op in const_expr.get_operators_reader() { + let op = op?; + match op { + wasmparser::Operator::End => {} + wasmparser::Operator::RefFunc { function_index } => { + func = Some(Func::from(function_index)); + } + wasmparser::Operator::RefNull { .. } => { + func = Some(Func::invalid()); + } + _ => panic!("Unsupported table-init op: {:?}", op), + } + } + funcs.push(func.unwrap_or(Func::invalid())); + } + funcs + } + }) +} + #[derive(Default)] struct ExtraSections<'a> { #[cfg(feature = "dwarf")] @@ -402,39 +440,7 @@ fn handle_payload<'a>( } => { let table = Table::from(table_index.unwrap_or(0)); let offset = parse_init_expr(&offset_expr)?.unwrap_or(0) as usize; - let funcs = match element.items { - wasmparser::ElementItems::Functions(items) => { - let mut funcs = vec![]; - for item in items { - let item = item?; - let func = Func::from(item); - funcs.push(func); - } - funcs - } - wasmparser::ElementItems::Expressions(_, const_exprs) => { - let mut funcs = vec![]; - for const_expr in const_exprs { - let const_expr = const_expr?; - let mut func = None; - for op in const_expr.get_operators_reader() { - let op = op?; - match op { - wasmparser::Operator::End => {} - wasmparser::Operator::RefFunc { function_index } => { - func = Some(Func::from(function_index)); - } - wasmparser::Operator::RefNull { .. } => { - func = Some(Func::invalid()); - } - _ => panic!("Unsupported table-init op: {:?}", op), - } - } - funcs.push(func.unwrap_or(Func::invalid())); - } - funcs - } - }; + let funcs = parse_element_items(element.items)?; let table_items = module.tables[table].func_elements.as_mut().unwrap(); let new_size = offset.checked_add(funcs.len()).ok_or_else(|| { From a186c601f754b0d7b3cae90dc7e01b4beb31ba90 Mon Sep 17 00:00:00 2001 From: Till Schneidereit Date: Tue, 10 Nov 2026 23:43:54 +0100 Subject: [PATCH 2/5] Frontend: reject unsupported element item expressions with an error. An element segment item that is a constant expression other than `ref.func` or `ref.null`, such as `global.get`, made the frontend panic. Return `FrontendError::UnsupportedFeature` instead, as the frontend does for other constructs it does not support. --- src/frontend.rs | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/src/frontend.rs b/src/frontend.rs index bd11b59..bf7e69f 100644 --- a/src/frontend.rs +++ b/src/frontend.rs @@ -117,7 +117,10 @@ fn parse_element_items(items: wasmparser::ElementItems) -> Result> { wasmparser::Operator::RefNull { .. } => { func = Some(Func::invalid()); } - _ => panic!("Unsupported table-init op: {:?}", op), + _ => bail!(FrontendError::UnsupportedFeature(format!( + "Unsupported element segment item operator: {:?}", + op + ))), } } funcs.push(func.unwrap_or(Func::invalid())); @@ -2071,3 +2074,26 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> { Ok(()) } } + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn element_item_global_get_is_unsupported() { + let bytes = wat::parse_str( + r#" + (module + (import "m" "g" (global funcref)) + (table 1 funcref) + (elem (i32.const 0) funcref (global.get 0))) + "#, + ) + .unwrap(); + let err = Module::from_wasm_bytes(&bytes, &FrontendOptions::default()).unwrap_err(); + assert!(matches!( + err.downcast::(), + Ok(FrontendError::UnsupportedFeature(_)) + )); + } +} From 8218cb1cdbd5207f1bf00c24f395976351617d15 Mon Sep 17 00:00:00 2001 From: Till Schneidereit Date: Tue, 10 Nov 2026 23:45:49 +0100 Subject: [PATCH 3/5] Preserve passive and declarative segments and emit DataCount. The frontend dropped passive data segments and passive and declarative element segments, and the backend never emitted a DataCount section. Function bodies that are not expanded are copied byte for byte, so a `memory.init`, `data.drop`, `table.init` or `elem.drop` in such a body then referred to a different segment or to one that no longer existed, a module using `memory.init` or `data.drop` failed validation because DataCount was missing, and a `ref.func` of a function that only a declarative segment declared failed validation as well. Record these segments in the module with their original segment index: `Module::passive_data_segments` holds passive data segments and `Module::element_segments` holds passive and declarative element segments. `Module::has_data_count` records whether the input had a DataCount section, and `Module::orig_data_segment_count` and `Module::orig_element_segment_count` record how many segments of each kind the input had. The backend lays out each segment index space so that every recorded segment lands at its original index. Active segments fill the remaining indices in order. Instantiation drops each active segment after applying it, so code that refers to an active data segment's index behaves the same whichever active data segment occupies it, or if an empty data segment occupies it. The same holds for element segments of the same element type. When there are fewer active segments than free indices below the highest recorded index or below the input's segment count, empty segments fill the rest, so every index the input had stays valid. Active segments beyond that are appended. Data segments are padded to the input's count only when the input had a DataCount section. Validation requires that section for every instruction that names a data segment, so code in an input without one names no data segment. Empty data segments are passive. Empty element segments are active segments of no entries at offset 0 of table 0, in the 1.0 encoding, when table 0 is a `funcref` table, and passive segments otherwise. Instantiation applies an empty active segment without writing an entry or trapping, for any table size, and then drops it. Code that names its index therefore behaves as it does for an empty passive segment. For every input that validates under WebAssembly 1.0 or 2.0, the output requires bulk memory only when the input did. A module that uses reference types without bulk memory and has a table 0 that is not a `funcref` table still gets passive padding. Empty element segments are `funcref` segments. A `table.init` into a typed function reference table that names such an index, or an index now holding an active segment of another element type, fails validation. A DataCount section is emitted when the module has a passive data segment or the input had a DataCount section. --- Cargo.toml | 2 + src/backend/mod.rs | 267 ++++++++++++++++++++++++++++++++------ src/frontend.rs | 51 +++++++- src/ir/module.rs | 68 ++++++++++ tests/segments.rs | 316 +++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 660 insertions(+), 44 deletions(-) create mode 100644 tests/segments.rs diff --git a/Cargo.toml b/Cargo.toml index cec721e..b7ab52f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,6 +26,8 @@ wasm-smith = { version = "0.248", optional = true } [dev-dependencies] wat = "1.248.0" +# Enables the `WasmFeatures` constants of `waffle::wasmparser` in tests. +wasmparser = { version = "0.248", default-features = false, features = ["std", "validate", "features"] } env_logger = "0.11" [features] diff --git a/src/backend/mod.rs b/src/backend/mod.rs index 5c81890..582d2df 100644 --- a/src/backend/mod.rs +++ b/src/backend/mod.rs @@ -2,7 +2,10 @@ use crate::cfg::CFGInfo; use crate::entity::EntityRef; -use crate::ir::{ExportKind, FuncDecl, FunctionBody, ImportKind, Module, Type, Value, ValueDef}; +use crate::ir::{ + ElementSegmentKind, ExportKind, Func, FuncDecl, FunctionBody, ImportKind, Module, Type, Value, + ValueDef, +}; use crate::Operator; use anyhow::Result; #[cfg(feature = "parallel")] @@ -1173,43 +1176,112 @@ pub fn compile(module: &Module<'_>) -> anyhow::Result> { into_mod.section(&start); } - let mut elem = wasm_encoder::ElementSection::new(); + let mut active_elements = vec![]; for (table, table_data) in module.tables.entries() { if let Some(elts) = &table_data.func_elements { - for (i, &elt) in elts.iter().enumerate() { + for (i, elt) in elts.iter().enumerate() { if elt.is_valid() { - match table_data.ty { - Type::FuncRef => { - elem.active( - Some(table.index() as u32), - &wasm_encoder::ConstExpr::i32_const(i as i32), - wasm_encoder::Elements::Functions(std::borrow::Cow::Borrowed(&[ - u32::try_from(elt.index()).unwrap(), - ])), - ); - } - Type::TypedFuncRef(..) => { - elem.active( - Some(table.index() as u32), - &wasm_encoder::ConstExpr::i32_const(i as i32), - wasm_encoder::Elements::Expressions( - table_data.ty.into(), - std::borrow::Cow::Borrowed(&[ - wasm_encoder::ConstExpr::ref_func( - u32::try_from(elt.index()).unwrap(), - ), - ]), - ), - ); - } - _ => unreachable!(), - } + active_elements.push((table, table_data.ty, i, std::slice::from_ref(elt))); } } } } + let element_slots = segment_layout( + active_elements, + module + .element_segments + .iter() + .map(|segment| (segment.index, segment)) + .collect(), + module.orig_element_segment_count, + )?; + // Empty element segments are active segments of no entries at offset 0 + // of table 0 when table 0 is a `funcref` table, and passive segments + // otherwise. Offset 0 is in bounds for every table size. The active + // form uses the 1.0 encoding, so it does not require bulk memory. + let empty_elements_are_active = module + .tables + .values() + .next() + .map_or(false, |table| table.ty == Type::FuncRef); + let mut elem = wasm_encoder::ElementSection::new(); + for slot in element_slots { + match slot { + SegmentSlot::Active((table, ty, offset, funcs)) => { + elem.active( + Some(table.index() as u32), + &wasm_encoder::ConstExpr::i32_const(offset as i32), + element_items(ty, funcs)?, + ); + } + SegmentSlot::Preserved(segment) => { + let items = element_items(segment.ty, &segment.elements)?; + match segment.kind { + ElementSegmentKind::Passive => elem.passive(items), + ElementSegmentKind::Declarative => elem.declared(items), + }; + } + SegmentSlot::Empty if empty_elements_are_active => { + elem.active( + None, + &wasm_encoder::ConstExpr::i32_const(0), + wasm_encoder::Elements::Functions(Cow::Borrowed(&[])), + ); + } + SegmentSlot::Empty => { + elem.passive(wasm_encoder::Elements::Functions(Cow::Borrowed(&[]))); + } + } + } into_mod.section(&elem); + let mut active_data = vec![]; + for (mem, mem_data) in module.memories.entries() { + for segment in &mem_data.segments { + active_data.push((mem, segment)); + } + } + // Validation requires a DataCount section for every instruction that + // names a data segment, so code in a module without one names no data + // segment. We pad to the original data segment count only when the + // module had a DataCount section, so that modules without one get no + // empty passive segments. + let min_data_segments = if module.has_data_count { + module.orig_data_segment_count + } else { + 0 + }; + let data_slots = segment_layout( + active_data, + module + .passive_data_segments + .iter() + .map(|segment| (segment.index, segment)) + .collect(), + min_data_segments, + )?; + let mut data = wasm_encoder::DataSection::new(); + for slot in data_slots { + match slot { + SegmentSlot::Active((mem, segment)) => { + data.active( + mem.index() as u32, + &wasm_encoder::ConstExpr::i32_const(segment.offset as i32), + segment.data.iter().copied(), + ); + } + SegmentSlot::Preserved(segment) => { + data.passive(segment.data.iter().copied()); + } + SegmentSlot::Empty => { + data.passive(std::iter::empty()); + } + } + } + if module.has_data_count || !module.passive_data_segments.is_empty() { + into_mod.section(&wasm_encoder::DataCountSection { count: data.len() }); + } + let mut code = wasm_encoder::CodeSection::new(); let entries = module @@ -1244,16 +1316,6 @@ pub fn compile(module: &Module<'_>) -> anyhow::Result> { } into_mod.section(&code); - let mut data = wasm_encoder::DataSection::new(); - for (mem, mem_data) in module.memories.entries() { - for segment in &mem_data.segments { - data.active( - mem.index() as u32, - &wasm_encoder::ConstExpr::i32_const(segment.offset as i32), - segment.data.iter().copied(), - ); - } - } into_mod.section(&data); let mut names = wasm_encoder::NameSection::new(); @@ -1275,6 +1337,104 @@ pub fn compile(module: &Module<'_>) -> anyhow::Result> { Ok(into_mod.finish()) } +/// An entry in a data or element segment index space, as returned by +/// `segment_layout`. +#[derive(Debug, PartialEq, Eq)] +enum SegmentSlot { + /// An active segment. + Active(A), + /// A passive or declarative segment, at its recorded index. + Preserved(P), + /// An empty segment. + Empty, +} + +/// Lays out one segment index space and returns its entries in index +/// order. +/// +/// Each segment in `preserved` is placed at the index paired with it. +/// Function bodies that are emitted without being expanded refer to +/// passive and declarative segments by their original index in +/// `memory.init`, `data.drop`, `table.init` and `elem.drop`, so these +/// indices must not change. The segments in `active` fill the remaining +/// indices in order. Instantiation drops each active segment after +/// applying it, so those instructions behave the same on any active data +/// segment as on an empty passive or empty active data segment, and the +/// same holds for element segments of the same element type. This makes +/// it safe to move active segments between the free indices and to fill +/// free indices with either kind of empty segment. `SegmentSlot::Empty` +/// entries fill the free indices that remain below `min_len` and below +/// the highest preserved index after the active segments are used up, so +/// that every index the original module had stays valid. Active segments +/// that do not fit below these bounds follow them. +/// +/// Note: empty element segments are `funcref` segments. A +/// `table.init` into a typed function reference table that names an +/// index now holding an empty segment or an active segment of another +/// element type fails validation. +/// +/// Fails if two preserved segments have the same index. +fn segment_layout( + active: Vec, + mut preserved: Vec<(usize, P)>, + min_len: usize, +) -> Result>> { + preserved.sort_by_key(|&(index, _)| index); + let mut active = active.into_iter(); + let mut next_free = || match active.next() { + Some(segment) => SegmentSlot::Active(segment), + None => SegmentSlot::Empty, + }; + let mut slots = vec![]; + for (index, segment) in preserved { + if index < slots.len() { + anyhow::bail!("Two segments have the same segment index {}", index); + } + while slots.len() < index { + slots.push(next_free()); + } + slots.push(SegmentSlot::Preserved(segment)); + } + while slots.len() < min_len { + slots.push(next_free()); + } + slots.extend(active.map(SegmentSlot::Active)); + Ok(slots) +} + +/// Encodes `funcs` as the items of an element segment with element type +/// `ty`. `Func::invalid()` entries are encoded as `ref.null`. +fn element_items(ty: Type, funcs: &[Func]) -> Result> { + let null = match ty { + Type::FuncRef if funcs.iter().all(|func| func.is_valid()) => { + return Ok(wasm_encoder::Elements::Functions(Cow::Owned( + funcs + .iter() + .map(|func| u32::try_from(func.index()).unwrap()) + .collect(), + ))); + } + Type::FuncRef => wasm_encoder::HeapType::FUNC, + Type::TypedFuncRef(_, sig) => wasm_encoder::HeapType::Concrete(sig), + _ => anyhow::bail!("Element segment has non-reference element type {}", ty), + }; + Ok(wasm_encoder::Elements::Expressions( + ty.into(), + Cow::Owned( + funcs + .iter() + .map(|func| { + if func.is_valid() { + wasm_encoder::ConstExpr::ref_func(u32::try_from(func.index()).unwrap()) + } else { + wasm_encoder::ConstExpr::ref_null(null) + } + }) + .collect(), + ), + )) +} + fn const_init(ty: Type, value: Option) -> wasm_encoder::ConstExpr { let bits = value.unwrap_or(0); match ty { @@ -1289,3 +1449,32 @@ fn const_init(ty: Type, value: Option) -> wasm_encoder::ConstExpr { _ => unimplemented!(), } } + +#[cfg(test)] +mod tests { + use super::{segment_layout, SegmentSlot}; + + #[test] + fn segment_layout_places_preserved_segments_at_their_index() { + let slots = segment_layout(vec!['a'], vec![(2, 'Q'), (0, 'P')], 0).unwrap(); + assert_eq!( + slots, + vec![ + SegmentSlot::Preserved('P'), + SegmentSlot::Active('a'), + SegmentSlot::Preserved('Q'), + ] + ); + } + + #[test] + fn segment_layout_pads_missing_active_segments() { + let slots = segment_layout::<(), _>(vec![], vec![(1, 'P')], 0).unwrap(); + assert_eq!(slots, vec![SegmentSlot::Empty, SegmentSlot::Preserved('P')]); + } + + #[test] + fn segment_layout_rejects_duplicate_indices() { + assert!(segment_layout(vec!['a'], vec![(1, 'P'), (1, 'Q')], 0).is_err()); + } +} diff --git a/src/frontend.rs b/src/frontend.rs index bf7e69f..b7f610e 100644 --- a/src/frontend.rs +++ b/src/frontend.rs @@ -89,6 +89,23 @@ fn parse_init_expr<'a>(init_expr: &wasmparser::ConstExpr<'a>) -> Result Result { + match items { + wasmparser::ElementItems::Functions(_) => Ok(Type::FuncRef), + wasmparser::ElementItems::Expressions(ty, _) + if *ty == wasmparser::RefType::FUNCREF || ty.type_index().is_some() => + { + Ok((*ty).into()) + } + wasmparser::ElementItems::Expressions(ty, _) => bail!(FrontendError::UnsupportedFeature( + format!("Unsupported element segment type: {:?}", ty) + )), + } +} + /// The functions an element segment refers to, in order, with /// `Func::invalid()` for each `ref.null`. fn parse_element_items(items: wasmparser::ElementItems) -> Result> { @@ -317,11 +334,20 @@ fn handle_payload<'a>( }); } } + Payload::DataCountSection { .. } => { + module.has_data_count = true; + } Payload::DataSection(reader) => { - for segment in reader { + module.orig_data_segment_count = reader.count() as usize; + for (index, segment) in reader.into_iter().enumerate() { let segment = segment?; match &segment.kind { - DataKind::Passive => {} + DataKind::Passive => { + module.passive_data_segments.push(PassiveDataSegment { + index, + data: segment.data.to_vec(), + }); + } DataKind::Active { memory_index, offset_expr, @@ -432,11 +458,26 @@ fn handle_payload<'a>( } Payload::Version { .. } => {} Payload::ElementSection(reader) => { - for element in reader { + module.orig_element_segment_count = reader.count() as usize; + for (index, element) in reader.into_iter().enumerate() { let element = element?; match &element.kind { - wasmparser::ElementKind::Passive => {} - wasmparser::ElementKind::Declared => {} + wasmparser::ElementKind::Passive => { + module.element_segments.push(ElementSegment { + index, + kind: ElementSegmentKind::Passive, + ty: element_type(&element.items)?, + elements: parse_element_items(element.items)?, + }); + } + wasmparser::ElementKind::Declared => { + module.element_segments.push(ElementSegment { + index, + kind: ElementSegmentKind::Declarative, + ty: element_type(&element.items)?, + elements: parse_element_items(element.items)?, + }); + } wasmparser::ElementKind::Active { table_index, offset_expr, diff --git a/src/ir/module.rs b/src/ir/module.rs index 7f7cc3b..cc49fdd 100644 --- a/src/ir/module.rs +++ b/src/ir/module.rs @@ -61,6 +61,23 @@ pub struct Module<'a> { pub debug_map: DebugMap, /// Other custom sections retained for re-serialization. pub custom_sections: BTreeMap, + /// Passive data segments. Active data segments are part of + /// `MemoryData::segments`. + pub passive_data_segments: Vec, + /// Passive and declarative element segments. Active element + /// segments are part of `TableData::func_elements`. + pub element_segments: Vec, + /// Whether the module had a DataCount section when it was + /// parsed. The backend emits a DataCount section when this is set + /// or when `passive_data_segments` is not empty. + pub has_data_count: bool, + /// The number of data segments the module had when it was parsed. + /// When `has_data_count` is set, the backend emits at least this + /// many data segments. + pub orig_data_segment_count: usize, + /// The number of element segments the module had when it was + /// parsed. The backend emits at least this many element segments. + pub orig_element_segment_count: usize, } /// A function signature definition. @@ -113,6 +130,42 @@ pub struct TableData { pub func_elements: Option>, } +/// A passive data segment. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct PassiveDataSegment { + /// The index of this segment in the module's data segment index + /// space. The backend emits the segment at this index. + pub index: usize, + /// The contents of this segment. + pub data: Vec, +} + +/// The mode of an `ElementSegment`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum ElementSegmentKind { + /// A passive segment, used by `table.init`. + Passive, + /// A declarative segment, which declares functions for use by + /// `ref.func`. + Declarative, +} + +/// A passive or declarative element segment. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ElementSegment { + /// The index of this segment in the module's element segment index + /// space. The backend emits the segment at this index. + pub index: usize, + /// Whether this segment is passive or declarative. + pub kind: ElementSegmentKind, + /// The type of the segment's elements: `Type::FuncRef` or + /// `Type::TypedFuncRef`. + pub ty: Type, + /// The segment's elements. `null` funcrefs are represented by + /// `Func::invalid()`. + pub elements: Vec, +} + /// A global-variable definition. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct GlobalData { @@ -237,6 +290,11 @@ impl<'a> Module<'a> { debug: Debug::default(), debug_map: DebugMap::default(), custom_sections: BTreeMap::default(), + passive_data_segments: vec![], + element_segments: vec![], + has_data_count: false, + orig_data_segment_count: 0, + orig_element_segment_count: 0, } } @@ -276,6 +334,11 @@ impl<'a> Module<'a> { debug: self.debug, debug_map: self.debug_map, custom_sections: BTreeMap::default(), + passive_data_segments: self.passive_data_segments, + element_segments: self.element_segments, + has_data_count: self.has_data_count, + orig_data_segment_count: self.orig_data_segment_count, + orig_element_segment_count: self.orig_element_segment_count, } } @@ -373,6 +436,11 @@ impl<'a> Module<'a> { debug: Debug::default(), debug_map: DebugMap::default(), custom_sections: BTreeMap::default(), + passive_data_segments: vec![], + element_segments: vec![], + has_data_count: false, + orig_data_segment_count: 0, + orig_element_segment_count: 0, } } } diff --git a/tests/segments.rs b/tests/segments.rs new file mode 100644 index 0000000..2333cee --- /dev/null +++ b/tests/segments.rs @@ -0,0 +1,316 @@ +//! Integration tests for passive and declarative segments in modules +//! whose function bodies are not expanded. + +use waffle::wasmparser::{ + DataKind, ElementItems, ElementKind, Operator, Parser, Payload, Validator, WasmFeatures, +}; +use waffle::{FrontendOptions, MemorySegment, Module}; + +/// A module whose code refers to passive data and element segments by +/// index, and takes a reference to a function that only a declarative +/// element segment declares. +/// +/// Data segments: 0 active, 1 passive, 2 active. +/// Element segments: 0 active, 1 passive with a null entry, 2 active, +/// 3 declarative, 4 passive with a typed element type and a null entry. +const BULK_WAT: &str = r#" +(module + (type $t (func)) + + (memory 1) + (table $tab 3 funcref) + (table $typed 1 (ref null $t)) + + (data (i32.const 0) "active-0") + (data $p1 "passive-1") + (data (i32.const 16) "active-2") + + (elem (table $tab) (i32.const 0) func $a) + (elem $e1 funcref (ref.func $a) (ref.null func)) + (elem (table $tab) (i32.const 2) func $a) + (elem declare func $declared) + (elem $e4 (ref null $t) (ref.func $a) (ref.null $t)) + + (func $a (type $t)) + (func $declared (type $t)) + (func + (memory.init $p1 (i32.const 0) (i32.const 0) (i32.const 0)) + (table.init $tab $e1 (i32.const 0) (i32.const 0) (i32.const 0)) + (table.init $typed $e4 (i32.const 0) (i32.const 0) (i32.const 0)) + (drop (ref.func $declared)))) +"#; + +const A: u32 = 0; +const DECLARED: u32 = 1; + +#[derive(Debug, PartialEq, Eq)] +enum Mode { + Active, + Passive, + Declared, +} + +/// The segments of a serialized module, in index order. Element items are +/// function indices, with `None` for `ref.null`. +struct Segments { + data: Vec<(Mode, Vec)>, + data_count: Option, + elements: Vec<(Mode, Vec>)>, +} + +fn segments(bytes: &[u8]) -> Segments { + let mut out = Segments { + data: vec![], + data_count: None, + elements: vec![], + }; + for payload in Parser::new(0).parse_all(bytes) { + match payload.unwrap() { + Payload::DataCountSection { count, .. } => out.data_count = Some(count), + Payload::DataSection(reader) => { + for segment in reader { + let segment = segment.unwrap(); + let mode = match segment.kind { + DataKind::Active { .. } => Mode::Active, + DataKind::Passive => Mode::Passive, + }; + out.data.push((mode, segment.data.to_vec())); + } + } + Payload::ElementSection(reader) => { + for segment in reader { + let segment = segment.unwrap(); + let mode = match segment.kind { + ElementKind::Active { .. } => Mode::Active, + ElementKind::Passive => Mode::Passive, + ElementKind::Declared => Mode::Declared, + }; + let items = match segment.items { + ElementItems::Functions(reader) => { + reader.into_iter().map(|f| Some(f.unwrap())).collect() + } + ElementItems::Expressions(_, reader) => reader + .into_iter() + .map(|expr| { + let mut ops = expr.unwrap().get_operators_reader(); + match ops.read().unwrap() { + Operator::RefFunc { function_index } => Some(function_index), + Operator::RefNull { .. } => None, + op => panic!("unexpected element expression {:?}", op), + } + }) + .collect(), + }; + out.elements.push((mode, items)); + } + } + _ => {} + } + } + out +} + +fn validate(bytes: &[u8]) { + if let Err(e) = Validator::new().validate_all(bytes) { + panic!("output does not validate: {}", e); + } +} + +#[test] +fn unexpanded_bodies_keep_segment_indices() { + let input = wat::parse_str(BULK_WAT).unwrap(); + let module = Module::from_wasm_bytes(&input, &FrontendOptions::default()).unwrap(); + let output = module.to_wasm_bytes().unwrap(); + validate(&output); + + let out = segments(&output); + assert_eq!( + out.data, + vec![ + (Mode::Active, b"active-0".to_vec()), + (Mode::Passive, b"passive-1".to_vec()), + (Mode::Active, b"active-2".to_vec()), + ] + ); + assert_eq!(out.data_count, Some(3)); + assert_eq!(out.elements[1], (Mode::Passive, vec![Some(A), None])); + assert_eq!(out.elements[3], (Mode::Declared, vec![Some(DECLARED)])); + assert_eq!(out.elements[4], (Mode::Passive, vec![Some(A), None])); +} + +#[test] +fn extra_active_segments_follow_the_preserved_ones() { + let input = wat::parse_str( + r#" + (module + (memory 1) + (data "passive-0") + (func (data.drop 0))) + "#, + ) + .unwrap(); + let mut module = Module::from_wasm_bytes(&input, &FrontendOptions::default()).unwrap(); + module.memories.values_mut().next().unwrap().segments = vec![MemorySegment { + offset: 0, + data: b"new-0".to_vec(), + }]; + let output = module.to_wasm_bytes().unwrap(); + validate(&output); + + let out = segments(&output); + assert_eq!( + out.data, + vec![ + (Mode::Passive, b"passive-0".to_vec()), + (Mode::Active, b"new-0".to_vec()), + ] + ); + assert_eq!(out.data_count, Some(2)); +} + +#[test] +fn data_count_section_is_kept_without_passive_segments() { + let input = wat::parse_str( + r#" + (module + (memory 1) + (data (i32.const 0) "active-0") + (func (data.drop 0))) + "#, + ) + .unwrap(); + let module = Module::from_wasm_bytes(&input, &FrontendOptions::default()).unwrap(); + let output = module.to_wasm_bytes().unwrap(); + validate(&output); + + let out = segments(&output); + assert_eq!(out.data_count, Some(1)); + assert_eq!(out.data, vec![(Mode::Active, b"active-0".to_vec())]); +} + +/// Parses `bytes` and serializes the module again without expanding any +/// function body. +fn reserialize(bytes: &[u8]) -> Vec { + let module = Module::from_wasm_bytes(bytes, &FrontendOptions::default()).unwrap(); + module.to_wasm_bytes().unwrap() +} + +#[test] +fn fewer_active_data_segments_keep_original_indices_valid() { + let input = wat::parse_str( + r#" + (module + (memory 1) + (data (i32.const 0) "active-0") + (data (i32.const 16) "active-1") + (func (data.drop 1))) + "#, + ) + .unwrap(); + let mut module = Module::from_wasm_bytes(&input, &FrontendOptions::default()).unwrap(); + module + .memories + .values_mut() + .next() + .unwrap() + .segments + .truncate(1); + let output = module.to_wasm_bytes().unwrap(); + validate(&output); + + let out = segments(&output); + assert_eq!( + out.data, + vec![ + (Mode::Active, b"active-0".to_vec()), + (Mode::Passive, vec![]), + ] + ); + assert_eq!(out.data_count, Some(2)); +} + +#[test] +fn fewer_active_data_segments_without_data_count_are_not_padded() { + let input = wat::parse_str( + r#" + (module + (memory 1) + (data (i32.const 0) "active-0") + (data (i32.const 16) "active-1")) + "#, + ) + .unwrap(); + let mut module = Module::from_wasm_bytes(&input, &FrontendOptions::default()).unwrap(); + module + .memories + .values_mut() + .next() + .unwrap() + .segments + .truncate(1); + let output = module.to_wasm_bytes().unwrap(); + validate(&output); + + let out = segments(&output); + assert_eq!(out.data, vec![(Mode::Active, b"active-0".to_vec())]); + assert_eq!(out.data_count, None); +} + +#[test] +fn element_padding_is_passive_without_a_funcref_table_0() { + let input = wat::parse_str( + r#" + (module + (type $t (func)) + (table 0 (ref null $t)) + (elem (i32.const 0) (ref null $t))) + "#, + ) + .unwrap(); + let output = reserialize(&input); + validate(&output); + + assert_eq!(segments(&output).elements, vec![(Mode::Passive, vec![])]); +} + +fn validate_wasm1(bytes: &[u8]) { + let mut validator = Validator::new_with_features(WasmFeatures::WASM1); + if let Err(e) = validator.validate_all(bytes) { + panic!("module does not validate under WasmFeatures::WASM1: {}", e); + } +} + +#[test] +fn element_padding_needs_no_bulk_memory() { + let input = wat::parse_str( + "(module (table 1 funcref) (elem (i32.const 0) func 0) (elem (i32.const 0) func 0) (func))", + ) + .unwrap(); + let output = reserialize(&input); + validate_wasm1(&output); + assert_eq!( + segments(&output).elements.len(), + segments(&input).elements.len() + ); + + // The last element segment is padding. It uses the 1.0 encoding, + // which has no table index. + let mut padding = None; + for payload in Parser::new(0).parse_all(&output) { + if let Payload::ElementSection(reader) = payload.unwrap() { + padding = reader.into_iter().last().map(|segment| segment.unwrap()); + } + } + let padding = padding.unwrap(); + assert!(matches!( + padding.kind, + ElementKind::Active { + table_index: None, + .. + } + )); + match padding.items { + ElementItems::Functions(reader) => assert_eq!(reader.count(), 0), + ElementItems::Expressions(..) => panic!("padding uses expressions"), + } +} From 1518cecde6a25fe176bf80c99d09e1ee4c733a5a Mon Sep 17 00:00:00 2001 From: Till Schneidereit Date: Tue, 10 Nov 2026 23:46:04 +0100 Subject: [PATCH 4/5] Print passive and declarative segments in module display. `ModuleDisplay` printed table contents and active data segments only. Print `Module::passive_data_segments` and `Module::element_segments` as well, in the same format. --- src/ir/display.rs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/ir/display.rs b/src/ir/display.rs index 1eda466..cdf4da1 100644 --- a/src/ir/display.rs +++ b/src/ir/display.rs @@ -1,6 +1,6 @@ //! Displaying IR. -use super::{Func, FuncDecl, FunctionBody, Module, SourceLoc, ValueDef}; +use super::{ElementSegmentKind, Func, FuncDecl, FunctionBody, Module, SourceLoc, ValueDef}; use crate::entity::EntityRef; use fxhash::FxHashMap as HashMap; use std::fmt::{self, Display, Formatter, Result as FmtResult}; @@ -300,6 +300,28 @@ impl<'a, PD: PrintDecorator> Display for ModuleDisplay<'a, PD> { )?; } } + for segment in &self.module.passive_data_segments { + writeln!( + f, + " data segment {}: passive # {} bytes", + segment.index, + segment.data.len() + )?; + } + for segment in &self.module.element_segments { + let kind = match segment.kind { + ElementSegmentKind::Passive => "passive", + ElementSegmentKind::Declarative => "declarative", + }; + writeln!( + f, + " elem segment {}: {} {}", + segment.index, kind, segment.ty + )?; + for (i, &func) in segment.elements.iter().enumerate() { + writeln!(f, " elem segment {}[{}]: {}", segment.index, i, func)?; + } + } for import in &self.module.imports { writeln!( f, From e8fcc9d20159ef7bf2cdbf69a5ce69df56339297 Mon Sep 17 00:00:00 2001 From: Till Schneidereit Date: Tue, 10 Nov 2026 23:30:45 +0100 Subject: [PATCH 5/5] Backend: emit one element segment per run of table entries. The backend emitted one active element segment for each non-null table entry, so a module whose table was initialized by one segment of n entries came back with n single-entry segments. The table contents are the same, but each segment repeats the segment header in the binary and is applied separately at instantiation. Emit one active segment for each run of consecutive non-null entries instead. Null entries are still not emitted. The runs go through `segment_layout`, which pads the element segment index space to the input's element segment count, so an unexpanded `elem.drop` or `table.init` that names an active segment's index still validates when merging lowers the number of active segments. --- src/backend/mod.rs | 26 +++++++++++-- tests/element_segments.rs | 80 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+), 4 deletions(-) create mode 100644 tests/element_segments.rs diff --git a/src/backend/mod.rs b/src/backend/mod.rs index 582d2df..c23e98e 100644 --- a/src/backend/mod.rs +++ b/src/backend/mod.rs @@ -1179,10 +1179,8 @@ pub fn compile(module: &Module<'_>) -> anyhow::Result> { let mut active_elements = vec![]; for (table, table_data) in module.tables.entries() { if let Some(elts) = &table_data.func_elements { - for (i, elt) in elts.iter().enumerate() { - if elt.is_valid() { - active_elements.push((table, table_data.ty, i, std::slice::from_ref(elt))); - } + for (offset, run) in non_null_runs(elts) { + active_elements.push((table, table_data.ty, offset, run)); } } } @@ -1435,6 +1433,26 @@ fn element_items(ty: Type, funcs: &[Func]) -> Result Vec<(usize, &[Func])> { + let mut runs = vec![]; + let mut i = 0; + while i < elts.len() { + if !elts[i].is_valid() { + i += 1; + continue; + } + let start = i; + while i < elts.len() && elts[i].is_valid() { + i += 1; + } + runs.push((start, &elts[start..i])); + } + runs +} + fn const_init(ty: Type, value: Option) -> wasm_encoder::ConstExpr { let bits = value.unwrap_or(0); match ty { diff --git a/tests/element_segments.rs b/tests/element_segments.rs new file mode 100644 index 0000000..7205e3b --- /dev/null +++ b/tests/element_segments.rs @@ -0,0 +1,80 @@ +//! Integration tests for the active element segments that the backend +//! emits for table contents. + +use waffle::wasmparser::{ElementItems, ElementKind, Operator, Parser, Payload, Validator}; +use waffle::{FrontendOptions, Module, OptOptions}; + +/// An active element segment as `(table, offset, function indices)`. +type Segment = (u32, i32, Vec); + +/// The active element segments of a serialized module, in index order. +fn active_segments(bytes: &[u8]) -> Vec { + let mut out = vec![]; + for payload in Parser::new(0).parse_all(bytes) { + if let Payload::ElementSection(reader) = payload.unwrap() { + for segment in reader { + let segment = segment.unwrap(); + let (table, offset) = match segment.kind { + ElementKind::Active { + table_index, + offset_expr, + } => match offset_expr.get_operators_reader().read().unwrap() { + Operator::I32Const { value } => (table_index.unwrap_or(0), value), + op => panic!("unexpected offset expression {:?}", op), + }, + _ => panic!("unexpected non-active element segment"), + }; + let funcs = match segment.items { + ElementItems::Functions(reader) => { + reader.into_iter().map(|f| f.unwrap()).collect() + } + ElementItems::Expressions(_, reader) => reader + .into_iter() + .map( + |expr| match expr.unwrap().get_operators_reader().read().unwrap() { + Operator::RefFunc { function_index } => function_index, + op => panic!("unexpected element expression {:?}", op), + }, + ) + .collect(), + }; + out.push((table, offset, funcs)); + } + } + } + out +} + +/// Parses `input`, expands and optimizes every function body, and +/// serializes the module again. Checks that the output validates. +fn roundtrip(input: &[u8]) -> Vec { + let mut module = Module::from_wasm_bytes(input, &FrontendOptions::default()).unwrap(); + module.expand_all_funcs().unwrap(); + module.per_func_body(|func| func.optimize(&OptOptions::default())); + let output = module.to_wasm_bytes().unwrap(); + if let Err(e) = Validator::new().validate_all(&output) { + panic!("output does not validate: {}", e); + } + output +} + +#[test] +fn null_entries_split_segments() { + let input = wat::parse_str( + r#" + (module + (table 4 funcref) + (elem (i32.const 0) + funcref (ref.func 0) (ref.func 1) (ref.null func) (ref.func 0)) + (func) + (func)) + "#, + ) + .unwrap(); + + let output = roundtrip(&input); + assert_eq!( + active_segments(&output), + vec![(0, 0, vec![0, 1]), (0, 3, vec![0])] + ); +}