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 5be0944..b7f610e 100644 --- a/src/frontend.rs +++ b/src/frontend.rs @@ -89,6 +89,64 @@ 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> { + 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()); + } + _ => bail!(FrontendError::UnsupportedFeature(format!( + "Unsupported element segment item operator: {:?}", + op + ))), + } + } + funcs.push(func.unwrap_or(Func::invalid())); + } + funcs + } + }) +} + #[derive(Default)] struct ExtraSections<'a> { #[cfg(feature = "dwarf")] @@ -276,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, @@ -391,50 +458,33 @@ 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, } => { 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(|| { @@ -2065,3 +2115,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(_)) + )); + } +} 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, 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"), + } +}