Skip to content

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

Clean up `gc_ops` fuzzing mutator (#12533)

Nick Fitzgerald06be78088b53
diff --git a/crates/fuzzing/src/generators/gc_ops/mutator.rs b/crates/fuzzing/src/generators/gc_ops/mutator.rs
index 9ed63b003e..a68af681bb 100644
--- a/crates/fuzzing/src/generators/gc_ops/mutator.rs
+++ b/crates/fuzzing/src/generators/gc_ops/mutator.rs
@@ -12,7 +12,7 @@ impl Mutate<GcOps> for GcOpsMutator {
if !c.shrink() {
c.mutation(|ctx| {
if let Some(idx) = ctx.rng().gen_index(ops.ops.len() + 1) {
- let op = GcOp::generate(ctx, &ops)?;
+ let op = GcOp::generate(ctx)?;
ops.ops.insert(idx, op);
}
Ok(())
diff --git a/crates/fuzzing/src/generators/gc_ops/ops.rs b/crates/fuzzing/src/generators/gc_ops/ops.rs
index 8d09e163a0..4b1f500829 100644
--- a/crates/fuzzing/src/generators/gc_ops/ops.rs
+++ b/crates/fuzzing/src/generators/gc_ops/ops.rs
@@ -5,7 +5,6 @@ use crate::generators::gc_ops::{
limits::GcOpsLimits,
types::{CompositeType, RecGroupId, StructType, TypeId, Types},
};
-use mutatis::{Context, Generate, mutators as m};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use wasm_encoder::{
@@ -315,7 +314,7 @@ impl GcOps {
let mut func = Function::new(local_decls);
func.instruction(&Instruction::Loop(wasm_encoder::BlockType::Empty));
for op in &self.ops {
- op.insert(&mut func, scratch_local, storage_bases);
+ op.encode(&mut func, scratch_local, storage_bases);
}
func.instruction(&Instruction::Br(0));
func.instruction(&Instruction::End);
@@ -353,56 +352,18 @@ impl GcOps {
let mut new_ops = Vec::with_capacity(self.ops.len());
let mut stack: Vec<StackType> = Vec::new();
- let num_types = u32::try_from(self.types.type_defs.len())
- .expect("types len should be within u32 range");
+ let num_types = u32::try_from(self.types.type_defs.len()).unwrap();
let mut operand_types = Vec::new();
-
- for mut op in self.ops.iter().copied() {
- if self.limits.max_types == 0
- && matches!(
- op,
- GcOp::StructNew(..)
- | GcOp::TakeStructCall(..)
- | GcOp::TakeTypedStructCall(..)
- | GcOp::TypedStructLocalSet(..)
- | GcOp::TypedStructLocalGet(..)
- | GcOp::TypedStructGlobalSet(..)
- | GcOp::TypedStructGlobalGet(..)
- | GcOp::TypedStructTableSet(..)
- | GcOp::TypedStructTableGet(..)
- | GcOp::StructTableSet(..)
- | GcOp::StructTableGet(..)
- | GcOp::StructLocalSet(..)
- | GcOp::StructLocalGet(..)
- | GcOp::StructGlobalSet(..)
- | GcOp::StructGlobalGet(..)
- )
- {
- continue;
- }
- if self.limits.num_params == 0 && matches!(op, GcOp::LocalGet(..) | GcOp::LocalSet(..))
- {
- continue;
- }
- if self.limits.num_globals == 0
- && matches!(op, GcOp::GlobalGet(..) | GcOp::GlobalSet(..))
- {
- continue;
- }
-
- op.fixup(&self.limits, num_types);
-
- let op = if let Some(op) = op.fixup(&self.limits, num_types) {
- op
- } else {
+ for op in &self.ops {
+ let Some(op) = op.fixup(&self.limits, num_types) else {
continue;
};
- operand_types.clear();
+ debug_assert!(operand_types.is_empty());
op.operand_types(&mut operand_types);
- for ty in &operand_types {
- StackType::fixup(*ty, &mut stack, &mut new_ops, num_types);
+ for ty in operand_types.drain(..) {
+ StackType::fixup(ty, &mut stack, &mut new_ops, num_types);
}
// Finally, emit the op itself (updates stack abstractly)
@@ -410,10 +371,12 @@ impl GcOps {
StackType::emit(op, &mut stack, &mut new_ops, num_types, &mut result_types);
}
- // Balance any leftovers with drops (works for any type)
+ // Drop any remaining values on the operand stack.
for _ in 0..stack.len() {
- new_ops.push(GcOp::Drop());
+ new_ops.push(GcOp::Drop);
}
+
+ log::trace!("ops after fixup: {new_ops:#?}");
self.ops = new_ops;
}
@@ -426,319 +389,490 @@ impl GcOps {
}
}
-macro_rules! define_gc_ops {
+macro_rules! for_each_gc_op {
+ ( $mac:ident ) => {
+ $mac! {
+ #[operands([])]
+ #[results([ExternRef, ExternRef, ExternRef])]
+ Gc,
+
+ #[operands([])]
+ #[results([ExternRef, ExternRef, ExternRef])]
+ MakeRefs,
+
+ #[operands([Some(ExternRef), Some(ExternRef), Some(ExternRef)])]
+ #[results([])]
+ TakeRefs,
+
+ #[operands([])]
+ #[results([ExternRef])]
+ #[fixup(|limits, _num_types| {
+ // Add one to make sure that out-of-bounds table accesses are
+ // possible, but still rare.
+ elem_index = elem_index % (limits.table_size + 1);
+ })]
+ TableGet { elem_index: u32 },
+
+ #[operands([Some(ExternRef)])]
+ #[results([])]
+ #[fixup(|limits, _num_types| {
+ // Add one to make sure that out-of-bounds table accesses are
+ // possible, but still rare.
+ elem_index = elem_index % (limits.table_size + 1);
+ })]
+ TableSet { elem_index: u32 },
+
+ #[operands([])]
+ #[results([ExternRef])]
+ #[fixup(|limits, _num_types| {
+ global_index = global_index.checked_rem(limits.num_globals)?;
+ })]
+ GlobalGet { global_index: u32 },
+
+ #[operands([Some(ExternRef)])]
+ #[results([])]
+ #[fixup(|limits, _num_types| {
+ global_index = global_index.checked_rem(limits.num_globals)?;
+ })]
+ GlobalSet { global_index: u32 },
+
+ #[operands([])]
+ #[results([ExternRef])]
+ #[fixup(|limits, _num_types| {
+ local_index = local_index.checked_rem(limits.num_params)?;
+ })]
+ LocalGet { local_index: u32 },
+
+ #[operands([Some(ExternRef)])]
+ #[results([])]
+ #[fixup(|limits, _num_types| {
+ local_index = local_index.checked_rem(limits.num_params)?;
+ })]
+ LocalSet { local_index: u32 },
+
+ #[operands([])]
+ #[results([Struct(Some(type_index))])]
+ #[fixup(|_limits, num_types| {
+ type_index = type_index.checked_rem(num_types)?;
+ })]
+ StructNew { type_index: u32 },
+
+ #[operands([Some(Struct(None))])]
+ #[results([])]
+ TakeStructCall,
+
+ #[operands([Some(Struct(Some(type_index)))])]
+ #[results([])]
+ #[fixup(|_limits, num_types| {
+ type_index = type_index.checked_rem(num_types)?;
+ })]
+ TakeTypedStructCall { type_index: u32 },
+
+ #[operands([Some(Struct(None))])]
+ #[results([])]
+ StructLocalSet,
+
+ #[operands([])]
+ #[results([Struct(None)])]
+ StructLocalGet,
+
+ #[operands([Some(Struct(Some(type_index)))])]
+ #[results([])]
+ #[fixup(|_limits, num_types| {
+ type_index = type_index.checked_rem(num_types)?;
+ })]
+ TypedStructLocalSet { type_index: u32 },
+
+ #[operands([])]
+ #[results([Struct(Some(type_index))])]
+ #[fixup(|_limits, num_types| {
+ type_index = type_index.checked_rem(num_types)?;
+ })]
+ TypedStructLocalGet { type_index: u32 },
+
+ #[operands([Some(Struct(None))])]
+ #[results([])]
+ StructGlobalSet,
+
+ #[operands([])]
+ #[results([Struct(None)])]
+ StructGlobalGet,
+
+ #[operands([Some(Struct(Some(type_index)))])]
+ #[results([])]
+ #[fixup(|_limits, num_types| {
+ type_index = type_index.checked_rem(num_types)?;
+ })]
+ TypedStructGlobalSet { type_index: u32 },
+
+ #[operands([])]
+ #[results([Struct(Some(type_index))])]
+ #[fixup(|_limits, num_types| {
+ type_index = type_index.checked_rem(num_types)?;
+ })]
+ TypedStructGlobalGet { type_index: u32 },
+
+ #[operands([Some(Struct(None))])]
+ #[results([])]
+ #[fixup(|limits, _num_types| {
+ // Add one to make sure that out-of-bounds table accesses are
+ // possible, but still rare.
+ elem_index = elem_index % (limits.table_size + 1);
+ })]
+ StructTableSet { elem_index: u32 },
+
+ #[operands([])]
+ #[results([Struct(None)])]
+ #[fixup(|limits, _num_types| {
+ // Add one to make sure that out-of-bounds table accesses are
+ // possible, but still rare.
+ elem_index = elem_index % (limits.table_size + 1);
+ })]
+ StructTableGet { elem_index: u32 },
+
+ #[operands([Some(Struct(Some(type_index)))])]
+ #[results([])]
+ #[fixup(|limits, num_types| {
+ // Add one to make sure that out-of-bounds table accesses are
+ // possible, but still rare.
+ elem_index = elem_index % (limits.table_size + 1);
+ type_index = type_index.checked_rem(num_types)?;
+ })]
+ TypedStructTableSet { elem_index: u32, type_index: u32 },
+
+ #[operands([])]
+ #[results([Struct(Some(type_index))])]
+ #[fixup(|limits, num_types| {
+ // Add one to make sure that out-of-bounds table accesses are
+ // possible, but still rare.
+ elem_index = elem_index % (limits.table_size + 1);
+ type_index = type_index.checked_rem(num_types)?;
+ })]
+ TypedStructTableGet { elem_index: u32, type_index: u32 },
+
+ #[operands([None])]
+ #[results([])]
+ Drop,
+
+ #[operands([])]
+ #[results([ExternRef])]
+ NullExtern,
+
+ #[operands([])]
+ #[results([Struct(None)])]
+ NullStruct,
+
+ #[operands([])]
+ #[results([Struct(Some(type_index))])]
+ #[fixup(|_limits, num_types| {
+ type_index = type_index.checked_rem(num_types)?;
+ })]
+ NullTypedStruct { type_index: u32 },
+ }
+ };
+}
+
+macro_rules! define_gc_op_variants {
(
$(
- $op:ident
- $( ( $($limit_var:ident : $limit:expr => $ty:ty),* ) )?
- : [ $($operand:expr),* $(,)? ] => [ $($result:expr),* $(,)? ] ,
+ $( #[$attr:meta] )*
+ $op:ident $( { $( $field:ident : $field_ty:ty ),* } )? ,
)*
) => {
-
/// The operations that can be performed by the `gc` function.
- #[derive(Copy, Clone, Debug, Serialize, Deserialize)]
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+ #[allow(missing_docs, reason = "self-describing")]
pub enum GcOp {
$(
- #[allow(missing_docs, reason = "macro-generated code")]
- $op ( $( $($ty),* )? ),
+ $op $( { $( $field : $field_ty ),* } )? ,
)*
}
+ };
+}
+for_each_gc_op!(define_gc_op_variants);
+macro_rules! define_op_names {
+ (
+ $(
+ $( #[$attr:meta] )*
+ $op:ident $( { $( $field:ident : $field_ty:ty ),* } )? ,
+ )*
+ ) => {
#[cfg(test)]
- pub(crate) const OP_NAMES: &'static [&'static str] = &[
- $( stringify!($op), )*
+ pub(crate) const OP_NAMES: &[&str] = &[
+ $(stringify!($op)),*
];
+ }
+}
+for_each_gc_op!(define_op_names);
- impl GcOp {
- #[cfg(test)]
- pub(crate) fn name(&self) -> &'static str {
- match self { $( Self::$op(..) => stringify!($op), )* }
- }
-
- #[allow(unreachable_patterns, reason = "macro-generated code")]
- pub(crate) fn operand_types(&self, out: &mut Vec<Option<StackType>>) {
-
+impl GcOp {
+ #[cfg(test)]
+ pub(crate) fn name(&self) -> &'static str {
+ macro_rules! define_gc_op_name {
+ (
+ $(
+ $( #[$attr:meta] )*
+ $op:ident $( { $( $field:ident : $field_ty:ty ),* } )? ,
+ )*
+ ) => {
match self {
- Self::TakeTypedStructCall(t) => {
- out.push(Some(StackType::Struct(Some(*t))));
- }
- Self::TypedStructLocalSet(t) => {
- out.push(Some(StackType::Struct(Some(*t))));
- }
- Self::TypedStructGlobalSet(t) => {
- out.push(Some(StackType::Struct(Some(*t))));
- }
- Self::TypedStructTableSet(_, t) => {
- out.push(Some(StackType::Struct(Some(*t))));
- }
$(
- Self::$op(..) => {
- $( out.push($operand); )*
- }
- ),*
+ Self::$op $( { $($field: _),* } )? => stringify!($op),
+ )*
}
- }
+ };
+ }
+ for_each_gc_op!(define_gc_op_name)
+ }
- #[allow(unreachable_patterns, reason = "macro-generated code")]
- pub(crate) fn result_types(&self, out: &mut Vec<StackType>) {
+ pub(crate) fn operand_types(&self, out: &mut Vec<Option<StackType>>) {
+ macro_rules! define_gc_op_operand_types {
+ (
+ $(
+ #[operands($operands:expr)]
+ $( #[$attr:meta] )*
+ $op:ident $( { $( $field:ident : $field_ty:ty ),* } )? ,
+ )*
+ ) => {{
+ use StackType::*;
match self {
- Self::StructNew(t) => {
- out.push(StackType::Struct(Some(*t)));
- }
- Self::TypedStructLocalGet(t) => {
- out.push(StackType::Struct(Some(*t)));
- }
- Self::TypedStructGlobalGet(t) => {
- out.push(StackType::Struct(Some(*t)));
- }
- Self::TypedStructTableGet(_, t) => {
- out.push(StackType::Struct(Some(*t)));
- }
- $( Self::$op(..) => { $( out.push($result); )* }, )*
+ $(
+ Self::$op $( { $($field),* } )? => {
+ $(
+ $(
+ #[allow(unused, reason = "macro code")]
+ let $field = *$field;
+ )*
+ )?
+ let operands: [Option<StackType>; _] = $operands;
+ out.extend(operands);
+ }
+ )*
}
- }
+ }};
+ }
+ for_each_gc_op!(define_gc_op_operand_types)
+ }
- pub(crate) fn fixup(&mut self, limits: &GcOpsLimits, num_types: u32) -> Option<Self> {
+ pub(crate) fn result_types(&self, out: &mut Vec<StackType>) {
+ macro_rules! define_gc_op_result_types {
+ (
+ $(
+ #[operands($operands:expr)]
+ #[results($results:expr)]
+ $( #[$attr:meta] )*
+ $op:ident $( { $( $field:ident : $field_ty:ty ),* } )? ,
+ )*
+ ) => {{
+ use StackType::*;
match self {
$(
- Self::$op( $( $( $limit_var ),* )? ) => {
- $( $(
- let limit_fn = $limit as fn(&GcOpsLimits) -> $ty;
- let limit = (limit_fn)(limits);
- if limit == 0 {
- return None;
- }
- *$limit_var = *$limit_var % limit;
- )* )?
+ Self::$op $( { $($field),* } )? => {
+ $(
+ $(
+ #[allow(unused, reason = "macro code")]
+ let $field = *$field;
+ )*
+ )?
+ let results: [StackType; _] = $results;
+ out.extend(results);
}
)*
}
+ }};
+ }
+ for_each_gc_op!(define_gc_op_result_types)
+ }
+
+ pub(crate) fn fixup(&self, limits: &GcOpsLimits, num_types: u32) -> Option<Self> {
+ macro_rules! define_gc_op_fixup {
+ (
+ $(
+ #[operands($operands:expr)]
+ #[results($results:expr)]
+ $( #[fixup(|$limits:ident, $num_types:ident| $fixup:expr)] )?
+ $op:ident $( { $( $field:ident : $field_ty:ty ),* } )? ,
+ )*
+ ) => {{
match self {
- Self::StructNew(t)
- | Self::TakeStructCall(t)
- | Self::TakeTypedStructCall(t)
- | Self::TypedStructLocalSet(t)
- | Self::TypedStructLocalGet(t)
- | Self::TypedStructGlobalSet(t)
- | Self::TypedStructGlobalGet(t)
- | Self::TypedStructTableSet(_, t)
- | Self::TypedStructTableGet(_, t)
-
- => {
- if num_types == 0 {
- return None;
+ $(
+ Self::$op $( { $($field),* } )? => {
+ $(
+ $(
+ #[allow(unused_mut, reason = "macro code")]
+ let mut $field = *$field;
+ )*
+ let $limits = limits;
+ let $num_types = num_types;
+ $fixup;
+ )?
+ Some(Self::$op $( { $( $field ),* } )? )
}
- *t %= num_types;
- }
- _ => {}
+ )*
}
+ }};
+ }
+ for_each_gc_op!(define_gc_op_fixup)
+ }
- Some(*self)
- }
-
- /// Generate an arbitrary op without stack-depth awareness.
- /// The fixup pass will make the sequence valid.
- pub(crate) fn generate(
- ctx: &mut mutatis::Context,
- ops: &GcOps,
- ) -> mutatis::Result<GcOp> {
- let mut valid_choices: Vec<
- fn(&mut Context, &GcOpsLimits) -> mutatis::Result<GcOp>
- > = vec![];
-
+ pub(crate) fn generate(ctx: &mut mutatis::Context) -> mutatis::Result<GcOp> {
+ macro_rules! define_gc_op_generate {
+ (
$(
- valid_choices.push($op);
+ $( #[$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(&valid_choices)
- .expect("should always have a valid op choice");
- (f)(ctx, &ops.limits)
- }
+ .choose(choices)
+ .unwrap();
+ (f)(ctx)
+ }};
}
+ for_each_gc_op!(define_gc_op_generate)
+ }
- $(
- #[allow(non_snake_case, reason = "macro-generated code")]
- fn $op(
- _ctx: &mut mutatis::Context,
- _limits: &GcOpsLimits,
- ) -> mutatis::Result<GcOp> {
- let op = GcOp::$op(
- $($({
- let limit_fn = $limit as fn(&GcOpsLimits) -> $ty;
- let limit = (limit_fn)(_limits);
- // Generate a value even if limit is 0; fixup will handle it
- if limit > 0 {
- m::range(0..=limit - 1).generate(_ctx)?
- } else {
- 0
- }
- }),*)?
- );
- Ok(op)
- }
- )*
- };
-}
-
-define_gc_ops! {
- Gc : [] => [StackType::ExternRef, StackType::ExternRef, StackType::ExternRef],
-
- MakeRefs : [] => [StackType::ExternRef, StackType::ExternRef, StackType::ExternRef],
- TakeRefs : [Some(StackType::ExternRef), Some(StackType::ExternRef), Some(StackType::ExternRef)] => [],
-
- // Add one to make sure that out of bounds table accesses are possible, but still rare.
- TableGet(elem_index: |ops| ops.table_size + 1 => u32)
- : [] => [StackType::ExternRef],
- TableSet(elem_index: |ops| ops.table_size + 1 => u32)
- : [Some(StackType::ExternRef)] => [],
-
- GlobalGet(global_index: |ops| ops.num_globals => u32)
- : [] => [StackType::ExternRef],
- GlobalSet(global_index: |ops| ops.num_globals => u32)
- : [Some(StackType::ExternRef)] => [],
-
- LocalGet(local_index: |ops| ops.num_params => u32)
- : [] => [StackType::ExternRef],
- LocalSet(local_index: |ops| ops.num_params => u32)
- : [Some(StackType::ExternRef)] => [],
-
- // `StructNew` result is special-cased to push `Struct(Some(t))`, so results list is empty.
- StructNew(type_index: |ops| ops.max_types => u32)
- : [] => [],
-
- TakeStructCall(type_index: |ops| ops.max_types => u32)
- : [Some(StackType::Struct(None))] => [],
-
- // `TakeTypedStructCall` operand is special-cased to require `Struct(Some(t))`, so operands list is empty.
- TakeTypedStructCall(type_index: |ops| ops.max_types => u32)
- : [] => [],
-
- StructLocalSet() : [Some(StackType::Struct(None))] => [],
- StructLocalGet() : [] => [StackType::Struct(None)],
- // `TypedStructLocalSet` operand is special-cased to require `Struct(Some(t))`, so operands list is empty.
- TypedStructLocalSet(type_index: |ops| ops.max_types => u32) : [] => [],
- // `TypedStructLocalGet` result is special-cased to push `Struct(Some(t))`, so results list is empty.
- TypedStructLocalGet(type_index: |ops| ops.max_types => u32) : [] => [],
-
- StructGlobalSet() : [Some(StackType::Struct(None))] => [],
- StructGlobalGet() : [] => [StackType::Struct(None)],
- // `TypedStructGlobalSet` operand is special-cased to require `Struct(Some(t))`, so operands list is empty.
- TypedStructGlobalSet(type_index: |ops| ops.max_types => u32) : [] => [],
- // `TypedStructGlobalGet` result is special-cased to push `Struct(Some(t))`, so results list is empty.
- TypedStructGlobalGet(type_index: |ops| ops.max_types => u32) : [] => [],
-
- StructTableSet(elem_index: |ops| ops.table_size => u32) : [Some(StackType::Struct(None))] => [],
- StructTableGet(elem_index: |ops| ops.table_size => u32) : [] => [StackType::Struct(None)],
- // `TypedStructTableSet` operand is special-cased to require `Struct(Some(t))`, so operands list is empty.
- TypedStructTableSet(elem_index: |ops| ops.table_size => u32, type_index: |ops| ops.max_types => u32) : [] => [],
- // `TypedStructTableGet` result is special-cased to push `Struct(Some(t))`, so results list is empty.
- TypedStructTableGet(elem_index: |ops| ops.table_size => u32, type_index: |ops| ops.max_types => u32) : [] => [],
-
- Drop : [None] => [],
-
- Null : [] => [StackType ::ExternRef],
-}
-
-impl GcOp {
- fn insert(self, func: &mut Function, scratch_local: u32, storage_bases: WasmEncodingBases) {
+ fn encode(&self, func: &mut Function, scratch_local: u32, encoding_bases: WasmEncodingBases) {
let gc_func_idx = 0;
let take_refs_func_idx = 1;
let make_refs_func_idx = 2;
let take_structref_idx = 3;
- match self {
- Self::Gc() => {
+ match *self {
+ Self::Gc => {
func.instruction(&Instruction::Call(gc_func_idx));
}
- Self::MakeRefs() => {
+ Self::MakeRefs => {
func.instruction(&Instruction::Call(make_refs_func_idx));
}
- Self::TakeRefs() => {
+ Self::TakeRefs => {
func.instruction(&Instruction::Call(take_refs_func_idx));
}
- Self::TableGet(x) => {
+ Self::TableGet { elem_index: x } => {
func.instruction(&Instruction::I32Const(x.cast_signed()));
func.instruction(&Instruction::TableGet(0));
}
- Self::TableSet(x) => {
+ Self::TableSet { elem_index: x } => {
func.instruction(&Instruction::LocalSet(scratch_local));
func.instruction(&Instruction::I32Const(x.cast_signed()));
func.instruction(&Instruction::LocalGet(scratch_local));
func.instruction(&Instruction::TableSet(0));
}
- Self::GlobalGet(x) => {
+ Self::GlobalGet { global_index: x } => {
func.instruction(&Instruction::GlobalGet(x));
}
- Self::GlobalSet(x) => {
+ Self::GlobalSet { global_index: x } => {
func.instruction(&Instruction::GlobalSet(x));
}
- Self::LocalGet(x) => {
+ Self::LocalGet { local_index: x } => {
func.instruction(&Instruction::LocalGet(x));
}
- Self::LocalSet(x) => {
+ Self::LocalSet { local_index: x } => {
func.instruction(&Instruction::LocalSet(x));
}
- Self::Drop() => {
+ Self::Drop => {
func.instruction(&Instruction::Drop);
}
- Self::Null() => {
+ Self::NullExtern => {
func.instruction(&Instruction::RefNull(wasm_encoder::HeapType::EXTERN));
}
- Self::StructNew(x) => {
- func.instruction(&Instruction::StructNew(x + storage_bases.struct_type_base));
+ Self::NullStruct => {
+ func.instruction(&Instruction::RefNull(wasm_encoder::HeapType::Abstract {
+ shared: false,
+ ty: wasm_encoder::AbstractHeapType::Struct,
+ }));
+ }
+ Self::NullTypedStruct { type_index } => {
+ func.instruction(&Instruction::RefNull(wasm_encoder::HeapType::Concrete(
+ encoding_bases.struct_type_base + type_index,
+ )));
}
- Self::TakeStructCall(_x) => {
+ Self::StructNew { type_index: x } => {
+ func.instruction(&Instruction::StructNew(encoding_bases.struct_type_base + x));
+ }
+ Self::TakeStructCall => {
func.instruction(&Instruction::Call(take_structref_idx));
}
- Self::TakeTypedStructCall(x) => {
- let f = storage_bases.typed_first_func_index + x;
+ Self::TakeTypedStructCall { type_index: x } => {
+ let f = encoding_bases.typed_first_func_index + x;
func.instruction(&Instruction::Call(f));
}
- Self::StructLocalGet() => {
- func.instruction(&Instruction::LocalGet(storage_bases.struct_local_idx));
+ Self::StructLocalGet => {
+ func.instruction(&Instruction::LocalGet(encoding_bases.struct_local_idx));
}
- Self::TypedStructLocalGet(x) => {
- func.instruction(&Instruction::LocalGet(storage_bases.typed_local_base + x));
+ Self::TypedStructLocalGet { type_index: x } => {
+ func.instruction(&Instruction::LocalGet(encoding_bases.typed_local_base + x));
}
- Self::StructLocalSet() => {
- func.instruction(&Instruction::LocalSet(storage_bases.struct_local_idx));
+ Self::StructLocalSet => {
+ func.instruction(&Instruction::LocalSet(encoding_bases.struct_local_idx));
}
- Self::TypedStructLocalSet(x) => {
- func.instruction(&Instruction::LocalSet(storage_bases.typed_local_base + x));
+ Self::TypedStructLocalSet { type_index: x } => {
+ func.instruction(&Instruction::LocalSet(encoding_bases.typed_local_base + x));
}
- Self::StructGlobalGet() => {
- func.instruction(&Instruction::GlobalGet(storage_bases.struct_global_idx));
+ Self::StructGlobalGet => {
+ func.instruction(&Instruction::GlobalGet(encoding_bases.struct_global_idx));
}
- Self::TypedStructGlobalGet(x) => {
- func.instruction(&Instruction::GlobalGet(storage_bases.typed_global_base + x));
+ Self::TypedStructGlobalGet { type_index: x } => {
+ func.instruction(&Instruction::GlobalGet(
+ encoding_bases.typed_global_base + x,
+ ));
}
- Self::StructGlobalSet() => {
- func.instruction(&Instruction::GlobalSet(storage_bases.struct_global_idx));
+ Self::StructGlobalSet => {
+ func.instruction(&Instruction::GlobalSet(encoding_bases.struct_global_idx));
}
- Self::TypedStructGlobalSet(x) => {
- func.instruction(&Instruction::GlobalSet(storage_bases.typed_global_base + x));
+ Self::TypedStructGlobalSet { type_index: x } => {
+ func.instruction(&Instruction::GlobalSet(
+ encoding_bases.typed_global_base + x,
+ ));
}
- Self::StructTableGet(elem_index) => {
+ Self::StructTableGet { elem_index } => {
func.instruction(&Instruction::I32Const(elem_index.cast_signed()));
- func.instruction(&Instruction::TableGet(storage_bases.struct_table_idx));
+ func.instruction(&Instruction::TableGet(encoding_bases.struct_table_idx));
}
- Self::TypedStructTableGet(elem_index, x) => {
+ Self::TypedStructTableGet {
+ elem_index,
+ type_index,
+ } => {
func.instruction(&Instruction::I32Const(elem_index.cast_signed()));
- func.instruction(&Instruction::TableGet(storage_bases.typed_table_base + x));
+ func.instruction(&Instruction::TableGet(
+ encoding_bases.typed_table_base + type_index,
+ ));
}
- Self::StructTableSet(elem_index) => {
+ Self::StructTableSet { elem_index } => {
// Use struct_local_idx (anyref) to temporarily store the value before table.set
- func.instruction(&Instruction::LocalSet(storage_bases.struct_local_idx));
+ func.instruction(&Instruction::LocalSet(encoding_bases.struct_local_idx));
func.instruction(&Instruction::I32Const(elem_index.cast_signed()));
- func.instruction(&Instruction::LocalGet(storage_bases.struct_local_idx));
- func.instruction(&Instruction::TableSet(storage_bases.struct_table_idx));
- }
- Self::TypedStructTableSet(elem_index, x) => {
- func.instruction(&Instruction::LocalSet(storage_bases.typed_local_base + x));
+ func.instruction(&Instruction::LocalGet(encoding_bases.struct_local_idx));
+ func.instruction(&Instruction::TableSet(encoding_bases.struct_table_idx));
+ }
+ Self::TypedStructTableSet {
+ elem_index,
+ type_index,
+ } => {
+ func.instruction(&Instruction::LocalSet(
+ encoding_bases.typed_local_base + type_index,
+ ));
func.instruction(&Instruction::I32Const(elem_index.cast_signed()));
- func.instruction(&Instruction::LocalGet(storage_bases.typed_local_base + x));
- func.instruction(&Instruction::TableSet(storage_bases.typed_table_base + x));
+ func.instruction(&Instruction::LocalGet(
+ encoding_bases.typed_local_base + type_index,
+ ));
+ func.instruction(&Instruction::TableSet(
+ encoding_bases.typed_table_base + type_index,
+ ));
}
}
}
diff --git a/crates/fuzzing/src/generators/gc_ops/tests.rs b/crates/fuzzing/src/generators/gc_ops/tests.rs
index dcb2568614..57f3073d8c 100644
--- a/crates/fuzzing/src/generators/gc_ops/tests.rs
+++ b/crates/fuzzing/src/generators/gc_ops/tests.rs
@@ -39,56 +39,72 @@ fn test_ops(num_params: u32, num_globals: u32, table_size: u32) -> GcOps {
max_types: 10,
},
ops: vec![
- GcOp::Null(),
- GcOp::Drop(),
- GcOp::Gc(),
- GcOp::LocalSet(0),
- GcOp::LocalGet(0),
- GcOp::GlobalSet(0),
- GcOp::GlobalGet(0),
- GcOp::StructNew(0),
+ GcOp::NullExtern,
+ GcOp::Drop,
+ GcOp::Gc,
+ GcOp::LocalSet { local_index: 0 },
+ GcOp::LocalGet { local_index: 0 },
+ GcOp::GlobalSet { global_index: 0 },
+ GcOp::GlobalGet { global_index: 0 },
+ GcOp::StructNew { type_index: 0 },
],
types: Types::new(),
};
+
for i in 0..t.limits.max_rec_groups {
t.types.insert_rec_group(RecGroupId(i));
}
+ let mut rng = StdRng::seed_from_u64(0xC0FFEE);
if t.limits.max_rec_groups > 0 {
- let mut rng = StdRng::seed_from_u64(0xC0FFEE);
for i in 0..t.limits.max_types {
let gid = RecGroupId(rng.gen_range(0..t.limits.max_rec_groups));
t.types.insert_empty_struct(TypeId(i), gid);
}
}
+
t
}
#[test]
fn mutate_gc_ops_with_default_mutator() -> mutatis::Result<()> {
let _ = env_logger::try_init();
- let mut res = test_ops(5, 5, 5);
- let mut session = mutatis::Session::new();
+ let mut features = wasmparser::WasmFeatures::default();
+ features.insert(wasmparser::WasmFeatures::REFERENCE_TYPES);
+ features.insert(wasmparser::WasmFeatures::FUNCTION_REFERENCES);
+ features.insert(wasmparser::WasmFeatures::GC_TYPES);
+ features.insert(wasmparser::WasmFeatures::GC);
+
+ let mut ops = test_ops(5, 5, 5);
+ let mut session = mutatis::Session::new();
for _ in 0..2048 {
- session.mutate(&mut res)?;
- let wasm = res.to_wasm_binary();
-
- 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}");
- assert!(
- result.is_ok(),
- "\n[-] Invalid wat: {}\n\t\t==== Failed Wat ====\n{}",
- result.err().expect("[-] Failed .err() in assert macro."),
- wat
- );
+ session.mutate(&mut ops)?;
+
+ let wasm = ops.to_wasm_binary();
+ crate::oracles::log_wasm(&wasm);
+
+ let mut validator = wasmparser::Validator::new_with_features(features);
+ if let Err(e) = validator.validate_all(&wasm) {
+ let mut config = wasmprinter::Config::new();
+ config.print_offsets(true);
+ config.print_operand_stack(true);
+ let mut wat = String::new();
+ let wat = match config.print(&wasm, &mut wasmprinter::PrintFmtWrite(&mut wat)) {
+ Ok(()) => wat,
+ Err(e) => format!("<failed to disassemble Wasm binary to WAT: {e}>"),
+ };
+ panic!(
+ "Emitted Wasm binary is not valid!\n\n\
+ === Validation Error ===\n\n\
+ {e}\n\n\
+ === GcOps ===\n\n\
+ {ops:#?}\n\n\
+ === Wat ===\n\n\
+ {wat}"
+ );
+ }
}
Ok(())
}
@@ -99,12 +115,13 @@ fn struct_new_removed_when_no_types() -> mutatis::Result<()> {
let mut ops = test_ops(0, 0, 0);
ops.limits.max_types = 0;
- ops.ops = vec![GcOp::StructNew(42)];
-
- let _ = ops.fixup();
+ ops.ops = vec![GcOp::StructNew { type_index: 42 }];
+ ops.fixup();
assert!(
- ops.ops.iter().all(|op| !matches!(op, GcOp::StructNew(..))),
+ ops.ops
+ .iter()
+ .all(|op| !matches!(op, GcOp::StructNew { .. })),
"StructNew should be removed when there are no types"
);
Ok(())
@@ -116,14 +133,16 @@ fn local_ops_removed_when_no_params() -> mutatis::Result<()> {
let mut ops = test_ops(0, 0, 0);
ops.limits.num_params = 0;
- ops.ops = vec![GcOp::LocalGet(42), GcOp::LocalSet(99)];
+ ops.ops = vec![
+ GcOp::LocalGet { local_index: 42 },
+ GcOp::LocalSet { local_index: 99 },
+ ];
ops.fixup();
-
assert!(
ops.ops
.iter()
- .all(|op| !matches!(op, GcOp::LocalGet(..) | GcOp::LocalSet(..))),
+ .all(|op| !matches!(op, GcOp::LocalGet { .. } | GcOp::LocalSet { .. })),
"LocalGet/LocalSet should be removed when there are no params"
);
Ok(())
@@ -135,14 +154,16 @@ fn global_ops_removed_when_no_globals() -> mutatis::Result<()> {
let mut ops = test_ops(0, 0, 0);
ops.limits.num_globals = 0;
- ops.ops = vec![GcOp::GlobalGet(42), GcOp::GlobalSet(99)];
+ ops.ops = vec![
+ GcOp::GlobalGet { global_index: 42 },
+ GcOp::GlobalSet { global_index: 99 },
+ ];
ops.fixup();
-
assert!(
ops.ops
.iter()
- .all(|op| !matches!(op, GcOp::GlobalGet(..) | GcOp::GlobalSet(..))),
+ .all(|op| !matches!(op, GcOp::GlobalGet { .. } | GcOp::GlobalSet { .. })),
"GlobalGet/GlobalSet should be removed when there are no globals"
);
Ok(())
@@ -170,129 +191,6 @@ fn every_op_generated() -> mutatis::Result<()> {
Ok(())
}
-#[test]
-fn test_wat_string() -> mutatis::Result<()> {
- let _ = env_logger::try_init();
-
- let mut gc_ops = test_ops(2, 2, 5);
-
- let wasm = gc_ops.to_wasm_binary();
-
- let actual_wat = wasmprinter::print_bytes(&wasm).expect("Failed to convert to WAT");
- let actual_wat = actual_wat.trim();
-
- let expected_wat = 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)))
- (type (;4;) (func (param structref)))
- (rec
- (type (;5;) (struct))
- )
- (rec)
- (rec
- (type (;6;) (struct))
- )
- (rec
- (type (;7;) (struct))
- (type (;8;) (struct))
- (type (;9;) (struct))
- )
- (rec
- (type (;10;) (struct))
- (type (;11;) (struct))
- )
- (rec
- (type (;12;) (struct))
- (type (;13;) (struct))
- )
- (rec
- (type (;14;) (struct))
- )
- (type (;15;) (func (param (ref null 5))))
- (type (;16;) (func (param (ref null 6))))
- (type (;17;) (func (param (ref null 7))))
- (type (;18;) (func (param (ref null 8))))
- (type (;19;) (func (param (ref null 9))))
- (type (;20;) (func (param (ref null 10))))
- (type (;21;) (func (param (ref null 11))))
- (type (;22;) (func (param (ref null 12))))
- (type (;23;) (func (param (ref null 13))))
- (type (;24;) (func (param (ref null 14))))
- (import "" "gc" (func (;0;) (type 0)))
- (import "" "take_refs" (func (;1;) (type 2)))
- (import "" "make_refs" (func (;2;) (type 3)))
- (import "" "take_struct" (func (;3;) (type 4)))
- (import "" "take_struct_5" (func (;4;) (type 15)))
- (import "" "take_struct_6" (func (;5;) (type 16)))
- (import "" "take_struct_7" (func (;6;) (type 17)))
- (import "" "take_struct_8" (func (;7;) (type 18)))
- (import "" "take_struct_9" (func (;8;) (type 19)))
- (import "" "take_struct_10" (func (;9;) (type 20)))
- (import "" "take_struct_11" (func (;10;) (type 21)))
- (import "" "take_struct_12" (func (;11;) (type 22)))
- (import "" "take_struct_13" (func (;12;) (type 23)))
- (import "" "take_struct_14" (func (;13;) (type 24)))
- (table (;0;) 5 externref)
- (table (;1;) 5 structref)
- (table (;2;) 5 (ref null 5))
- (table (;3;) 5 (ref null 6))
- (table (;4;) 5 (ref null 7))
- (table (;5;) 5 (ref null 8))
- (table (;6;) 5 (ref null 9))
- (table (;7;) 5 (ref null 10))
- (table (;8;) 5 (ref null 11))
- (table (;9;) 5 (ref null 12))
- (table (;10;) 5 (ref null 13))
- (table (;11;) 5 (ref null 14))
- (global (;0;) (mut externref) ref.null extern)
- (global (;1;) (mut externref) ref.null extern)
- (global (;2;) (mut structref) ref.null struct)
- (global (;3;) (mut (ref null 5)) ref.null 5)
- (global (;4;) (mut (ref null 6)) ref.null 6)
- (global (;5;) (mut (ref null 7)) ref.null 7)
- (global (;6;) (mut (ref null 8)) ref.null 8)
- (global (;7;) (mut (ref null 9)) ref.null 9)
- (global (;8;) (mut (ref null 10)) ref.null 10)
- (global (;9;) (mut (ref null 11)) ref.null 11)
- (global (;10;) (mut (ref null 12)) ref.null 12)
- (global (;11;) (mut (ref null 13)) ref.null 13)
- (global (;12;) (mut (ref null 14)) ref.null 14)
- (export "run" (func 14))
- (func (;14;) (type 1) (param externref externref)
- (local externref structref (ref null 5) (ref null 6) (ref null 7) (ref null 8) (ref null 9) (ref null 10) (ref null 11) (ref null 12) (ref null 13) (ref null 14))
- loop ;; label = @1
- ref.null extern
- drop
- call 0
- local.set 0
- local.get 0
- global.set 0
- global.get 0
- struct.new 5
- drop
- drop
- drop
- drop
- br 0 (;@1;)
- end
- )
-)
- "#;
- let expected_wat = expected_wat.trim();
-
- eprintln!("=== actual ===\n{actual_wat}");
- eprintln!("=== expected ===\n{expected_wat}");
- assert_eq!(
- actual_wat, expected_wat,
- "actual WAT does not match expected"
- );
-
- Ok(())
-}
-
#[test]
fn emits_empty_rec_groups_and_validates() -> mutatis::Result<()> {
let _ = env_logger::try_init();
@@ -324,67 +222,57 @@ fn emits_empty_rec_groups_and_validates() -> mutatis::Result<()> {
fn fixup_check_types_and_indexes() -> mutatis::Result<()> {
let _ = env_logger::try_init();
- // Create GcOps with 5 types so that 7 % 5 = 2
let mut ops = test_ops(5, 5, 5);
- ops.limits.max_types = 5;
- // We create max types 5 and out ouf bounds for the type index
+ // These `GcOp`s do not have their operands satisfied, and their results are
+ // not the operands of the next op, so `fixup` will need to deal with
+ // that. Additionally, their immediates are out-of-bounds of their
+ // respective index spaces, which `fixup` will also need to address.
ops.ops = vec![
- GcOp::TakeTypedStructCall(27),
- GcOp::GlobalSet(0),
- GcOp::StructNew(24),
- GcOp::LocalSet(0),
+ GcOp::TakeTypedStructCall {
+ type_index: ops.limits.max_types + 7,
+ },
+ GcOp::GlobalSet {
+ global_index: ops.limits.num_globals * 2,
+ },
+ GcOp::StructNew {
+ type_index: ops.limits.max_types + 9,
+ },
+ GcOp::LocalSet {
+ local_index: ops.limits.num_params * 5,
+ },
];
- // Call fixup to resolve dependencies
- // this should fix the types by inserting missing types
- // also put the indexes in the correct bounds
+ // Call `fixup` to insert missing types, rewrite the immediates such that
+ // they are within their bounds, insert missing operands, and drop unused
+ // results.
ops.fixup();
- // Verify that fixup()
- // The expected sequence should be:
- // 1. StructNew(_) - inserted by fixup to satisfy TakeTypedStructCall(_)
- // 2. TakeTypedStructCall(_) - now has Struct(_) on stack
- // 3. Null() - inserted by fixup to satisfy GlobalSet(0)
- // 4. GlobalSet(0) - now has ExternRef on stack
- // 5. StructNew(_) - produces Struct(_)
- // 6. Null() - inserted by fixup to satisfy LocalSet(0)
- // 7. LocalSet(0) - now has ExternRef on stack
- // 8. Drop() - inserted by fixup to consume ExternRef before Drop()
-
- // This is the expected sequence in wat format:
- // loop ;; label = @1
- // struct.new 7
- // call 6
- // ref.null extern
- // global.set 0
- // struct.new 9
- // ref.null extern
- // local.set 0
- // drop
- // br 0 (;@1;)
- // end
-
- // Find the index of TakeTypedStructCall(_) after fixup
- let take_call_idx = ops
- .ops
- .iter()
- .position(|op| matches!(op, GcOp::TakeTypedStructCall(_)))
- .expect("TakeTypedStructCall(_) should be present after fixup");
-
- // Verify that StructNew(_) appears before TakeTypedStructCall(_)
- let struct_new_2_before = ops
- .ops
- .iter()
- .take(take_call_idx)
- .any(|op| matches!(op, GcOp::StructNew(_)));
-
- assert!(
- struct_new_2_before,
- "fixup should insert StructNew(_) before TakeTypedStructCall(_) to satisfy the dependency"
+ // Check that we got the expected `GcOp` sequence after `fixup`:
+ assert_eq!(
+ ops.ops,
+ [
+ // Inserted by `fixup` to satisfy `TakeTypedStructCall`'s operands.
+ GcOp::StructNew { type_index: 7 },
+ // The `type_index` is now valid.
+ GcOp::TakeTypedStructCall { type_index: 7 },
+ // Inserted by `fixup` to satisfy `GlobalSet`'s operands.
+ GcOp::NullExtern,
+ // The `global_index` is now valid.
+ GcOp::GlobalSet { global_index: 0 },
+ // The `type_index` is now valid.
+ GcOp::StructNew { type_index: 9 },
+ // Inserted by `fixup` to satisfy `LocalSet`'s operands.
+ GcOp::NullExtern,
+ // The `local_index` is now valid.
+ GcOp::LocalSet { local_index: 0 },
+ // Inserted by `fixup` to make sure the operand stack is empty at
+ // the end of the block.
+ GcOp::Drop,
+ ]
);
- // Verify the sequence validates correctly
+ // Verify that we generate a valid Wasm binary after calling `fixup`.
let wasm = ops.to_wasm_binary();
let wat = wasmprinter::print_bytes(&wasm).unwrap();
log::debug!("{wat}");
diff --git a/crates/fuzzing/src/generators/gc_ops/types.rs b/crates/fuzzing/src/generators/gc_ops/types.rs
index fb51491950..1542aafafe 100644
--- a/crates/fuzzing/src/generators/gc_ops/types.rs
+++ b/crates/fuzzing/src/generators/gc_ops/types.rs
@@ -111,7 +111,7 @@ impl StackType {
match req {
None => {
if stack.is_empty() {
- Self::emit(GcOp::Null(), stack, out, num_types, &mut result_types);
+ Self::emit(GcOp::NullExtern, stack, out, num_types, &mut result_types);
}
stack.pop(); // always consume exactly one value
}
@@ -120,7 +120,7 @@ impl StackType {
stack.pop();
}
_ => {
- Self::emit(GcOp::Null(), stack, out, num_types, &mut result_types);
+ Self::emit(GcOp::NullExtern, stack, out, num_types, &mut result_types);
stack.pop(); // consume just-synthesized externref
}
},
@@ -135,11 +135,17 @@ impl StackType {
stack.pop();
} else {
// Ensure there *is* a struct to consume.
- let t = match wanted {
+ let type_index = match wanted {
Some(t) => Self::clamp(t, num_types),
None => Self::clamp(0, num_types),
};
- Self::emit(GcOp::StructNew(t), stack, out, num_types, &mut result_types);
+ Self::emit(
+ GcOp::StructNew { type_index },
+ stack,
+ out,
+ num_types,
+ &mut result_types,
+ );
stack.pop(); // consume the synthesized struct
}
}
diff --git a/crates/fuzzing/src/oracles.rs b/crates/fuzzing/src/oracles.rs
index 060bbaf863..9b89849c07 100644
--- a/crates/fuzzing/src/oracles.rs
+++ b/crates/fuzzing/src/oracles.rs
@@ -58,13 +58,16 @@ pub fn log_wasm(wasm: &[u8]) {
log::debug!("wrote wasm file to `{name}`");
let wat = format!("testcase{i}.wat");
match wasmprinter::print_bytes(wasm) {
- Ok(s) => std::fs::write(&wat, s).expect("failed to write wat file"),
+ Ok(s) => {
+ std::fs::write(&wat, s).expect("failed to write wat file");
+ log::debug!("wrote wat file to `{wat}`");
+ }
// If wasmprinter failed remove a `*.wat` file, if any, to avoid
// confusing a preexisting one with this wasm which failed to get
// printed.
Err(e) => {
log::debug!("failed to print to wat: {e}");
- drop(std::fs::remove_file(&wat))
+ drop(std::fs::remove_file(&wat));
}
}
}