Skip to content
systemcoding.dev
Security

The Complete Guide to Fuzzing C and C++ Code

Fuzz C and C++ with libFuzzer and AFL++ on Clang 19: write targets, use sanitizers, build corpora and dictionaries, triage crashes and run fuzzing in CI.

28 min read
Summarize in AI
Flat illustration of a shield with a lock, a key and a password field, with the C, C++ and Rust logos.

A unit test checks the inputs its author thought of. A fuzzer checks the inputs nobody thought of, millions of them an hour, steered by feedback from the program itself. For code that parses bytes it did not produce (image decoders, network protocols, file formats, configuration, archive readers, font loaders), that difference is where nearly all the serious bugs live. A parser that survives its unit tests and fails on the first malformed file is the normal case, not the exception, and fuzzing is the cheapest way to find those failures before someone else does.

This guide takes a C or C++ project from no fuzzing to continuous fuzzing. It uses Clang 19 with libFuzzer as the main engine, shows AFL++ 4.x for programs that read files or sockets, and covers the supporting work that decides whether a fuzzing campaign finds anything: harness design, sanitizer pairing, corpora, dictionaries, structure-aware mutation, crash triage, coverage measurement and running it in CI. Every example is written to compile as shown and the outputs are worked out from the code. Addresses, seeds, hashes and timings in the output will differ on your machine.

The guide assumes you can build C or C++ with Clang and have used a sanitizer at least once. If the sanitizers are new, read the companion guide to them first, because a fuzzer without a sanitizer finds only crashes, and most memory bugs do not crash at the moment they happen.

How fuzzing finds bugs

A coverage-guided fuzzer runs a loop. It picks an input from a collection called the corpus, mutates it (flips bits, inserts and deletes bytes, splices two inputs, substitutes interesting integers), runs the target on the result and watches which parts of the program executed. If the new input reached code no earlier input reached, it joins the corpus. If the program crashed, hung or tripped a sanitizer, the input is saved as a finding.

The feedback is what makes it work. A blind random generator has almost no chance of producing a valid file header followed by a malformed chunk, because the header check rejects nearly everything. A coverage-guided fuzzer retains the rare input that passed the first check and mutates it further, so over time it builds inputs that reach deep code. The mechanism is instrumentation inserted by the compiler: each basic block or edge increments a counter, and the engine reads the counters after each run. Clang provides this through -fsanitize=fuzzer and -fsanitize-coverage=..., and AFL++ provides it through its own compiler wrappers.

Three consequences shape everything that follows. The target must be fast, since throughput is what finds bugs, and a function that takes a second per call will complete a few thousand runs a day. The target must be deterministic for a given input, or the feedback is noise. And the target must be checked by a sanitizer, because the fuzzer can only report what the program reports.

Choose what to fuzz

Fuzz code that takes untrusted bytes and does real work on them. Good targets share a signature: bytes in, structured result or error out, no network or disk access needed.

TargetWhy it is a good fit
Image, audio, video and font decodersComplex binary formats, historically bug-rich
Network protocol parsers (DNS, TLS records, HTTP)Parse attacker-controlled bytes before authentication
Archive and compression readersNested lengths and offsets
Configuration, markup and language parsersLarge state machines
Serialization (protobuf, JSON, ASN.1, custom TLV)Length-prefixed fields
Data-structure libraries with a command interfaceSequences of operations expose invariants

Poor targets are code that is mostly I/O waiting, code whose result depends on the clock or a random number, and code that runs for seconds per call. Wrap those parts, or fuzz the pure function inside them. The parser inside a network daemon is a good target even when the daemon is not.

A useful test of a candidate: could you describe it as parse(const uint8_t *data, size_t size)? If yes, the harness is ten lines. If the function wants a file path, a socket or a global initialization, the harness needs more care, covered below.

Your first fuzz target with libFuzzer

libFuzzer is an in-process engine linked into the program under test, shipped with Clang as part of compiler-rt. A harness is a single function with a fixed name.

First, a small parser with two real bugs: it trusts the length byte without checking it against the buffer size or the destination.

tlv.cc
#include <stdint.h>
#include <stddef.h>
#include <string.h>

/* Message layout: type (1 byte), length (1 byte), payload. */
int tlv_parse(const uint8_t *buf, size_t n)
{
    if (n < 2)
        return -1;

    uint8_t type = buf[0];
    uint8_t len  = buf[1];
    char name[16];

    if (type == 0x42) {
        memcpy(name, buf + 2, len);     /* no check against sizeof name or n - 2 */
        return name[0];
    }
    return 0;
}
tlv.hc
#include <stdint.h>
#include <stddef.h>

