honggfuzz 0.5.60

Fuzz your Rust code with Google-developped Honggfuzz !
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
use rustc_version::Channel;
use std::env;
use std::fs;
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{self, Command, Stdio};

const VERSION: &str = env!("CARGO_PKG_VERSION");
const HONGGFUZZ_TARGET: &str = "hfuzz_target";
const HONGGFUZZ_WORKSPACE: &str = "hfuzz_workspace";

#[cfg(target_family = "windows")]
compile_error!("honggfuzz-rs does not currently support Windows but works well under WSL (Windows Subsystem for Linux)");

#[derive(PartialEq)]
enum BuildType {
    ReleaseInstrumented,
    ReleaseNotInstrumented,
    ProfileWithGrcov,
    Debug,
}

// TODO: maybe use `rustc_version` crate
fn target_triple() -> String {
    let output = Command::new("rustc").args(&["-v", "-V"]).output().unwrap();
    let stdout = String::from_utf8(output.stdout).unwrap();
    let triple = stdout
        .lines()
        .filter(|l| l.starts_with("host: "))
        .next()
        .unwrap()
        .get(6..)
        .unwrap();
    triple.into()
}

fn find_crate_root() -> Option<PathBuf> {
    let mut path = env::current_dir().unwrap();

    while !path.join("Cargo.toml").is_file() {
        // move to parent path
        path = match path.parent() {
            Some(parent) => parent.into(),
            None => return None, // early return
        };
    }

    Some(path)
}

fn debugger_command(target: &str) -> Command {
    let debugger = env::var("HFUZZ_DEBUGGER").unwrap_or_else(|_| "rust-lldb".into());
    let honggfuzz_target = env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| HONGGFUZZ_TARGET.into());

    let mut cmd = Command::new(&debugger);

    match Path::new(&debugger)
        .file_name()
        .map(|f| f.to_string_lossy().contains("lldb"))
    {
        Some(true) => {
            cmd.args(&[
                "-o",
                "b rust_panic",
                "-o",
                "r",
                "-o",
                "bt",
                "-f",
                &format!("{}/{}/debug/{}", &honggfuzz_target, target_triple(), target),
                "--",
            ]);
        }
        _ => {
            cmd.args(&[
                "-ex",
                "b rust_panic",
                "-ex",
                "r",
                "-ex",
                "bt",
                "--args",
                &format!("{}/{}/debug/{}", &honggfuzz_target, target_triple(), target),
            ]);
        }
    };

    cmd
}

fn hfuzz_version() {
    println!("cargo-hfuzz {}", VERSION);
}

fn hfuzz_run<T>(mut args: T, crate_root: &Path, build_type: &BuildType)
where
    T: std::iter::Iterator<Item = String>,
{
    let target = args.next().unwrap_or_else(||{
        eprintln!("please specify the name of the target like this \"cargo hfuzz run[-debug|-no-instr] TARGET [ ARGS ... ]\"");
        process::exit(1);
    });

    let honggfuzz_target = env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| HONGGFUZZ_TARGET.into());
    let honggfuzz_workspace =
        env::var("HFUZZ_WORKSPACE").unwrap_or_else(|_| HONGGFUZZ_WORKSPACE.into());
    let honggfuzz_input = env::var("HFUZZ_INPUT")
        .unwrap_or_else(|_| format!("{}/{}/input", honggfuzz_workspace, target));

    hfuzz_build(
        vec!["--bin".to_string(), target.clone()].into_iter(),
        crate_root,
        build_type,
    );

    match *build_type {
        BuildType::Debug => {
            let crash_filename = args.next().unwrap_or_else(||{
                eprintln!("please specify the crash filename like this \"cargo hfuzz run-debug TARGET CRASH_FILENAME [ ARGS ... ]\"");
                process::exit(1);
            });

            let status = debugger_command(&target)
                .args(args)
                .env("CARGO_HONGGFUZZ_CRASH_FILENAME", crash_filename)
                .env(
                    "RUST_BACKTRACE",
                    env::var("RUST_BACKTRACE").unwrap_or_else(|_| "1".into()),
                )
                .status()
                .unwrap();
            if !status.success() {
                process::exit(status.code().unwrap_or(1));
            }
        }
        _ => {
            // add some flags to sanitizers to make them work with Rust code
            let asan_options = env::var("ASAN_OPTIONS").unwrap_or_default();
            let asan_options = format!("detect_odr_violation=0:{}", asan_options);

            let tsan_options = env::var("TSAN_OPTIONS").unwrap_or_default();
            let tsan_options = format!("report_signal_unsafe=0:{}", tsan_options);

            // get user-defined args for honggfuzz
            let hfuzz_run_args = env::var("HFUZZ_RUN_ARGS").unwrap_or_default();
            // FIXME: we split by whitespace without respecting escaping or quotes
            let hfuzz_run_args = hfuzz_run_args.split_whitespace();

            // get user-defined args for building
            let hfuzz_build_args = env::var("HFUZZ_BUILD_ARGS").unwrap_or_default();
            // FIXME: we split by whitespace without respecting escaping or quotes
            let hfuzz_build_args: Vec<_> = hfuzz_build_args.split_whitespace().collect();

            let hfuzz_build_profile =
                if let Some(arg) = hfuzz_build_args.iter().find(|f| &f[..9] == "--profile") {
                    arg.split("=")
                        .collect::<Vec<_>>()
                        .get(1)
                        .expect("--profile not in correct format (eg. --profile=<label>)")
                } else {
                    "release"
                };

            fs::create_dir_all(&format!("{}/{}/input", &honggfuzz_workspace, target))
                .unwrap_or_else(|_| {
                    println!(
                        "error: failed to create \"{}/{}/input\"",
                        &honggfuzz_workspace, target
                    );
                });

            let command = format!("{}/honggfuzz", &honggfuzz_target);
            let err = Command::new(&command) // exec honggfuzz replacing current process
                .args(&[
                    "-W",
                    &format!("{}/{}", &honggfuzz_workspace, target),
                    "-f",
                    &honggfuzz_input,
                    "-P",
                ])
                .args(hfuzz_run_args) // allows user-specified arguments to be given to honggfuzz
                .args(&[
                    "--",
                    &format!(
                        "{}/{}/{}/{}",
                        &honggfuzz_target,
                        target_triple(),
                        hfuzz_build_profile,
                        target
                    ),
                ])
                .args(args)
                .env("ASAN_OPTIONS", asan_options)
                .env("TSAN_OPTIONS", tsan_options)
                .exec();

            // code flow will only reach here if honggfuzz failed to execute
            eprintln!("cannot execute {}, try to execute \"cargo hfuzz build\" from fuzzed project directory", &command);
            eprintln!("{:?}", err);
            process::exit(1);
        }
    }
}

