The Art of Fuzzing, Part 2: native code and managed languages

Security research · Part 2

A notebook sketch of an input being mutated into variants, next to a stack of test cases with one flagged red

Overview

This is the second of five articles on fuzz testing. Part 1 introduced the technique and worked through a heap buffer over-read in a small packet parser using libFuzzer. This article continues with the same parser and assumes the files and container environment set up there: packet.cc, packet_fixed.cc and the seeds directory.

  • Section 2 explains how coverage is measured inside a running program.
  • Section 3 applies AFL++ to the parser as a file-reading program and discusses its main engineering features.
  • Sections 4 and 5 examine what campaign statistics measure, how to obtain true source coverage, and how to respond when coverage stops increasing.
  • Section 6 surveys fuzzing of targets for which no source code is available, including firmware and operating-system kernels.
  • Sections 7 and 8 apply fuzzing to five memory-safe languages and describe continuous fuzzing in a build pipeline.

1. Introduction

The coverage-guided fuzzers described in Part 1 depend on two capabilities: observing which parts of a program each input executes, and running a very large number of inputs quickly. Both capabilities are easiest to obtain when the source code is available and the target can be recompiled. Most of this article concerns that setting, which covers the majority of fuzzing in practice, from individual libraries to the thousands of projects tested by OSS-Fuzz.

The article also addresses two common misconceptions. The first is that the numbers displayed by a fuzzer are measures of how thoroughly a program has been tested; for the most part they are not. The second is that programs written in memory-safe languages do not benefit from fuzzing. Such languages eliminate one important class of defect, but they leave crashes, hangs, incorrect results and authorisation errors entirely possible, and fuzzing finds these as readily as it finds memory corruption.

2. How coverage is measured

A coverage-guided fuzzer needs to know, after each execution, whether the input caused the program to do anything new. Conventional coverage tools can answer this question, but they slow execution considerably, and fuzzing depends on executing as many inputs as possible. Fuzzers therefore use their own lightweight instrumentation, inserted by a modified compiler [1].

AFL and its successors record edge coverage rather than line coverage. An edge is a transition between two basic blocks of code, so edge coverage distinguishes, for every conditional branch, whether the branch was taken, not taken, or both. The instrumentation assigns an identifier to each block, combines the identifiers of the previous and current blocks into a hash, and increments the corresponding entry in a shared table, often called the coverage map or bitmap. After the execution finishes, the fuzzer compares the map with the union of all previous maps. If any entry is non-zero for the first time, the input is considered interesting and is added to the corpus [1]. AFL additionally places the counts into coarse buckets (one, two, three, four to seven, and so on), so that executing a loop a substantially different number of times also counts as new behaviour.

libFuzzer, the engine built into Clang, applies the same principle to an individual function rather than to a whole program. The user writes a harness function, LLVMFuzzerTestOneInput, which receives a byte buffer and passes it to the code under test; the engine calls it repeatedly within one process [1], [4]. This makes libFuzzer particularly suitable for reaching internal functions that would be difficult to drive through the program's normal interface, such as code reached only after user interaction.

3. AFL++: fuzzing a file-reading program

Many targets are complete programs that read their input from a file named on the command line or from standard input. AFL++, the actively maintained successor to AFL, is designed for this setting. The Debian package (apt-get install -y afl++) provides version 4.04c, which was used for the results below; later versions behave identically for the purposes of this section.

3.1 A file-reading driver

To run the packet parser from Part 1 as a program, a small driver reads a file into memory and passes it to the existing harness function (Figure 1).

#include <cstddef>
#include <cstdint>
#include <fstream>
#include <iterator>
#include <vector>

extern "C" int LLVMFuzzerTestOneInput(const uint8_t*, size_t);

int main(int argc, char** argv) {
    if (argc != 2) return 2;
    std::ifstream file(argv[1], std::ios::binary);
    if (!file) return 2;
    std::vector<uint8_t> bytes((std::istreambuf_iterator<char>(file)),
                               std::istreambuf_iterator<char>());
    return LLVMFuzzerTestOneInput(bytes.data(), bytes.size());
}
Figure 1. driver.cc: a command-line driver for the packet harness.

The program is compiled with AFL++'s compiler wrapper, which inserts the coverage instrumentation described in Section 2, and with AddressSanitizer enabled through an environment variable:

