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..8854253 100644 --- a/src/backend/mod.rs +++ b/src/backend/mod.rs @@ -2,13 +2,19 @@ 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, Table, + TableData, Type, Value, ValueDef, +}; use crate::Operator; use anyhow::Result; +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; @@ -1096,13 +1102,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); @@ -1173,43 +1183,150 @@ pub fn compile(module: &Module<'_>) -> anyhow::Result> { into_mod.section(&start); } - let mut elem = wasm_encoder::ElementSection::new(); + 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 (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!(), + // 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 &restores { + active_elements.push((*table, module.tables[*table].ty, *offset, &funcs[..])); + } + // 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 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 (index, slot) in element_slots.into_iter().enumerate() { + 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 => { + 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), + }; } } } 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 +1361,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 +1382,260 @@ 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. 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. +/// +/// 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. 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_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 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 { + if index < slots.len() { + anyhow::bail!("Two segments have the same segment index {}", index); + } + while slots.len() < index { + slots.push(next_free(slots.len())); + } + slots.push(SegmentSlot::Preserved(segment)); + } + while slots.len() < min_len { + slots.push(next_free(slots.len())); + } + slots.extend(active.into_iter().flatten().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(), + ), + )) +} + +/// 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] == before(i) { + i += 1; + continue; + } + let start = i; + while i < elts.len() && elts[i] != before(i) { + i += 1; + } + runs.push((start, &elts[start..i])); + } + 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 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 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, +) -> ( + Vec<(Table, usize, Vec)>, + Vec<(Table, usize, Vec)>, +) { + 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 { + 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 restores = vec![]; + for element in &module.overwritten_elements { + let table_data = &module.tables[element.table]; + let elts = match &table_data.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)); + 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)); + 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 +/// 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 +} + +/// 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 { @@ -1289,3 +1650,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..d308d09 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")] @@ -104,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>, @@ -156,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) @@ -221,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), }); } } @@ -276,11 +382,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 +506,42 @@ 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 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)?; let table_items = module.tables[table].func_elements.as_mut().unwrap(); let new_size = offset.checked_add(funcs.len()).ok_or_else(|| { @@ -445,7 +552,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: {:?}", @@ -454,6 +560,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[..]); } } @@ -2065,3 +2181,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..68f3bea 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}; @@ -277,13 +277,23 @@ 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)?; } } } + 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, @@ -300,6 +310,35 @@ 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.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", + 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..5854561 100644 --- a/src/ir/module.rs +++ b/src/ir/module.rs @@ -61,6 +61,39 @@ 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, + /// 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 + /// 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. + 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. @@ -107,12 +140,78 @@ 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()`. 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, +} + +/// 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)] +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 { @@ -237,6 +336,13 @@ impl<'a> Module<'a> { debug: Debug::default(), debug_map: DebugMap::default(), 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, + orig_element_segment_count: 0, } } @@ -276,6 +382,13 @@ 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, + 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, + orig_element_segment_count: self.orig_element_segment_count, } } @@ -373,6 +486,13 @@ impl<'a> Module<'a> { debug: Debug::default(), debug_map: DebugMap::default(), 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, + orig_element_segment_count: 0, } } } diff --git a/tests/element_segments.rs b/tests/element_segments.rs new file mode 100644 index 0000000..47e03b5 --- /dev/null +++ b/tests/element_segments.rs @@ -0,0 +1,169 @@ +//! 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)`. +/// `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![]; + 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, + Operator::RefNull { .. } => NULL, + 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])] + ); +} + +#[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![])] + ); +} diff --git a/tests/segments.rs b/tests/segments.rs new file mode 100644 index 0000000..edb4603 --- /dev/null +++ b/tests/segments.rs @@ -0,0 +1,351 @@ +//! 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 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![])]); +} + +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"), + } +} + +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)])] + ); +} 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 + ); +}