Data structurecore
Edge coverage bitmap
Also called AFL bitmap, hit count bitmap.
A small array indexed by a hash of the previous and current basic block that counts edge hits in buckets, used as fuzzer feedback.
- Time
- O(m + v) worstO(1) per_step
- Space
- Θ(m) extra
- Where
- m = the number of cells of the map; v = the number of block visits in one run
- Model
- Word RAM
- Properties
- not concurrentnot externalnot persistent
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Michał Zalewski, 2013
The edge coverage bitmap is the feedback memory of AFL and of most greybox fuzzers after it. It is an array of one-byte counters, 64 kB in AFL. Each basic block of the target gets a random id when it is compiled, and each time a block runs, the counter at index goes up by one, where is the id of the block before, shifted right by one bit. So each cell stands for one edge of the control flow graph, up to hash collisions. After a run, each counter is replaced by its bucket (1, 2, 3, 4 to 7, 8 to 15, 16 to 31, 32 to 127, 128 or more), and the result is compared with a second array, the virgin map, that remembers every (cell, bucket) pair seen so far. The comparison says whether the run did something new, and that one bit drives the queue of coverage-guided fuzzing. The map is cheap because it is small, has no pointers and fits in the cache; it is inexact because two edges can share a cell.
In plain words
Give each block of code a random number. Keep a row of small counters, one row for the whole program. When the program jumps from one block to the next, mix the two block numbers into a counter position and add one to that counter. At the end of the run, round each counter to a coarse class: once, twice, three times, a few times, many times. Then compare the classes with a second row that remembers every class seen in any earlier run. If a counter that was always empty is now in use, the run reached a new jump. If only a class changed, a loop ran a different number of times. Two jumps can land on the same counter by bad luck, and then the fuzzer cannot tell them apart.
The abstract type
The map is an approximate summary of one run, and a set of everything seen so far. The operations are:
- start run: forget the counts of the last run;
- visit(cur): record that the block with id runs now;
- classify: turn each count into its bucket;
- has new bits: say whether the classified run has a (cell, bucket) pair that no earlier compared run had, and add its pairs to the seen set.
The exact type it approximates is the set of pairs (edge, bucket of the edge count) of a run, with the union over all runs as the seen set. When the cell function is one to one on the edges of the program and no count reaches 256, the map is exact (Correctness, item 4).
Representation
The map holds:
- , a power of two;
- , one 8-bit counter per cell, for the current run;
- , the id of the last block of the run shifted right by one bit; it is 0 when the run starts;
- , one byte per cell; it starts at 255 (all eight bits set), and bit of is cleared when some compared run had bucket bit in cell .
A block id is a number from 0 to . The buckets are written as one bit each, so that a set of buckets is one byte:
| count | 0 | 1 | 2 | 3 | 4 to 7 | 8 to 15 | 16 to 31 | 32 to 127 | 128 to 255 |
|---|---|---|---|---|---|---|---|---|---|
| BUCKET | 0 | 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128 |
The invariant is: is the number of visits whose cell was , modulo 256, since the last start (or its bucket bit, after classify); is the last id shifted right; and with the bits of cleared, where runs over the classified traces compared so far. AFL keeps a second virgin map for crashes and a third for hangs, with the same rules.
Operations
VISIT(B, cur)- 1
i <- (cur xor B.prev) mod m - 2
B.trace[i] <- (B.trace[i] + 1) mod 256 - 3
B.prev <- cur >> 1 CLASSIFY(B)- 4
for i <- 0 to m - 1 do - 5
B.trace[i] <- BUCKET(B.trace[i]) HAS-NEW-BITS(B)- 6
result <- 0 - 7
for i <- 0 to m - 1 do - 8
if B.trace[i] and B.virgin[i] is not 0 then - 9
if B.virgin[i] = 255 then result <- 2 - 10
else if result = 0 then result <- 1 - 11
B.virgin[i] <- B.virgin[i] and not B.trace[i] - 12
return result
START-RUN(B)S1 B.trace[0 .. m - 1] <- 0S2 B.prev <- 0
VISIT is the code that the compiler puts at the start of each block; in AFL it is the three lines cur_location = <COMPILE_TIME_RANDOM>; shared_mem[cur_location ^ prev_location]++; prev_location = cur_location >> 1;. The shift in line L3 has two uses that the AFL document gives: without it the edges and get the same cell, and a block that jumps to itself gets cell 0 for every such block. Line L2 wraps at 256, because the counter is one byte.
CLASSIFY makes the counts coarse. A loop that runs 4 times and one that runs 7 times look the same; a loop that runs 7 times and one that runs 8 times do not. The boundaries are AFL's design choice, a heuristic: they make small changes in a loop count visible and ignore the rest.
HAS-NEW-BITS reads the run against the virgin map. In line L8, and is the bitwise and of two bytes. A cell whose virgin byte is still 255 was empty in every earlier run, so the run reached a new cell, which is the strong signal 2. Otherwise a nonzero and means a new bucket of a known cell, the weak signal 1. Line L11 clears the bucket bits of the run. The fuzzer keeps the input when the result is not 0.
Costs: START-RUN, CLASSIFY and HAS-NEW-BITS read the whole map, each; VISIT is . AFL reads the map one machine word at a time and skips words that are 0, so a run that touches few cells costs about word operations for a word of bits.
Example
A map of cells and a small target with six blocks. Block A is the entry. If the first byte is F, block B runs, and then block C if the second byte is Z, else block D. If the first byte is not F, block E runs. Then block L runs once for each zero byte of the input. The ids are A = 10, B = 6, C = 7, D = 8, E = 1 and L = 5.
The cells of the edges, from , are: start to A, 10; A to B, ; A to E, ; B to C, ; B to D, ; D to L, ; L to L, . The edges A to E and B to C share cell 4.
Nine runs, each one START-RUN, the visits, CLASSIFY and HAS-NEW-BITS. "F00" means F and then two zero bytes.
| run | input | blocks | classified trace (cell: bucket) | result | cells with virgin byte below 255 |
|---|---|---|---|---|---|
| 1 | A | A E | 4: 1, 10: 1 | 2 | 4, 10 |
| 2 | F | A B D | 3: 1, 10: 1, 11: 1 | 2 | 3, 4, 10, 11 |
| 3 | FZ | A B C | 3: 1, 4: 1, 10: 1 | 0 | 3, 4, 10, 11 |
| 4 | F0 | A B D L | 1: 1, 3: 1, 10: 1, 11: 1 | 2 | 1, 3, 4, 10, 11 |
| 5 | F00 | A B D L L | as run 4, and 7: 1 | 2 | 1, 3, 4, 7, 10, 11 |
| 6 | F000 | A B D L L L | as run 4, and 7: 2 | 1 | the same |
| 7 | F00000 | A B D and five L | as run 4, and 7: 8 (count 4) | 1 | the same |
| 8 | F000000 | A B D and six L | as run 4, and 7: 8 (count 5) | 0 | the same |
| 9 | B | A E | 4: 1, 10: 1 | 0 | the same |
Run 3 is the lesson of the example: it reached block C, which no earlier run reached, and the map reports nothing new, because the edge B to C lands in cell 4 of the edge A to E. A fuzzer with this map throws the input away. Runs 6 and 7 are new only in their bucket. Run 8 has a new count, 5, but the same bucket as 4, so it is not new. After run 7, . The test file replays these nine runs.
Correctness
The proof file shows that each operation keeps the invariant of the representation, and derives these facts.
- The trace counts cells. After START-RUN and visits with ids , is the number of with , modulo 256, with read as 0.
- The virgin map is the complement of the seen set. After any sequence of operations, bit of is clear exactly when some compared run had bucket bit in cell .
- The answer is right for the map. HAS-NEW-BITS returns 2 exactly when the run has a nonzero cell that every earlier compared run had at 0, and 1 exactly when this is not the case but the run has a (cell, bucket) pair that no earlier run had.
- Exactness without collisions. If the cell function is one to one on the edges of the program (with the entry edge included) and no edge is taken 256 times or more in a run, then the answer of item 3 is the answer for the exact pairs (edge, bucket).
- Collisions. If distinct edges get cells that are independent and uniform on , the expected number of edges that share a cell with another edge, counted as minus the number of occupied cells, is .
Item 5 is a theorem about the uniform model; real block ids are random, but the edges of a program are not chosen at random, so the formula is an estimate. The map never claims more than item 3: it reports cells, not edges.
Proof: The edge coverage bitmap keeps its invariant and answers "new" exactly for its cellsfull
We use the pseudocode of the page. The map has cells, a power of two, so "mod " in line L1 keeps the low bits. A block id is a number with . Write for the cell of a visit of after a visit of , and for the first visit of a run, where is read as 0. Write BUCKET for the table of the page; it maps 0 to 0 and each count from 1 to 255 to exactly one of the eight bits .
A run is START-RUN, then visits with ids , then CLASSIFY, then HAS-NEW-BITS. The runs are numbered in the order of their HAS-NEW-BITS calls, and is the value of in run after CLASSIFY. Let in run , with .
Invariant. (A) During a run, after the visits and before CLASSIFY, for every , and (or 0 when ). (B) After CLASSIFY, . (C) After the HAS-NEW-BITS call of run , for every , and before the first call .
Claim 1 (each operation keeps the invariant).
Create. The constructor sets for all , which is (C) with the empty union.
START-RUN. Lines S1 and S2 set every and to 0. This is (A) with , since every count over the empty set of visits is 0. The virgin map is not changed, so (C) still holds.
VISIT. Assume (A) after and let . Line L1 computes . By (A), , or 0 when , so . Line L2 adds 1 to modulo 256, so is again the count of visits with that cell, modulo 256, and the other cells are unchanged, which is right because the new visit is not in their count. Line L3 sets . So (A) holds after . Since , .
CLASSIFY. At the end of the visits, (A) gives . Lines L4 and L5 replace each by once, which is (B). The flag of the implementation stops a second pass, which would be wrong because BUCKET is not idempotent.
HAS-NEW-BITS. Let be the virgin byte before the call; by (C) it is . Line L11 runs for each cell with and sets ; for the other cells , so already. In both cases the new byte is , which is (C) for .
Claim 2 (the answer). HAS-NEW-BITS of run returns 2 if there is a cell with and for all ; else 1 if there is a cell and a bit in that is in no with ; else 0.
Proof. By (C), exactly when , that is, when every earlier run had . And a bit of is in exactly when no earlier has it; so exactly when cell has a new bucket. Line L6 starts with 0. Line L9 sets the result to 2 for a cell with a new bucket and ; since , these are exactly the cells with that all earlier runs had at 0. Once the result is 2, line L10 never lowers it. Line L10 sets 1 for a cell with a new bucket when the result is still 0. So the result after the loop of line L7 is 2 if a cell of the first kind exists, else 1 if a cell with a new bucket exists, else 0. Line L12 returns it.
Claim 3 (exactness without collisions). Let be the set of edges that some run takes, including the entry edges . Assume that is one to one on and that no run takes an edge 256 times or more. For an edge let be the number of times run takes it, and let . Then the result of run is 2 if run takes an edge that no earlier run took, else 1 if , else 0.
Proof. Since cell is one to one on , each cell is the cell of at most one edge of , and (or 0 if there is none). Since , (B) gives , and exactly when . So "a cell with and all earlier " means "an edge taken by run and by no earlier run", and "a new bucket bit in cell " means "a pair that is in no earlier ". Claim 2 then gives the statement.
When cell is not one to one on , Claim 2 still holds, but two edges with one cell add their counts into one counter, and a new edge in an old cell can give the answer 0. The example of the page shows this case.
Claim 4 (expected hidden edges in the uniform model). Let distinct edges get cells that are independent and uniform on , and let be the number of distinct values among them. Then .
Proof. , where if some . By independence, . By linearity of expectation, , and .
Complexity
| operation | time | memory |
|---|---|---|
| create | bytes | |
| start run | , or word writes | |
| visit | : one xor, one increment, one shift | |
| classify | , or when zero words are skipped | |
| has new bits | , or word operations | |
| one run of visits |
The model is the word RAM. A visit touches one byte at a random position of the map, so a map that fits in the cache of the processor keeps each visit fast; this is the reason for 64 kB. A larger map has fewer collisions and costs more per run, because START-RUN, CLASSIFY and HAS-NEW-BITS read all of it.
Collisions in numbers. With item 5 and , the expected share of hidden edges is 0.76 percent for 1000 edges, 1.5 percent for 2000, 3.7 for 5000, 7.3 for 10000, 13.8 for 20000 and 30.0 for 50000. The AFL document gives 0.75, 1.5, 3.5, 7, 14 and 30 percent for the same numbers of branches, as its estimate for real targets.
Variants
- Ids without collisions. CollAFL (Gan et al. 2018) chooses the block ids, and the formula of the index, after it sees the control flow graph, so that the edges get different cells. Compilers can also number the edges directly and give each edge its own counter, as the edge counters of Clang's SanitizerCoverage do for libFuzzer.
- Larger maps. A map of 256 kB or more for large targets. Collisions go down, and the cost of each run goes up.
- Context and paths. Mix more history into the index, for example the ids of the last two blocks, or a hash of the calling context. The map then separates more behaviors and fills faster.
- Other feedback in the same array. Directed fuzzers add the distance of the run to a target (directed greybox fuzzing); others count comparisons that are close to being true.
- Use in the other parts of the fuzzer. The cells of a kept input feed corpus minimization and the path frequencies of a power schedule; the crash virgin map is AFL's coverage-based crash bucketing.
The map is a relative of the Bloom filter with one hash function and counters instead of bits: both answer "seen before" for a set with false positives, and both trade the size of the array against the rate of collisions.
When to use it
Use the map when the fuzzer runs the target thousands of times per second and needs one cheap answer per run: did this input do something new? It suits compiled targets with instrumentation at each block. When exactness matters more than speed, for example to compare the coverage of two tools, measure coverage with an exact tool after the campaign instead. When the program has far more edges than the map has cells, use a larger map or ids without collisions.
Pitfalls
- No shift. Writing line L3 as
B.prev <- curmakes and one cell, and sends every self loop to cell 0. The right line isB.prev <- cur >> 1. - No reset between runs. Without START-RUN, the counts of the last run stay in the trace, and line L8 sees old cells as part of the new run. Clear the trace and before each run.
- Raw counts against the virgin map. Skipping CLASSIFY (lines L4 and L5) makes every change of a loop count new, and the queue fills with copies of one input. Classify first; and classify only once per run, because BUCKET applied to a bucket is not the same bucket ().
- Reading cells as edges. A collision hides an edge, as run 3 of the example shows. Do not report the number of cells as the number of edges, and do not compare fuzzers by their map density.
- Counter wrap. A cell hit 256 times reads 0 (the counter is one byte), so a long loop can look like no loop. Some fuzzers stop the counter at 255 or skip 0 on overflow.
- Nondeterministic blocks. A block that runs or not depending on time or threads makes new bits appear in runs of the same input.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/edge-coverage-bitmap/. The authors are listed in prov/4X4W12.jsonl.
"""The edge coverage bitmap of AFL, as a small Python class.
Each basic block of the target has a block id, a number from 0 to m - 1
fixed before the run (AFL draws it at compile time). When a block runs,
the instrumentation calls visit(cur): the cell (cur xor prev) of the trace
map counts one more hit, and prev becomes cur >> 1. The shift keeps the
direction of an edge (A to B and B to A get different cells) and keeps a
block that jumps to itself away from cell 0.
After the run, classify() replaces each 8-bit counter by its bucket bit
(1, 2, 3, 4 to 7, 8 to 15, 16 to 31, 32 to 127, 128 to 255), and
has_new_bits() compares the trace with the virgin map. The virgin map
starts with all bits set and loses each bit that some kept run had. The
result is 2 if the run reached a cell that no earlier run reached, 1 if it
only reached a new bucket of a known cell, and 0 otherwise.
The bucket boundaries are AFL's design choice, not a theorem. Two edges
whose cells are equal are one cell for the map, so the map can hide an
edge (see expected_hidden_edges).
The targets in the tests are small Python functions that call visit; this
module never runs a real program.
"""
from typing import Callable
# BUCKET(c) for c = 0 .. 255, as a bit: 0, 1, 2, 4, 8, 16, 32, 64, 128.
COUNT_CLASS: tuple[int, ...] = tuple(
0 if c == 0 else
1 if c == 1 else
2 if c == 2 else
4 if c == 3 else
8 if c <= 7 else
16 if c <= 15 else
32 if c <= 31 else
64 if c <= 127 else
128
for c in range(256)
)
BUCKET_BITS = frozenset((0, 1, 2, 4, 8, 16, 32, 64, 128))
def bucket(count: int) -> int:
"""Return the bucket bit of an 8-bit hit count.
Precondition: 0 <= count <= 255. Cost: O(1).
"""
if not 0 <= count <= 255:
raise ValueError("a hit count of the map is one byte")
return COUNT_CLASS[count]
class EdgeCoverageBitmap:
"""A trace map and a virgin map of m cells each, with m a power of two.
Fields: size (m), trace (one 8-bit hit counter per cell), virgin (one
byte per cell; a set bit is a bucket that no kept run had), prev (the
shifted id of the last block of the current run) and classified (True
after classify and before the next start_run or visit).
Space: 2m bytes.
"""
def __init__(self, size: int = 65536) -> None:
"""Make an empty map of size cells.
Precondition: size is a power of two and at least 2.
Cost: O(m) to fill the two arrays.
"""
if size < 2 or size & (size - 1):
raise ValueError("the map size must be a power of two, at least 2")
self.size = size
self.trace = bytearray(size)
self.virgin = bytearray(b"\xff") * size
self.prev = 0
self.classified = False
def start_run(self) -> None:
"""Clear the trace map and prev before a run of the target.
Cost: O(m).
"""
self.trace[:] = bytes(self.size)
self.prev = 0
self.classified = False
def visit(self, cur: int) -> None:
"""Record that the block with id cur runs now.
Precondition: 0 <= cur < m, and classify was not called since the
last start_run. Cost: O(1).
"""
if not 0 <= cur < self.size:
raise ValueError("a block id is a cell number of the map")
if self.classified:
raise ValueError("call start_run before a new run")
i = (cur ^ self.prev) & (self.size - 1) # @line L1
self.trace[i] = (self.trace[i] + 1) & 0xFF # @line L2
self.prev = cur >> 1 # @line L3
def classify(self) -> None:
"""Replace each hit counter of the trace by its bucket bit.
Cost: O(m). A second call does nothing: BUCKET is not idempotent
(BUCKET(8) = 16), so the flag classified stops a second pass.
"""
if self.classified:
return
for i in range(self.size): # @line L4
self.trace[i] = COUNT_CLASS[self.trace[i]] # @line L5
self.classified = True
def has_new_bits(self) -> int:
"""Compare the classified trace with the virgin map and update it.
Returns 2 if some cell was reached for the first time, 1 if only a
new bucket of a known cell was reached, 0 otherwise. Every bucket
bit of the trace is cleared in the virgin map.
Precondition: classify was called for this run. Cost: O(m).
"""
if not self.classified:
raise ValueError("classify the trace first")
result = 0 # @line L6
for i in range(self.size): # @line L7
t = self.trace[i]
v = self.virgin[i]
if t & v: # @line L8
if v == 0xFF:
result = 2 # @line L9
elif result == 0:
result = 1 # @line L10
self.virgin[i] = v & ~t & 0xFF # @line L11
return result # @line L12
def run(self, target: Callable[[bytes, Callable[[int], None]], None], data: bytes) -> int:
"""Run target(data, visit) with a fresh trace, classify it and
return has_new_bits.
Cost: O(m) plus the cost of the target, with O(1) per visit.
"""
self.start_run()
target(data, self.visit)
self.classify()
return self.has_new_bits()
def covered_cells(self) -> list[int]:
"""Return the cells that some kept run reached (virgin byte not 255).
Cost: O(m).
"""
return [i for i in range(self.size) if self.virgin[i] != 0xFF]
def check_invariant(self) -> None:
"""Raise AssertionError if a field breaks the representation invariant.
Cost: O(m).
"""
m = self.size
assert m >= 2 and m & (m - 1) == 0
assert len(self.trace) == m and len(self.virgin) == m
assert 0 <= self.prev < m // 2
if self.classified:
assert all(t in BUCKET_BITS for t in self.trace)
def expected_hidden_edges(n: int, m: int) -> float:
"""Expected number of edges that share a cell with an earlier edge.
Model: n distinct edges, each hashed to a cell uniform on 0 .. m - 1,
independently. The map then has n - (number of occupied cells) fewer
cells than edges. The expected number of occupied cells is
m (1 - (1 - 1/m)^n). Precondition: n >= 0, m >= 1. Cost: O(log n).
"""
return n - m * (1.0 - (1.0 - 1.0 / m) ** n)
test_edge_coverage_bitmap.py 234 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/edge-coverage-bitmap/. The authors are listed in prov/4X4W12.jsonl.
import itertools
import random
from fractions import Fraction
import pytest
from edge_coverage_bitmap import COUNT_CLASS, EdgeCoverageBitmap, bucket, expected_hidden_edges
# The block ids of the example on the page, for a map of 16 cells.
PAGE_ID = {"A": 10, "B": 6, "C": 7, "D": 8, "E": 1, "L": 5}
def page_target(ids):
def target(data, visit):
visit(ids["A"])
if data[:1] == b"F":
visit(ids["B"])
if data[1:2] == b"Z":
visit(ids["C"])
else:
visit(ids["D"])
else:
visit(ids["E"])
for b in data:
if b == 0:
visit(ids["L"])
return target
def bucket_by_ranges(c):
"""Independent statement of the AFL buckets, from the documented ranges."""
ranges = [(0, 0, 0), (1, 1, 1), (2, 2, 2), (3, 3, 4), (4, 7, 8), (8, 15, 16),
(16, 31, 32), (32, 127, 64), (128, 255, 128)]
for lo, hi, bit in ranges:
if lo <= c <= hi:
return bit
raise AssertionError(c)
def test_page_example():
bm = EdgeCoverageBitmap(16)
target = page_target(PAGE_ID)
runs = [b"A", b"F", b"FZ", b"F\x00", b"F\x00\x00", b"F\x00\x00\x00",
b"F" + b"\x00" * 5, b"F" + b"\x00" * 6, b"B"]
results = []
for data in runs:
results.append(bm.run(target, data))
bm.check_invariant()
assert results == [2, 2, 0, 2, 2, 1, 1, 0, 0]
assert bm.covered_cells() == [1, 3, 4, 7, 10, 11]
assert bm.virgin[7] == 244 # buckets 1, 2 and 8 of cell 7 were seen
# The run "FZ" reached block C, but its edge B to C has cell 4, the cell of A to E.
assert (PAGE_ID["C"] ^ (PAGE_ID["B"] >> 1)) == (PAGE_ID["E"] ^ (PAGE_ID["A"] >> 1)) == 4
def test_bucket_table():
for c in range(256):
assert COUNT_CLASS[c] == bucket_by_ranges(c) == bucket(c)
with pytest.raises(ValueError):
bucket(256)
def test_direction_and_self_loop():
bm = EdgeCoverageBitmap(64)
bm.start_run()
bm.visit(12)
bm.visit(40) # edge 12 -> 40: cell 40 ^ 6
first = bytes(bm.trace)
bm.start_run()
bm.visit(40)
bm.visit(12) # edge 40 -> 12: cell 12 ^ 20
assert first != bytes(bm.trace)
bm.start_run()
bm.visit(9)
bm.visit(9) # self loop: cell 9 ^ 4 = 13, not 0
assert bm.trace[13] == 1 and bm.trace[0] == 0
def test_counter_wraps_at_256():
bm = EdgeCoverageBitmap(4)
bm.start_run()
for _ in range(256):
bm.visit(0)
assert bm.trace[0] == 0 # 256 hits of cell 0 read as no hit
bm.classify()
assert bm.has_new_bits() == 0
def test_errors_and_empty_run():
with pytest.raises(ValueError):
EdgeCoverageBitmap(12)
bm = EdgeCoverageBitmap(8)
with pytest.raises(ValueError):
bm.visit(8)
with pytest.raises(ValueError):
bm.has_new_bits()
bm.start_run()
bm.classify()
assert bm.has_new_bits() == 0 # an empty run reaches nothing
with pytest.raises(ValueError):
bm.visit(1)
bm.check_invariant()
def nested_target(ids):
"""A small byte parser with nested branches and a loop."""
def target(data, visit):
visit(ids[0])
if len(data) >= 1 and data[0] == 70:
visit(ids[1])
if len(data) >= 2 and data[1] == 90:
visit(ids[2])
if len(data) >= 3 and data[2] == 255:
visit(ids[3])
else:
visit(ids[4])
elif len(data) >= 1 and data[0] < 16:
visit(ids[5])
for b in data[1:]:
if b == 0:
visit(ids[6])
else:
visit(ids[7])
visit(ids[8])
return target
def block_sequence(target, data):
seq = []
target(data, seq.append)
return seq
def small_inputs():
alphabet = [0, 1, 70, 90, 255]
out = [bytes([b]) for b in range(256)] + [b""]
for n in (2, 3, 4):
out.extend(bytes(t) for t in itertools.product(alphabet, repeat=n))
return out
def test_against_exact_edges_on_all_small_inputs():
"""With no collision, the map decides "new" exactly as exact edge coverage."""
inputs = small_inputs()
rng = random.Random(7)
m = 256
# Exact edges, found by brute force over all the inputs, with block labels 0..8.
labels = list(range(9))
label_target = nested_target(labels)
all_edges = set()
for data in inputs:
seq = block_sequence(label_target, data)
all_edges.update(zip([None] + seq, seq))
while True:
ids = rng.sample(range(m), 9)
cells = {(ids[b] if a is None else ids[b] ^ (ids[a] >> 1)) for a, b in all_edges}
if len(cells) == len(all_edges):
break
target = nested_target(ids)
bm = EdgeCoverageBitmap(m)
seen_edges = set()
seen_pairs = set()
order = inputs[:]
rng.shuffle(order)
for data in order:
seq = block_sequence(label_target, data)
counts = {}
for e in zip([None] + seq, seq):
counts[e] = counts.get(e, 0) + 1
pairs = {(e, bucket_by_ranges(c % 256)) for e, c in counts.items()}
if set(counts) - seen_edges:
expected = 2
elif pairs - seen_pairs:
expected = 1
else:
expected = 0
assert bm.run(target, data) == expected
bm.check_invariant()
seen_edges |= set(counts)
seen_pairs |= pairs
assert len(bm.covered_cells()) == len(seen_edges) == len(all_edges)
def test_random_operations_against_model():
rng = random.Random(2024)
for _ in range(500):
m = rng.choice([2, 4, 8, 16])
bm = EdgeCoverageBitmap(m)
trace = [0] * m
virgin = [255] * m
prev = 0
classified = False
for _ in range(rng.randrange(1, 40)):
op = rng.random()
if op < 0.1:
bm.start_run()
trace, prev, classified = [0] * m, 0, False
elif op < 0.75 and not classified:
cur = rng.randrange(m)
bm.visit(cur)
cell = (cur ^ prev) % m
trace[cell] = (trace[cell] + 1) % 256
prev = cur // 2
elif not classified:
bm.classify()
trace = [bucket_by_ranges(t) for t in trace]
classified = True
else:
got = bm.has_new_bits()
new_cell = any(t and v == 255 for t, v in zip(trace, virgin))
new_bucket = any(t & v for t, v in zip(trace, virgin))
assert got == (2 if new_cell else 1 if new_bucket else 0)
virgin = [v & ~t & 255 for t, v in zip(trace, virgin)]
assert list(bm.trace) == trace
assert list(bm.virgin) == virgin
assert bm.prev == prev
bm.check_invariant()
def test_expected_hidden_edges_against_all_hash_assignments():
for n in range(0, 5):
for m in (1, 2, 3, 4):
total = Fraction(0)
for cells in itertools.product(range(m), repeat=n):
total += n - len(set(cells))
exact = total / m ** n
assert abs(expected_hidden_edges(n, m) - float(exact)) < 1e-9
def test_hidden_fraction_for_afl_map():
got = [round(100 * expected_hidden_edges(n, 65536) / n, 2) for n in (1000, 10000, 50000)]
assert got == [0.76, 7.26, 30.05]
History
Michał Zalewski released AFL in 2013 and described the map in its technical whitepaper: compile-time random block ids, the index into a 64 kB shared memory region, the hit count buckets, and the virgin maps for new behaviors, crashes and hangs. The whitepaper also gave the table of collisions for 1000 to 50000 branches. The design spread to most greybox fuzzers. Böhme, Pham and Roychoudhury (2016) used the paths that the map tells apart as the states of their Markov chain. Gan et al. (2018) measured the collisions in real programs and removed them with CollAFL's choice of ids.
References
- Michał Zalewski, Technical whitepaper for afl-fuzz, AFL documentation, Section 1 (coverage measurements, the instrumentation, the 64 kB map and the table of collisions) and Section 2 (detecting new behaviors, the hit count buckets)
- Shuitao Gan, Chao Zhang, Xiaojun Qin, Xuwen Tu, Kang Li, Zhongyu Pei and Zuoning Chen, CollAFL, path sensitive fuzzing, IEEE Symposium on Security and Privacy 2018, pp. 679 to 696, the edge collisions of the AFL map and the assignment of block ids without collisions
- Marcel Böhme, Van-Thuan Pham and Abhik Roychoudhury, Coverage-based greybox fuzzing as Markov chain, Proceedings of CCS 2016, pp. 1032 to 1043, the background section on AFL and its coverage feedback
- Valentin J. M. Manès, HyungSeok Han, Choongwoo Han, Sang Kil Cha, Manuel Egele, Edward J. Schwartz and Maverick Woo, The art, science, and engineering of fuzzing, a survey, IEEE Transactions on Software Engineering 47(11), 2021, pp. 2312 to 2331, the sections on greybox fuzzing and coverage feedback
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 4X4W12 Edit this page History Report an error Markdown