Debian Codegraph @

fuzz/fuzz_targets/fuzz_echo.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 #![no_main]
7
8 use libfuzzer_sys::fuzz_target;
9 use uu_echo::uumain;
10
11 use rand::RngExt;
12 use rand::prelude::IndexedRandom;
13 use std::ffi::OsString;
14
15 use uufuzz::CommandResult;
16 use uufuzz::{compare_result, generate_and_run_uumain, generate_random_string, run_gnu_cmd};
17
18 static CMD_PATH: &str = "echo";
19
20 fn generate_echo() -> String {
21 let mut rng = rand::rng();
22 let mut echo_str = String::new();
23
24 // Randomly decide whether to include options
25 let include_n = rng.random_bool(0.1); // 10% chance
26 let include_e = rng.random_bool(0.1); // 10% chance
27 #[allow(non_snake_case)]
28 let include_E = rng.random_bool(0.1); // 10% chance
29
30 if include_n {
31 echo_str.push_str("-n ");
32 }
33 if include_e {
34 echo_str.push_str("-e ");
35 }
36 if include_E {
37 echo_str.push_str("-E ");
38 }
39
40 // Add a random string
41 echo_str.push_str(&generate_random_string(rng.random_range(1..=10)));
42
43 // Include escape sequences if -e is enabled
44 if include_e {
45 // Add a 10% chance of including an escape sequence
46 if rng.random_bool(0.1) {
47 echo_str.push_str(&generate_escape_sequence(&mut rng));
48 }
49 }
50
51 echo_str
52 }
53
54 fn generate_escape_sequence(rng: &mut impl RngExt) -> String {
55 let escape_sequences = [
56 "\\\\", "\\a", "\\b", "\\c", "\\e", "\\f", "\\n", "\\r", "\\t", "\\v", "\\0NNN", "\\xHH",
57 ];
58 // \0NNN and \xHH need more work
59 escape_sequences.choose(rng).unwrap().to_string()
60 }
61
62 fuzz_target!(|_data: &[u8]| {
63 let echo_input = generate_echo();
64 let mut args = vec![OsString::from("echo")];
65 args.extend(echo_input.split_whitespace().map(OsString::from));
66 let rust_result = generate_and_run_uumain(&args, uumain, None);
67
68 let gnu_result = match run_gnu_cmd(CMD_PATH, &args[1..], false, None) {
69 Ok(result) => result,
70 Err(error_result) => {
71 eprintln!("Failed to run GNU command:");
72 eprintln!("Stderr: {}", error_result.stderr);
73 eprintln!("Exit Code: {}", error_result.exit_code);
74 CommandResult {
75 stdout: String::new(),
76 stderr: error_result.stderr,
77 exit_code: error_result.exit_code,
78 }
79 }
80 };
81
82 compare_result(
83 "echo",
84 &format!("{:?}", &args[1..]),
85 None,
86 &rust_result,
87 &gnu_result,
88 true,
89 );
90 });