Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Use derived and default mutators in the GC ops fuzzer (#14157)

Nick Fitzgeraldd57be54dd921
diff --git a/crates/fuzzing/src/generators/gc_ops/limits.rs b/crates/fuzzing/src/generators/gc_ops/limits.rs
index 79faddafd8..1b667a46a6 100644
--- a/crates/fuzzing/src/generators/gc_ops/limits.rs
+++ b/crates/fuzzing/src/generators/gc_ops/limits.rs
@@ -17,18 +17,23 @@ pub const MAX_REC_GROUPS_RANGE: RangeInclusive<u32> = 0..=10;
pub const MAX_FIELDS_RANGE: RangeInclusive<u32> = 0..=8;
/// Range for the length of created arrays.
pub const ARRAY_LENGTH_RANGE: RangeInclusive<u32> = 1..=16;
-/// Maximum number of operations.
-pub const MAX_OPS: usize = 100;
/// Limits controlling the structure of a generated Wasm module.
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Clone, Debug, Serialize, Deserialize, mutatis::Mutate)]
pub struct GcOpsLimits {
+ #[mutatis(default_mutate)]
pub(crate) num_params: u32,
+ #[mutatis(default_mutate)]
pub(crate) num_globals: u32,
+ #[mutatis(default_mutate)]
pub(crate) table_size: u32,
+ #[mutatis(default_mutate)]
pub(crate) max_rec_groups: u32,
+ #[mutatis(default_mutate)]
pub(crate) max_types: u32,
+ #[mutatis(default_mutate)]
pub(crate) max_fields: u32,
+ #[mutatis(default_mutate)]
pub(crate) array_length: u32,
}
@@ -59,15 +64,18 @@ impl GcOpsLimits {
array_length,
} = self;
- let clamp = |limit: &mut u32, range: RangeInclusive<u32>| {
- *limit = (*limit).clamp(*range.start(), *range.end())
+ let fixup = |limit: &mut u32, range: RangeInclusive<u32>| {
+ if !range.contains(limit) {
+ let (start, end) = (*range.start(), *range.end());
+ *limit = start + *limit % (end - start + 1);
+ }
};
- clamp(table_size, TABLE_SIZE_RANGE);
- clamp(num_params, NUM_PARAMS_RANGE);
- clamp(num_globals, NUM_GLOBALS_RANGE);
- clamp(max_rec_groups, MAX_REC_GROUPS_RANGE);
- clamp(max_types, MAX_TYPES_RANGE);
- clamp(max_fields, MAX_FIELDS_RANGE);
- clamp(array_length, ARRAY_LENGTH_RANGE);
+ fixup(table_size, TABLE_SIZE_RANGE);
+ fixup(num_params, NUM_PARAMS_RANGE);
+ fixup(num_globals, NUM_GLOBALS_RANGE);
+ fixup(max_rec_groups, MAX_REC_GROUPS_RANGE);
+ fixup(max_types, MAX_TYPES_RANGE);
+ fixup(max_fields, MAX_FIELDS_RANGE);
+ fixup(array_length, ARRAY_LENGTH_RANGE);
}
}
diff --git a/crates/fuzzing/src/generators/gc_ops/mutator.rs b/crates/fuzzing/src/generators/gc_ops/mutator.rs
index 5da1634ad4..a0ca1a35a5 100644
--- a/crates/fuzzing/src/generators/gc_ops/mutator.rs
+++ b/crates/fuzzing/src/generators/gc_ops/mutator.rs
@@ -1,9 +1,7 @@
//! Mutators for the `gc` operations.
use crate::generators::gc_ops::limits::GcOpsLimits;
-use crate::generators::gc_ops::ops::{GcOp, GcOps};
-use crate::generators::gc_ops::types::{
- ArrayType, CompositeType, FieldType, StructField, TypeId, Types,
-};
+use crate::generators::gc_ops::ops::{GcOp, GcOpMutator, GcOps};
+use crate::generators::gc_ops::types::{SubType, TypeId, Types};
use mutatis::{
Candidates, Context, DefaultMutate, Generate, Mutate, Result as MutResult, mutators as m,
};
@@ -16,53 +14,9 @@ use std::collections::BTreeMap;
pub struct TypesMutator;
impl TypesMutator {
- /// Add an empty struct in a random existing rec group, or create a rec group
- /// and add there when `rec_groups` is empty (if `limits.max_rec_groups` allows).
- fn add_struct(
- &mut self,
- c: &mut Candidates<'_>,
- types: &mut Types,
- limits: &GcOpsLimits,
- ) -> mutatis::Result<()> {
- if c.shrink() || types.type_defs.len() >= usize::try_from(limits.max_types).unwrap() {
- return Ok(());
- }
-
- let max_rec_groups = usize::try_from(limits.max_rec_groups).unwrap();
- if types.rec_groups.is_empty() && max_rec_groups == 0 {
- return Ok(());
- }
-
- c.mutation(|ctx| {
- let gid = if types.rec_groups.is_empty() {
- let new_gid = types.fresh_rec_group_id(ctx.rng());
- types.insert_rec_group(new_gid);
- new_gid
- } else {
- let Some(gid) = ctx.rng().choose(types.rec_groups.keys()).copied() else {
- return Ok(());
- };
- gid
- };
-
- let tid = types.fresh_type_id(ctx.rng());
- let is_final = (ctx.rng().gen_u32() % 4) == 0;
- let supertype = if (ctx.rng().gen_u32() % 4) == 0 {
- ctx.rng().choose(types.type_defs.keys()).copied()
- } else {
- None
- };
- // Add struct with no fields; fields can be added later by `mutate_type_members`.
- types.insert_struct(tid, gid, is_final, supertype, Vec::new());
- log::debug!("Added struct {tid:?} to rec group {gid:?}");
- Ok(())
- })?;
- Ok(())
- }
-
- /// Add an array type with a random element to a random existing rec group,
- /// or create a rec group when there are none (if `limits` allow).
- fn add_array(
+ /// Add a type with a randomly generated definition to a random existing rec
+ /// group, or create a rec group when there are none (if `limits` allow).
+ fn add_type(
&mut self,
c: &mut Candidates<'_>,
types: &mut Types,
@@ -72,52 +26,32 @@ impl TypesMutator {
return Ok(());
}
- let max_rec_groups = usize::try_from(limits.max_rec_groups).unwrap();
- if types.rec_groups.is_empty() && max_rec_groups == 0 {
+ if types.rec_groups.is_empty() && limits.max_rec_groups == 0 {
return Ok(());
}
c.mutation(|ctx| {
- let gid = if types.rec_groups.is_empty() {
- let new_gid = types.fresh_rec_group_id(ctx.rng());
- types.insert_rec_group(new_gid);
- new_gid
- } else {
- let Some(gid) = ctx.rng().choose(types.rec_groups.keys()).copied() else {
- return Ok(());
- };
- gid
+ let gid = match ctx.rng().choose(types.rec_groups.keys()).copied() {
+ Some(gid) => gid,
+ None => {
+ let new_gid = types.fresh_rec_group_id(ctx.rng());
+ types.insert_rec_group(new_gid);
+ new_gid
+ }
};
let tid = types.fresh_type_id(ctx.rng());
- let is_final = (ctx.rng().gen_u32() % 4) == 0;
- let supertype = if (ctx.rng().gen_u32() % 4) == 0 {
- ctx.rng().choose(types.type_defs.keys()).copied()
- } else {
- None
- };
+ let def = m::default::<SubType>().generate(ctx)?;
- // Arrays always have exactly one element, so generate it now.
- let candidates: Vec<TypeId> = types.type_defs.keys().copied().collect();
- let element = StructField {
- field_type: FieldType::generate(ctx.rng(), &candidates),
- mutable: (ctx.rng().gen_u32() % 2) == 0,
- };
- types.insert_type(
- tid,
- gid,
- is_final,
- supertype,
- CompositeType::Array(ArrayType { element }),
- );
- log::debug!("Added array {tid:?} to rec group {gid:?}");
+ types.insert_type(tid, gid, def.is_final, def.supertype, def.composite_type);
+ log::debug!("Added type {tid:?} to rec group {gid:?}");
Ok(())
})?;
Ok(())
}
/// Remove a random type from its rec group.
- fn remove_struct(&mut self, c: &mut Candidates<'_>, types: &mut Types) -> mutatis::Result<()> {
+ fn remove_type(&mut self, c: &mut Candidates<'_>, types: &mut Types) -> mutatis::Result<()> {
if types.type_defs.is_empty() {
return Ok(());
}
@@ -126,7 +60,7 @@ impl TypesMutator {
return Ok(());
};
types.remove_type(tid);
- log::debug!("Removed struct type {tid:?}");
+ log::debug!("Removed type {tid:?}");
Ok(())
})?;
Ok(())
@@ -271,22 +205,11 @@ impl TypesMutator {
return Ok(());
}
- // Collect (TypeId, is_final, supertype, composite_type) for members
- // of the source group (works for both structs and arrays).
- let members: SmallVec<[(TypeId, bool, Option<TypeId>, CompositeType); 32]> =
- src_members
- .iter()
- .filter_map(|tid| {
- types.type_defs.get(tid).map(|def| {
- (
- *tid,
- def.is_final,
- def.supertype,
- def.composite_type.clone(),
- )
- })
- })
- .collect();
+ // Snapshot the source group's members.
+ let members: SmallVec<[(TypeId, SubType); 32]> = src_members
+ .iter()
+ .filter_map(|tid| types.type_defs.get(tid).map(|def| (*tid, def.clone())))
+ .collect();
if members.is_empty() {
return Ok(());
@@ -298,20 +221,20 @@ impl TypesMutator {
// Allocate fresh type ids for each member and build old-to-new map.
let mut old_to_new: BTreeMap<TypeId, TypeId> = BTreeMap::new();
- for (old_tid, _, _, _) in &members {
+ for (old_tid, _) in &members {
old_to_new.insert(*old_tid, types.fresh_type_id(ctx.rng()));
}
// Insert duplicated defs, rewriting intra-group supertype edges to cloned ids.
- for (old_tid, is_final, supertype, composite_type) in &members {
+ for (old_tid, def) in &members {
let new_tid = old_to_new[old_tid];
- let mapped_super = supertype.map(|st| *old_to_new.get(&st).unwrap_or(&st));
+ let mapped_super = def.supertype.map(|st| *old_to_new.get(&st).unwrap_or(&st));
types.insert_type(
new_tid,
new_gid,
- *is_final,
+ def.is_final,
mapped_super,
- composite_type.clone(),
+ def.composite_type.clone(),
);
}
@@ -454,33 +377,6 @@ impl TypesMutator {
Ok(())
}
- /// Mutate struct fields (add/remove/modify via `m::vec`) and array elements.
- fn mutate_type_members(
- &mut self,
- c: &mut Candidates<'_>,
- types: &mut Types,
- ) -> mutatis::Result<()> {
- // Snapshot target types up front so fields can reference any type (incl. self) without borrowing `types`.
- let candidates: Vec<TypeId> = types.type_defs.keys().copied().collect();
- for (_, def) in types.type_defs.iter_mut() {
- match &mut def.composite_type {
- CompositeType::Struct(st) => {
- m::vec(StructFieldMutator {
- candidates: &candidates,
- })
- .mutate(c, &mut st.fields)?;
- }
- CompositeType::Array(at) => {
- StructFieldMutator {
- candidates: &candidates,
- }
- .mutate(c, &mut at.element)?;
- }
- }
- }
- Ok(())
- }
-
/// Run all type / rec-group mutations. [`GcOpsLimits`] come from [`GcOps`].
fn mutate_with_limits(
&mut self,
@@ -488,55 +384,25 @@ impl TypesMutator {
types: &mut Types,
limits: &GcOpsLimits,
) -> mutatis::Result<()> {
- self.add_struct(c, types, limits)?;
- self.add_array(c, types, limits)?;
- self.remove_struct(c, types)?;
+ self.add_type(c, types, limits)?;
+ self.remove_type(c, types)?;
self.swap_within_group(c, types)?;
self.move_between_groups(c, types)?;
self.duplicate_group(c, types, limits)?;
self.remove_group(c, types)?;
self.merge_groups(c, types)?;
self.split_group(c, types, limits)?;
- self.mutate_type_members(c, types)?;
- Ok(())
- }
-}
-
-/// Mutator for [`StructField`] (add/remove/modify fields).
-#[derive(Debug)]
-pub struct StructFieldMutator<'a> {
- candidates: &'a [TypeId],
-}
+ // Add, remove, rename, and redefine individual types, then let `fixup`
+ // clean things up.
+ m::btree_map(m::default::<TypeId>(), m::default::<SubType>())
+ .mutate(c, &mut types.type_defs)?;
-impl Mutate<StructField> for StructFieldMutator<'_> {
- fn mutate(&mut self, c: &mut Candidates<'_>, field: &mut StructField) -> MutResult<()> {
- c.mutation(|ctx| {
- let old = format!("{field:?}");
- field.field_type = FieldType::generate(ctx.rng(), self.candidates);
- field.mutable = (ctx.rng().gen_u32() % 2) == 0;
- log::debug!("Mutated field {old} -> {field:?}");
- Ok(())
- })?;
Ok(())
}
}
-impl Generate<StructField> for StructFieldMutator<'_> {
- fn generate(&mut self, ctx: &mut Context) -> MutResult<StructField> {
- let field = StructField {
- field_type: FieldType::generate(ctx.rng(), self.candidates),
- mutable: (ctx.rng().gen_u32() % 2) == 0,
- };
- log::debug!("Generated field {field:?}");
- Ok(field)
- }
-}
-
-/// Mutator for [`GcOps`].
-///
-/// Also implements [`Mutate`] / [`Generate`] for [`GcOp`] so `m::vec` can mutate
-/// `Vec<GcOp>` without a second struct.
+/// Mutator for `GcOps`.
#[derive(Debug, Default)]
pub struct GcOpsMutator {
types_mutator: TypesMutator,
@@ -544,17 +410,22 @@ pub struct GcOpsMutator {
impl Mutate<GcOp> for GcOpsMutator {
fn mutate(&mut self, c: &mut Candidates<'_>, value: &mut GcOp) -> MutResult<()> {
+ // The derived `GcOpMutator` is deliberately not `GcOp`'s default
+ // mutator: it offers one candidate per variant plus one per field, so
+ // across a test case's ops it would account for the overwhelming
+ // majority of the candidates and starve the type and rec-group
+ // mutations below. Every operand is an index that `fixup` normalizes
+ // anyway, so regenerating doesn't hurt.
c.mutation(|ctx| {
- *value = GcOp::generate(ctx)?;
+ *value = GcOpMutator::default().generate(ctx)?;
Ok(())
- })?;
- Ok(())
+ })
}
}
impl Generate<GcOp> for GcOpsMutator {
- fn generate(&mut self, context: &mut Context) -> MutResult<GcOp> {
- GcOp::generate(context)
+ fn generate(&mut self, ctx: &mut Context) -> MutResult<GcOp> {
+ GcOpMutator::default().generate(ctx)
}
}
@@ -563,8 +434,14 @@ impl DefaultMutate for GcOp {
}
impl Mutate<GcOps> for GcOpsMutator {
- fn mutate(&mut self, c: &mut Candidates<'_>, ops: &mut GcOps) -> mutatis::Result<()> {
- m::vec(GcOpsMutator::default()).mutate(c, &mut ops.ops)?;
+ fn mutate(&mut self, c: &mut Candidates<'_>, ops: &mut GcOps) -> MutResult<()> {
+ m::default::<GcOpsLimits>()
+ .map(|_ctx, limits: &mut GcOpsLimits| {
+ limits.fixup();
+ Ok(())
+ })
+ .mutate(c, &mut ops.limits)?;
+ m::vec(m::default::<GcOp>()).mutate(c, &mut ops.ops)?;
self.types_mutator
.mutate_with_limits(c, &mut ops.types, &ops.limits)?;
Ok(())
@@ -585,14 +462,12 @@ impl<'a> arbitrary::Arbitrary<'a> for GcOps {
}
impl Generate<GcOps> for GcOpsMutator {
- fn generate(&mut self, _ctx: &mut Context) -> MutResult<GcOps> {
+ fn generate(&mut self, ctx: &mut Context) -> MutResult<GcOps> {
let mut ops = GcOps::default();
- let mut session = mutatis::Session::new();
-
+ let mut session = mutatis::Session::new().seed(ctx.rng().gen_u64());
for _ in 0..2048 {
session.mutate(&mut ops)?;
}
-
Ok(ops)
}
}
diff --git a/crates/fuzzing/src/generators/gc_ops/ops.rs b/crates/fuzzing/src/generators/gc_ops/ops.rs
index 44cbda1673..59a65ec90a 100644
--- a/crates/fuzzing/src/generators/gc_ops/ops.rs
+++ b/crates/fuzzing/src/generators/gc_ops/ops.rs
@@ -5,6 +5,7 @@ use crate::generators::gc_ops::{
limits::GcOpsLimits,
types::{CompositeType, RecGroupId, TypeId, Types},
};
+use mutatis::Generate;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use wasm_encoder::{
@@ -49,7 +50,7 @@ struct WasmEncodingBases {
/// A description of a Wasm module that makes a series of `externref` table
/// operations.
-#[derive(Debug, Default, Serialize, Deserialize)]
+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct GcOps {
pub(crate) limits: GcOpsLimits,
pub(crate) ops: Vec<GcOp>,
@@ -1125,11 +1126,14 @@ macro_rules! define_gc_op_variants {
)*
) => {
/// The operations that can be performed by the `gc` function.
- #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+ #[derive(
+ Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, mutatis::Mutate,
+ )]
+ #[mutatis(default_mutate = false)]
#[allow(missing_docs, reason = "self-describing")]
pub enum GcOp {
$(
- $op $( { $( $field : $field_ty ),* } )? ,
+ $op $( { $( #[mutatis(default_mutate)] $field : $field_ty ),* } )? ,
)*
}
};
@@ -1278,36 +1282,6 @@ impl GcOp {
for_each_gc_op!(define_gc_op_fixup)
}
- pub(crate) fn generate(ctx: &mut mutatis::Context) -> mutatis::Result<GcOp> {
- macro_rules! define_gc_op_generate {
- (
- $(
- $( #[$attr:meta] )*
- $op:ident $( { $( $field:ident : $field_ty:ty ),* } )? ,
- )*
- ) => {{
- let choices: &[fn(&mut mutatis::Context) -> mutatis::Result<GcOp>] = &[
- $(
- |_ctx| Ok(GcOp::$op $( {
- $(
- $field: {
- let mut mutator = <$field_ty as mutatis::DefaultMutate>::DefaultMutate::default();
- mutatis::Generate::<$field_ty>::generate(&mut mutator, _ctx)?
- }
- ),*
- } )? ),
- )*
- ];
-
- let f = *ctx.rng()
- .choose(choices)
- .unwrap();
- (f)(ctx)
- }};
- }
- for_each_gc_op!(define_gc_op_generate)
- }
-
fn encode(
&self,
func: &mut Function,
diff --git a/crates/fuzzing/src/generators/gc_ops/tests.rs b/crates/fuzzing/src/generators/gc_ops/tests.rs
index f7aabde517..c0acfb4288 100644
--- a/crates/fuzzing/src/generators/gc_ops/tests.rs
+++ b/crates/fuzzing/src/generators/gc_ops/tests.rs
@@ -1,9 +1,12 @@
use crate::generators::gc_ops::{
limits::GcOpsLimits,
ops::{GcOp, GcOps, OP_NAMES},
- types::{RecGroupId, StackType, TypeId, Types},
+ types::{
+ ArrayType, CompositeType, FieldType, RecGroupId, StackType, StructField, TypeId, Types,
+ },
};
use mutatis;
+use mutatis::mutators as m;
use rand::rngs::StdRng;
use rand::{RngExt, SeedableRng};
use std::collections::BTreeSet;
@@ -117,18 +120,21 @@ fn test_ops(num_params: u32, num_globals: u32, table_size: u32) -> GcOps {
t
}
-/// Validate that a GcOps produces a valid Wasm binary.
-fn assert_valid_wasm(ops: &mut GcOps) {
+/// Check that a `GcOps` emits a valid Wasm binary, describing the failure if
+/// not.
+fn check_valid_wasm(ops: &GcOps) -> Result<(), String> {
+ let mut ops = ops.clone();
let wasm = ops.to_wasm_binary();
- let feats = wasmparser::WasmFeatures::default();
- feats.reference_types();
- feats.gc();
+ let feats = wasmparser::WasmFeatures::default()
+ | wasmparser::WasmFeatures::REFERENCE_TYPES
+ | wasmparser::WasmFeatures::GC
+ | wasmparser::WasmFeatures::GC_TYPES;
let mut validator = wasmparser::Validator::new_with_features(feats);
- if let Err(e) = validator.validate_all(&wasm) {
+ validator.validate_all(&wasm).map(|_| ()).map_err(|e| {
let wat =
wasmprinter::print_bytes(&wasm).unwrap_or_else(|e| format!("<disasm failed: {e}>"));
- panic!(
+ format!(
"Emitted Wasm binary is not valid!\n\n\
=== Validation Error ===\n\n\
{e}\n\n\
@@ -136,21 +142,58 @@ fn assert_valid_wasm(ops: &mut GcOps) {
{ops:#?}\n\n\
=== Wat ===\n\n\
{wat}"
- );
+ )
+ })
+}
+
+/// Validate that a GcOps produces a valid Wasm binary.
+fn assert_valid_wasm(ops: &GcOps) {
+ if let Err(e) = check_valid_wasm(ops) {
+ panic!("{e}");
}
}
#[test]
-fn mutate_gc_ops_with_default_mutator() -> mutatis::Result<()> {
+fn always_produces_valid_wasm() {
+ let _ = env_logger::try_init();
+
+ mutatis::check::Check::new()
+ .iters(2048)
+ .shrink_iters(1024)
+ .seed(0xC0FFEE)
+ .run_with(
+ m::default::<GcOps>(),
+ [test_ops(5, 5, 5), empty_test_ops(), cast_test_ops(vec![])],
+ check_valid_wasm,
+ )
+ .unwrap();
+}
+
+/// Every limit must stay inside its declared range under mutation.
+#[test]
+fn limits_stay_in_range() -> mutatis::Result<()> {
+ use crate::generators::gc_ops::limits::{
+ ARRAY_LENGTH_RANGE, MAX_FIELDS_RANGE, MAX_REC_GROUPS_RANGE, MAX_TYPES_RANGE,
+ NUM_GLOBALS_RANGE, NUM_PARAMS_RANGE, TABLE_SIZE_RANGE,
+ };
let _ = env_logger::try_init();
let mut ops = test_ops(5, 5, 5);
+ ops.limits.fixup();
- let mut session = mutatis::Session::new();
+ let mut session = mutatis::Session::new().seed(0xC0FFEE);
for _ in 0..2048 {
session.mutate(&mut ops)?;
- assert_valid_wasm(&mut ops);
+ let l = &ops.limits;
+ assert!(NUM_PARAMS_RANGE.contains(&l.num_params), "{l:?}");
+ assert!(NUM_GLOBALS_RANGE.contains(&l.num_globals), "{l:?}");
+ assert!(TABLE_SIZE_RANGE.contains(&l.table_size), "{l:?}");
+ assert!(MAX_REC_GROUPS_RANGE.contains(&l.max_rec_groups), "{l:?}");
+ assert!(MAX_TYPES_RANGE.contains(&l.max_types), "{l:?}");
+ assert!(MAX_FIELDS_RANGE.contains(&l.max_fields), "{l:?}");
+ assert!(ARRAY_LENGTH_RANGE.contains(&l.array_length), "{l:?}");
}
+
Ok(())
}
@@ -222,7 +265,7 @@ fn every_op_generated() -> mutatis::Result<()> {
let mut res = empty_test_ops();
let mut session = mutatis::Session::new().seed(0xC0FFEE);
- 'outer: for _ in 0..=8192 {
+ 'outer: for _ in 0..=32768 {
session.mutate(&mut res)?;
for op in &res.ops {
unseen_ops.remove(op.name());
@@ -272,7 +315,7 @@ fn i31_and_eq_upcast_ops_validate() -> mutatis::Result<()> {
GcOp::TypedStructRefAsEq { type_index: 0 },
GcOp::TakeEqCall,
];
- assert_valid_wasm(&mut ops);
+ assert_valid_wasm(&ops);
Ok(())
}
@@ -282,7 +325,7 @@ fn emits_rec_groups_and_validates() -> mutatis::Result<()> {
let _ = env_logger::try_init();
let mut ops = test_ops(5, 5, 5);
- assert_valid_wasm(&mut ops);
+ assert_valid_wasm(&ops);
let wasm = ops.to_wasm_binary();
let wat = wasmprinter::print_bytes(&wasm).expect("to WAT");
@@ -358,7 +401,7 @@ fn fixup_check_types_and_indexes() -> mutatis::Result<()> {
);
// Verify that we generate a valid Wasm binary after calling `fixup`.
- assert_valid_wasm(&mut ops);
+ assert_valid_wasm(&ops);
Ok(())
}
@@ -888,7 +931,7 @@ fn upcast_valid_pair() {
"valid upcast pair should be preserved: {:#?}",
ops.ops
);
- assert_valid_wasm(&mut ops);
+ assert_valid_wasm(&ops);
}
/// Case 2: wrong pair — repaired to sub's direct supertype.
@@ -915,7 +958,7 @@ fn upcast_wrong_pair_repaired_via_supertype() {
"upcast should be repaired to sub's direct supertype: {:#?}",
ops.ops
);
- assert_valid_wasm(&mut ops);
+ assert_valid_wasm(&ops);
}
/// Case 3: sub has no supertype — falls back to self-cast.
@@ -941,7 +984,7 @@ fn upcast_no_supertype_self_cast() {
"upcast with no supertype should become self-cast: {:#?}",
ops.ops
);
- assert_valid_wasm(&mut ops);
+ assert_valid_wasm(&ops);
}
/// Case 4: flat hierarchy (no supertypes at all) — self-cast.
@@ -965,7 +1008,7 @@ fn upcast_flat_hierarchy_self_cast() {
"upcast in flat hierarchy should become self-cast: {:#?}",
ops.ops
);
- assert_valid_wasm(&mut ops);
+ assert_valid_wasm(&ops);
}
// ---- RefCastDownward tests ----
@@ -992,7 +1035,7 @@ fn downcast_valid_pair() {
"valid downcast pair should be preserved: {:#?}",
ops.ops
);
- assert_valid_wasm(&mut ops);
+ assert_valid_wasm(&ops);
}
/// Case 2: wrong pair — super (operand) is kept, sub (result) is
@@ -1021,7 +1064,7 @@ fn downcast_wrong_pair_repaired_finds_subtype() {
"downcast should keep super and find a valid sub: {:#?}",
ops.ops
);
- assert_valid_wasm(&mut ops);
+ assert_valid_wasm(&ops);
}
/// Case 3: super has no subtypes — falls back to self-cast keeping
@@ -1048,7 +1091,7 @@ fn downcast_no_subtype_self_cast() {
"downcast with no subtypes should self-cast keeping super: {:#?}",
ops.ops
);
- assert_valid_wasm(&mut ops);
+ assert_valid_wasm(&ops);
}
/// Case 4: flat hierarchy — self-cast.
@@ -1072,5 +1115,69 @@ fn downcast_flat_hierarchy_self_cast() {
"downcast in flat hierarchy should become self-cast: {:#?}",
ops.ops
);
- assert_valid_wasm(&mut ops);
+ assert_valid_wasm(&ops);
+}
+
+/// `Types::fixup` must re-point dangling type references at live types rather
+/// than erasing them, because a mutated type id is essentially never live and
+/// erasing would leave the fuzzer with no concrete references and no subtyping.
+#[test]
+fn fixup_repoints_dangling_references() {
+ let limits = GcOpsLimits::default();
+ let gid = RecGroupId(0);
+ let mut types = Types::new();
+ types.insert_rec_group(gid);
+
+ // A final struct and an array: neither is a legal supertype for a
+ // non-final struct, so resolution must not pick either of them.
+ types.insert_struct(TypeId(10), gid, true, None, Vec::new());
+ types.insert_type(
+ TypeId(20),
+ gid,
+ false,
+ None,
+ CompositeType::Array(ArrayType {
+ element: StructField {
+ field_type: FieldType::I32,
+ mutable: false,
+ },
+ }),
+ );
+ // The one legal supertype.
+ types.insert_struct(TypeId(30), gid, false, None, Vec::new());
+
+ // The type under test: a dangling supertype and a dangling field
+ // reference, both pointing at ids that do not exist.
+ types.insert_struct(
+ TypeId(40),
+ gid,
+ false,
+ Some(TypeId(0xdead_beef)),
+ vec![StructField {
+ field_type: FieldType::Ref {
+ nullable: true,
+ type_id: TypeId(0xfeed_face),
+ },
+ mutable: false,
+ }],
+ );
+
+ types.fixup(&limits, &mut Vec::new());
+
+ let def = types.type_defs.get(&TypeId(40)).unwrap();
+ assert_eq!(
+ def.supertype,
+ Some(TypeId(30)),
+ "a dangling supertype must resolve to the one non-final struct, \
+ not to the final struct, the array, or `None`"
+ );
+
+ let field = &def.composite_type.fields()[0];
+ match field.field_type {
+ FieldType::Ref { type_id, .. } => assert!(
+ types.type_defs.contains_key(&type_id),
+ "a dangling reference must resolve to a live type, got {type_id:?}"
+ ),
+ ref other => panic!("dangling reference was erased instead of re-pointed: {other:?}"),
+ }
}
diff --git a/crates/fuzzing/src/generators/gc_ops/types.rs b/crates/fuzzing/src/generators/gc_ops/types.rs
index 04889ba402..2e691b6b94 100644
--- a/crates/fuzzing/src/generators/gc_ops/types.rs
+++ b/crates/fuzzing/src/generators/gc_ops/types.rs
@@ -2,6 +2,7 @@
use crate::generators::gc_ops::limits::GcOpsLimits;
use crate::generators::gc_ops::ops::GcOp;
+use mutatis::Generate;
use serde::{Deserialize, Serialize};
use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, BTreeSet, HashMap};
@@ -16,9 +17,20 @@ pub struct RecGroupId(pub(crate) u32);
/// Identifies a type within a rec group.
#[derive(
- Debug, Copy, Clone, Eq, PartialOrd, PartialEq, Ord, Hash, Default, Serialize, Deserialize,
+ Debug,
+ Copy,
+ Clone,
+ Eq,
+ PartialOrd,
+ PartialEq,
+ Ord,
+ Hash,
+ Default,
+ Serialize,
+ Deserialize,
+ mutatis::Mutate,
)]
-pub struct TypeId(pub(crate) u32);
+pub struct TypeId(#[mutatis(default_mutate)] pub(crate) u32);
macro_rules! for_each_field_type {
( $mac:ident ) => {
@@ -69,26 +81,34 @@ macro_rules! for_each_field_type {
macro_rules! define_field_type_enum {
( $( #[storage($storage:expr)] #[default_val($default_val:expr)] $variant:ident, )* ) => {
/// The storage type of a struct field.
- #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+ #[derive(
+ Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, mutatis::Mutate,
+ )]
#[allow(missing_docs, reason = "self-describing")]
pub enum FieldType {
$( $variant, )*
+
/// Abstract `(ref null? struct)`.
- StructRef { nullable: bool },
+ StructRef {
+ #[mutatis(ignore)]
+ nullable: bool,
+ },
+
/// Concrete `(ref null? $t)` referencing a defined struct type.
- Ref { nullable: bool, type_id: TypeId },
+ Ref {
+ // `nullable` is ignored because support for non-nullable
+ // references isn't implemented yet and so `Types::fixup`
+ // unconditionally forces it to `true`. Mutating it here would
+ // be a waste of time.
+ #[mutatis(ignore)]
+ nullable: bool,
+
+ #[mutatis(default_mutate)]
+ type_id: TypeId,
+ },
}
impl FieldType {
- /// All scalar/abstract-leaf field type variants, for random selection.
- pub const ALL: &[FieldType] = &[ $( FieldType::$variant, )* ];
-
- /// Pick a random scalar/abstract-leaf field type.
- pub fn random(rng: &mut mutatis::Rng) -> FieldType {
- let idx = rng.gen_index(FieldType::ALL.len()).unwrap();
- FieldType::ALL[idx]
- }
-
/// Convert to a `wasm_encoder::StorageType`.
pub fn to_storage_type(
self,
@@ -169,56 +189,40 @@ macro_rules! define_field_type_enum {
}
for_each_field_type!(define_field_type_enum);
-impl FieldType {
- /// Generate a random field type, including reference types.
- pub fn generate(rng: &mut mutatis::Rng, candidates: &[TypeId]) -> FieldType {
- match rng.gen_u32() % 4 {
- // Abstract `structref`.
- 0 => FieldType::StructRef { nullable: true },
- // Concrete `(ref null $t)`, when we have a type to point at.
- 1 => match rng.choose(candidates).copied() {
- Some(type_id) => FieldType::Ref {
- nullable: true,
- type_id,
- },
- None => FieldType::random(rng),
- },
- // Scalar / abstract-leaf type.
- _ => FieldType::random(rng),
- }
- }
-}
-
/// A single field within a struct type.
-#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, mutatis::Mutate)]
pub struct StructField {
/// The storage type of this field.
+ #[mutatis(default_mutate)]
pub(crate) field_type: FieldType,
/// Whether this field is mutable.
+ #[mutatis(default_mutate)]
pub(crate) mutable: bool,
}
/// A struct type definition.
-#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+#[derive(Clone, Debug, Default, Serialize, Deserialize, mutatis::Mutate)]
pub struct StructType {
/// The fields of this struct type.
+ #[mutatis(default_mutate)]
pub(crate) fields: Vec<StructField>,
}
/// An array type definition: a single element storage type plus mutability.
-#[derive(Clone, Debug, Serialize, Deserialize)]
+#[derive(Clone, Debug, Serialize, Deserialize, mutatis::Mutate)]
pub struct ArrayType {
/// The element storage type of this array type.
+ #[mutatis(default_mutate)]
pub(crate) element: StructField,
}
/// A composite type: either a struct or an array.
-#[derive(Clone, Debug, Serialize, Deserialize)]
+#[derive(Clone, Debug, Serialize, Deserialize, mutatis::Mutate)]
pub enum CompositeType {
/// A struct composite type.
- Struct(StructType),
+ Struct(#[mutatis(default_mutate)] StructType),
/// An array composite type.
- Array(ArrayType),
+ Array(#[mutatis(default_mutate)] ArrayType),
}
impl CompositeType {
@@ -227,8 +231,8 @@ impl CompositeType {
matches!(self, CompositeType::Array(_))
}
- /// The storage fields of this composite type.
- /// All struct fields or the single array element.
+ /// The storage fields of this composite type: all struct fields or the
+ /// single array element.
pub(crate) fn fields(&self) -> &[StructField] {
match self {
CompositeType::Struct(st) => &st.fields,
@@ -236,7 +240,7 @@ impl CompositeType {
}
}
- /// Mutable view of the storage fields; see [`CompositeType::fields`].
+ /// Mutable view of the storage fields.
pub(crate) fn fields_mut(&mut self) -> &mut [StructField] {
match self {
CompositeType::Struct(st) => &mut st.fields,
@@ -246,10 +250,13 @@ impl CompositeType {
}
/// A sub-type definition (the per-type payload).
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Clone, Debug, Serialize, Deserialize, mutatis::Mutate)]
pub struct SubType {
+ #[mutatis(default_mutate)]
pub(crate) is_final: bool,
+ #[mutatis(default_mutate)]
pub(crate) supertype: Option<TypeId>,
+ #[mutatis(default_mutate)]
pub(crate) composite_type: CompositeType,
}
@@ -377,7 +384,7 @@ impl Graph<RecGroupNode> for DenseRecGroupGraph {
///
/// Rec groups own sets of [`TypeId`]s; moving a type between groups is
/// just a set remove + set insert with no cascading index fixups.
-#[derive(Debug, Default, Serialize, Deserialize)]
+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Types {
/// Map from rec-group id to the set of types it contains.
pub(crate) rec_groups: BTreeMap<RecGroupId, BTreeSet<TypeId>>,
@@ -385,6 +392,24 @@ pub struct Types {
pub(crate) type_defs: BTreeMap<TypeId, SubType>,
}
+/// The live id at or after `id`, wrapping around, skipping `exclude`.
+fn nearest_live_type_id(
+ live: &BTreeSet<TypeId>,
+ id: TypeId,
+ exclude: Option<TypeId>,
+) -> Option<TypeId> {
+ // Type ids are drawn uniformly from the whole `u32` range (see
+ // `Types::fresh_type_id`), so walking the sorted id ring from an arbitrary
+ // starting point spreads resolutions evenly over the live
+ // types. Additionally, unlike indexing modulo the type count, it is also
+ // stable: adding or removing an unrelated type only changes the ids that
+ // fall in its immediate neighborhood.
+ live.range(id..)
+ .chain(live.range(..id))
+ .copied()
+ .find(|t| Some(*t) != exclude)
+}
+
impl Types {
/// Create empty type state.
pub fn new() -> Self {
@@ -685,6 +710,48 @@ impl Types {
}
}
+ /// Point every supertype edge at a type that may legally be a supertype:
+ /// one that exists, is not final, and has the same composite kind as the
+ /// subtype.
+ ///
+ /// This does not consider cycles; that is left to `break_supertype_cycles`.
+ fn fixup_supertypes(&mut self) {
+ // Only non-final types may be named as a supertype, and only by a
+ // subtype of the same composite kind.
+ let mut structs = BTreeSet::new();
+ let mut arrays = BTreeSet::new();
+ for (id, def) in self.type_defs.iter() {
+ if def.is_final {
+ continue;
+ }
+ if def.composite_type.is_array() {
+ arrays.insert(*id);
+ } else {
+ structs.insert(*id);
+ }
+ }
+
+ let ids: Vec<TypeId> = self.type_defs.keys().copied().collect();
+ for tid in ids {
+ let def = &self.type_defs[&tid];
+ let Some(supertype) = def.supertype else {
+ continue;
+ };
+ let candidates = if def.composite_type.is_array() {
+ &arrays
+ } else {
+ &structs
+ };
+ // A type cannot be its own supertype.
+ let resolved = if candidates.contains(&supertype) && supertype != tid {
+ Some(supertype)
+ } else {
+ nearest_live_type_id(candidates, supertype, Some(tid))
+ };
+ self.type_defs.get_mut(&tid).unwrap().supertype = resolved;
+ }
+ }
+
/// Fix up the types to ensure they are within the limits.
pub fn fixup(
&mut self,
@@ -736,47 +803,10 @@ impl Types {
}
}
- // 6. Clear supertypes that reference removed types.
- let valid_type_ids: BTreeSet<TypeId> = self.type_defs.keys().copied().collect();
- for def in self.type_defs.values_mut() {
- if let Some(st) = def.supertype {
- if !valid_type_ids.contains(&st) {
- def.supertype = None;
- }
- }
- }
+ // 6. Repair supertype edges.
+ self.fixup_supertypes();
- // 7. A subtype cannot have a final supertype.
- let final_type_ids: BTreeSet<TypeId> = self
- .type_defs
- .iter()
- .filter(|(_, d)| d.is_final)
- .map(|(id, _)| *id)
- .collect();
- for def in self.type_defs.values_mut() {
- if let Some(st) = def.supertype {
- if final_type_ids.contains(&st) {
- def.supertype = None;
- }
- }
- }
-
- // 7b. A subtype must have the same composite kind as its supertype
- // (a struct cannot subtype an array, or vice versa).
- let kinds: BTreeMap<TypeId, bool> = self
- .type_defs
- .iter()
- .map(|(id, d)| (*id, d.composite_type.is_array()))
- .collect();
- for (tid, def) in self.type_defs.iter_mut() {
- if let Some(super_id) = def.supertype {
- if kinds.get(&super_id) != kinds.get(tid) {
- def.supertype = None;
- }
- }
- }
-
- // 8. Trim struct fields to max_fields limit (arrays always have exactly
+ // 7. Trim struct fields to max_fields limit (arrays always have exactly
// one element).
let max_fields = usize::try_from(limits.max_fields).unwrap();
for def in self.type_defs.values_mut() {
@@ -785,16 +815,24 @@ impl Types {
}
}
- // 9. Normalize reference fields (struct fields and array elements alike).
+ // 8. Normalize reference fields (struct fields and array elements alike).
let valid_type_ids: BTreeSet<TypeId> = self.type_defs.keys().copied().collect();
for def in self.type_defs.values_mut() {
for field in def.composite_type.fields_mut() {
match &mut field.field_type {
FieldType::StructRef { nullable } => *nullable = true,
FieldType::Ref { nullable, type_id } => {
+ if !valid_type_ids.contains(type_id) {
+ if let Some(live) =
+ nearest_live_type_id(&valid_type_ids, *type_id, None)
+ {
+ *type_id = live;
+ }
+ }
if valid_type_ids.contains(type_id) {
*nullable = true;
} else {
+ // There are no types at all to point at.
field.field_type = FieldType::StructRef { nullable: true };
}
}
@@ -803,7 +841,7 @@ impl Types {
}
}
- // 10. Break supertype cycles and merge rec-group reference cycles, so
+ // 9. Break supertype cycles and merge rec-group reference cycles, so
// the type graph is well-founded before we encode it.
self.break_supertype_cycles();
let type_to_group = self.type_to_group_map();
@@ -812,7 +850,7 @@ impl Types {
// the encoding-order computation below.
let type_to_group = self.type_to_group_map();
- // 11. Ensure subtype fields are prefix-compatible with supertype fields.
+ // 10. Ensure subtype fields are prefix-compatible with supertype fields.
// Process in topological order (supertype before subtype).
let mut topo_order = Vec::new();
self.sort_types_topo(&mut topo_order);
@@ -826,7 +864,7 @@ impl Types {
let Some(super_def) = self.type_defs.get(&super_id) else {
continue;
};
- // Step 7b guarantees the subtype and supertype share a composite
+ // Step 6 guarantees the subtype and supertype share a composite
// kind. so match on the supertype and repair the subtype to match.
match &super_def.composite_type {
CompositeType::Struct(super_st) => {
@@ -861,7 +899,7 @@ impl Types {
debug_assert!(self.is_well_formed(limits));
- // 12. Compute encoding order (reuses type_to_group from step 10).
+ // 11. Compute encoding order (reuses type_to_group from step 9).
self.encoding_order_grouped(encoding_order_grouped, &type_to_group);
}