int tlv_parse(const uint8_t *buf, size_t n);

The harness calls it with whatever the fuzzer generates. The function name and signature are fixed by libFuzzer, and the return value must be zero.

fuzz_tlv.cc
#include <stdint.h>
#include <stddef.h>
#include "tlv.h"

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
    tlv_parse(data, size);
    return 0;
}

Build all code with the sanitizers and the fuzzer runtime. -fsanitize=fuzzer adds coverage instrumentation and links libFuzzer's main, so the harness has no main of its own.

Shell
clang-19 -g -O1 -fno-omit-frame-pointer \
    -fsanitize=fuzzer,address,undefined \
    fuzz_tlv.c tlv.c -o fuzz_tlv
mkdir -p corpus
./fuzz_tlv corpus

The fuzzer starts from an empty corpus, finds the type byte 0x42 through feedback from the branch, then grows the length until memory checks fire:

Text
INFO: Running with entropic power schedule (0xFF, 100).
INFO: Seed: 2845731913
INFO: Loaded 1 modules   (11 inline 8-bit counters): 11 [0x5604f0a2c0a8, 0x5604f0a2c0b3), 
INFO: Loaded 1 PC tables (11 PCs): 11 [0x5604f0a2c0b8,0x5604f0a2c168), 
INFO:        0 files found in corpus
INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 4096 bytes
INFO: A corpus is not provided, starting from an empty corpus
#2	INITED cov: 3 ft: 3 corp: 1/1b exec/s: 0 rss: 41Mb
#41	NEW    cov: 4 ft: 4 corp: 2/3b lim: 4 exec/s: 0 rss: 41Mb L: 2/2 MS: 4 ChangeBit-ChangeByte-ShuffleBytes-InsertByte-
#1263	NEW    cov: 5 ft: 5 corp: 3/18b lim: 17 exec/s: 0 rss: 41Mb L: 15/15 MS: 2 InsertRepeatedBytes-ChangeByte-
=================================================================
==48210==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffe7e3e0b50 at pc 0x5604f0968b6e bp 0x7ffe7e3e0b10 sp 0x7ffe7e3e02d8
WRITE of size 24 at 0x7ffe7e3e0b50 thread T0
    #0 0x5604f0968b6d in __asan_memcpy (fuzz_tlv+0x9eb6d)
    #1 0x5604f0a1a31d in tlv_parse tlv.c:15:9
    #2 0x5604f0a1a3a1 in LLVMFuzzerTestOneInput fuzz_tlv.c:6:5
...
SUMMARY: AddressSanitizer: stack-buffer-overflow tlv.c:15:9 in tlv_parse
MS: 2 InsertRepeatedBytes-ChangeByte-; base unit: 1c7a4e0b6d3d2f19b1a0b2f6c8a7d9e04f3b2a18
0x42,0x18,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,
artifact_prefix='./'; Test unit written to ./crash-9f2c1a77e03b5d46c8a1b09e7d2f6a5c4b13e0d8
Base64: QhhBQUFBQUFBQUFBQUFBQUFB

Read the output from the bottom. The crashing input is saved as crash-<sha1>, its bytes are printed in hex (0x42 is the type, 0x18 is a length of 24, larger than the 16-byte name), and the sanitizer names the line. Replaying the saved file is just running the binary with the path as an argument:

Shell
./fuzz_tlv crash-9f2c1a77e03b5d46c8a1b09e7d2f6a5c4b13e0d8

That prints the same report and returns, which makes the crash file a regression test you can commit. Fix the parser by checking len <= sizeof name and n - 2 >= len, rebuild, and replay the file; it now passes. The fuzzer ran for roughly a second here, and the run found a bug a human reviewer might read past because the code looks plausible.

The rules for a good harness

A harness is production code in a hostile environment, and a handful of rules decide whether the campaign works.

Be fast and stay in memory. No disk reads, no sleeps, no network, no process spawning. Anything slow per iteration divides your throughput.

Be deterministic. The same input must give the same coverage every time. Seed any pseudo-random generator from the input, not the clock, and avoid reading the time or reading environment state that varies.

Be stateless between calls. libFuzzer calls the function millions of times in one process, so global state that survives a call turns every input into a function of every earlier input. Free what you allocate and reset what you change. A leak that grows by a few bytes per call exhausts memory within hours, and libFuzzer will stop on its -rss_limit_mb limit (2048 by default) with an out-of-memory report. Clean up in the harness.

