Algorithm Search⌘K

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
Properties
not concurrentnot externalnot persistent
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 mm 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 cur⊕prevcur \oplus prev goes up by one, where prevprev 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 curcur 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:

  • mm, a power of two;
  • trace[0…m−1]trace[0 \ldots m-1], one 8-bit counter per cell, for the current run;
  • prevprev, the id of the last block of the run shifted right by one bit; it is 0 when the run starts;
  • virgin[0…m−1]virgin[0 \ldots m-1], one byte per cell; it starts at 255 (all eight bits set), and bit bb of virgin[i]virgin[i] is cleared when some compared run had bucket bit bb in cell ii.

A block id is a number from 0 to m−1m - 1. 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: trace[i]trace[i] is the number of visits whose cell was ii, modulo 256, since the last start (or its bucket bit, after classify); prevprev is the last id shifted right; and virgin[i]=255virgin[i] = 255 with the bits of ⋁rtracer[i]\bigvee_r trace_r[i] cleared, where rr 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

  1. VISIT(B, cur)
  2. 1i <- (cur xor B.prev) mod m
  3. 2B.trace[i] <- (B.trace[i] + 1) mod 256
  4. 3B.prev <- cur >> 1
  5. CLASSIFY(B)
  6. 4for i <- 0 to m - 1 do
  7. 5B.trace[i] <- BUCKET(B.trace[i])
  8. HAS-NEW-BITS(B)
  9. 6result <- 0
  10. 7for i <- 0 to m - 1 do
  11. 8if B.trace[i] and B.virgin[i] is not 0 then
  12. 9if B.virgin[i] = 255 then result <- 2
  13. 10else if result = 0 then result <- 1
  14. 11B.virgin[i] <- B.virgin[i] and not B.trace[i]
  15. 12return result
  1. START-RUN(B)
  2. S1 B.trace[0 .. m - 1] <- 0
  3. S2 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 A→BA \to B and B→AB \to A 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, Θ(m)\Theta(m) each; VISIT is O(1)O(1). 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 m/wm/w word operations for a word of ww bits.

Example

A map of m=16m = 16 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 cur⊕(prev≫1)cur \oplus (prev \gg 1), are: start to A, 10; A to B, 6⊕5=36 \oplus 5 = 3; A to E, 1⊕5=41 \oplus 5 = 4; B to C, 7⊕3=47 \oplus 3 = 4; B to D, 8⊕3=118 \oplus 3 = 11; D to L, 5⊕4=15 \oplus 4 = 1; L to L, 5⊕2=75 \oplus 2 = 7. 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, virgin[7]=255−1−2−8=244virgin[7] = 255 - 1 - 2 - 8 = 244. 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.

  1. The trace counts cells. After START-RUN and visits with ids c1,…,ckc_1, \ldots, c_k, trace[i]trace[i] is the number of jj with cj⊕(cj−1≫1)=ic_j \oplus (c_{j-1} \gg 1) = i, modulo 256, with c0≫1c_0 \gg 1 read as 0.
  2. The virgin map is the complement of the seen set. After any sequence of operations, bit bb of virgin[i]virgin[i] is clear exactly when some compared run had bucket bit bb in cell ii.
  3. 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.
  4. Exactness without collisions. If the cell function (a,b)↦cb⊕(ca≫1)(a, b) \mapsto c_b \oplus (c_a \gg 1) 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).
  5. Collisions. If nn distinct edges get cells that are independent and uniform on {0,…,m−1}\{0, \ldots, m-1\}, the expected number of edges that share a cell with another edge, counted as nn minus the number of occupied cells, is n−m(1−(1−1/m)n)n - m(1 - (1 - 1/m)^n).

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 mm cells, mm a power of two, so "mod mm" in line L1 keeps the low bits. A block id is a number cc with 0≤c<m0 \le c < m. Write cell(a,c)=(c⊕(a≫1)) mod m\text{cell}(a, c) = (c \oplus (a \gg 1)) \bmod m for the cell of a visit of cc after a visit of aa, and cell(⊥,c)=c\text{cell}(\bot, c) = c for the first visit of a run, where ⊥≫1\bot \gg 1 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 1,2,4,…,1281, 2, 4, \ldots, 128.

