Debian Codegraph @

fuzz/src/lib.rs

raw
1 use arbitrary::{Result, Unstructured};
2 use std::fmt::Debug;
3 use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
4 use wasm_smith::{Component, Config, Module};
5
6 pub mod incremental_parse;
7 pub mod mutate;
8 pub mod no_traps;
9 pub mod print;
10 pub mod reencode;
11 pub mod roundtrip;
12 pub mod roundtrip_wit;
13 pub mod text_parser;
14 pub mod validate;
15 pub mod validate_valid_module;
16 pub mod wit64;
17
18 pub fn generate_valid_module(
19 u: &mut Unstructured,
20 configure: impl FnOnce(&mut Config, &mut Unstructured<'_>) -> Result<()>,
21 ) -> Result<(Vec<u8>, Config)> {
22 let mut config: Config = u.arbitrary()?;
23
24 // These are disabled in the swarm config by default, but we want to test
25 // them. Use the input data to determine whether these features are enabled.
26 config.canonicalize_nans = u.arbitrary()?;
27 config.custom_page_sizes_enabled = u.arbitrary()?;
28 config.wide_arithmetic_enabled = u.arbitrary()?;
29 config.shared_everything_threads_enabled = u.arbitrary()?;
30
31 configure(&mut config, u)?;
32
33 // Use wasm-smith to generate an arbitrary module and convert it to wasm
34 // bytes.
35 let mut module = Module::new(config.clone(), u)?;
36 let bytes = module.to_bytes();
37
38 // 10% of the time, ish, test that the `ensure_termination` method will
39 // still produce a valid module.
40 if u.ratio(1, 10)? {
41 log::debug!("ensuring termination with 100 fuel");
42 let _ = module.ensure_termination(100);
43 }
44
45 log_wasm(&bytes, &config);
46
47 Ok((bytes, config))
48 }
49
50 pub fn generate_valid_component(
51 u: &mut Unstructured,
52 configure: impl FnOnce(&mut Config, &mut Unstructured<'_>) -> Result<()>,
53 ) -> Result<(Vec<u8>, Config)> {
54 let mut config: Config = u.arbitrary()?;
55
56 // These are disabled in the swarm config by default, but we want to test
57 // them. Use the input data to determine whether these features are enabled.
58 config.simd_enabled = u.arbitrary()?;
59 config.relaxed_simd_enabled = config.simd_enabled && u.arbitrary()?;
60 config.exceptions_enabled = u.arbitrary()?;
61 config.canonicalize_nans = u.arbitrary()?;
62
63 configure(&mut config, u)?;
64
65 // Use wasm-smith to generate an arbitrary component and convert it to wasm
66 // bytes.
67 let component = Component::new(config.clone(), u)?;
68 let bytes = component.to_bytes();
69
70 log_wasm(&bytes, &config);
71
72 Ok((bytes, config))
73 }
74
75 pub fn validator_for_config(config: &Config) -> wasmparser::Validator {
76 wasmparser::Validator::new_with_features(config.features())
77 }
78
79 // Optionally log the module and its configuration if we've gotten this
80 // far. Note that we don't do this unconditionally to avoid slowing down
81 // fuzzing, but this is expected to be enabled when debugging a failing
82 // fuzzer.
83 pub fn log_wasm(wasm: &[u8], config: impl Debug) {
84 drop(env_logger::try_init());
85
86 if !log::log_enabled!(log::Level::Debug) {
87 return;
88 }
89
90 static CNT: AtomicUsize = AtomicUsize::new(0);
91
92 let i = CNT.fetch_add(1, SeqCst);
93
94 let wasm_file = format!("test{i}.wasm");
95 let config_file = format!("test{i}.config");
96 let wat_file = format!("test{i}.wat");
97
98 log::debug!("writing test case to `{wasm_file}` ...");
99 std::fs::write(&wasm_file, wasm).unwrap();
100 std::fs::write(&config_file, format!("{config:#?}")).unwrap();
101 if let Ok(wat) = wasmprinter::print_bytes(wasm) {
102 log::debug!("writing text format to `{wat_file}` ...");
103 std::fs::write(&wat_file, wat).unwrap();
104 } else {
105 drop(std::fs::remove_file(&wat_file));
106 }
107 }
108 #[cfg(test)]
109 mod test {
110 use arbitrary::{Result, Unstructured};
111 use rand::{RngCore, SeedableRng, rngs::SmallRng};
112
113 fn gen_until_pass(mut f: impl FnMut(&mut Unstructured<'_>) -> Result<bool>) -> bool {
114 let mut rng = SmallRng::seed_from_u64(0);
115 let mut buf = vec![0; 2048];
116 let n = 3000;
117 for _ in 0..n {
118 rng.fill_bytes(&mut buf);
119 let mut u = Unstructured::new(&buf);
120
121 if f(&mut u).unwrap() {
122 return true;
123 }
124 }
125 false
126 }
127
128 /// Runs `f` with random data until it returns `Ok(())` `iters` times.
129 pub fn test_n_times(
130 iters: u32,
131 mut f: impl FnMut(&mut Unstructured<'_>) -> arbitrary::Result<()>,
132 ) {
133 let mut to_test = 0..iters;
134 let ok = gen_until_pass(|b| {
135 if f(b).is_ok() {
136 Ok(to_test.next().is_none())
137 } else {
138 Ok(false)
139 }
140 });
141 assert!(ok);
142 }
143 }