Never exit or abort on bad input. A library that calls exit() on a parse error ends the whole fuzzing process. Patch the call out under a macro, or wrap it.

**Do one-time setup in LLVMFuzzerInitialize.** Loading tables, parsing a schema or initializing a library belongs there, not in the per-input function:

fuzz_init.cc
#include <stdint.h>
#include <stddef.h>
#include "decoder.h"

static decoder_ctx *ctx;

int LLVMFuzzerInitialize(int *argc, char ***argv)
{
    (void)argc; (void)argv;
    ctx = decoder_new();               /* done once, not per input */
    return 0;
}

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
    decoder_reset(ctx);                /* put the state back for the next input */
    decoder_feed(ctx, data, size);
    return 0;
}

Do not fight the fuzzer with validation. Rejecting inputs early inside the harness (for example, requiring size >= 16) is fine to avoid known-boring cases, but filtering for validity in the harness removes the malformed inputs that find bugs. Let the library under test reject them.

Why the sanitizers belong in the build

A fuzzer discovers crashes: segfaults, aborts, timeouts and out-of-memory. A large share of memory-safety bugs do not crash at the time they occur. An out-of-bounds read of a heap neighbor returns garbage and the program carries on; an off-by-one write corrupts an allocator field that is not read for another thousand inputs. With AddressSanitizer the first bad access stops the run and reports it, so every one of those silent bugs becomes a finding. UndefinedBehaviorSanitizer adds signed overflow, bad shifts and null dereferences, and MemorySanitizer adds uninitialized reads (in a separate build, because it cannot be combined with ASan).

The standard fuzzing build is therefore -fsanitize=fuzzer,address,undefined. Add -fno-sanitize-recover=undefined so a UBSan finding stops the run, because otherwise a fuzzer sees only a printed warning and moves on. For libraries linked into the target, compile them with -fsanitize=fuzzer-no-link (coverage without the main) so the fuzzer sees their branches. A library built without instrumentation is a black box to the engine, and the fuzzer cannot steer into it.

Useful libFuzzer options

libFuzzer is configured through command-line flags of the form -name=value, listed by ./fuzz_tlv -help=1. These matter in practice:

FlagPurpose
-max_len=NMaximum input size; set to a realistic size for the format
-runs=NStop after N executions; -runs=0 only replays the corpus
-timeout=SReport an input that takes longer than S seconds as a timeout
-rss_limit_mb=NReport memory use above N megabytes
-dict=fileUse a dictionary of tokens (see below)
-jobs=N -workers=MRun N fuzzing jobs on M worker processes
-fork=NRun N child processes, so a crash does not stop the campaign
-merge=1 new_dir old_dirMerge corpora, keeping only inputs that add coverage
-minimize_crash=1Shrink a crashing input while it still crashes
-use_value_profile=1Use comparison operand values as feedback
-print_final_stats=1Print execution statistics on exit
-artifact_prefix=dir/Where to write crash, timeout and OOM files

A typical long run looks like this:

Shell
./fuzz_tlv corpus -max_len=256 -timeout=5 -fork=4 -ignore_crashes=1 -artifact_prefix=findings/

With -fork=4 the parent keeps running while four children fuzz, and -ignore_crashes=1 lets the campaign continue past a crash, writing each distinct one to findings/.

Seeds: start from valid inputs

An empty corpus works for tiny formats and wastes hours on large ones. A seed corpus of a few valid files gives the fuzzer a map of the reachable code from the first second. Put real samples in the corpus directory: a handful of small valid images, a few real protocol messages, minimal configuration files. Smaller seeds are better than large ones, because mutation cost scales with size. After a run, shrink the collection with -merge=1:

Shell
mkdir corpus_min
./fuzz_tlv -merge=1 corpus_min corpus
Text
MERGE-OUTER: 214 files, 0 in the initial corpus, 0 processed earlier
MERGE-OUTER: attempt 1
...
MERGE-OUTER: successful in 1 attempt(s)
MERGE-OUTER: the control file has 0 bytes
MERGE-OUTER: consumed 0Mb (0Mb rss) to parse the control file
MERGE-OUTER: 9 new files with 14 new features added; 14 new coverage edges

The merge keeps the smallest set of files that preserves the same coverage, which is what you commit and what CI replays. A dedicated post covers building and minimizing a corpus in more depth.

Dictionaries for tokens and magic values

Mutation by random byte flips is slow at producing multi-byte constants such as "GIF89a" or "HTTP/1.1". A dictionary lists the tokens the format uses, and the engine splices them into inputs.