A run is START-RUN, then visits with ids c1,…,ckc_1, \ldots, c_k, then CLASSIFY, then HAS-NEW-BITS. The runs 1,2,…1, 2, \ldots are numbered in the order of their HAS-NEW-BITS calls, and Tr[i]T_r[i] is the value of trace[i]trace[i] in run rr after CLASSIFY. Let Nr[i]=#{j:cell(cj−1,cj)=i}N_r[i] = \#\{ j : \text{cell}(c_{j-1}, c_j) = i \} in run rr, with c0=⊥c_0 = \bot.

Invariant. (A) During a run, after the visits c1,…,cjc_1, \ldots, c_j and before CLASSIFY, trace[i]=#{l≤j:cell(cl−1,cl)=i} mod 256trace[i] = \#\{ l \le j : \text{cell}(c_{l-1}, c_l) = i \} \bmod 256 for every ii, and prev=cj≫1prev = c_j \gg 1 (or 0 when j=0j = 0). (B) After CLASSIFY, trace[i]=BUCKET(Nr[i] mod 256)trace[i] = \text{BUCKET}(N_r[i] \bmod 256). (C) After the HAS-NEW-BITS call of run rr, virgin[i]=255∧¬⋁s≤rTs[i]virgin[i] = 255 \wedge \neg \bigvee_{s \le r} T_s[i] for every ii, and before the first call virgin[i]=255virgin[i] = 255.

Claim 1 (each operation keeps the invariant).

Create. The constructor sets virgin[i]=255virgin[i] = 255 for all ii, which is (C) with the empty union.

START-RUN. Lines S1 and S2 set every trace[i]trace[i] and prevprev to 0. This is (A) with j=0j = 0, 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 c1,…,cj−1c_1, \ldots, c_{j-1} and let c=cjc = c_j. Line L1 computes i∗=(c⊕prev) mod mi^* = (c \oplus prev) \bmod m. By (A), prev=cj−1≫1prev = c_{j-1} \gg 1, or 0 when j=1j = 1, so i∗=cell(cj−1,cj)i^* = \text{cell}(c_{j-1}, c_j). Line L2 adds 1 to trace[i∗]trace[i^*] modulo 256, so trace[i∗]trace[i^*] 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 prev=cj≫1prev = c_j \gg 1. So (A) holds after c1,…,cjc_1, \ldots, c_j. Since c<mc < m, prev=c≫1<m/2prev = c \gg 1 < m/2.

CLASSIFY. At the end of the visits, (A) gives trace[i]=Nr[i] mod 256trace[i] = N_r[i] \bmod 256. Lines L4 and L5 replace each trace[i]trace[i] by BUCKET(trace[i])\text{BUCKET}(trace[i]) 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 V[i]V[i] be the virgin byte before the call; by (C) it is 255∧¬⋁s<rTs[i]255 \wedge \neg \bigvee_{s < r} T_s[i]. Line L11 runs for each cell with Tr[i]∧V[i]≠0T_r[i] \wedge V[i] \ne 0 and sets virgin[i]=V[i]∧¬Tr[i]virgin[i] = V[i] \wedge \neg T_r[i]; for the other cells Tr[i]∧V[i]=0T_r[i] \wedge V[i] = 0, so V[i]∧¬Tr[i]=V[i]V[i] \wedge \neg T_r[i] = V[i] already. In both cases the new byte is 255∧¬⋁s≤rTs[i]255 \wedge \neg \bigvee_{s \le r} T_s[i], which is (C) for rr. □\square

Claim 2 (the answer). HAS-NEW-BITS of run rr returns 2 if there is a cell ii with Tr[i]≠0T_r[i] \ne 0 and Ts[i]=0T_s[i] = 0 for all s<rs < r; else 1 if there is a cell ii and a bit bb in Tr[i]T_r[i] that is in no Ts[i]T_s[i] with s<rs < r; else 0.

