liveBook · Manning

Fuzzing

As explained in Code Like a Pro in Rust

Fuzz testing is a software-testing technique that exercises programs with automatically generated or mutated inputs to reveal unexpected behavior, including failures caused by invalid data.

Fuzz testing feeds generated inputs into code to expose unexpected failures. Unlike property testing, which generally selects inputs considered valid, fuzzing can exercise code with arbitrary bytes. This is useful for parsers and other public-facing inputs that must tolerate misuse. section 7.5

A practical Rust workflow uses cargo-fuzz with LLVM’s libFuzzer:

  • Install the tool with `cargo install cargo-fuzz`, then create a target with `cargo fuzz new myfuzztest`. section 3.8.3
  • Put the function under test in the generated fuzz target and run it with `cargo fuzz run myfuzztest`. section 3.8.3
  • For structured input, derive `arbitrary::Arbitrary` on an input type and pass its generated values to `fuzz_target!`. section 7.5

A parser that accepts more than it can parse

A string parser accepts up to ten decimal digits with a regular expression, then calls `s.parse().expect("Parsing failed")` for an `i32`. An accepted string can still be outside the `i32` range, turning that expectation into a failure. A fuzz target that repeatedly calls the parser with generated strings exposes the mismatch. section 7.5

Listing 7.11 Fuzz test
#![no_main]
use arbitrary::Arbitrary;
use libfuzzer_sys::fuzz_target;
 
#[derive(Arbitrary, Debug)]         #1
struct Input {
    s: String,                      #2
}
 
fuzz_target!(|input: Input| {       #3
    use fuzzme::parse_integer;
 
    parse_integer(&input.s);        #4
});

The target derives `Arbitrary` for a struct containing a `String` and passes each generated string to the parser. section 7.5

Do not expect to exhaust every possible input: that can take an unfeasible amount of time. A run can still find a failure quickly, and cargo-fuzz reports a failing input as an artifact for investigation. section 7.5

How Code Like a Pro in Rust covers it

How deep it goes
Shows cargo-fuzz setup, a typed fuzz target, execution, and a failure; stops short of libFuzzer internals.
Examples
Uses a string-to-`i32` parser, an `Arbitrary` string input, and a cargo-fuzz failure artifact.
What it assumes
Assumes a Rust project and familiarity with testing; supplies cargo-fuzz installation and target boilerplate.
What you can do after
Apply it via cargo-fuzz to create and run a libFuzzer target against a Rust function.
How it connects
Contrasts property testing with fuzzing and links generated inputs to parsing, validation, and security-sensitive code.

Also explained in

Compare how 7 books explain fuzzing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.