tlv.dictText
type_name="\x42"
magic="TLV1"
long_len="\xff"
Shell
./fuzz_tlv corpus -dict=tlv.dict

Dictionary entries are quoted strings with \xNN escapes, optionally named. Parser sources and format specifications are the best place to harvest tokens. The dictionary post in this series shows how to write one for structured input.

Fuzzing a program that reads files: AFL++

libFuzzer needs a function to call. When the target is an existing program that reads a file or standard input, AFL++ is the practical engine, because it runs the whole program on each input and needs no harness at all. AFL++ 4.x instruments through compiler wrappers.

Shell
export AFL_USE_ASAN=1
afl-clang-fast -g -O1 tlvmain.c tlv.c -o tlv_afl
mkdir -p in out
printf 'B\x04abcd' > in/seed1
afl-fuzz -i in -o out -- ./tlv_afl @@

@@ is replaced with the path of each generated input file. AFL_USE_ASAN=1 builds with AddressSanitizer, so memory bugs are findings and not silent. The status screen shows executions per second, paths found, and a count of unique crashes; crashing inputs are saved in out/default/crashes/, and afl-fuzz also keeps the queue of interesting inputs in out/default/queue/.

Process-per-input is slow, so AFL++ offers a persistent mode that loops inside one process, using __AFL_FUZZ_INIT() and __AFL_LOOP(), and shared-memory input delivery with __AFL_FUZZ_TESTCASE_BUF. That can multiply throughput by a large factor, which the persistent mode post in this series shows in full. For choosing between engines:

QuestionlibFuzzerAFL++
Need a harness functionyesno (a program is enough)
Runs in-processyesforkserver by default, persistent mode optional
Custom mutatorsLLVMFuzzerCustomMutatorshared-library mutators in C or Python
Binary-only targetsnoyes, with QEMU or Frida mode
Corpus sync across machinesmanual mergebuilt-in parallel mode with -M and -S

Neither is universally better. Library code with a clean entry point fits libFuzzer, and a command-line tool or a closed-source binary fits AFL++. Many projects fuzz with both on the same corpus, since the engines have different mutation strategies and find different bugs.

Structure-aware fuzzing: getting past checksums and nesting

Coverage guidance cannot get past a check that random mutation almost never satisfies. A CRC over the body, a length field that must equal the payload size, or a nested format inside a compressed container will reject nearly every mutated input at the first gate, and the fuzzer's feedback flatlines.

libFuzzer's answer is a custom mutator: a function that mutates the input and then repairs it so it still passes the gate. Here a message ends with a one-byte checksum.

fuzz_checksum.cc
#include <stdint.h>
#include <stddef.h>
#include "tlv.h"

extern size_t LLVMFuzzerMutate(uint8_t *data, size_t size, size_t max_size);

static uint8_t sum(const uint8_t *p, size_t n)
{
    uint8_t s = 0;
    while (n--)
        s += *p++;
    return s;
}

/* Keep the last byte equal to the sum of the others. */
size_t LLVMFuzzerCustomMutator(uint8_t *data, size_t size, size_t max_size, unsigned int seed)
{
    (void)seed;
    if (size < 3)
        return LLVMFuzzerMutate(data, size, max_size);
    size = LLVMFuzzerMutate(data, size - 1, max_size - 1);
    data[size] = sum(data, size);
    return size + 1;
}

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
    if (size < 3 || sum(data, size - 1) != data[size - 1])
        return 0;
    tlv_parse(data, size - 1);
    return 0;
}

LLVMFuzzerMutate is the engine's own mutation, supplied by libFuzzer for use inside a custom mutator. The wrapper mutates the body, recomputes the checksum and returns the new size, so every candidate reaches the parser. For nested structured formats, such as protocol buffers, the next step is to mutate a typed message and serialize it, which the libprotobuf-mutator post covers.

C++ harnesses can use FuzzedDataProvider from <fuzzer/FuzzedDataProvider.h> to carve typed values out of the byte stream, such as integers in a range, a length-limited string or a vector of bytes. That suits APIs that take several arguments or a sequence of operations on a data structure rather than one buffer.

Case study: fuzzing a length-prefixed record reader end to end

The earlier parser was small enough to show every step in one screen. A realistic target has state, nested lengths and an allocation per record, and its bugs are about how those pieces interact. This section builds one and walks the campaign from first harness to fixed bug, so the order of decisions is visible.

The library reads a stream of records, each with a two-byte big-endian length followed by that many bytes, and returns an array of copies.

