Debian Codegraph @

fuzz/fuzz_targets/fuzz_cut.rs

raw
1 // This file is part of the uutils coreutils package.
2 //
3 // For the full copyright and license information, please view the LICENSE
4 // file that was distributed with this source code.
5
6 // spell-checker:ignore parens
7
8 #![no_main]
9 use libfuzzer_sys::fuzz_target;
10 use uu_cut::uumain;
11
12 use rand::RngExt;
13 use std::ffi::OsString;
14
15 use uufuzz::{
16 CommandResult, compare_result, generate_and_run_uumain, generate_random_string, run_gnu_cmd,
17 };
18 static CMD_PATH: &str = "cut";
19
20 fn generate_cut_args() -> String {
21 let mut rng = rand::rng();
22 let arg_count = rng.random_range(1..=6);
23 let mut args = Vec::new();
24
25 for _ in 0..arg_count {
26 if rng.random_bool(0.1) {
27 args.push(generate_random_string(rng.random_range(1..=20)));
28 } else {
29 match rng.random_range(0..=4) {
30 0 => args.push(String::from("-b") + &rng.random_range(1..=10).to_string()),
31 1 => args.push(String::from("-c") + &rng.random_range(1..=10).to_string()),
32 2 => args.push(String::from("-d,") + &generate_random_string(1)), // Using a comma as a default delimiter
33 3 => args.push(String::from("-f") + &rng.random_range(1..=5).to_string()),
34 _ => (),
35 }
36 }
37 }
38
39 args.join(" ")
40 }
41
42 fn generate_delimited_data(count: usize) -> String {
43 let mut rng = rand::rng();
44 let mut lines = Vec::new();
45
46 for _ in 0..count {
47 let fields = (0..rng.random_range(1..=5))
48 .map(|_| generate_random_string(rng.random_range(1..=10)))
49 .collect::<Vec<_>>()
50 .join(",");
51 lines.push(fields);
52 }
53
54 lines.join("\n")
55 }
56
57 fuzz_target!(|_data: &[u8]| {
58 let cut_args = generate_cut_args();
59 let mut args = vec![OsString::from("cut")];
60 args.extend(cut_args.split_whitespace().map(OsString::from));
61
62 let input_lines = generate_delimited_data(10);
63
64 let rust_result = generate_and_run_uumain(&args, uumain, Some(&input_lines));
65 let gnu_result = match run_gnu_cmd(CMD_PATH, &args[1..], false, Some(&input_lines)) {
66 Ok(result) => result,
67 Err(error_result) => {
68 eprintln!("Failed to run GNU command:");
69 eprintln!("Stderr: {}", error_result.stderr);
70 eprintln!("Exit Code: {}", error_result.exit_code);
71 CommandResult {
72 stdout: String::new(),
73 stderr: error_result.stderr,
74 exit_code: error_result.exit_code,
75 }
76 }
77 };
78
79 compare_result(
80 "cut",
81 &format!("{:?}", &args[1..]),
82 Some(&input_lines),
83 &rust_result,
84 &gnu_result,
85 false, // Set to true if you want to fail on stderr diff
86 );
87 });