fn hfuzz_build<T>(args: T, crate_root: &Path, build_type: &BuildType)
where
    T: std::iter::Iterator<Item = String>,
{
    let honggfuzz_target = env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| HONGGFUZZ_TARGET.into());

    // HACK: temporary fix, see https://github.com/rust-lang/rust/issues/53945#issuecomment-426824324
    let use_gold_linker: bool = match rustc_version::version_meta() {
        Ok(version_meta) => match version_meta.channel {
            Channel::Nightly | Channel::Dev => {
                // old nightly
                version_meta
                    .commit_date
                    .map_or(false, |date| *date < *"2025-03-08")
            }
            Channel::Stable | Channel::Beta => {
                // old non-nightly
                version_meta.semver < semver::Version::new(1, 87, 0)
            }
        },
        Err(_) => false,
    } && match Command::new("which") // only if gold linker is available
        .args(&["ld.gold"])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .stdin(Stdio::null())
        .status()
    {
        Err(_) => false,
        Ok(status) => match status.code() {
            Some(0) => true,
            _ => false,
        },
    };

    let mut rustflags = String::new();
    rustflags.push_str("--cfg fuzzing ");
    rustflags.push_str("-C debug-assertions=y ");
    rustflags.push_str("-C overflow-checks=y ");
    rustflags.push_str("-C force-frame-pointers=y ");

    let mut cargo_incremental = "1";
    match *build_type {
        BuildType::Debug => {
            rustflags.push_str("--cfg fuzzing_debug ");
            rustflags.push_str("-C opt-level=0 ");
            rustflags.push_str("-C debuginfo=2 ");
        }

        BuildType::ProfileWithGrcov => {
            rustflags.push_str("--cfg fuzzing_debug ");
            rustflags.push_str("-Zprofile ");
            rustflags.push_str("-C panic=abort ");
            rustflags.push_str("-C opt-level=0 ");
            rustflags.push_str("-C debuginfo=2 ");
            rustflags.push_str("-C codegen-units=1 ");
            rustflags.push_str("-C link-dead-code ");
            //rustflags.push_str("-Coverflow-checks=off ");
            cargo_incremental = "0";
        }

        _ => {
            rustflags.push_str("-C opt-level=3 ");
            rustflags.push_str("-C target-cpu=native ");
            rustflags.push_str("-C debuginfo=0 ");

            if *build_type == BuildType::ReleaseInstrumented {
                // The new LLVM pass manager was not enabled in rustc 1.57 as expected:
                // https://github.com/rust-lang/rust/pull/91263
                // The fix for now is to pass `-C passes=sancov-module` only to
                // compilers for which the LLVM version is >= 13.
                let version_meta = rustc_version::version_meta().unwrap();
                if version_meta.llvm_version.map_or(true, |v| v.major >= 13) {
                    rustflags.push_str("-C passes=sancov-module ");
                } else {
                    rustflags.push_str("-C passes=sancov ");
                };

                rustflags.push_str("-C llvm-args=-sanitizer-coverage-level=4 "); // enables indirect calls
                rustflags.push_str("-C llvm-args=-sanitizer-coverage-trace-pc-guard ");
                rustflags.push_str("-C llvm-args=-sanitizer-coverage-trace-divs ");
                rustflags.push_str("-C llvm-args=-sanitizer-coverage-trace-geps ");
                rustflags.push_str("-C llvm-args=-sanitizer-coverage-stack-depth ");

                // trace-compares doesn't work on macOS without a sanitizer
                if cfg!(not(target_os = "macos")) {
                    rustflags.push_str("-C llvm-args=-sanitizer-coverage-trace-compares ");
                }

                // HACK: temporary fix, see https://github.com/rust-lang/rust/issues/53945#issuecomment-426824324
                if use_gold_linker {
                    rustflags.push_str("-Clink-arg=-fuse-ld=gold ");
                }
            }
        }
    }

    // add user provided flags
    rustflags.push_str(&env::var("RUSTFLAGS").unwrap_or_default());

    // get user-defined args for building
    let hfuzz_build_args = env::var("HFUZZ_BUILD_ARGS").unwrap_or_default();
    // FIXME: we split by whitespace without respecting escaping or quotes
    let mut hfuzz_build_args = hfuzz_build_args.split_whitespace();

    let cargo_bin = env::var("CARGO").unwrap_or_else(|_| "cargo".into());
    let mut command = Command::new(cargo_bin);
    command
        .args(&["build", "--target", &target_triple()]) // HACK to avoid building build scripts with rustflags
        .args(args)
        .args(hfuzz_build_args.clone()) // allows user-specified arguments to be given to cargo build
        .env("RUSTFLAGS", rustflags)
        .env("CARGO_INCREMENTAL", cargo_incremental)
        .env("CARGO_TARGET_DIR", &honggfuzz_target) // change target_dir to not clash with regular builds
        .env("CRATE_ROOT", &crate_root);

    if *build_type == BuildType::ProfileWithGrcov {
        command
            .env("CARGO_HONGGFUZZ_BUILD_VERSION", VERSION) // used by build.rs to check that versions are in sync
            .env("CARGO_HONGGFUZZ_TARGET_DIR", &honggfuzz_target); // env variable to be read by build.rs script
    }
    // to place honggfuzz executable at a known location
    else if *build_type != BuildType::Debug {
        // ensure we do not set --release when one of the build args
        // contains a --profile
        if !hfuzz_build_args.any(|f| f.starts_with("--profile")) {
            command.arg("--release");
        }

        command
            .env("CARGO_HONGGFUZZ_BUILD_VERSION", VERSION) // used by build.rs to check that versions are in sync
            .env("CARGO_HONGGFUZZ_TARGET_DIR", &honggfuzz_target); // env variable to be read by build.rs script
    } // to place honggfuzz executable at a known location

    let status = command.status().unwrap();
    if !status.success() {
        process::exit(status.code().unwrap_or(1));
    }
}

