libFuzzer Harnesses and Sanitizers as Oracles
The Python fuzzer of the previous lessons runs a few thousand inputs per second. A compiled, in-process fuzzer runs tens or hundreds of thousands, with coverage counters the compiler inserted into every edge. libFuzzer, part of LLVM and enabled with clang -fsanitize=fuzzer, is the simplest of them to start with: you write one function, the harness, and the compiler links in the fuzzing engine. Memory Safety's first look at fuzzing found one bug this way. This lesson runs a full campaign on the course's toy parser with two seeded bugs, fixes them one at a time, and looks at what makes a sanitizer a good oracle.
The harness
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
tlv_parse(data, size);
return 0;
}The engine calls it once per input. Rules that follow from running millions of inputs in one process:
- Deterministic: the same bytes must take the same path. No clocks, no random numbers without a fixed seed, no threads.
- No state between calls: free what you allocate, reset globals. Leaks are reported (LeakSanitizer is on with ASan), and state that survives makes crashes irreproducible.
- Fast and local: no network, no disk writes, no
exit(). If the API takes a file, usefmemopenor a memory-buffer API. - Don't hide crashes: no
catch (...), no signal handlers, noabort()turned intoreturn. - Return 0. (Returning -1 tells recent libFuzzer versions not to add the input to the corpus; leave that for later.)
The build combines the engine with sanitizers: -fsanitize=fuzzer,address,undefined, plus -fno-sanitize-recover=undefined so a UBSan report stops the run instead of printing and carrying on. -g -O1 keeps reports readable at good speed.
A campaign, two bugs, two fixes
The session writes the toy parser tlv.c (the same file as in the introduction), the harness and a one-file seed corpus, then runs three campaigns of at most 60 seconds each with a fixed seed. After each crash it saves the input into regress/, fixes the bug, and continues. It prints stable properties of each report (kind, access, location) because the exact crashing bytes and the fuzzer's statistics lines differ from machine to machine. It runs in your sandbox, on one core:
cat > tlv.c <<'SRC'
#include <stddef.h>
#include <stdint.h>
#include <string.h>
/* Toy format "TLV1": magic, then records of type (1 byte), length (1 byte), value. */
static int rec_name(const uint8_t *v, size_t len) {
char name[16];
memcpy(name, v, len); /* seeded bug 1: len is never checked against 16 */
return name[0];
}
static int rec_sum(const uint8_t *v, size_t len) {
unsigned sum = 0;
for (size_t i = 0; i <= len; i++) /* seeded bug 2: <= reads one byte too many */
sum += v[i];
return (int)(sum & 0xff);
}
int tlv_parse(const uint8_t *data, size_t size) {
if (size < 4 || memcmp(data, "TLV1", 4) != 0) return -1;
size_t pos = 4;
int acc = 0;
while (pos + 2 <= size) {
uint8_t type = data[pos], len = data[pos + 1];
pos += 2;
if (len > size - pos) return -1; /* the input-length check is correct */
if (type == 1) acc += rec_name(data + pos, len);
else if (type == 2) acc += rec_sum(data + pos, len);
pos += len;
}
return acc;
}
SRC
cat > fuzz_tlv.c <<'SRC'
#include <stddef.h>
#include <stdint.h>
int tlv_parse(const uint8_t *data, size_t size);
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
tlv_parse(data, size); /* one input in, no state kept between calls */
return 0;
}
SRC
build() { clang -g -O1 -fsanitize=fuzzer,address,undefined -fno-sanitize-recover=undefined tlv.c fuzz_tlv.c -o fuzz_tlv; }
report() { # what was found, where, and which input: stable properties only
grep -m1 -oE 'AddressSanitizer: [a-z-]+' "$1"
grep -m1 -E '^(READ|WRITE) of size' "$1" | cut -d' ' -f1-4
grep -m1 -E '#[01] .* in (rec_|tlv_)' "$1" | sed 's/.* in / in /'
ls crash-* | wc -l | sed 's/^/ crash files: /'
}
build
mkdir corpus && printf 'TLV1\x01\x03bob\x02\x02\x01\x02\x00\x00' > corpus/seed
echo "== campaign 1"
./fuzz_tlv -seed=1 -max_total_time=60 corpus > c1.log 2>&1; echo " fuzzer exit code: $?"
report c1.log
echo "== fix bug 2 (<= becomes <), campaign 2"
mkdir regress && mv crash-* regress/bug2-crash
sed -i 's|i <= len; i++) /\* seeded bug 2: <= reads one byte too many \*/|i < len; i++)|' tlv.c
build
./fuzz_tlv -seed=1 -max_total_time=60 corpus > c2.log 2>&1; echo " fuzzer exit code: $?"
report c2.log
mv crash-* regress/bug1-crash
python3 - regress/bug1-crash <<'PY'
import sys
d, pos = open(sys.argv[1], "rb").read(), 4
while pos + 2 <= len(d): # walk the records like tlv_parse does
t, n = d[pos], d[pos + 1]
if t == 1 and n > 16:
print(f" record at offset {pos}: type 1 (name), length {n} > 16")
break
pos += 2 + n
PY
echo "== fix bug 1, replay both crash inputs, campaign 3"
sed -i 's| memcpy(name, v, len); /\* seeded bug 1: len is never checked against 16 \*/| if (len > sizeof name) return 0;\n memcpy(name, v, len);|' tlv.c
build
for f in regress/*; do ./fuzz_tlv "$f" > replay.log 2>&1; echo " replay $f: exit code $?"; done
./fuzz_tlv -seed=1 -runs=300000 corpus > c3.log 2>&1; echo " 300000 runs, exit code: $?, sanitizer reports: $(grep -c ERROR c3.log)"== campaign 1
fuzzer exit code: 1
AddressSanitizer: heap-buffer-overflow
READ of size 1
in rec_sum /home/learner/tlv.c:15:16
crash files: 1
== fix bug 2 (<= becomes <), campaign 2
fuzzer exit code: 1
AddressSanitizer: stack-buffer-overflow
WRITE of size 35
in rec_name /home/learner/tlv.c:8:5
crash files: 1
record at offset 4: type 1 (name), length 35 > 16
== fix bug 1, replay both crash inputs, campaign 3
replay regress/bug1-crash: exit code 0
replay regress/bug2-crash: exit code 0
300000 runs, exit code: 0, sanitizer reports: 0
What each campaign shows:
- Campaign 1 finds the easier bug first: the off-by-one in
rec_sumreads one byte past a sum record that ends the file. It is aREAD of size 1on the heap (libFuzzer copies each input into an exactly-sized heap buffer, so ASan's redzone sits right after the last byte). Without ASan this read returns some neighbouring byte and nothing visible happens. - Campaign 2, after the one-character fix, finds the stack overflow in
rec_name: aWRITE of size 35from a name record whose length byte says 35, with 35 bytes really present (the input-length check is correct; the buffer check is missing). A read bug hid a write bug: fuzzers stop at the first crash, which is why you fix and continue. - Campaign 3, after the second fix, replays both saved inputs cleanly and runs 300,000 inputs without a report. The two files in
regress/are now regression tests: run them in CI with every build.
Useful libFuzzer options
| Option | Effect |
|---|---|
-seed=N |
fixed random seed (reproducible campaigns) |
-runs=N, -max_total_time=S |
stop after N inputs or S seconds |
-max_len=N |
longest input to generate |
-dict=file |
tokens to insert, such as magic values |
-jobs=N -workers=N, -fork=N |
parallel campaigns sharing a corpus |
-merge=1 out in… |
keep a minimal set of inputs with the same coverage |
-minimize_crash=1 -runs=N crash |
shrink a crashing input |
-artifact_prefix=dir/ |
where crash, leak and timeout files go |
-timeout=S, -rss_limit_mb=M |
report slow inputs and memory blow-ups as bugs too |
libFuzzer itself is in maintenance mode (its authors moved on to newer engines), but it remains supported with bug fixes, ships with Clang, and its harness interface (LLVMFuzzerTestOneInput) is the de facto standard: AFL++, honggfuzz and OSS-Fuzz all accept the same harness.
Sanitizers as oracles
A fuzzer can only find what its oracle reports. Each sanitizer turns a class of silent bugs into crashes:
| Oracle | Reports | Build | Notes |
|---|---|---|---|
| ASan (+ LSan) | out-of-bounds, use-after-free, double free, leaks | -fsanitize=address |
about 2x slower; the default for fuzzing |
| UBSan | signed overflow, bad shifts, misaligned or null pointer use, invalid enum or bool values | -fsanitize=undefined -fno-sanitize-recover=undefined |
cheap, combine with ASan |
| MSan | reads of uninitialised memory | -fsanitize=memory (Clang) |
every library must be built with it |
| TSan | data races | -fsanitize=thread |
for multi-threaded harnesses |
| assertions | broken invariants of your own | assert() in the code |
free, and often the best oracle for logic |
| differential | two implementations disagree | harness compares results | finds logic bugs no sanitizer sees |
| round trip | decode(encode(x)) != x |
harness checks it | for codecs, serialisers |
The second session shows why the oracle matters. A toy image header computes width * height * 4 in a signed int. For large images that overflows, which is undefined behaviour in C and, in real code, the classic first step of an undersized allocation (Integer Overflow to Undersized Allocation). The same fuzzer, run with ASan only and then with UBSan:
cat > dims.c <<'SRC'
#include <stddef.h>
#include <stdint.h>
/* Toy image header: 16-bit width, 16-bit height; returns the pixel buffer size in bytes. */
int image_bytes(const uint8_t *d, size_t n) {
if (n < 4) return 0;
int w = d[0] << 8 | d[1], h = d[2] << 8 | d[3];
return w * h * 4; /* signed overflow for large images: undefined behaviour */
}
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
image_bytes(data, size);
return 0;
}
SRC
mkdir corpus && printf '\x00\x10\x00\x10' > corpus/seed # a 16 x 16 image
echo "== ASan only"
clang -g -O1 -fsanitize=fuzzer,address dims.c -o dims-asan
./dims-asan -seed=1 -runs=100000 corpus > a.log 2>&1; echo " exit code: $?, reports: $(grep -c ERROR a.log)"
echo "== UBSan as the oracle"
clang -g -O1 -fsanitize=fuzzer,undefined -fno-sanitize-recover=undefined dims.c -o dims-ubsan
./dims-ubsan -seed=1 -runs=100000 corpus > u.log 2>&1; echo " exit code: $?"
grep -m1 -oE 'dims.c:[0-9]+:[0-9]+: runtime error: [a-z ]+' u.log== ASan only
exit code: 0, reports: 0
== UBSan as the oracle
exit code: 1
dims.c:7:14: runtime error: signed integer overflow
With ASan alone, 100,000 inputs pass silently: the multiplication overflows all the time, but no memory is touched out of bounds, so nothing is reported. With UBSan as the oracle, the overflow at dims.c:7 stops the first campaign. Use both, and add assertions for the invariants only you know.
How these bugs are fixed and kept fixed
Each fix in the session is the smallest correct change at the root cause: compare the length with the destination buffer, loop with <. The integer overflow is fixed by computing the size in a wider unsigned type and checking it against a maximum (if ((uint64_t)w * h * 4 > MAX_IMAGE) reject). The crash inputs go into the regression corpus, and the harness goes into CI, so the next change that reintroduces either bug fails within minutes.
Pitfalls
- Fuzzing a release build without sanitizers finds only the bugs that happen to crash.
- Stopping at the first crash. Fix (or temporarily patch around) it and continue; the next bug is often worse.
- Harnesses that test the harness. If the harness itself allocates or parses, its own bugs show up as findings. Keep it minimal.
- Recoverable UBSan. Without
-fno-sanitize-recover, UBSan prints and continues, and the fuzzer never saves the input.
Practice
1. Why did campaign 1 report a heap overflow, when rec_sum has no heap buffer of its own?
The value it reads belongs to the input, and libFuzzer passes each input in a heap buffer of exactly size bytes. Reading one byte past a record at the end of the input reads past that heap buffer.
2. Write the harness for a library function int cfg_load(FILE *f).
Wrap the bytes in a memory stream: FILE *f = fmemopen((void *)data, size, "rb"); if (!f) return 0; cfg_load(f); fclose(f); return 0;. Handle size == 0 (some fmemopen versions reject it) by returning early.
3. Fix image_bytes so the UBSan campaign runs clean.
uint64_t bytes = (uint64_t)w * (uint64_t)h * 4; if (bytes > INT_MAX) return -1; return (int)bytes; (or reject images above a documented maximum size). With 16-bit dimensions the product fits in 64 bits, so no overflow remains.
Test yourself
What must a libFuzzer harness avoid?
- Returning 0
- State that survives between calls, non-determinism, and catching crashes
- Using the data pointer
- Being short
Why did campaign 2 find a bug that campaign 1 did not report?
- Different compiler
- libFuzzer stops at the first crash; once the read bug was fixed, the write bug became the first
- Campaign 1 was shorter
- The corpus was deleted
Why did the ASan-only build find nothing in image_bytes?
- The fuzzer was broken
- Signed integer overflow touches no memory out of bounds; only UBSan reports it
- The seed was wrong
- ASan was disabled
What does -fno-sanitize-recover=undefined do?
- Disables UBSan
- Makes the first UBSan report fatal, so the fuzzer saves the input
- Speeds up ASan
- Removes debug info