Debian Codegraph @

fuzz/fuzz_targets/fuzz_expr.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_expr::uumain;
11
12 use rand::RngExt;
13 use rand::prelude::IndexedRandom;
14 use std::{env, ffi::OsString};
15
16 use uufuzz::CommandResult;
17 use uufuzz::{compare_result, generate_and_run_uumain, generate_random_string, run_gnu_cmd};
18 static CMD_PATH: &str = "expr";
19
20 fn generate_expr(max_depth: u32) -> String {
21 let mut rng = rand::rng();
22 let ops = [
23 "+", "-", "*", "/", "%", "<", ">", "=", "&", "|", "!=", "<=", ">=", ":", "index", "length",
24 "substr",
25 ];
26
27 let mut expr = String::new();
28 let mut depth = 0;
29 let mut last_was_operator = false;
30
31 while depth <= max_depth {
32 if last_was_operator || depth == 0 {
33 // Add a number
34 expr.push_str(&rng.random_range(1..=100).to_string());
35 last_was_operator = false;
36 } else {
37 // 90% chance to add an operator followed by a number
38 if rng.random_bool(0.9) {
39 let op = *ops.choose(&mut rng).unwrap();
40 expr.push_str(&format!(" {op} "));
41 last_was_operator = true;
42 }
43 // 10% chance to add a random string (potentially invalid syntax)
44 else {
45 let random_str = generate_random_string(rng.random_range(1..=10));
46 expr.push_str(&random_str);
47 last_was_operator = false;
48 }
49 }
50 depth += 1;
51 }
52
53 // Ensure the expression ends with a number if it ended with an operator
54 if last_was_operator {
55 expr.push_str(&rng.random_range(1..=100).to_string());
56 }
57
58 expr
59 }
60
61 fuzz_target!(|_data: &[u8]| {
62 let mut rng = rand::rng();
63 let expr = generate_expr(rng.random_range(0..=20));
64 let mut args = vec![OsString::from("expr")];
65 args.extend(expr.split_whitespace().map(OsString::from));
66
67 // Use C locale to avoid false positives, like in https://github.com/uutils/coreutils/issues/5378,
68 // because uutils expr doesn't support localization yet
69 // TODO remove once uutils expr supports localization
70 unsafe {
71 env::set_var("LC_COLLATE", "C");
72 }
73 let rust_result = generate_and_run_uumain(&args, uumain, None);
74
75 let gnu_result = match run_gnu_cmd(CMD_PATH, &args[1..], false, None) {
76 Ok(result) => result,
77 Err(error_result) => {
78 eprintln!("Failed to run GNU command:");
79 eprintln!("Stderr: {}", error_result.stderr);
80 eprintln!("Exit Code: {}", error_result.exit_code);
81 CommandResult {
82 stdout: String::new(),
83 stderr: error_result.stderr,
84 exit_code: error_result.exit_code,
85 }
86 }
87 };
88
89 compare_result(
90 "expr",
91 &format!("{:?}", &args[1..]),
92 None,
93 &rust_result,
94 &gnu_result,
95 false, // Set to true if you want to fail on stderr diff
96 );
97 });