records.cc
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "records.h"

struct record_set {
    size_t count;
    uint8_t **items;
    size_t *sizes;
};

struct record_set *records_read(const uint8_t *buf, size_t n)
{
    struct record_set *rs = calloc(1, sizeof *rs);
    size_t off = 0;

    while (off + 2 <= n) {
        size_t len = ((size_t)buf[off] << 8) | buf[off + 1];
        off += 2;

        uint8_t *copy = malloc(len);
        memcpy(copy, buf + off, len);         /* bug 1: len may exceed n - off */
        off += len;

        rs->items = realloc(rs->items, (rs->count + 1) * sizeof *rs->items);
        rs->sizes = realloc(rs->sizes, (rs->count + 1) * sizeof *rs->sizes);
        rs->items[rs->count] = copy;
        rs->sizes[rs->count] = len;
        rs->count++;
    }
    return rs;
}

void records_free(struct record_set *rs)
{
    for (size_t i = 0; i < rs->count; i++)
        free(rs->items[i]);
    free(rs->items);                           /* bug 2: rs->sizes is never freed */
    free(rs);
}

The harness must free what the library returns, or the fuzzer's own leak would end the run, and it is also where a leak in the library becomes visible, since LeakSanitizer is part of the ASan build.

fuzz_records.cc
#include <stdint.h>
#include <stddef.h>
#include "records.h"

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
    struct record_set *rs = records_read(data, size);
    if (rs)
        records_free(rs);
    return 0;
}

Build and run with a size cap, because the format's two-byte length is meaningful only up to the input size:

Shell
clang-19 -g -O1 -fno-omit-frame-pointer -fsanitize=fuzzer,address,undefined \
    fuzz_records.c records.c -o fuzz_records
./fuzz_records corpus -max_len=512

The first finding is the read overflow. The crashing input is a handful of bytes: a length of several hundred followed by almost nothing.

Text
==51377==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6020000000b8 at pc 0x55d0b4a2f18d bp 0x7ffc20e53b50 sp 0x7ffc20e53310
READ of size 300 at 0x6020000000b8 thread T0
    #0 0x55d0b4a2f18c in __asan_memcpy (fuzz_records+0x9e18c)
    #1 0x55d0b4ae14a9 in records_read records.c:21:9
    #2 0x55d0b4ae15b2 in LLVMFuzzerTestOneInput fuzz_records.c:7:35

0x6020000000b8 is located 0 bytes after 8-byte region [0x6020000000b0,0x6020000000b8)
allocated by thread T0 here:
    #0 0x55d0b4a2c9ee in operator new[](unsigned long) (fuzz_records+0x9b9ee)
...
SUMMARY: AddressSanitizer: heap-buffer-overflow records.c:21:9 in records_read

Notice what the report says: the read began exactly at the end of the 8-byte region, which is libFuzzer's copy of the input. libFuzzer passes each input in a heap block of exactly its size, so any read past the end is caught on the first byte. That is a property worth remembering when you write a harness: never copy the input into a bigger buffer first, because that hides the overflow the fuzzer is trying to find.

The fix is a bounds check before the copy.

records.cc
        if (len > n - off)
            break;                             /* truncated record: stop reading */

After rebuilding, the next run finds the second bug, found not by a crash but at exit:

Text
==51402==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 16 byte(s) in 1 object(s) allocated from:
    #0 0x55b1c2a2e5ee in realloc (fuzz_records+0x9d5ee)
    #1 0x55b1c2ae1612 in records_read records.c:26:17
    #2 0x55b1c2ae16a8 in LLVMFuzzerTestOneInput fuzz_records.c:7:35

SUMMARY: AddressSanitizer: 16 byte(s) leaked in 1 allocation(s).

libFuzzer treats a leak as a failure and stops, since leak detection is on by default. Adding free(rs->sizes); in records_free fixes it. Two observations from the case study carry over to any project. First, two unrelated bugs were found within minutes by a harness of eight lines, and neither required the fuzzer to understand the format; it needed only enough coverage feedback to learn that a two-byte length controls a branch. Second, the leak is the kind of bug a unit test never reveals because tests rarely free everything on every path, and a fuzzer exercises every error path on every run.

Two more allocation bugs remain in the library even after both fixes, and a fuzzer will find them given time. malloc(len) with len == 0 returns either a null pointer or a unique pointer, and memcpy with a null pointer is undefined behavior that UBSan reports as a null argument. And realloc failure is never checked, which no fuzzer will find without a fault-injecting allocator. That last point is a boundary: fuzzing explores inputs, not environmental failures. Tools such as a failing-malloc wrapper explore the second space, and they are worth adding when allocation failure matters.

