| 1 |
use arbitrary::{Result, Unstructured}; |
| 2 |
|
| 3 |
// Define a fuzz target that accepts arbitrary |
| 4 |
// `Module`s or `Component`s as input. |
| 5 |
pub fn run(u: &mut Unstructured<'_>) -> Result<()> { |
| 6 |
// We want to prioritize fuzzing of modules for the time being |
| 7 |
// so we'll only generate a component 10% of the time |
| 8 |
// |
| 9 |
// TODO: remove this `false && ...` once this fuzzer works again for |
| 10 |
// components. |
| 11 |
let generate_component = false |
| 12 |
&& match u.ratio::<u8>(1, 10) { |
| 13 |
Ok(b) => b, |
| 14 |
Err(_) => false, |
| 15 |
}; |
| 16 |
let (wasm_bytes, config) = if generate_component { |
| 17 |
crate::generate_valid_component(u, |c, u| { |
| 18 |
c.max_components = u.int_in_range(0..=1_000)?; |
| 19 |
c.max_instances = u.int_in_range(0..=1_000)?; |
| 20 |
c.max_values = u.int_in_range(0..=1_000)?; |
| 21 |
Ok(()) |
| 22 |
})? |
| 23 |
} else { |
| 24 |
crate::generate_valid_module(u, |_, _| Ok(()))? |
| 25 |
}; |
| 26 |
|
| 27 |
// Validate the module or component and assert that it passes validation. |
| 28 |
let mut validator = crate::validator_for_config(&config); |
| 29 |
if let Err(e) = validator.validate_all(&wasm_bytes) { |
| 30 |
let component_or_module = if generate_component { |
| 31 |
"component" |
| 32 |
} else { |
| 33 |
"module" |
| 34 |
}; |
| 35 |
panic!("Invalid {component_or_module}: {e}"); |
| 36 |
} |
| 37 |
|
| 38 |
// Round-trip `wasm_bytes` through text and back to binary. |
| 39 |
let wat_string = wasmprinter::print_bytes(&wasm_bytes).unwrap_or_else(|e| { |
| 40 |
panic!("failed first disassembly of Wasm into wat with `wasmprinter::print_bytes`: {e}") |
| 41 |
}); |
| 42 |
let wasm_bytes = wat::parse_str(&wat_string) |
| 43 |
.unwrap_or_else(|e| panic!("failed to assemble wat into Wasm with `wat::parse_str`: {e}")); |
| 44 |
crate::log_wasm(&wasm_bytes, &config); |
| 45 |
|
| 46 |
let mut wat_string2 = String::new(); |
| 47 |
// Now round-trip the result one more time, but this time with "folded |
| 48 |
// instructions" (e.g. s-expressions in the text format). |
| 49 |
wasmprinter::Config::new() |
| 50 |
.fold_instructions(true) |
| 51 |
.print( |
| 52 |
&wasm_bytes, |
| 53 |
&mut wasmprinter::PrintFmtWrite(&mut wat_string2), |
| 54 |
) |
| 55 |
.unwrap_or_else(|e| { |
| 56 |
panic!( |
| 57 |
"failed second disassembly of Wasm into wat with `wasmprinter::print_bytes`: {e}" |
| 58 |
) |
| 59 |
}); |
| 60 |
let wasm_bytes2 = wat::parse_str(&wat_string2) |
| 61 |
.unwrap_or_else(|e| panic!("failed to assemble wat into Wasm with `wat::parse_str`: {e}")); |
| 62 |
crate::log_wasm(&wasm_bytes2, &config); |
| 63 |
|
| 64 |
if wasm_bytes != wasm_bytes2 { |
| 65 |
panic!("failed to roundtrip valid module"); |
| 66 |
} |
| 67 |
Ok(()) |
| 68 |
} |
| 69 |
|
| 70 |
#[test] |
| 71 |
fn smoke() { |
| 72 |
super::test::test_n_times(100, run); |
| 73 |
} |