AFL_USE_ASAN=1 afl-clang-fast++ -std=c++17 -O1 -g packet.cc driver.cc -o packet_afl
afl-fuzz -i seeds -o afl-out -m none -V 60 -- ./packet_afl @@

In the command line, @@ marks the position at which AFL++ substitutes the path of each test file; it is omitted when the target reads standard input. The option -V 60 limits the campaign to 60 seconds. The option -m none removes AFL++'s own memory limit, which is incompatible with the large virtual address space reserved by AddressSanitizer; the container's memory limit should be relied on instead.

3.2 Results

The recorded campaign ended with the following summary:

Statistics: 11 new corpus items found, 44.93% coverage achieved, 2 crashes saved

Two crashing inputs were saved, both caused by the single defect described in Part 1. Crashing inputs are stored in afl-out/default/crashes/. Each can be replayed directly, and AFL++ provides two tools for reduction: afl-tmin minimises a single input while preserving its behaviour, and afl-cmin reduces a corpus to the smallest subset of files with the same total coverage.

./packet_afl afl-out/default/crashes/id:000000*
afl-tmin -i afl-out/default/crashes/id:000000* -o crash.min -m none -- ./packet_afl @@
afl-cmin -i seeds -o seeds-small -m none -- ./packet_afl @@

3.3 Engineering features

Much of AFL's effectiveness comes from well-tuned engineering rather than from the core algorithm. Its mutation stages proceed from deterministic to random: flipping single bits and runs of bits, replacing words with boundary values such as 0, 1 and the maximum integer, then random byte replacement, insertion and deletion, and finally splicing two corpus entries together, a step analogous to crossover in genetic algorithms [1]. The user may also supply a dictionary of tokens relevant to the format, such as SQL keywords or file signatures, which the mutator inserts at random positions.

Two further features affect throughput. The fork server avoids the cost of repeated program start-up by initialising the program once and creating each test process as a copy of it. Persistent mode goes further, running many inputs within a single process in the manner of libFuzzer, which can increase throughput several times over. It is correct only if the program's state is fully reset between inputs; otherwise one input can influence the behaviour of the next, and failures become difficult to reproduce. The AFL++ documentation describes these features, together with its CmpLog comparison feedback, in detail [2].

honggfuzz is a third widely used engine, with a comparable feature set and a different input placeholder, ___FILE___ in place of @@. Because engines differ in their mutation strategies, running two of them against the same target with the same seeds is an inexpensive way to increase the variety of inputs explored, an instance of the portfolio approach described in Part 1.

4. Interpreting campaign statistics

Fuzzers report a large number of statistics during a campaign. Several of them are routinely misread as measures of test thoroughness. Table 1 summarises the most commonly displayed figures and the interpretation each one supports.

StatisticWhat it measuresCommon misreading
Executions per secondThroughput of the harness on this machineA sudden fall usually indicates slow paths or resource leaks, which should be fixed before extending the campaign.
libFuzzer cov:The number of instrumented points reachedIt is a count, not a percentage of the program.
AFL++ coverage percentageThe occupancy of AFL++'s internal coverage mapThe 44.93% above describes map occupancy and says nothing about the proportion of source code executed.
Saved crashesFailing inputs, grouped by the engine's heuristicsIt is not a count of distinct defects; the two crashes above share one cause.
AFL++ stabilityWhether repeated executions of an input follow the same pathLow stability indicates randomness, threads or retained state, all of which undermine reproducibility.
Table 1. Common fuzzing statistics and their interpretation.

The same caution applies when comparing fuzzers. Klees and colleagues showed that fuzzing results vary widely between runs with identical configurations, and that many published comparisons drew conclusions from too few trials, from short time budgets, or from crash counts rather than distinct bugs [3]. A comparison between two techniques should hold the target, seeds, resources and measurement fixed, repeat each configuration several times, and report the distribution of results rather than a single run.

5. Measuring source coverage

To determine which parts of the source code a campaign has exercised, the corpus is replayed through a separate build instrumented for source-based coverage. The following commands build such a version of the repaired parser, replay the corpus without generating new inputs (-runs=0), and produce a report:

clang++-14 -std=c++17 -O1 -g -fsanitize=fuzzer \
  -fprofile-instr-generate -fcoverage-mapping packet_fixed.cc -o fuzz_coverage