Proof. By (C), V[i]=255V[i] = 255 exactly when ⋁s<rTs[i]=0\bigvee_{s<r} T_s[i] = 0, that is, when every earlier run had Ts[i]=0T_s[i] = 0. And a bit bb of Tr[i]T_r[i] is in V[i]V[i] exactly when no earlier Ts[i]T_s[i] has it; so Tr[i]∧V[i]≠0T_r[i] \wedge V[i] \ne 0 exactly when cell ii has a new bucket. Line L6 starts with 0. Line L9 sets the result to 2 for a cell with a new bucket and V[i]=255V[i] = 255; since Tr[i]∧255=Tr[i]T_r[i] \wedge 255 = T_r[i], these are exactly the cells with Tr[i]≠0T_r[i] \ne 0 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. □\square

Claim 3 (exactness without collisions). Let EE be the set of edges (a,c)(a, c) that some run takes, including the entry edges (⊥,c)(\bot, c). Assume that cell\text{cell} is one to one on EE and that no run takes an edge 256 times or more. For an edge ee let nr(e)n_r(e) be the number of times run rr takes it, and let Pr={(e,BUCKET(nr(e))):nr(e)>0}P_r = \{ (e, \text{BUCKET}(n_r(e))) : n_r(e) > 0 \}. Then the result of run rr is 2 if run rr takes an edge that no earlier run took, else 1 if Pr⊈⋃s<rPsP_r \not\subseteq \bigcup_{s<r} P_s, else 0.

Proof. Since cell is one to one on EE, each cell ii is the cell of at most one edge eie_i of EE, and Nr[i]=nr(ei)N_r[i] = n_r(e_i) (or 0 if there is none). Since nr(ei)<256n_r(e_i) < 256, (B) gives Tr[i]=BUCKET(nr(ei))T_r[i] = \text{BUCKET}(n_r(e_i)), and Tr[i]≠0T_r[i] \ne 0 exactly when nr(ei)>0n_r(e_i) > 0. So "a cell with Tr[i]≠0T_r[i] \ne 0 and all earlier Ts[i]=0T_s[i] = 0" means "an edge taken by run rr and by no earlier run", and "a new bucket bit in cell ii" means "a pair (ei,BUCKET(nr(ei)))(e_i, \text{BUCKET}(n_r(e_i))) that is in no earlier PsP_s". Claim 2 then gives the statement. □\square

When cell is not one to one on EE, 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 nn distinct edges get cells X1,…,XnX_1, \ldots, X_n that are independent and uniform on {0,…,m−1}\{0, \ldots, m-1\}, and let OO be the number of distinct values among them. Then E[n−O]=n−m(1−(1−1/m)n)\mathbb{E}[n - O] = n - m(1 - (1 - 1/m)^n).

Proof. O=∑i=0m−1IiO = \sum_{i=0}^{m-1} I_i, where Ii=1I_i = 1 if some Xj=iX_j = i. By independence, Pr⁡[Ii=0]=∏jPr⁡[Xj≠i]=(1−1/m)n\Pr[I_i = 0] = \prod_j \Pr[X_j \ne i] = (1 - 1/m)^n. By linearity of expectation, E[O]=m(1−(1−1/m)n)\mathbb{E}[O] = m(1 - (1 - 1/m)^n), and E[n−O]=n−E[O]\mathbb{E}[n - O] = n - \mathbb{E}[O]. ■\blacksquare

Complexity

operation time memory
create Θ(m)\Theta(m) 2m2m bytes
start run Θ(m)\Theta(m), or Θ(m/w)\Theta(m/w) word writes
visit O(1)O(1): one xor, one increment, one shift
classify Θ(m)\Theta(m), or Θ(m/w)\Theta(m/w) when zero words are skipped
has new bits Θ(m)\Theta(m), or Θ(m/w)\Theta(m/w) word operations
one run of vv visits O(m+v)O(m + v)

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 m=65536m = 65536, 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 <- cur makes A→BA \to B and B→AB \to A one cell, and sends every self loop to cell 0. The right line is B.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 prevprev 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 (BUCKET(8)=16\text{BUCKET}(8) = 16).
  • 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.

edge_coverage_bitmap.pyI0RawGitHub
# 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 cur⊕(prev≫1)cur \oplus (prev \gg 1) 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

  1. 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)
  2. 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
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.per_step
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/4X4W12/text.yaml