Working with large inputs and slow targets

Throughput falls as inputs grow, since every mutation and every run costs more. Keep -max_len as small as the format allows. If a file format has a 4 KiB header and a megabyte of payload, fuzz the header parser and the payload decoder as separate targets, with their own limits, instead of one target that sees megabyte inputs.

For targets that are slow because of expensive setup, move the setup out of the per-input path. For targets that are slow because of real work, such as decompression, cap the work with a limit the production code might also have, such as a maximum output size. A decompression bomb is a real finding in its own right, and libFuzzer reports it as a timeout or an out-of-memory error, which is the fuzzer working as intended.

When one input takes long enough to stall progress, -timeout=N stops it and saves it. Treat each saved timeout as a bug report: either the code has an algorithmic-complexity problem an attacker can trigger, or the limit is too tight for a legitimate input.

Parallelism scales roughly with cores until the shared corpus becomes a bottleneck. -fork=N with -ignore_crashes=1 keeps all cores busy and survives crashes, and for very long runs AFL++'s parallel mode with one main instance (-M) and several secondary instances (-S) syncs queues automatically through the output directory.

Reading libFuzzer status lines

The lines starting with # are the heartbeat of a run, and each field answers a question.

Text
#8934	NEW    cov: 74 ft: 118 corp: 31/402b lim: 64 exec/s: 4467 rss: 58Mb L: 33/60 MS: 3 CopyPart-ChangeBit-InsertByte-

#8934 is the number of executions so far. NEW means the last input added coverage. cov: 74 counts covered code blocks or edges, and ft: 118 counts features, a finer measure that includes counters of how many times a block ran. corp: 31/402b says the corpus holds 31 inputs totaling 402 bytes. lim: 64 is the current input-length limit, which libFuzzer raises gradually. exec/s: 4467 is throughput, the number to watch when you optimize the harness. L: 33/60 is the new input's length and the longest so far. MS: 3 CopyPart-ChangeBit-InsertByte- lists the mutations applied.

Other tags appear too: pulse is a periodic status when nothing new is found, REDUCE means an existing input was replaced by a smaller one with the same coverage, and DONE ends a bounded run. A run that shows pulse lines with unchanged cov for a long time is stuck, which is the cue to look at the coverage report, add seeds or write a mutator.

Fuzzing C++ with FuzzedDataProvider

Many C++ entry points take typed arguments instead of one buffer: a count, a flag, a string and a vector. Slicing the input by hand with fixed offsets is brittle, because a mutation that changes one byte shifts every later field. FuzzedDataProvider solves it by consuming typed values from the front or the back of the input, falling back to defaults when the data runs out.

fuzz_table.cppcpp
#include <cstdint>
#include <cstddef>
#include <string>
#include <vector>
#include <fuzzer/FuzzedDataProvider.h>
#include "table.hpp"

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
    FuzzedDataProvider in(data, size);

    Table table;
    int ops = in.ConsumeIntegralInRange<int>(0, 64);
    for (int i = 0; i < ops; i++) {
        switch (in.ConsumeIntegralInRange<int>(0, 2)) {
        case 0:
            table.insert(in.ConsumeRandomLengthString(32), in.ConsumeIntegral<int32_t>());
            break;
        case 1:
            table.erase(in.ConsumeRandomLengthString(32));
            break;
        default:
            table.lookup(in.ConsumeRandomLengthString(32));
            break;
        }
    }
    table.check_invariants();            /* aborts if the structure is inconsistent */
    return 0;
}

This is the shape for fuzzing a data structure: a random sequence of operations, then an invariant check at the end. The sequence tests state transitions the author never wrote a test for, and check_invariants() gives the fuzzer an oracle, because a crash is the only signal it understands. The same pattern finds bugs in containers, caches, allocators and parsers with incremental APIs.

Instrumenting only part of the program

Coverage instrumentation slows the code it covers and clutters the feedback with irrelevant edges. In a large project, compile only the code under test with -fsanitize=fuzzer-no-link and leave third-party libraries and test utilities uninstrumented. The fuzzer then spends its effort on the parser, not on the logging library.

Clang lets you narrow it further with -fsanitize-coverage allow and deny lists, which name files or functions to include or exclude from instrumentation. A deny list for a vendored compression library you trust keeps the signal clean, and an allow list for the one module you care about does the opposite. The trade-off is blindness: an excluded function cannot guide the fuzzer into itself, so exclude code only when it is large, stable and not an input gate.