LLVM_PROFILE_FILE=coverage.profraw ./fuzz_coverage seeds -runs=0
llvm-profdata-14 merge -sparse coverage.profraw -o coverage.profdata
llvm-cov-14 report ./fuzz_coverage -instr-profile=coverage.profdata
llvm-cov-14 show ./fuzz_coverage -instr-profile=coverage.profdata -show-branches=count
Filename          Lines  Missed Lines   Cover   Branches  Missed Branches   Cover
packet_fixed.cc      13             0  100.00%         8                1  87.50%

Every line was executed, but one of the eight branch outcomes was never taken. The show command marks the missed outcome in the annotated source, which indicates where an additional seed, dictionary entry or harness change is needed. Even complete branch coverage would establish only that each branch was taken at least once; it would say nothing about the values that flowed through it. As Godefroid observes, full statement coverage is a necessary but not sufficient condition for finding all bugs [5].

5.1 When coverage stops increasing

A campaign whose coverage has stopped increasing is said to have reached a plateau. The cause is usually identifiable from the pattern of statistics, as Table 2 summarises.

ObservationLikely causeRemedy
High throughput, very low coverageInputs are rejected at the first validation checkProvide valid seeds or a dictionary of format tokens
Coverage confined to the harnessThe library under test was not instrumentedRebuild the library with the fuzzing compiler flags
Nested structures never generatedByte-level mutation destroys the syntaxUse structure-aware or grammar-based generation
Frequent timeoutsBlocking input or output, or a non-terminating loopReplay a slow input in isolation and time it
Results depend on input orderState persists between inputsReset global state; replay in a fresh process
Table 2. Diagnosing a coverage plateau.

6. Targets without source code

When the source code is unavailable, instrumentation cannot be inserted at compile time and must instead be added at run time. AFL++ supports this through emulation in QEMU mode:

afl-fuzz -Q -i seeds -o qemu-out -- ./parser @@

Emulation typically reduces throughput by a factor of several compared with a source build. QEMU mode must be built as part of the AFL++ installation, which distribution packages do not always include, and the binary must target an architecture that QEMU supports. FRIDA mode (-O) is an alternative based on dynamic binary instrumentation. In either mode it is essential to confirm that the code of interest is actually executed, since it is easy to fuzz a launcher or wrapper that never reaches the intended parser. Table 3 summarises the usual starting points for other kinds of binary target; Part 5 treats WinAFL, together with the FuzzTest and LibAFL frameworks, in detail.

TargetUsual approachTypical difficulty
Linux ELF executableAFL++ in QEMU or FRIDA modeArchitecture mismatch, missing libraries
Windows executable or DLLWinAFL, targeting a single functionCalling convention and state reset
Android applicationExtract and fuzz the native library independentlyDependencies on the Android framework
FirmwareEmulate an isolated parser, for example with Unicorn modeMissing memory map and peripheral behaviour
Linux kernelsyzkaller in disposable virtual machinesSubstantial set-up effort
Table 3. Approaches to binary-only and system targets.

Kernel fuzzing differs from the other cases because its inputs are sequences of system calls rather than byte buffers. syzkaller generates such sequences from descriptions of the system-call interface, so it can reach defects that appear only after a particular history of operations, such as opening a resource, mapping memory and issuing requests in a specific order. It runs the kernel under test in virtual machines that are discarded when they crash; its QEMU set-up guide describes the required configuration.

7. Memory-safe languages

A memory-safe language prevents a program from reading or writing outside the bounds of its objects, but it enforces this by raising an error, a panic or an exception at the moment of the invalid access. The program still fails; it simply fails safely. Fuzzing therefore remains effective in these languages for finding crashes and unhandled errors, as well as non-termination, excessive resource use and violations of application-level properties. To illustrate, each of the following examples contains the same defect: if the first byte of the input is F, the code reads a second byte without checking that one exists. In each case the language's standard fuzzer found the failure within seconds.

7.1 Go

Go has supported fuzzing in its standard test tool since version 1.18. After initialising a module with go mod init example/fuzzdemo, the test in Figure 2 defines a fuzz target with one seed.

package parser

import "testing"

func parse(data []byte) {
    if len(data) > 0 && data[0] == 'F' {
        _ = data[1] // Deliberate missing-length-check bug.
    }
}

