A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Add initial empty rec groups (#11487)
Khagan (Khan) Karimov4c39cb92c7b8
diff --git a/crates/fuzzing/src/generators/table_ops.rs b/crates/fuzzing/src/generators/table_ops.rsindex 96d7666ae0..77e2e6fee0 100644--- a/crates/fuzzing/src/generators/table_ops.rs+++ b/crates/fuzzing/src/generators/table_ops.rs@@ -10,12 +10,42 @@ use wasm_encoder::{TypeSection, ValType,};+/// RecGroup ID struct definition.+#[derive(Debug, Clone, Eq, PartialOrd, PartialEq, Ord, Hash, Default, Serialize, Deserialize)]+pub struct RecGroupId(u32);++/// Struct types definition.+#[derive(Debug, Default, Serialize, Deserialize)]+pub struct Types {+ rec_groups: std::collections::BTreeSet<RecGroupId>,+}++impl Types {+ /// Create a fresh `Types` allocator with no recursive groups defined yet.+ pub fn new() -> Self {+ Self {+ rec_groups: Default::default(),+ }+ }++ /// Insert a rec-group id. Returns true if newly inserted, false if it already existed.+ pub fn insert_rec_group(&mut self, id: RecGroupId) -> bool {+ self.rec_groups.insert(id)+ }++ /// Iterate over all allocated recursive groups.+ pub fn groups(&self) -> impl Iterator<Item = &RecGroupId> {+ self.rec_groups.iter()+ }+}+/// Limits controlling the structure of a generated Wasm module.#[derive(Debug, Default, Serialize, Deserialize)]pub struct TableOpsLimits {pub(crate) num_params: u32,pub(crate) num_globals: u32,pub(crate) table_size: i32,+ pub(crate) num_rec_groups: u32,}/// A description of a Wasm module that makes a series of `externref` table@@ -24,11 +54,13 @@ pub struct TableOpsLimits {pub struct TableOps {pub(crate) limits: TableOpsLimits,pub(crate) ops: Vec<TableOp>,+ pub(crate) types: Types,}const NUM_PARAMS_RANGE: RangeInclusive<u32> = 0..=10;const NUM_GLOBALS_RANGE: RangeInclusive<u32> = 0..=10;const TABLE_SIZE_RANGE: RangeInclusive<i32> = 0..=100;+const NUM_REC_GROUPS_RANGE: RangeInclusive<u32> = 0..=10;const MAX_OPS: usize = 100;impl TableOps {@@ -49,15 +81,22 @@ impl TableOps {.limits.table_size.clamp(*TABLE_SIZE_RANGE.start(), *TABLE_SIZE_RANGE.end());+self.limits.num_params = self.limits.num_params.clamp(*NUM_PARAMS_RANGE.start(), *NUM_PARAMS_RANGE.end());+self.limits.num_globals = self.limits.num_globals.clamp(*NUM_GLOBALS_RANGE.start(), *NUM_GLOBALS_RANGE.end());+ self.limits.num_rec_groups = self+ .limits+ .num_rec_groups+ .clamp(*NUM_REC_GROUPS_RANGE.start(), *NUM_REC_GROUPS_RANGE.end());+let mut module = Module::new();// Encode the types for all functions that we are using.@@ -143,6 +182,11 @@ impl TableOps {func.instruction(&Instruction::End);func.instruction(&Instruction::End);+ // Emit one empty (rec ...) per declared group.+ for _ in self.types.groups() {+ types.ty().rec(Vec::<wasm_encoder::SubType>::new());+ }+let mut code = CodeSection::new();code.function(&func);@@ -217,7 +261,6 @@ pub struct TableOpsMutator;impl Mutate<TableOps> for TableOpsMutator {fn mutate(&mut self, c: &mut Candidates<'_>, ops: &mut TableOps) -> mutatis::Result<()> {- // Insertif !c.shrink() {c.mutation(|ctx| {if let Some(idx) = ctx.rng().gen_index(ops.ops.len() + 1) {@@ -229,8 +272,6 @@ impl Mutate<TableOps> for TableOpsMutator {Ok(())})?;}-- // Removeif !ops.ops.is_empty() {c.mutation(|ctx| {let idx = ctx@@ -272,11 +313,14 @@ impl Generate<TableOps> for TableOpsMutator {let num_globals = m::range(NUM_GLOBALS_RANGE).generate(ctx)?;let table_size = m::range(TABLE_SIZE_RANGE).generate(ctx)?;+ let num_rec_groups = m::range(NUM_REC_GROUPS_RANGE).generate(ctx)?;+let mut ops = TableOps {limits: TableOpsLimits {num_params,num_globals,table_size,+ num_rec_groups,},ops: vec![TableOp::Null(),@@ -287,8 +331,13 @@ impl Generate<TableOps> for TableOpsMutator {TableOp::GlobalSet(0),TableOp::GlobalGet(0),],+ types: Types::new(),};+ for i in 0..ops.limits.num_rec_groups {+ ops.types.insert_rec_group(RecGroupId(i));+ }+let mut stack: usize = 0;while ops.ops.len() < MAX_OPS {let (op, new_stack_len) = TableOp::generate(ctx, &ops, stack)?;@@ -497,24 +546,31 @@ mod tests {use super::*;/// Creates empty TableOps- fn empty_test_ops(num_params: u32, num_globals: u32, table_size: i32) -> TableOps {- TableOps {+ fn empty_test_ops() -> TableOps {+ let mut t = TableOps {limits: TableOpsLimits {- num_params,- num_globals,- table_size,+ num_params: 5,+ num_globals: 5,+ table_size: 5,+ num_rec_groups: 5,},ops: vec![],+ types: Types::new(),+ };+ for i in 0..t.limits.num_rec_groups {+ t.types.insert_rec_group(RecGroupId(i));}+ t}/// Creates TableOps with all default opcodesfn test_ops(num_params: u32, num_globals: u32, table_size: i32) -> TableOps {- TableOps {+ let mut t = TableOps {limits: TableOpsLimits {num_params,num_globals,table_size,+ num_rec_groups: 3,},ops: vec![TableOp::Null(),@@ -524,22 +580,40 @@ mod tests {TableOp::LocalGet(0),TableOp::GlobalSet(0),TableOp::GlobalGet(0),+ TableOp::Null(),+ TableOp::Drop(),+ TableOp::Gc(),+ TableOp::LocalSet(0),+ TableOp::LocalGet(0),+ TableOp::GlobalSet(0),+ TableOp::GlobalGet(0),+ TableOp::Null(),+ TableOp::Drop(),],+ types: Types::new(),+ };+ for i in 0..t.limits.num_rec_groups {+ t.types.insert_rec_group(RecGroupId(i));}+ t}#[test]fn mutate_table_ops_with_default_mutator() -> mutatis::Result<()> {let _ = env_logger::try_init();- use mutatis::Session;- use wasmparser::Validator;let mut res = test_ops(5, 5, 5);- let mut session = Session::new();++ let mut session = mutatis::Session::new();for _ in 0..1024 {session.mutate(&mut res)?;let wasm = res.to_wasm_binary();- let mut validator = Validator::new();++ let feats = wasmparser::WasmFeatures::default();+ feats.reference_types();+ feats.gc();+ let mut validator = wasmparser::Validator::new_with_features(feats);+let wat = wasmprinter::print_bytes(&wasm).expect("[-] Failed .print_bytes(&wasm).");let result = validator.validate_all(&wasm);log::debug!("{wat}");@@ -558,7 +632,7 @@ mod tests {let _ = env_logger::try_init();let mut unseen_ops: std::collections::HashSet<_> = OP_NAMES.iter().copied().collect();- let mut res = empty_test_ops(5, 5, 5);+ let mut res = empty_test_ops();let mut generator = TableOpsMutator;let mut session = mutatis::Session::new();@@ -580,69 +654,48 @@ mod tests {let _ = env_logger::try_init();let mut table_ops = test_ops(2, 2, 5);- table_ops.ops.extend([- TableOp::Null(),- TableOp::Drop(),- TableOp::Gc(),- TableOp::LocalSet(0),- TableOp::LocalGet(0),- TableOp::GlobalSet(0),- TableOp::GlobalGet(0),- TableOp::Null(),- TableOp::Drop(),- TableOp::Gc(),- TableOp::LocalSet(0),- TableOp::LocalGet(0),- TableOp::GlobalSet(0),- TableOp::GlobalGet(0),- TableOp::Null(),- TableOp::Drop(),- ]);+let wasm = table_ops.to_wasm_binary();let wat = wasmprinter::print_bytes(&wasm).expect("Failed to convert to WAT");let expected = r#"- (module- (type (;0;) (func (result externref externref externref)))- (type (;1;) (func (param externref externref)))- (type (;2;) (func (param externref externref externref)))- (type (;3;) (func (result externref externref externref)))- (import "" "gc" (func (;0;) (type 0)))- (import "" "take_refs" (func (;1;) (type 2)))- (import "" "make_refs" (func (;2;) (type 3)))- (table (;0;) 5 externref)- (global (;0;) (mut externref) ref.null extern)- (global (;1;) (mut externref) ref.null extern)- (export "run" (func 3))- (func (;3;) (type 1) (param externref externref)- (local externref)- loop ;; label = @1- ref.null extern- drop- call 0- local.set 0- local.get 0- global.set 0- global.get 0- ref.null extern- drop- call 0- local.set 0- local.get 0- global.set 0- global.get 0- ref.null extern- drop- call 0- local.set 0- local.get 0- global.set 0- global.get 0- ref.null extern- drop- br 0 (;@1;)- end- )- )+ (module+ (type (;0;) (func (result externref externref externref)))+ (type (;1;) (func (param externref externref)))+ (type (;2;) (func (param externref externref externref)))+ (type (;3;) (func (result externref externref externref)))+ (rec)+ (rec)+ (rec)+ (import "" "gc" (func (;0;) (type 0)))+ (import "" "take_refs" (func (;1;) (type 2)))+ (import "" "make_refs" (func (;2;) (type 3)))+ (table (;0;) 5 externref)+ (global (;0;) (mut externref) ref.null extern)+ (global (;1;) (mut externref) ref.null extern)+ (export "run" (func 3))+ (func (;3;) (type 1) (param externref externref)+ (local externref)+ loop ;; label = @1+ ref.null extern+ drop+ call 0+ local.set 0+ local.get 0+ global.set 0+ global.get 0+ ref.null extern+ drop+ call 0+ local.set 0+ local.get 0+ global.set 0+ global.get 0+ ref.null extern+ drop+ br 0 (;@1;)+ end+ )+ )"#;let generated = wat.split_whitespace().collect::<Vec<_>>().join(" ");@@ -651,4 +704,45 @@ mod tests {Ok(())}++ #[test]+ fn emits_empty_rec_groups_and_validates() -> mutatis::Result<()> {+ let _ = env_logger::try_init();++ let mut ops = TableOps {+ limits: TableOpsLimits {+ num_params: 2,+ num_globals: 1,+ table_size: 5,+ num_rec_groups: 2,+ },+ ops: vec![TableOp::Null(), TableOp::Drop()],+ types: Types::new(),+ };++ for i in 0..ops.limits.num_rec_groups {+ ops.types.insert_rec_group(RecGroupId(i));+ }++ let wasm = ops.to_wasm_binary();++ let feats = wasmparser::WasmFeatures::default();+ feats.reference_types();+ feats.gc();+ let mut validator = wasmparser::Validator::new_with_features(feats);+ assert!(+ validator.validate_all(&wasm).is_ok(),+ "GC validation failed"+ );++ let wat = wasmprinter::print_bytes(&wasm).expect("to WAT");+ let recs = wat.matches("(rec").count();+ let structs = wat.matches("(struct)").count();++ assert_eq!(recs, 2, "expected 2 (rec) blocks, got {recs}");+ // Still keep as zero. Will update in the next PR+ assert_eq!(structs, 0, "expected no struct types, got {structs}");++ Ok(())+ }}