Common mistakes that waste a campaign

MistakeSymptomFix
Library not instrumentedCoverage stuck at a handful of edgesCompile it with -fsanitize=fuzzer-no-link
Harness copies input into a larger bufferOverreads never reportedPass data and size straight through
Global state kept between callsFindings that do not reproduceReset state at the start of each call
Checksum or magic gateFuzzer never gets past the headerAdd seeds, a dictionary or a custom mutator
No -max_len on a format with a small limitSlow, huge inputsSet the real maximum
Sanitizers offOnly crashes foundBuild with address and undefined
Leaks in the harnessOut-of-memory after hoursFree what the call allocates
exit() in the libraryRun ends with no findingPatch it behind a macro such as FUZZING_BUILD_MODE
Different flags for fuzz and release buildsBug found in fuzz build, absent in releaseReproduce the finding in the shipping configuration

The last row deserves emphasis. A finding is a bug in the source, and it should reproduce with the production build flags too, perhaps without the sanitizer message. If it does not, the difference points at undefined behavior that the optimizer treats differently, and that is a finding of its own.

Libraries sometimes provide a macro for fuzzing builds. The convention in the libFuzzer documentation is FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION, which clang defines for fuzz builds when you pass -fsanitize=fuzzer. Code can use it to disable checksums and cryptographic verification so the fuzzer reaches the parser behind them, and to remove calls to abort. Use it sparingly and never let it escape into a release build, since a build that skips signature verification is a vulnerability.

Sustaining the effort

Fuzzing is not a project with an end date. The value comes from keeping it running and acting on what it finds. A few habits make that sustainable.

Give each fuzz target an owner, the person who reads its findings. A target nobody owns accumulates unread crashes. Keep fuzz targets in the repository next to the code they test, and build them in the normal CI so a refactor that breaks a harness is caught on the same day. Track a few numbers over time: executions per second per target, corpus size, and covered edges. A sudden drop in coverage after a change means the harness no longer reaches something it used to.

When a finding is a real bug, write a unit test from the minimized input, and keep the input file as well. The unit test documents the bug in readable terms, and the input file protects against the engine's own behavior changing. When the fuzzer reports something that is not a bug, such as an intentionally slow path, fix the harness or add a limit, and write down why, so the next maintainer does not remove the limit.

Finally, review the sanitizer and fuzzer versions when you upgrade the compiler. A new Clang can change instrumentation, default options and report text. Pin the version in CI, and upgrade it deliberately, rerunning the corpus to confirm that nothing that passed before now fails for an unrelated reason.

Triage: from a crash file to a fixed bug

A campaign produces findings faster than a person can read them, so triage in a fixed order.

  1. Reproduce. Run the saved file through the harness. A finding that does not reproduce is usually an environment or state-leak problem in the harness.

  2. Minimize. ./fuzz_tlv -minimize_crash=1 -runs=10000 crash-... shrinks the file while it still triggers an error of the same kind, making the root cause visible.

  3. Deduplicate. The sanitizer's SUMMARY: line, naming the error type, file and line, is a stable key. Many different inputs share one bug.

  4. Classify. A read overflow that leaks memory, a write overflow and an infinite loop have different severity. The sanitizer's error kind and the access size give a first answer.

  5. Fix and keep the file. Commit the minimized input to a regression/ directory and run it on every build.

The triage post goes through crash grouping with real report text.

Measure coverage to see what the fuzzer has not reached

A fuzzer that has run for a day with no new findings has either exhausted the target or is stuck behind a gate. Coverage reports tell the two apart. Build a second binary with source-based coverage and replay the corpus through it.

Shell
clang-19 -g -O1 -fprofile-instr-generate -fcoverage-mapping \
    -fsanitize=fuzzer fuzz_tlv.c tlv.c -o fuzz_tlv_cov
LLVM_PROFILE_FILE=fuzz.profraw ./fuzz_tlv_cov corpus_min -runs=0
llvm-profdata-19 merge -sparse fuzz.profraw -o fuzz.profdata
llvm-cov-19 show ./fuzz_tlv_cov -instr-profile=fuzz.profdata tlv.c

llvm-cov show prints each source line with its execution count, and unexecuted lines stand out. Lines behind an unreached if show you which input shape the fuzzer failed to build: a missing dictionary token, a checksum, a state that needs a sequence of messages. Fix the gate (seed, dictionary, custom mutator, or a harness that skips the gate) and rerun.