func FuzzParse(f *testing.F) {
    f.Add([]byte("OK"))
    f.Fuzz(func(t *testing.T, data []byte) {
        parse(data)
    })
}
Figure 2. parser_test.go.
go test -fuzz=FuzzParse -fuzztime=10s
go test -run=FuzzParse/<identifier printed by the run>

The failing input is written to testdata/fuzz/FuzzParse/. Because an ordinary go test replays every input in that directory, committing it to version control turns the failure into a permanent regression test. The example was verified with Go 1.26.3.

7.2 Rust

In Rust, cargo-fuzz provides a libFuzzer-based workflow and requires the nightly toolchain:

rustup toolchain install nightly
cargo install cargo-fuzz --version 0.13.2
cargo new --lib fuzzdemo && cd fuzzdemo
cargo +nightly fuzz init
// src/lib.rs
pub fn parse(data: &[u8]) {
    if !data.is_empty() && data[0] == b'F' {
        let _ = data[1]; // Deliberate bug.
    }
}

// fuzz/fuzz_targets/fuzz_target_1.rs
#![no_main]
use libfuzzer_sys::fuzz_target;

fuzz_target!(|data: &[u8]| {
    fuzzdemo::parse(data);
});
Figure 3. The Rust library function and its fuzz target.
cargo +nightly fuzz run fuzz_target_1 -- -max_total_time=10

The target panics on the single-byte input F. The crash file is named after the SHA-1 digest of its contents, so every run that finds this input produces the same file name, crash-e69f20e9…. A panic in safe Rust is a genuine defect but not a memory-safety violation; sanitizers are most valuable for unsafe blocks and for C dependencies linked into the program.

7.3 Python

Atheris brings coverage-guided fuzzing to Python by instrumenting the interpreter's execution of selected functions (Figure 4).

import sys
import atheris

@atheris.instrument_func
def parse(data):
    if data and data[0] == ord("F"):
        return data[1]  # Deliberate bug.
    return 0

def test_one_input(data):
    parse(data)

atheris.Setup(sys.argv, test_one_input)
atheris.Fuzz()
Figure 4. fuzz_parser.py.

Atheris must be built against libFuzzer, and native installation on Apple Silicon failed in testing. An x86-64 container provided a reliable environment:

docker run --rm --platform linux/amd64 -v "$PWD:/work" -w /work python:3.11-slim \
  sh -c 'pip install atheris==3.0.0 && python fuzz_parser.py -max_total_time=10'

The fuzzer reports an IndexError on the input F. When fuzzing a real library, its import should be wrapped in with atheris.instrument_imports(): so that coverage is collected inside the library and not only in the harness.

7.4 Java

Jazzer provides coverage-guided fuzzing for the Java Virtual Machine. With a release extracted (version 0.30.0 was used), the class in Figure 5 serves as the fuzz target.

public class ParserFuzzer {
    public static void fuzzerTestOneInput(byte[] data) {
        if (data.length > 0 && data[0] == 'F') {
            if (data[1] == 'Z') { // Deliberate bug.
                return;
            }
        }
    }
}
Figure 5. ParserFuzzer.java.
javac ParserFuzzer.java
./jazzer --cp=. --target_class=ParserFuzzer -max_total_time=10

Jazzer reports an ArrayIndexOutOfBoundsException and writes both the raw failing input and a Java reproducer that can be added to a unit-test suite.

7.5 JavaScript

Jazzer.js applies the same approach to Node.js. After npm init -y and npm install --save-dev @jazzer.js/core@4.0.0, the module in Figure 6 serves as the target.

module.exports.fuzz = function (data) {
  if (data.length > 0 && data[0] === 0x46) {
    data.readUInt16BE(0); // Deliberate bug: this read needs two bytes.
  }
};
Figure 6. FuzzTarget.js.
npx jazzer FuzzTarget.js -- -max_total_time=10

The fuzzer reports a RangeError, and the choice of readUInt16BE in this example is deliberate and instructive. In JavaScript, indexing a one-byte buffer at position 1 does not raise an error; it returns undefined, and execution continues. A defect that the other four languages turn into an immediate failure is therefore silent here unless the code uses a checked accessor or the harness asserts an explicit property. This is the oracle problem of Part 1 in another form: where the language does not fail loudly, the test must define failure itself.

Comparable tools exist for other platforms, including SharpFuzz for .NET, and Foundry and Echidna for smart contracts. In smart contracts the important defects are almost always violations of invariants, such as the conservation of token balances, rather than crashes, so property-based oracles are the norm.

