Debian Codegraph @

crates/wasm-mutate-stats/src/bin/wasm-mutate-stats.rs

raw
1 use anyhow::Context;
2 use clap::Parser;
3 use core::sync::atomic::Ordering::{Relaxed, SeqCst};
4 use rand::Rng;
5 use rand::{SeedableRng, rngs::SmallRng};
6 use std::collections::hash_map::DefaultHasher;
7 use std::ffi::OsStr;
8 use std::fmt::Display;
9 use std::hash::{Hash, Hasher};
10 use std::path::{Path, PathBuf};
11 use std::sync::Mutex;
12 use std::sync::atomic::AtomicBool;
13 use std::time::Duration;
14 use std::{collections::HashMap, sync::Arc};
15 use std::{panic, process};
16 use wasm_mutate::WasmMutate;
17 use wasmtime::{Config, Engine, OptLevel};
18
19 #[derive(Debug)]
20 enum ParsingOptLevelError {
21 Parsing(String),
22 }
23
24 impl Display for ParsingOptLevelError {
25 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26 match self {
27 ParsingOptLevelError::Parsing(msg) => f.write_str(msg),
28 }
29 }
30 }
31
32 impl std::error::Error for ParsingOptLevelError {}
33
34 /// Parses the list of optimizations to set in wasmtime
35 fn parse_optimization_types(s: &str) -> Result<OptLevel, ParsingOptLevelError> {
36 match s {
37 "O0" => Ok(OptLevel::None),
38 "O2" => Ok(OptLevel::Speed),
39 "Os" => Ok(OptLevel::SpeedAndSize),
40 _ => Err(ParsingOptLevelError::Parsing(format!(
41 "Invalid optimization type {s}"
42 ))),
43 }
44 }
45
46 /// # Stats for wasm-mutate.
47 ///
48 /// `wasm-mutate-stats` is a benchmark to illustrate how many mutation of the same input Wasm can be generated
49 /// per time. This tool reads all Wasm in a folder (only in the root level) and for each Wasm file, it will iteratively
50 /// run the wasm-mutate tool until a timeout is reached. Every iteration mutates the previous mutated Wasm.
51 ///
52 /// The tool works in three main stages:
53 /// - Generate the mutations until timeout is reached.
54 /// - Compile the generated Wasm with the wasmtime engine to check for the preservation of the mutations
55 /// at low level.
56 /// - Generate a report.
57 ///
58 /// The final report illustrates, for each Wasm file in the input folder: how many unique mutations were generated,
59 /// and for each wasmtime configuration, how many of them still preserved.
60 ///
61 /// All the generated Wasm files are saved into al folder named **artifacts** in the same level of the input
62 /// folder.
63 ///
64 /// ## Example
65 /// `wasm-mutate-stats corpus 300 -c O0 -c O2 --triple x86_64-apple-darwin`
66 ///
67 /// The previous example will run wasm-mutate-stats over the folder corpus, with a timeout of 300 seconds,
68 /// checking preservation for O0(No optimizations) and O2(size and speed optimization), using architecture
69 /// triple `x86_64-apple-darwin`.
70 ///
71 #[derive(Parser)]
72 struct Options {
73 /// The input folder that contains the Wasm binaries.
74 input: PathBuf,
75 /// The timeout, 0 to wait for keyboard interrupt
76 timeout: u64,
77 /// The seed of the random mutation, 0 by default
78 #[clap(short = 's', long = "seed")]
79 seed: u64,
80 /// List of engine configurations.
81 /// Allowed values: [O0, O2, Os]
82 /// If it is not set, the default configuration of wasmtime will be used
83 #[clap(short = 'c', long = "compilation-configs", value_parser = parse_optimization_types)]
84 configs: Option<Vec<OptLevel>>,
85 /// Target triple during compilation, e.g. "x86_64-apple-darwin"
86 #[clap(short = 'a', long = "triple")]
87 triple: Option<String>,
88 /// Only generate report, if this option is set, it will skip the generation
89 #[clap(short = 'k', long = "skip")]
90 skip_generation: bool,
91 }
92
93 struct State {
94 // Tuples of filenames and the corresponding byte stream
95 corpus: Vec<(PathBuf, Vec<u8>)>,
96 // Engine used to compile the mutated Wasm
97 engines: Vec<(wasmtime::Engine, OptLevel)>,
98 // timeout_reached state
99 timeout_reached: AtomicBool,
100 // To avoid generation of mutations, just print report over preexisting folders
101 do_not_generate: bool,
102 // seed
103 seed: u64,
104 // timeout to stop generation
105 timeout: u64,
106 }
107
108 fn main() -> anyhow::Result<()> {
109 // Init logs
110 env_logger::init();
111
112 let opts = Options::parse();
113 let timeout = opts.timeout;
114 let seed = opts.seed;
115
116 let triple = &opts.triple;
117 let engines = opts
118 .configs
119 .map(|configs| {
120 configs
121 .iter()
122 .copied()
123 .map(|optlevel| {
124 let mut config = Config::default();
125 config.cranelift_opt_level(optlevel);
126 if let Some(triple) = triple {
127 config.target(triple).context("Invalid target")?;
128 }
129 Ok((
130 Engine::new(&config).context("Engine could not be initialized")?,
131 optlevel,
132 ))
133 })
134 .collect::<anyhow::Result<Vec<(Engine, OptLevel)>>>()
135 })
136 .or_else(|| Some(Ok(vec![]))) // To not compile the mutated Wasm is the default option, if no configs are passed
137 .context("Failed to created configurations")?;
138 // Start benchmarking
139 Arc::new(State::new(
140 opts.input,
141 engines?,
142 opts.skip_generation,
143 seed,
144 timeout,
145 )?)
146 .run()?;
147 Ok(())
148 }
149
150 impl State {
151 pub fn new(
152 input_folder: PathBuf,
153 engines: Vec<(Engine, OptLevel)>,
154 skip_generation: bool,
155 seed: u64,
156 timeout: u64,
157 ) -> anyhow::Result<Self> {
158 // Read corpus folder
159 let mut corpus = Vec::with_capacity(2000);
160 let entries = std::fs::read_dir(input_folder.clone())
161 .with_context(|| format!("failed to read directory {}", input_folder.display()))?;
162 for e in entries {
163 let e = e.context("failed to read dir entry")?;
164 if e.file_type()
165 .context("File type could not be retrieved")?
166 .is_file()
167 {
168 let seed = std::fs::read(e.path()).context("failed to read file content")?;
169 if e.path().extension() == Some(OsStr::new("wasm")) {
170 corpus.push((e.path(), seed));
171 }
172 }
173 }
174
175 Ok(State {
176 corpus,
177 timeout_reached: AtomicBool::new(false),
178 // Add many engines as configurations are passed
179 engines,
180 do_not_generate: skip_generation,
181 seed,
182 timeout,
183 })
184 }
185
186 fn run(self: &Arc<Self>) -> anyhow::Result<()> {
187 if self.corpus.is_empty() {
188 anyhow::bail!("No Wasm files into the directory");
189 }
190 // create a folder to save the mutated files
191 let artifact_folders = self
192 .corpus
193 .iter()
194 .map(|(name, _)| {
195 let filename = name.file_name().with_context(|| {
196 format!("File name could not be retrieved for {}", name.display())
197 })?;
198 let newfolder = self
199 .get_parent_folders(name.clone())?
200 .join(PathBuf::from("artifacts"))
201 .join(filename);
202
203 std::fs::create_dir_all(&newfolder).with_context(|| {
204 format!(
205 "Artifacts folder could not be created {}",
206 newfolder.display()
207 )
208 })?;
209 println!("Artifacts saved at {newfolder:?}");
210 Ok(newfolder)
211 })
212 .collect::<anyhow::Result<Vec<_>>>()?;
213
214 if !self.do_not_generate {
215 let elapsed = self.generate_wasm_files(&artifact_folders)?;
216 // Second stage, compile
217 for (wasmidx, (name, _)) in self.corpus.iter().enumerate() {
218 let filename = name
219 .file_name()
220 .with_context(|| format!("Unable to get file name for {}", name.display()))?;
221 let artifacts_folder = self
222 .get_parent_folders(name.clone())?
223 .join("artifacts")
224 .join(filename);
225
226 // Read dir looking for Wasm
227 let entries = std::fs::read_dir(&artifacts_folder).with_context(|| {
228 format!("Failed to read dir {}", artifacts_folder.display())
229 })?;
230
231 let mut worklist = Vec::new();
232 for e in entries {
233 let e = e.context("Failed to read dir entry")?;
234 if e.file_type()
235 .context("File type could not be retrieved")?
236 .is_file()
237 && e.path().extension() == Some(OsStr::new("wasm"))
238 {
239 worklist.push(e.path());
240 }
241 }
242 let files_count = worklist.clone().len();
243 println!(
244 "{} files generated (+ original) in {}.{:03} seconds for {}",
245 files_count,
246 elapsed.as_secs(),
247 elapsed.subsec_millis(),
248 name.display()
249 );
250 // Create shared worklist
251 // This is the second stage, to compile all saved Wasm
252 if !self.engines.is_empty() {
253 self.compile_and_save(&worklist, &artifact_folders[wasmidx])?;
254 }
255 }
256 }
257 for (wasmidx, (name, _)) in self.corpus.iter().enumerate() {
258 let filename = name.file_name().with_context(|| {
259 format!("File name could not be retrieved for {}", name.display())
260 })?;
261
262 println!("Input wasm \"{filename:?}\"");
263 let artifacts_folder = self
264 .get_parent_folders(name.clone())?
265 .join("artifacts")
266 .join(filename);
267
268 // Read dir looking for Wasm
269 let entries = std::fs::read_dir(&artifacts_folder)
270 .with_context(|| format!("Failed to read dir {}", artifacts_folder.display()))?;
271 let mut worklist = Vec::new();
272 for e in entries {
273 let e = e.context("failed to read dir entry")?;
274 if e.file_type()
275 .context("File type could not be retrieved")?
276 .is_file()
277 && e.path().extension() == Some(OsStr::new("wasm"))
278 {
279 worklist.push(e.path());
280 }
281 }
282 self.print_report(&artifact_folders[wasmidx], &worklist)?;
283 }
284 Ok(())
285 }
286
287 fn get_parent_folders(&self, path: PathBuf) -> anyhow::Result<PathBuf> {
288 Ok(path
289 .parent()
290 .context("corpus files always have a parent")?
291 .parent()
292 .context("corpus files always have a grandparent")?
293 .to_path_buf())
294 }
295
296 fn generate_wasm_files(
297 self: &Arc<Self>,
298 artifact_folders: &[PathBuf],
299 ) -> anyhow::Result<Duration> {
300 let generation_start = std::time::Instant::now();
301
302 let threads = (0..self.corpus.len())
303 .into_iter()
304 .map(|usize| {
305 let state = self.clone();
306 let artifact_folder = artifact_folders[usize].clone();
307 std::thread::spawn(move || state.generate(usize, state.seed, &artifact_folder))
308 })
309 .collect::<Vec<_>>();
310
311 // Sleep the main thread as many seconds are defined in the timeout
312 std::thread::sleep(std::time::Duration::new(self.timeout, 0));
313 // Send termination signal, false || true = true
314 self.timeout_reached.fetch_or(true, SeqCst);
315
316 for thread in threads {
317 // Expect all threads here
318 thread.join().expect("Thread panicked!")?;
319 }
320 let elapsed = generation_start.elapsed();
321
322 Ok(elapsed)
323 }
324
325 fn print_report(&self, artifact_folder: &Path, worklist: &[PathBuf]) -> anyhow::Result<()> {
326 let mut wasm_hashes = HashMap::new();
327
328 for w in worklist {
329 let data = std::fs::read(w).expect("Wasm file could not be read");
330 let h = self.hash(&data);
331
332 wasm_hashes
333 .entry(h)
334 .and_modify(|f: &mut Vec<_>| f.push(w.clone()))
335 .or_insert_with(|| vec![w.clone()]);
336 }
337 let whashes_len = wasm_hashes.len();
338 println!(
339 "\t{}/{} unique Wasm ({:.2}%)",
340 whashes_len,
341 worklist.len(),
342 100.0 * whashes_len as f64 / worklist.len() as f64
343 );
344
345 for (_, optlevel) in &self.engines {
346 self.print_report_compilation(artifact_folder, optlevel, whashes_len)?
347 }
348
349 Ok(())
350 }
351
352 fn print_report_compilation(
353 &self,
354 artifact_folder: &Path,
355 optlevel: &OptLevel,
356 number_of_wasm: usize,
357 ) -> anyhow::Result<()> {
358 let mut hashes = HashMap::new();
359 //let low_hashes = HashMap::new();
360 let objfolder = artifact_folder.join("obj").join(format!("{optlevel:?}"));
361 let entries = std::fs::read_dir(&objfolder)
362 .with_context(|| format!("failed to read dir {}", objfolder.display()))?;
363
364 for e in entries {
365 let e = e.context("failed to read dir entry")?;
366 if e.file_type()
367 .context("File type could not be retrieved")?
368 .is_file()
369 && e.path().extension() == Some(OsStr::new("obj"))
370 {
371 let data = std::fs::read(e.path()).with_context(|| {
372 format!("Object file could not be read {}", e.path().display())
373 })?;
374 let h = self.hash(&data);
375 hashes
376 .entry(h)
377 .and_modify(|f: &mut Vec<_>| f.push(e.path()))
378 .or_insert_with(|| vec![e.path()]);
379 }
380 }
381 let hashes_len = hashes.len();
382 println!(
383 "\t\t{}/{} unique objects for opt config ({:?}) ({:.2}%)",
384 hashes_len,
385 number_of_wasm,
386 optlevel,
387 100.0 * hashes_len as f64 / number_of_wasm as f64
388 );
389
390 Ok(())
391 }
392
393 fn compile_and_save(&self, worklist: &[PathBuf], artifact_folder: &Path) -> anyhow::Result<()> {
394 for (_, config) in &self.engines {
395 let newfolder = artifact_folder.join("obj").join(format!("{config:?}"));
396 std::fs::create_dir_all(&newfolder).with_context(|| {
397 format!(
398 "Artifacts folder {} could not be created",
399 newfolder.display()
400 )
401 })?;
402 }
403
404 for (entryidx, entry) in worklist.iter().enumerate() {
405 let data = std::fs::read(entry).context("failed to read seed file")?;
406 // Compile each configuration
407 // Spawn compilation
408 for (engine, optlevel) in &self.engines {
409 let module = wasmtime::Module::new(engine, &data).with_context(|| {
410 format!(
411 "The mutated Wasm should be valid, wasm file {:?}, config {:?}",
412 entry.display(),
413 optlevel,
414 )
415 })?;
416
417 let obj = module
418 .serialize()
419 .context("Wasm module could not be serialized")?;
420
421 // Save the obj to the file system as well
422
423 let filename = artifact_folder
424 .join("obj")
425 .join(format!("{optlevel:?}"))
426 .join(format!("{entryidx}.obj"));
427 std::fs::write(&filename, &obj)
428 .context("Aot file could be written to filesystem")?;
429 }
430 }
431 Ok(())
432 }
433
434 fn generate(
435 self: &Arc<Self>,
436 wasm_idx: usize,
437 seed: u64,
438 artifact_folder: &Path,
439 ) -> anyhow::Result<()> {
440 let mut wasmmutate = WasmMutate::default();
441 let (name, data) = &self.corpus[wasm_idx];
442 println!("Wasm input {}", name.display());
443 let mut wasm = data.clone();
444 let artifact_folder_cp = artifact_folder.to_path_buf();
445 // Generate until thread is interrupted
446 let to_write = Arc::new(Mutex::new(Vec::new()));
447 let to_write_clone = to_write.clone();
448 let finish_writing = AtomicBool::new(false);
449 let finish_writing_wrap = Arc::new(finish_writing);
450 let finish_writing_wrap_clone = finish_writing_wrap.clone();
451 // Spawn Wasm to file writer
452 let encoder = std::thread::spawn(move || -> anyhow::Result<()> {
453 let mut counter = 0;
454
455 while !finish_writing_wrap_clone.load(Relaxed) {
456 // pop from worklist
457 if let Some(wasm) = to_write_clone.lock().unwrap().pop() {
458 let filename = artifact_folder_cp.join(format!("mutated.{counter}.wasm"));
459 std::fs::write(filename, &wasm).context("Failed to write mutated wasm")?;
460 counter += 1;
461 }
462 }
463 eprintln!("Writing down pending mutated binaries!");
464 // Then write pending wasms
465 while let Some(wasm) = to_write_clone.lock().unwrap().pop() {
466 let filename = artifact_folder_cp.join(format!("mutated.{counter}.wasm"));
467
468 std::fs::write(filename, &wasm).context("Failed to write mutated wasm")?;
469 counter += 1;
470 }
471
472 Ok(())
473 });
474
475 // Save the original as well
476 to_write.lock().unwrap().push(wasm.clone());
477
478 let mut rng = SmallRng::seed_from_u64(seed);
479 let wasmcp = wasm.clone();
480
481 while !self.timeout_reached.load(Relaxed) {
482 let seed = rng.random();
483 wasmmutate.seed(seed);
484 wasmmutate.fuel(1000);
485 wasmmutate.preserve_semantics(true);
486
487 // Set a panic hook since some errors are not carried out, this looks more like a patch
488 let self_clone = self.clone();
489 let artifact_clone = artifact_folder.to_path_buf();
490 let finish_writing_wrap_clone2 = finish_writing_wrap.clone();
491
492 let data_clone = wasm.clone();
493 panic::set_hook(Box::new(move |panic_info| {
494 // invoke the default handler and exit the process
495 println!("Internal unhandled panic:\n{panic_info:?}!");
496 // stop generator
497 finish_writing_wrap_clone2.store(true, SeqCst);
498 // report current crash
499 if let Err(e) = self_clone.save_crash(&data_clone, None, seed, &artifact_clone) {
500 eprintln!("Failed to save crash: {e}");
501 }
502 process::exit(1);
503 }));
504
505 // First stage, generate and return the mutated
506 let it = match wasmmutate.run(&wasmcp) {
507 Ok(it) => it,
508 Err(e) => match e.kind() {
509 wasm_mutate::ErrorKind::NoMutationsApplicable => {
510 Box::new(std::iter::once(Ok(wasm.clone())))
511 }
512 _ => {
513 // Stop writing worker
514 finish_writing_wrap.store(true, SeqCst);
515 // Saving report
516 let h1 = self.hash(&wasm);
517 self.save_crash(&wasm, None, seed, artifact_folder)?;
518 anyhow::bail!(format!(
519 "Mutation invalid for entry {} seed {}.\n Crashing wasm is saved at crashes folder with name '<seed>.original.wasm'",
520 h1, seed
521 ))
522 }
523 },
524 };
525
526 for mutated in it {
527 let mut validator = wasmparser::Validator::new();
528 match mutated {
529 Ok(mutated) => {
530 match validator.validate_all(&mutated.clone()) {
531 Ok(_) => {
532 // send the bytes for storage and compilation to another worker
533 to_write.lock().unwrap().push(mutated.clone());
534 // FIXME, this will always set wasm to the result of the
535 // last mutation
536 wasm = mutated;
537 }
538 Err(_) => {
539 // Stop writing worker
540 finish_writing_wrap.store(true, SeqCst);
541 let h1 = self.hash(&wasm);
542 let h2 = self.hash(&mutated);
543 self.save_crash(&wasm, Some(&mutated), seed, artifact_folder)?;
544 anyhow::bail!(format!(
545 "All generated Wasm should be valid {} -> {}, seed {}",
546 h1, h2, seed
547 ));
548 }
549 }
550 }
551 Err(e) => {
552 // Stop writing worker
553 finish_writing_wrap.store(true, SeqCst);
554 self.save_crash(&wasm, None, seed, artifact_folder)?;
555 anyhow::bail!(format!("Error during module writing {:?}", e));
556 }
557 }
558 }
559 }
560
561 // Send signal to encoder to break infinite consumer loop
562 finish_writing_wrap.store(true, SeqCst);
563 encoder
564 .join()
565 .expect("Process exited or is not available")?;
566
567 Ok(())
568 }
569
570 fn save_crash(
571 &self,
572 wasm: &[u8],
573 mutated: Option<&[u8]>,
574 seed: u64,
575 artifacts_folder: &Path,
576 ) -> anyhow::Result<()> {
577 println!("Saving crash");
578 let newfolder = artifacts_folder.join("crashes");
579 std::fs::create_dir_all(&newfolder).with_context(|| {
580 format!("Crash folder could not be created {}", newfolder.display())
581 })?;
582
583 let newfile = newfolder.join(format!("{seed}.original.wasm"));
584
585 std::fs::write(&newfile, wasm)?;
586
587 // Saving the mutation if one
588
589 if let Some(mutated) = mutated {
590 let newfile = newfolder.join(format!("{seed}.mutated.wasm"));
591 std::fs::write(newfile, mutated)?;
592 }
593
594 println!("Crash saved with name {}", newfile.display());
595 Ok(())
596 }
597
598 fn hash(&self, data: &[u8]) -> u64 {
599 // Default hasher
600 let mut h = DefaultHasher::default();
601 data.hash(&mut h);
602 h.finish()
603 }
604 }