Continuous fuzzing

A fuzzer run once finds the bugs that exist today. A fuzzer run continuously finds the ones introduced next week. Two layers fit most projects.

Regression in CI. On every pull request, build the fuzz targets and replay the committed corpus and regression files with -runs=0. It takes seconds, it needs no fuzzing time, and it fails the build when a change breaks an input that used to pass. Add a short fuzzing burst on the changed targets, for example -max_total_time=60, so new code gets at least some exploration.

Long runs elsewhere. Run campaigns for hours or days on a schedule, with the corpus stored and reused between runs. OSS-Fuzz does this for open-source projects at no cost, and ClusterFuzzLite runs the same infrastructure inside your own CI with a smaller time budget. The dedicated post in this series covers both.

Store the corpus as a build artifact or in a bucket and merge each run's discoveries back with -merge=1. A corpus that starts from scratch every night re-learns the same ground each time.

Fuzzing other kinds of code

C and C++ libraries are the easy case. Others need adaptation:

  • Network daemons. Fuzz the parser function in-process, or use AFL++ with a preload library that turns socket reads into reads from the input file. Do not fuzz over a real network, which is slow and non-deterministic.

  • Embedded firmware. Compile the protocol and data-handling code for the host, behind a hardware abstraction layer with stub drivers, and fuzz it there with sanitizers. A separate post covers the firmware parser case.

  • The Linux kernel. syzkaller generates sequences of system calls with descriptions of the interfaces, and it runs the kernel in virtual machines with KASAN and other checkers enabled. The syzkaller posts in this series cover setup and the syzlang descriptions that drive it.

  • Closed-source binaries. AFL++ in QEMU mode instruments the binary at run time, so a target without source can be fuzzed with coverage feedback, at lower speed.

  • Other languages. Rust has cargo-fuzz, built on libFuzzer. Go has native fuzzing in the standard testing package since Go 1.18. Both have their own posts here.

What fuzzing does not find

Fuzzing is strong on parsers and weak on logic. It will not tell you that your authorization check is missing, that a protocol is designed insecurely, or that two correct components compose into a vulnerability. It finds bugs that make the program crash, trip a sanitizer or hang, and it finds nothing about behavior that is wrong but silent unless you add an oracle, such as comparing two implementations on the same input (differential fuzzing) or asserting an invariant after the call (round-trip: encode, decode and compare).

It is also limited by reachability. Code behind a cryptographic check, a long handshake or a rarely true condition is hard to reach, and the coverage report will show it. And it finds only the bugs the sanitizers can recognize: a race needs ThreadSanitizer, an information leak that stays inside valid memory needs MemorySanitizer or a differential check.

Who should not start here

If the project has no tests at all, write a few first; fuzzing a program you cannot build and run reliably is wasted effort. If the code under test is a thin wrapper over a library that is already fuzzed upstream, fuzz your layer and trust the dependency. If the only entry point is a graphical interface or a hardware peripheral, find the byte-handling function inside it. And if the code is not memory-unsafe (a language with bounds checks and no unsafe blocks), fuzzing still finds panics, hangs and logic errors, but the payoff per hour is lower than for C.

Deciding when a target is done

Teams ask when to stop fuzzing a target, and the honest answer is that a target is never proven clean, only well explored. Three signals together justify moving effort elsewhere. The coverage report shows that every reachable line outside known gates has executed. The corpus has stopped growing across several long runs with different seeds. And the harness has been reviewed for blind spots, such as an input shape the format allows that the seeds and dictionary never produce.

Even then, keep the target in CI. Code changes, and a new feature adds new parsing paths that need exploring from the existing corpus. The cost of keeping a finished target alive is a few seconds of corpus replay per build, which is trivially cheap compared with finding the same class of bug in production. Treat the corpus as part of the test suite, review it when the format changes, and refresh the seeds with new real-world samples when you get them.

A rollout plan

A realistic schedule for one project:

  1. Day one. Pick the single most exposed parser. Write a ten-line harness, build with -fsanitize=fuzzer,address,undefined, run for ten minutes and fix whatever it finds.

  2. Week one. Add seeds from real files, a dictionary, and -max_len. Commit the minimized corpus. Add the replay step to CI.

  3. Month one. Add targets for the next most exposed parsers. Measure coverage and write custom mutators for the gates that block it. Start a scheduled long run.

  4. Ongoing. Triage findings with a named owner, keep regression files, and track coverage over time. Treat a fuzz-target build failure as a build failure.

Also inDebugging
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.