8. Continuous fuzzing

A single campaign finds the defects present in one version of the code. Integrating fuzzing into the build pipeline extends this to every subsequent change. A practical arrangement has three stages: replay every saved failing input as a regression test, run a short exploratory campaign on each change, and run longer campaigns on a schedule using separate resources. Figure 7 shows a minimal script for the first two stages.

#!/usr/bin/env bash
set -euo pipefail
mkdir -p ci-artifacts
./fuzz_packet_fixed seeds -runs=0 > ci-artifacts/replay.log 2>&1
./fuzz_packet_fixed seeds -max_total_time=60 -timeout=2 \
  -artifact_prefix=ci-artifacts/ > ci-artifacts/fuzz.log 2>&1
Figure 7. A minimal continuous-integration fuzzing step.

Two details matter in practice. The CI system must retain the ci-artifacts directory even when the job fails, since that is where the reproducer is stored. And the script must never end with || true or an equivalent construct, which would convert a discovered failure into a successful build. The corpus produced by the longer scheduled campaigns should be fed back to the short runs, so that each benefits from the other's progress.

For widely used open-source projects, Google's OSS-Fuzz service provides this infrastructure without charge: it runs the project's harnesses continuously on a large cluster and reports defects privately to the maintainers [6]. ClusterFuzzLite offers a similar capability for any project's own CI system.

9. Conclusion

This article extended the worked example of Part 1 from libFuzzer to AFL++, which found the same defect in a file-reading version of the parser. It explained how edge coverage is recorded, examined which campaign statistics can and cannot be interpreted as measures of thoroughness, and used source-based coverage to locate the one branch outcome that the corpus had missed. It then surveyed fuzzing without source code, showed the same missing length check failing in five memory-safe languages, and described how fuzzing is sustained through continuous integration. The principal points are the following.

  • The engine should match the shape of the target. libFuzzer is best suited to a function that can be called directly; AFL++ is best suited to a program that reads a file or standard input.
  • Fuzzer statistics measure the fuzzer, not the program. Map occupancy, crash counts and execution rates must be interpreted with care, and comparisons between fuzzers require repeated trials [3].
  • Source coverage turns a plateau into a specific task. The uncovered branches identify where seeds, dictionaries or harness changes are needed, although full coverage would still not demonstrate correctness.
  • Fuzzing without source is slower but feasible. Emulation and dynamic instrumentation make binary targets accessible, provided the analyst confirms that the intended code is reached.
  • Memory safety removes one class of defect, not the need for testing. Crashes, hangs and property violations remain, and continuous fuzzing ensures that they are caught as the code changes.

Exercises

  • StackSmash. Determine the input length at which the service crashes, then analyse the crash to obtain control of execution.
  • BakuWind. A format-string vulnerability. Fuzzing the input with %p and %n variants and observing the output reveals what the service discloses.
  • FirmBase. A flat ARM firmware image, which provides practical experience of the firmware case in Table 3.

Next

Part 3 turns from compiled targets to services that can only be observed through their responses: a web application, an API described by a schema, and a network protocol. Part 3: web applications, APIs and protocols.

References

  1. D. Wagner, Fuzzing intro, lecture notes, CS261, UC Berkeley, January 2026.
  2. AFL++ project, Fuzzing in depth and the status screen.
  3. G. Klees, A. Ruef, B. Cooper, S. Wei and M. Hicks, Evaluating fuzz testing, Proc. ACM CCS, 2018.
  4. LLVM Project, libFuzzer and source-based code coverage.
  5. P. Godefroid, Fuzzing: hack, art, and science, Communications of the ACM 63(2), 2020.
  6. Google, OSS-Fuzz documentation and ClusterFuzzLite.
  7. Language tools: Go fuzzing; cargo-fuzz; Atheris; Jazzer; Jazzer.js; syzkaller.

Recorded runs: AFL++ 4.04c and Clang 14.0.6 on Linux x86-64 (26 November 2026); Go 1.26.3, cargo-fuzz 0.13.2, Atheris 3.0.0, Jazzer 0.30.0 and Jazzer.js 4.0.0.


TopicsFuzzingAFL++Code coverageGoRust
Share this article LinkedIn X Facebook Email
← Back to all posts