From 47f8baa6dcdfb255de5d6d0117122a1e84c2e876 Mon Sep 17 00:00:00 2001 From: Till Schneidereit Date: Tue, 10 Nov 2026 23:29:03 +0100 Subject: [PATCH 1/8] 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/8] 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/8] 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/8] 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/8] 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])] + ); +} From 973aab981ec071eed5437e293b89ac1da6895040 Mon Sep 17 00:00:00 2001 From: Till Schneidereit Date: Wed, 11 Nov 2026 16:45:32 +0100 Subject: [PATCH 6/8] Frontend, backend: keep functions declared when a later element segment overwrites them. A `ref.func` in a function body validates only if the module declares the function, for example as an element segment item or an export. The frontend applied each active element segment to `TableData::func_elements` and kept only the final contents of each table, and the backend emits active segments only from those contents. A function whose only declaration was a table entry that a later active segment overwrote, with another function or with `ref.null`, was then declared nowhere in the output, and a `ref.func` of it failed validation with "undeclared function reference". This happened for unexpanded and expanded function bodies. Record each overwritten entry in the new `Module::overwritten_elements`. The backend writes each recorded function that no table's final contents, passive or declarative segment or function export contains into its entry, in active segments placed before the segments for the final contents. Entries with consecutive indices share a segment. An entry whose final content is null is written with `ref.null` after them, so the tables' final contents do not change. Records whose entry is not within the table's `func_elements` are ignored. These are active segments, so they fill the element segment indices that passive and declarative segments leave free, like the segments for the final contents. --- src/backend/mod.rs | 83 +++++++++++++++++++++++++++++++++++- src/frontend.rs | 10 +++++ src/ir/display.rs | 7 +++ src/ir/module.rs | 24 +++++++++++ tests/element_segments.rs | 89 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 211 insertions(+), 2 deletions(-) diff --git a/src/backend/mod.rs b/src/backend/mod.rs index c23e98e..17cbbef 100644 --- a/src/backend/mod.rs +++ b/src/backend/mod.rs @@ -3,11 +3,12 @@ use crate::cfg::CFGInfo; use crate::entity::EntityRef; use crate::ir::{ - ElementSegmentKind, ExportKind, Func, FuncDecl, FunctionBody, ImportKind, Module, Type, Value, - ValueDef, + ElementSegmentKind, ExportKind, Func, FuncDecl, FunctionBody, ImportKind, Module, Table, Type, + Value, ValueDef, }; use crate::Operator; use anyhow::Result; +use fxhash::FxHashSet; #[cfg(feature = "parallel")] use rayon::prelude::*; use std::borrow::Cow; @@ -1176,7 +1177,11 @@ pub fn compile(module: &Module<'_>) -> anyhow::Result> { into_mod.section(&start); } + let (overwritten, null_entries) = overwritten_element_segments(module); let mut active_elements = vec![]; + for (table, offset, funcs) in &overwritten { + active_elements.push((*table, module.tables[*table].ty, *offset, &funcs[..])); + } for (table, table_data) in module.tables.entries() { if let Some(elts) = &table_data.func_elements { for (offset, run) in non_null_runs(elts) { @@ -1184,6 +1189,9 @@ pub fn compile(module: &Module<'_>) -> anyhow::Result> { } } } + for (table, offset, funcs) in &null_entries { + active_elements.push((*table, module.tables[*table].ty, *offset, &funcs[..])); + } let element_slots = segment_layout( active_elements, module @@ -1453,6 +1461,77 @@ fn non_null_runs(elts: &[Func]) -> Vec<(usize, &[Func])> { runs } +/// Returns the active element segments that write the functions in +/// `Module::overwritten_elements`, and the segments that restore null +/// entries, as two lists of `(table, offset, entries)`. +/// +/// The first list writes each overwritten function into its entry, +/// except for functions that a table's final contents, a passive or +/// declarative segment, a function export or an earlier entry of the +/// list contains. Records whose index is not below the length of their +/// table's `func_elements`, or whose table has no `func_elements`, are +/// ignored. The second list writes `ref.null` into each entry of +/// the first list whose final content is null. Entries with consecutive +/// indices in the same table share a segment. The first list must be +/// applied before the segments for the tables' final contents, and the +/// second after the first. +fn overwritten_element_segments( + module: &Module, +) -> ( + Vec<(Table, usize, Vec)>, + Vec<(Table, usize, Vec)>, +) { + let mut declared = FxHashSet::default(); + for table_data in module.tables.values() { + declared.extend(table_data.func_elements.iter().flatten().copied()); + } + for segment in &module.element_segments { + declared.extend(segment.elements.iter().copied()); + } + for export in &module.exports { + if let ExportKind::Func(func) = export.kind { + declared.insert(func); + } + } + let mut writes = vec![]; + let mut nulls = vec![]; + for element in &module.overwritten_elements { + let elts = match &module.tables[element.table].func_elements { + Some(elts) if element.index < elts.len() => elts, + _ => continue, + }; + if !element.func.is_valid() || !declared.insert(element.func) { + continue; + } + writes.push((element.table, element.index, element.func)); + if !elts[element.index].is_valid() { + nulls.push((element.table, element.index, Func::invalid())); + } + } + writes.sort_by_key(|&(table, index, _)| (table, index)); + nulls.sort_by_key(|&(table, index, _)| (table, index)); + nulls.dedup(); + (consecutive_runs(writes), consecutive_runs(nulls)) +} + +/// Groups `(table, index, func)` entries, sorted by table and index, into +/// runs of consecutive indices in the same table. Each run is returned +/// with its table and the index of its first entry. +fn consecutive_runs(entries: Vec<(Table, usize, Func)>) -> Vec<(Table, usize, Vec)> { + let mut runs: Vec<(Table, usize, Vec)> = vec![]; + for (table, index, func) in entries { + match runs.last_mut() { + Some((run_table, start, funcs)) + if *run_table == table && *start + funcs.len() == index => + { + funcs.push(func) + } + _ => runs.push((table, index, vec![func])), + } + } + runs +} + fn const_init(ty: Type, value: Option) -> wasm_encoder::ConstExpr { let bits = value.unwrap_or(0); match ty { diff --git a/src/frontend.rs b/src/frontend.rs index b7f610e..5682b62 100644 --- a/src/frontend.rs +++ b/src/frontend.rs @@ -504,6 +504,16 @@ fn handle_payload<'a>( } table_items.resize(new_size, Func::invalid()); } + for (i, &func) in funcs.iter().enumerate() { + let old = table_items[offset + i]; + if old.is_valid() && old != func { + module.overwritten_elements.push(OverwrittenElement { + table, + index: offset + i, + func: old, + }); + } + } table_items[offset..new_size].copy_from_slice(&funcs[..]); } } diff --git a/src/ir/display.rs b/src/ir/display.rs index cdf4da1..a12f43f 100644 --- a/src/ir/display.rs +++ b/src/ir/display.rs @@ -284,6 +284,13 @@ impl<'a, PD: PrintDecorator> Display for ModuleDisplay<'a, PD> { } } } + for element in &self.module.overwritten_elements { + writeln!( + f, + " {}[{}]: overwritten {}", + element.table, element.index, element.func + )?; + } for (memory, memory_data) in self.module.memories.entries() { writeln!( f, diff --git a/src/ir/module.rs b/src/ir/module.rs index cc49fdd..fdf17d4 100644 --- a/src/ir/module.rs +++ b/src/ir/module.rs @@ -67,6 +67,15 @@ pub struct Module<'a> { /// Passive and declarative element segments. Active element /// segments are part of `TableData::func_elements`. pub element_segments: Vec, + /// Functions that an active element segment wrote into a table + /// entry and a later active element segment overwrote. For each + /// function that nothing else in the output declares, the backend + /// emits an active element segment that writes the function into + /// its entry before the segments that write the table's final + /// contents. The backend ignores records whose index is not below + /// the length of their table's `func_elements`, and all records of + /// a table whose `func_elements` is `None`. + pub overwritten_elements: 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. @@ -166,6 +175,18 @@ pub struct ElementSegment { pub elements: Vec, } +/// A function that an active element segment wrote into a table entry +/// and a later active element segment overwrote. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct OverwrittenElement { + /// The table. + pub table: Table, + /// The index of the entry in the table. + pub index: usize, + /// The function that the entry held before it was overwritten. + pub func: Func, +} + /// A global-variable definition. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct GlobalData { @@ -292,6 +313,7 @@ impl<'a> Module<'a> { custom_sections: BTreeMap::default(), passive_data_segments: vec![], element_segments: vec![], + overwritten_elements: vec![], has_data_count: false, orig_data_segment_count: 0, orig_element_segment_count: 0, @@ -336,6 +358,7 @@ impl<'a> Module<'a> { custom_sections: BTreeMap::default(), passive_data_segments: self.passive_data_segments, element_segments: self.element_segments, + overwritten_elements: self.overwritten_elements, 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, @@ -438,6 +461,7 @@ impl<'a> Module<'a> { custom_sections: BTreeMap::default(), passive_data_segments: vec![], element_segments: vec![], + overwritten_elements: vec![], has_data_count: false, orig_data_segment_count: 0, orig_element_segment_count: 0, diff --git a/tests/element_segments.rs b/tests/element_segments.rs index 7205e3b..47e03b5 100644 --- a/tests/element_segments.rs +++ b/tests/element_segments.rs @@ -5,8 +5,13 @@ use waffle::wasmparser::{ElementItems, ElementKind, Operator, Parser, Payload, V use waffle::{FrontendOptions, Module, OptOptions}; /// An active element segment as `(table, offset, function indices)`. +/// `ref.null` items are `NULL`. type Segment = (u32, i32, Vec); +/// The function index that `active_segments` returns for a `ref.null` +/// item. +const NULL: u32 = u32::MAX; + /// The active element segments of a serialized module, in index order. fn active_segments(bytes: &[u8]) -> Vec { let mut out = vec![]; @@ -33,6 +38,7 @@ fn active_segments(bytes: &[u8]) -> Vec { .map( |expr| match expr.unwrap().get_operators_reader().read().unwrap() { Operator::RefFunc { function_index } => function_index, + Operator::RefNull { .. } => NULL, op => panic!("unexpected element expression {:?}", op), }, ) @@ -78,3 +84,86 @@ fn null_entries_split_segments() { vec![(0, 0, vec![0, 1]), (0, 3, vec![0])] ); } + +#[test] +fn overwritten_table_entries_stay_declared() { + let input = wat::parse_str( + r#" + (module + (table 1 funcref) + (elem (i32.const 0) func 0) + (elem (i32.const 0) func 1) + (func (result i32) (ref.is_null (ref.func 0))) + (func)) + "#, + ) + .unwrap(); + let module = Module::from_wasm_bytes(&input, &FrontendOptions::default()).unwrap(); + let output = module.to_wasm_bytes().unwrap(); + if let Err(e) = Validator::new().validate_all(&output) { + panic!("output does not validate: {}", e); + } + assert_eq!( + active_segments(&output), + vec![(0, 0, vec![0]), (0, 0, vec![1])] + ); + + let nulled = wat::parse_str( + r#" + (module + (table 2 funcref) + (elem (i32.const 0) func 0 1) + (elem (i32.const 0) funcref (ref.null func) (ref.null func)) + (func) + (func)) + "#, + ) + .unwrap(); + assert_eq!( + active_segments(&roundtrip(&nulled)), + vec![(0, 0, vec![0, 1]), (0, 0, vec![NULL, NULL])] + ); + + let exported = wat::parse_str( + r#" + (module + (table 1 funcref) + (elem (i32.const 0) func 0) + (elem (i32.const 0) func 1) + (func (export "f")) + (func)) + "#, + ) + .unwrap(); + assert_eq!( + active_segments(&roundtrip(&exported)), + vec![(0, 0, vec![1]), (0, 0, vec![])] + ); +} + +#[test] +fn overwritten_entries_beyond_table_contents_are_not_written() { + let input = wat::parse_str( + r#" + (module + (table 2 funcref) + (elem (i32.const 1) func 0) + (elem (i32.const 1) func 1) + (func) + (func)) + "#, + ) + .unwrap(); + let mut module = Module::from_wasm_bytes(&input, &FrontendOptions::default()).unwrap(); + let table = module.tables.values_mut().next().unwrap(); + table.initial = 1; + table.func_elements.as_mut().unwrap().truncate(1); + let output = module.to_wasm_bytes().unwrap(); + if let Err(e) = Validator::new().validate_all(&output) { + panic!("output does not validate: {}", e); + } + assert_eq!( + active_segments(&output), + vec![(0, 0, vec![]), (0, 0, vec![])] + ); +} From 5485b949375a2f4729c1d5d1cfbee42ab87916e7 Mon Sep 17 00:00:00 2001 From: Till Schneidereit Date: Wed, 11 Nov 2026 17:36:35 +0100 Subject: [PATCH 7/8] Frontend, backend: keep table initializer expressions. The frontend ignored a table's initializer expression, such as `(table 1 funcref (ref.func 0))`, and the backend emitted the table without one. The output's entries started as null instead of the initializer's value, a table of a non-nullable type failed validation with "non-defaultable element type", and a function declared only by the initializer failed validation with "undeclared function reference" when code used `ref.func` of it. Record the initializer in the new `TableData::initializer` field and emit tables that have one with `table_with_init`. `ref.func` and `ref.null` initializers are supported. Every other initializer expression returns `FrontendError::UnsupportedFeature`. For a `ref.func` initializer, the frontend fills `func_elements` with the function for every index below the table's initial size before element segments are applied, so `func_elements` holds the table's initial contents. The backend emits an element segment entry only for entries that differ from their value before element segments are applied, and emits `ref.null` for a null entry that replaces an initializer's function. The segments for overwritten functions use the same rule. An entry that a recorded function is written into is restored to its final content when that content equals the entry's value before element segments are applied, because the final-content segments skip it. Before, only null entries were restored, so an entry that went from the initializer's function to another function and back read as the other function. The initializer's function counts as declared, so overwriting it produces no record segment. Tables without an initializer produce the same output as before. --- src/backend/mod.rs | 92 +++++++++++++++++++++----------- src/frontend.rs | 51 +++++++++++++++++- src/ir/display.rs | 5 +- src/ir/module.rs | 5 ++ tests/table_initializers.rs | 103 ++++++++++++++++++++++++++++++++++++ 5 files changed, 222 insertions(+), 34 deletions(-) create mode 100644 tests/table_initializers.rs diff --git a/src/backend/mod.rs b/src/backend/mod.rs index 17cbbef..2dc63a4 100644 --- a/src/backend/mod.rs +++ b/src/backend/mod.rs @@ -3,8 +3,8 @@ use crate::cfg::CFGInfo; use crate::entity::EntityRef; use crate::ir::{ - ElementSegmentKind, ExportKind, Func, FuncDecl, FunctionBody, ImportKind, Module, Table, Type, - Value, ValueDef, + ElementSegmentKind, ExportKind, Func, FuncDecl, FunctionBody, ImportKind, Module, Table, + TableData, Type, Value, ValueDef, }; use crate::Operator; use anyhow::Result; @@ -1100,13 +1100,17 @@ pub fn compile(module: &Module<'_>) -> anyhow::Result> { let mut tables = wasm_encoder::TableSection::new(); for table_data in module.tables.values().skip(num_table_imports) { - tables.table(wasm_encoder::TableType { + let table_type = wasm_encoder::TableType { element_type: wasm_encoder::RefType::from(table_data.ty), minimum: table_data.initial, maximum: table_data.max, table64: false, shared: false, - }); + }; + match table_data.initializer { + Some(func) => tables.table_with_init(table_type, &func_ref_const(table_data.ty, func)), + None => tables.table(table_type), + }; } into_mod.section(&tables); @@ -1177,19 +1181,21 @@ pub fn compile(module: &Module<'_>) -> anyhow::Result> { into_mod.section(&start); } - let (overwritten, null_entries) = overwritten_element_segments(module); + let (overwritten, restores) = overwritten_element_segments(module); let mut active_elements = vec![]; for (table, offset, funcs) in &overwritten { active_elements.push((*table, module.tables[*table].ty, *offset, &funcs[..])); } for (table, table_data) in module.tables.entries() { if let Some(elts) = &table_data.func_elements { - for (offset, run) in non_null_runs(elts) { + // An entry is emitted only if it differs from its value + // before element segments are applied. + for (offset, run) in changed_runs(elts, |index| initial_entry(table_data, index)) { active_elements.push((table, table_data.ty, offset, run)); } } } - for (table, offset, funcs) in &null_entries { + for (table, offset, funcs) in &restores { active_elements.push((*table, module.tables[*table].ty, *offset, &funcs[..])); } let element_slots = segment_layout( @@ -1441,19 +1447,19 @@ fn element_items(ty: Type, funcs: &[Func]) -> Result Vec<(usize, &[Func])> { +/// Splits `elts` into runs of consecutive entries that differ from +/// `before` of their index. Each run is returned with the index of its +/// first entry. +fn changed_runs(elts: &[Func], before: impl Fn(usize) -> Func) -> Vec<(usize, &[Func])> { let mut runs = vec![]; let mut i = 0; while i < elts.len() { - if !elts[i].is_valid() { + if elts[i] == before(i) { i += 1; continue; } let start = i; - while i < elts.len() && elts[i].is_valid() { + while i < elts.len() && elts[i] != before(i) { i += 1; } runs.push((start, &elts[start..i])); @@ -1461,20 +1467,31 @@ fn non_null_runs(elts: &[Func]) -> Vec<(usize, &[Func])> { runs } +/// Returns the value of entry `index` of a table before element segments +/// are applied: the initializer's value below `initial`, and null +/// otherwise. +fn initial_entry(table_data: &TableData, index: usize) -> Func { + match table_data.initializer { + Some(func) if (index as u64) < table_data.initial => func, + _ => Func::invalid(), + } +} + /// Returns the active element segments that write the functions in -/// `Module::overwritten_elements`, and the segments that restore null -/// entries, as two lists of `(table, offset, entries)`. +/// `Module::overwritten_elements`, and the segments that restore the +/// final contents of those entries, as two lists of +/// `(table, offset, entries)`. /// /// The first list writes each overwritten function into its entry, -/// except for functions that a table's final contents, a passive or -/// declarative segment, a function export or an earlier entry of the -/// list contains. Records whose index is not below the length of their -/// table's `func_elements`, or whose table has no `func_elements`, are -/// ignored. The second list writes `ref.null` into each entry of -/// the first list whose final content is null. Entries with consecutive -/// indices in the same table share a segment. The first list must be -/// applied before the segments for the tables' final contents, and the -/// second after the first. +/// except for functions that a table's initializer or final contents, a +/// passive or declarative segment, a function export or an earlier entry +/// of the list contains. Records whose index is not below the length of +/// their table's `func_elements`, or whose table has no `func_elements`, +/// are ignored. The second list writes the final content into each entry +/// of the first list whose final content equals its `initial_entry`. +/// Entries with consecutive indices in the same table share a segment. +/// The first list must be applied before the segments for the tables' +/// final contents, and the second after the first. fn overwritten_element_segments( module: &Module, ) -> ( @@ -1483,6 +1500,7 @@ fn overwritten_element_segments( ) { let mut declared = FxHashSet::default(); for table_data in module.tables.values() { + declared.extend(table_data.initializer); declared.extend(table_data.func_elements.iter().flatten().copied()); } for segment in &module.element_segments { @@ -1494,9 +1512,10 @@ fn overwritten_element_segments( } } let mut writes = vec![]; - let mut nulls = vec![]; + let mut restores = vec![]; for element in &module.overwritten_elements { - let elts = match &module.tables[element.table].func_elements { + let table_data = &module.tables[element.table]; + let elts = match &table_data.func_elements { Some(elts) if element.index < elts.len() => elts, _ => continue, }; @@ -1504,14 +1523,15 @@ fn overwritten_element_segments( continue; } writes.push((element.table, element.index, element.func)); - if !elts[element.index].is_valid() { - nulls.push((element.table, element.index, Func::invalid())); + let content = elts[element.index]; + if content == initial_entry(table_data, element.index) { + restores.push((element.table, element.index, content)); } } writes.sort_by_key(|&(table, index, _)| (table, index)); - nulls.sort_by_key(|&(table, index, _)| (table, index)); - nulls.dedup(); - (consecutive_runs(writes), consecutive_runs(nulls)) + restores.sort_by_key(|&(table, index, _)| (table, index)); + restores.dedup(); + (consecutive_runs(writes), consecutive_runs(restores)) } /// Groups `(table, index, func)` entries, sorted by table and index, into @@ -1532,6 +1552,16 @@ fn consecutive_runs(entries: Vec<(Table, usize, Func)>) -> Vec<(Table, usize, Ve runs } +/// Returns `ref.func func`, or `ref.null` of the heap type of `ty` when +/// `func` is `Func::invalid()`. +fn func_ref_const(ty: Type, func: Func) -> wasm_encoder::ConstExpr { + if func.is_valid() { + wasm_encoder::ConstExpr::ref_func(u32::try_from(func.index()).unwrap()) + } else { + wasm_encoder::ConstExpr::ref_null(wasm_encoder::RefType::from(ty).heap_type) + } +} + fn const_init(ty: Type, value: Option) -> wasm_encoder::ConstExpr { let bits = value.unwrap_or(0); match ty { diff --git a/src/frontend.rs b/src/frontend.rs index 5682b62..6d6a032 100644 --- a/src/frontend.rs +++ b/src/frontend.rs @@ -162,6 +162,39 @@ struct ExtraSections<'a> { _phantom: std::marker::PhantomData<&'a ()>, } +/// The largest number of entries that the frontend stores in +/// `TableData::func_elements`. +const MAX_TABLE: usize = 100_000; + +/// Converts a table's initializer to the value of its entries before +/// element segments are applied: `None` for a table without an +/// initializer expression, `Some(func)` for `ref.func func`, and +/// `Some(Func::invalid())` for `ref.null` of any heap type. Returns +/// `FrontendError::UnsupportedFeature` for any other initializer +/// expression. +fn table_initializer(init: &wasmparser::TableInit) -> Result> { + let expr = match init { + wasmparser::TableInit::RefNull => return Ok(None), + wasmparser::TableInit::Expr(expr) => expr, + }; + let operators = expr + .get_operators_reader() + .into_iter() + .collect::, _>>()?; + match &operators[..] { + [wasmparser::Operator::RefFunc { function_index }, wasmparser::Operator::End] => { + Ok(Some(Func::from(*function_index))) + } + [wasmparser::Operator::RefNull { .. }, wasmparser::Operator::End] => { + Ok(Some(Func::invalid())) + } + _ => bail!(FrontendError::UnsupportedFeature(format!( + "Unsupported table initializer expression: {:?}", + operators + ))), + } +} + fn handle_payload<'a>( module: &mut Module<'a>, payload: Payload<'a>, @@ -214,6 +247,7 @@ fn handle_payload<'a>( ty: ty.element_type.into(), initial: ty.initial, max: ty.maximum, + initializer: None, func_elements: Some(vec![]), }); ImportKind::Table(table) @@ -279,11 +313,25 @@ fn handle_payload<'a>( Payload::TableSection(reader) => { for table in reader { let table = table?; + let initializer = table_initializer(&table.init)?; + let func_elements = match initializer { + Some(func) if func.is_valid() => { + if table.ty.initial > MAX_TABLE as u64 { + bail!(FrontendError::TooLarge(format!( + "Too many table elements: {:?}", + table.ty.initial + ))); + } + vec![func; table.ty.initial as usize] + } + _ => vec![], + }; module.tables.push(TableData { ty: table.ty.element_type.into(), initial: table.ty.initial, max: table.ty.maximum, - func_elements: Some(vec![]), + initializer, + func_elements: Some(func_elements), }); } } @@ -495,7 +543,6 @@ fn handle_payload<'a>( )) })?; if new_size > table_items.len() { - static MAX_TABLE: usize = 100_000; if new_size > MAX_TABLE { bail!(FrontendError::TooLarge(format!( "Too many table elements: {:?}", diff --git a/src/ir/display.rs b/src/ir/display.rs index a12f43f..4ef60fa 100644 --- a/src/ir/display.rs +++ b/src/ir/display.rs @@ -277,7 +277,10 @@ impl<'a, PD: PrintDecorator> Display for ModuleDisplay<'a, PD> { )?; } for (table, table_data) in self.module.tables.entries() { - writeln!(f, " {}: {}", table, table_data.ty)?; + match table_data.initializer { + Some(func) => writeln!(f, " {}: {} init {}", table, table_data.ty, func)?, + None => writeln!(f, " {}: {}", table, table_data.ty)?, + } if let Some(funcs) = &table_data.func_elements { for (i, &func) in funcs.iter().enumerate() { writeln!(f, " {}[{}]: {}", table, i, func)?; diff --git a/src/ir/module.rs b/src/ir/module.rs index fdf17d4..17f4547 100644 --- a/src/ir/module.rs +++ b/src/ir/module.rs @@ -133,6 +133,11 @@ pub struct TableData { pub initial: u64, /// The maximum size (in elements), if any, of this table. pub max: Option, + /// The value of the table's initializer expression, if it has one: + /// `Some(func)` for `ref.func func` and `Some(Func::invalid())` for + /// `ref.null`. When this is a function, `func_elements` holds an + /// entry for every index below `initial`. + pub initializer: Option, /// If this is a table of function references, the initial /// contents of the table. `null` funcrefs are represented by /// `Func::invalid()`. diff --git a/tests/table_initializers.rs b/tests/table_initializers.rs new file mode 100644 index 0000000..92a1bb7 --- /dev/null +++ b/tests/table_initializers.rs @@ -0,0 +1,103 @@ +//! Tests for tables with an initializer expression. + +use waffle::entity::EntityRef; +use waffle::wasmparser::{ElementItems, Parser, Payload, Validator, WasmFeatures}; +use waffle::{FrontendError, FrontendOptions, Func, Module, OptOptions, Table}; + +/// The features that table initializer expressions and `ref.func` in +/// function bodies require. +const FEATURES: WasmFeatures = WasmFeatures::WASM1 + .union(WasmFeatures::REFERENCE_TYPES) + .union(WasmFeatures::FUNCTION_REFERENCES); + +/// Returns the lazy output and the expanded and optimized output for +/// `wat`. +fn outputs(wat: &str) -> [Vec; 2] { + let bytes = wat::parse_str(wat).unwrap(); + Validator::new_with_features(FEATURES) + .validate_all(&bytes) + .unwrap(); + let opts = FrontendOptions::default(); + let lazy = Module::from_wasm_bytes(&bytes, &opts) + .unwrap() + .to_wasm_bytes() + .unwrap(); + let mut module = Module::from_wasm_bytes(&bytes, &opts).unwrap(); + module.expand_all_funcs().unwrap(); + module.per_func_body(|func| func.optimize(&OptOptions::default())); + let expanded = module.to_wasm_bytes().unwrap(); + [lazy, expanded] +} + +/// Returns the contents of table 0 of `bytes`. +fn table_contents(bytes: &[u8]) -> Vec { + let module = Module::from_wasm_bytes(bytes, &FrontendOptions::default()).unwrap(); + module.tables[Table::from(0u32)] + .func_elements + .clone() + .unwrap() +} + +/// Returns the number of items in all element segments of `bytes`. +fn element_item_count(bytes: &[u8]) -> u32 { + let mut count = 0; + for payload in Parser::new(0).parse_all(bytes) { + if let Payload::ElementSection(reader) = payload.unwrap() { + for element in reader { + count += match element.unwrap().items { + ElementItems::Functions(items) => items.count(), + ElementItems::Expressions(_, items) => items.count(), + }; + } + } + } + count +} + +#[test] +fn element_segments_overwrite_table_initializer() { + let wat = r#"(module + (table 4 funcref (ref.func 0)) + (elem (i32.const 1) funcref (ref.null func) (ref.func 1) (ref.func 2)) + (elem (i32.const 3) func 0) + (func) + (func) + (func))"#; + let expected = vec![ + Func::from(0u32), + Func::invalid(), + Func::from(1u32), + Func::from(0u32), + ]; + for output in outputs(wat) { + Validator::new_with_features(FEATURES) + .validate_all(&output) + .unwrap(); + assert_eq!(table_contents(&output), expected); + // Entries 1 and 2 differ from the initializer. Entry 3 is written + // with function 2, which keeps it declared, and then with + // function 0. + assert_eq!(element_item_count(&output), 4); + } +} + +#[test] +fn unsupported_table_initializer_is_rejected() { + let bytes = wat::parse_str( + r#"(module + (import "" "" (global funcref)) + (table 1 funcref (global.get 0)))"#, + ) + .unwrap(); + let err = Module::from_wasm_bytes(&bytes, &FrontendOptions::default()) + .err() + .expect("module was accepted"); + assert!( + matches!( + err.downcast_ref::(), + Some(FrontendError::UnsupportedFeature(_)) + ), + "unexpected error: {:?}", + err + ); +} From c75aeae344397b9c48ffcafe119ded7e669cef3d Mon Sep 17 00:00:00 2001 From: Till Schneidereit Date: Wed, 11 Nov 2026 18:27:17 +0100 Subject: [PATCH 8/8] Frontend, backend: keep the element type of each active element segment index. Unexpanded function bodies name element segments by their original index in `table.init`, and validation requires the segment's element type to be a subtype of the table's element type. The backend filled the indices of the input's active segments with the segments for the tables' contents in table order, regardless of element type, and padded the remaining ones with empty `funcref` segments. A `table.init` into a typed function reference table, or into an `externref` table once waffle keeps that type, then named a `funcref` segment and failed validation with "type mismatch". Record the index, table and element type of each active segment of the input in the new `Module::active_element_segments`. The backend places a segment for table contents only at a recorded index of its table's element type. A recorded index that no such segment takes gets an empty active segment at offset 0 of the recorded table, with the recorded element type. Segments that no index takes follow the original segment count. The segments of one table keep their order. Free indices without a record keep the previous padding. For modules whose active segments are all `funcref` segments, segments are placed as before. An empty segment at the index of an input segment on a table other than table 0 now writes to that table instead of table 0. --- src/backend/mod.rs | 156 +++++++++++++++++++++++++++++++++------------ src/frontend.rs | 9 +++ src/ir/display.rs | 7 ++ src/ir/module.rs | 23 +++++++ tests/segments.rs | 37 ++++++++++- 5 files changed, 190 insertions(+), 42 deletions(-) diff --git a/src/backend/mod.rs b/src/backend/mod.rs index 2dc63a4..8854253 100644 --- a/src/backend/mod.rs +++ b/src/backend/mod.rs @@ -8,11 +8,13 @@ use crate::ir::{ }; use crate::Operator; use anyhow::Result; -use fxhash::FxHashSet; +use fxhash::{FxHashMap, FxHashSet}; #[cfg(feature = "parallel")] use rayon::prelude::*; use std::borrow::Cow; +use std::collections::VecDeque; use std::convert::TryFrom; +use std::hash::Hash; pub(crate) mod bitset; pub(crate) mod cross_block_ids; @@ -1198,26 +1200,43 @@ pub fn compile(module: &Module<'_>) -> anyhow::Result> { for (table, offset, funcs) in &restores { active_elements.push((*table, module.tables[*table].ty, *offset, &funcs[..])); } - let element_slots = segment_layout( - active_elements, + // Each active segment is keyed by its element type, which is the + // element type of its table. An index that held an active segment in + // the input takes only segments of that segment's element type, so + // `table.init` in unexpanded bodies stays valid. The segments of one + // table share a key, so they keep their order. + let orig_active_elements = module + .active_element_segments + .iter() + .map(|segment| (segment.index, segment)) + .collect::>(); + let element_slots = segment_layout_by_key( + active_elements + .into_iter() + .map(|(table, ty, offset, funcs)| (ty, (table, ty, offset, funcs))) + .collect(), module .element_segments .iter() .map(|segment| (segment.index, segment)) .collect(), + |index| orig_active_elements.get(&index).map(|segment| segment.ty), 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. + // Empty element segments at the index of an active segment of the input + // are active segments of no entries at offset 0 of that segment's table, + // with its element type. Other 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. An empty `funcref` segment on table 0 uses the + // 1.0 encoding, which 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 { + for (index, slot) in element_slots.into_iter().enumerate() { match slot { SegmentSlot::Active((table, ty, offset, funcs)) => { elem.active( @@ -1233,15 +1252,29 @@ pub fn compile(module: &Module<'_>) -> anyhow::Result> { 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(&[]))); + let target = match orig_active_elements.get(&index) { + Some(segment) => Some((segment.table, segment.ty)), + None if empty_elements_are_active => Some((Table::from(0), Type::FuncRef)), + None => None, + }; + let no_funcs = wasm_encoder::Elements::Functions(Cow::Borrowed(&[])); + let offset = wasm_encoder::ConstExpr::i32_const(0); + match target { + Some((table, Type::FuncRef)) if table.index() == 0 => { + elem.active(None, &offset, no_funcs) + } + Some((table, ty)) => { + let items = match ty { + Type::FuncRef => no_funcs, + ty => { + wasm_encoder::Elements::Expressions(ty.into(), Cow::Borrowed(&[])) + } + }; + elem.active(Some(table.index() as u32), &offset, items) + } + None => elem.passive(no_funcs), + }; } } } @@ -1361,6 +1394,22 @@ enum SegmentSlot { Empty, } +/// Lays out one segment index space and returns its entries in index +/// order. This is `segment_layout_by_key` with every free index taking +/// active segments of any key. +fn segment_layout( + active: Vec, + preserved: Vec<(usize, P)>, + min_len: usize, +) -> Result>> { + segment_layout_by_key( + active.into_iter().map(|segment| ((), segment)).collect(), + preserved, + |_| None, + min_len, + ) +} + /// Lays out one segment index space and returns its entries in index /// order. /// @@ -1368,34 +1417,59 @@ enum SegmentSlot { /// 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. +/// indices must not change. Each segment in `active` is paired with a +/// key, and `free_key` returns the key of each remaining index. An index +/// with key `Some(key)` takes the first remaining active segment paired +/// with `key`, and an index with key `None` takes the first remaining +/// active segment. Active segments with the same key keep their 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 of one key and to fill free +/// indices with empty segments, provided that element segments are keyed +/// by their element type and that an empty element segment has the +/// element type of its index's key. +/// `SegmentSlot::Empty` entries fill the free indices that remain without +/// an active segment below `min_len` and below the highest preserved +/// index, so that every index the original module had stays valid. +/// Active segments that are not placed below these bounds follow them, in +/// order. /// /// Fails if two preserved segments have the same index. -fn segment_layout( - active: Vec, +fn segment_layout_by_key( + active: Vec<(K, A)>, mut preserved: Vec<(usize, P)>, + free_key: impl Fn(usize) -> Option, 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 positions_by_key: FxHashMap> = FxHashMap::default(); + let mut active = active + .into_iter() + .enumerate() + .map(|(position, (key, segment))| { + positions_by_key.entry(key).or_default().push_back(position); + Some(segment) + }) + .collect::>(); + let mut first_remaining = 0; + let mut next_free = |index: usize| { + let position = match free_key(index) { + Some(key) => positions_by_key.get_mut(&key).and_then(|positions| { + std::iter::from_fn(|| positions.pop_front()).find(|&p| active[p].is_some()) + }), + None => { + while first_remaining < active.len() && active[first_remaining].is_none() { + first_remaining += 1; + } + Some(first_remaining) + } + }; + match position.and_then(|p| active.get_mut(p)?.take()) { + Some(segment) => SegmentSlot::Active(segment), + None => SegmentSlot::Empty, + } }; let mut slots = vec![]; for (index, segment) in preserved { @@ -1403,14 +1477,14 @@ fn segment_layout( anyhow::bail!("Two segments have the same segment index {}", index); } while slots.len() < index { - slots.push(next_free()); + slots.push(next_free(slots.len())); } slots.push(SegmentSlot::Preserved(segment)); } while slots.len() < min_len { - slots.push(next_free()); + slots.push(next_free(slots.len())); } - slots.extend(active.map(SegmentSlot::Active)); + slots.extend(active.into_iter().flatten().map(SegmentSlot::Active)); Ok(slots) } diff --git a/src/frontend.rs b/src/frontend.rs index 6d6a032..d308d09 100644 --- a/src/frontend.rs +++ b/src/frontend.rs @@ -531,6 +531,15 @@ fn handle_payload<'a>( offset_expr, } => { let table = Table::from(table_index.unwrap_or(0)); + let ty = match &element.items { + wasmparser::ElementItems::Functions(_) => Type::FuncRef, + wasmparser::ElementItems::Expressions(ty, _) => (*ty).into(), + }; + module.active_element_segments.push(ActiveElementSegment { + index, + table, + ty, + }); let offset = parse_init_expr(&offset_expr)?.unwrap_or(0) as usize; let funcs = parse_element_items(element.items)?; diff --git a/src/ir/display.rs b/src/ir/display.rs index 4ef60fa..68f3bea 100644 --- a/src/ir/display.rs +++ b/src/ir/display.rs @@ -318,6 +318,13 @@ impl<'a, PD: PrintDecorator> Display for ModuleDisplay<'a, PD> { segment.data.len() )?; } + for segment in &self.module.active_element_segments { + writeln!( + f, + " elem segment {}: active {} {}", + segment.index, segment.table, segment.ty + )?; + } for segment in &self.module.element_segments { let kind = match segment.kind { ElementSegmentKind::Passive => "passive", diff --git a/src/ir/module.rs b/src/ir/module.rs index 17f4547..5854561 100644 --- a/src/ir/module.rs +++ b/src/ir/module.rs @@ -67,6 +67,13 @@ pub struct Module<'a> { /// Passive and declarative element segments. Active element /// segments are part of `TableData::func_elements`. pub element_segments: Vec, + /// The index, table and element type of each active element segment + /// the module had when it was parsed. The backend emits an active + /// element segment of the recorded element type at each of these + /// indices: a segment that writes entries of a table with that + /// element type, or an empty segment at offset 0 of the recorded + /// table. + pub active_element_segments: Vec, /// Functions that an active element segment wrote into a table /// entry and a later active element segment overwrote. For each /// function that nothing else in the output declares, the backend @@ -180,6 +187,19 @@ pub struct ElementSegment { pub elements: Vec, } +/// An active element segment of a parsed module. Its entries are part +/// of `TableData::func_elements`. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ActiveElementSegment { + /// The index of this segment in the module's element segment index + /// space. + pub index: usize, + /// The table the segment writes to. + pub table: Table, + /// The type of the segment's elements. + pub ty: Type, +} + /// A function that an active element segment wrote into a table entry /// and a later active element segment overwrote. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -318,6 +338,7 @@ impl<'a> Module<'a> { custom_sections: BTreeMap::default(), passive_data_segments: vec![], element_segments: vec![], + active_element_segments: vec![], overwritten_elements: vec![], has_data_count: false, orig_data_segment_count: 0, @@ -363,6 +384,7 @@ impl<'a> Module<'a> { custom_sections: BTreeMap::default(), passive_data_segments: self.passive_data_segments, element_segments: self.element_segments, + active_element_segments: self.active_element_segments, overwritten_elements: self.overwritten_elements, has_data_count: self.has_data_count, orig_data_segment_count: self.orig_data_segment_count, @@ -466,6 +488,7 @@ impl<'a> Module<'a> { custom_sections: BTreeMap::default(), passive_data_segments: vec![], element_segments: vec![], + active_element_segments: vec![], overwritten_elements: vec![], has_data_count: false, orig_data_segment_count: 0, diff --git a/tests/segments.rs b/tests/segments.rs index 2333cee..edb4603 100644 --- a/tests/segments.rs +++ b/tests/segments.rs @@ -267,7 +267,10 @@ fn element_padding_is_passive_without_a_funcref_table_0() { "#, ) .unwrap(); - let output = reserialize(&input); + let mut module = Module::from_wasm_bytes(&input, &FrontendOptions::default()).unwrap(); + // This padding applies to indices without a recorded active segment. + module.active_element_segments.clear(); + let output = module.to_wasm_bytes().unwrap(); validate(&output); assert_eq!(segments(&output).elements, vec![(Mode::Passive, vec![])]); @@ -314,3 +317,35 @@ fn element_padding_needs_no_bulk_memory() { ElementItems::Expressions(..) => panic!("padding uses expressions"), } } + +fn validate_typed(bytes: &[u8]) { + let features = WasmFeatures::WASM2 | WasmFeatures::FUNCTION_REFERENCES; + if let Err(e) = Validator::new_with_features(features).validate_all(bytes) { + panic!("module does not validate: {}", e); + } +} + +#[test] +fn indices_keep_the_element_type_of_their_input_segment() { + let input = wat::parse_str( + r#" + (module + (type $t (func)) + (table $f 1 funcref) + (table $typed 1 (ref null $t)) + (elem (table $f) (i32.const 0) (ref null $t) (ref.func $g)) + (func $g (type $t) + (table.init $typed 0 (i32.const 0) (i32.const 0) (i32.const 0)))) + "#, + ) + .unwrap(); + let output = reserialize(&input); + validate_typed(&output); + + // Index 0 holds an empty `(ref null $t)` segment on `$f`, and the + // `funcref` segment for the contents of `$f` follows it. + assert_eq!( + segments(&output).elements, + vec![(Mode::Active, vec![]), (Mode::Active, vec![Some(0)])] + ); +}