fn hfuzz_clean<T>(args: T)
where
    T: std::iter::Iterator<Item = String>,
{
    let honggfuzz_target = env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| HONGGFUZZ_TARGET.into());
    let cargo_bin = env::var("CARGO").unwrap_or_else(|_| "cargo".into());
    let status = Command::new(cargo_bin)
        .args(&["clean"])
        .args(args)
        .env("CARGO_TARGET_DIR", &honggfuzz_target) // change target_dir to not clash with regular builds
        .status()
        .unwrap();
    if !status.success() {
        process::exit(status.code().unwrap_or(1));
    }
}

fn main() {
    // TODO: maybe use `clap` crate

    let mut args = env::args().skip(1);
    if args.next() != Some("hfuzz".to_string()) {
        eprintln!("please launch as a cargo subcommand: \"cargo hfuzz ...\"");
        process::exit(1);
    }

    // change to crate root to have the same behavior as cargo build/run
    let crate_root = find_crate_root().unwrap_or_else(|| {
        eprintln!(
            "error: could not find `Cargo.toml` in current directory or any parent directory"
        );
        process::exit(1);
    });
    env::set_current_dir(&crate_root).unwrap();

    match args.next() {
        Some(ref s) if s == "build" => {
            hfuzz_build(args, &crate_root, &BuildType::ReleaseInstrumented);
        }
        Some(ref s) if s == "build-no-instr" => {
            hfuzz_build(args, &crate_root, &BuildType::ReleaseNotInstrumented);
        }
        Some(ref s) if s == "build-debug" => {
            hfuzz_build(args, &crate_root, &BuildType::Debug);
        }
        Some(ref s) if s == "build-grcov" => {
            hfuzz_build(args, &crate_root, &BuildType::ProfileWithGrcov);
        }
        Some(ref s) if s == "run" => {
            hfuzz_run(args, &crate_root, &BuildType::ReleaseInstrumented);
        }
        Some(ref s) if s == "run-no-instr" => {
            hfuzz_run(args, &crate_root, &BuildType::ReleaseNotInstrumented);
        }

        Some(ref s) if s == "run-debug" => {
            hfuzz_run(args, &crate_root, &BuildType::Debug);
        }
        Some(ref s) if s == "clean" => {
            hfuzz_clean(args);
        }
        Some(ref s) if s == "version" => {
            hfuzz_version();
        }
        _ => {
            eprintln!("possible commands are: run, run-no-instr, run-debug, build, build-no-instr, build-grcov, build-debug, clean, version");
            process::exit(1);
        }
    }
}