Algorithmcore
Crash bucketing
Also called crash deduplication, stack hash bucketing.
Groups crashes from fuzzing into likely distinct bugs by hashing the top frames of their call stacks.
- Time
- O(c m) worst
- Space
- O(c N) extra
- Where
- N = the number of frames in the key; c = the number of crashes; m = the largest number of frames in a stack
- Model
- Word RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- David Molnar, Xue Cong Li, David A. Wagner, 2009
Crash bucketing groups the failing inputs of a fuzzing campaign into buckets, with the hope that each bucket is one bug. A campaign can produce thousands of crashing inputs for a handful of bugs, and a person can read only a few. The usual key is the stack hash: take the call stack at the moment of the failure, drop frames of helper functions that every crash passes through, keep the top frames, and hash their function names together with the kind of failure. Crashes with the same key share a bucket. This is a heuristic, and Klees et al. (2018) showed by measurement that it fails both ways: a small merges different bugs that fail in the same function, and a large splits one bug that is reached along different paths.
In plain words
When a program crashes, it can report which function it was in, which function called that one, and so on back to the start. Two crashes that stopped in the same function, called from the same place, are probably the same problem. So for each crash, take the names of the last few functions, skip helpers that appear in every crash, and turn the list into a short code. Put crashes with the same code in one pile, and look at one crash from each pile. Taking too few names puts different problems in one pile. Taking too many names splits one problem into many piles when the program reaches it in different ways.
The problem
The input is a list of crash records, each with the kind of failure (for example "index out of range" or "assertion") and a call stack, innermost frame first, plus a number and a set of function names to ignore. The output is a partition of the crashes into buckets. The aim is that the buckets match the bugs, where a bug means a defect that one fix removes, but the true bugs are not known; the algorithm only sees the stacks.
The algorithm
BUCKET-CRASHES(crashes, N, ignore)- 1
buckets <- empty map from keys to lists of crashes - 2
for each crash c, in order do - 3
g <- the frames of c whose function is not in ignore, innermost first - 4
key <- HASH(the kind of c, and the (module, function) pairs of the first min(N, |g|) frames of g) - 5
append c to buckets[key] - 6
return buckets
Line L3 drops frames that carry no information about the bug, such as a memory copy helper or the frames of an error handler; without it, every crash that fails inside the helper has the same top frame. Line L4 leaves out addresses, because they change with every build, and by default leaves out line numbers, which change with every edit. The fuzzy stack hash of Molnar, Li and Wagner (2009) is a middle way: for each of the top three frames it hashes the function name, the object file and the line number without its last digit, so that small edits nearby do not change the key. Klees et al. note that is often chosen from 3 to 5. The hash is only a short name: the bucket is defined by the tuple. If the 64-bit names behave like random values, the chance that two different tuples among get the same name is at most by the union bound.
Example
A made-up program has three bugs. main calls f, g or h by the first byte of the input. Both f and g call format. Bug 1 is in format, which sets a wrong length when the second byte is 2; it fails later, in output called by prepare, inside the helper copy_bytes. Bug 2 is a failed check in check, called by h. Bug 3 is in h, which passes bad data to output directly. This is the shape of the example of Klees et al. (their Figure 7): one bug reached on two paths, and a shared function where different bugs fail. The stacks below have copy_bytes removed by the ignore list.
| crash | input | bug | stack, innermost first | |||
|---|---|---|---|---|---|---|
| 1 | 0 2 | 1 | output, prepare, format, f, main | b1 | b1 | b1 |
| 2 | 1 2 | 1 | output, prepare, format, g, main | b1 | b1 | b2 |
| 3 | 2 1 | 2 | check, h, main | b2 | b2 | b3 |
| 4 | 2 2 | 3 | output, h, main | b1 | b3 | b4 |
| 5 | 0 2 1 | 1 | output, prepare, format, f, main | b1 | b1 | b1 |
| 6 | 1 2 0 | 1 | output, prepare, format, g, main | b1 | b1 | b2 |
With , bugs 1 and 3 share bucket b1 because both fail in output: 2 buckets for 3 bugs. With , the buckets match the bugs. With , bug 1 splits into b1 and b2 by its caller, f or g: 4 buckets for 3 bugs. Without the ignore list, and both see copy_bytes and output on top for bugs 1 and 3, and merge them. Over all 16 crashing inputs of length up to 3 with bytes 0 to 2, the number of buckets is 2 for , 3 for and , and 4 for from 4 to 6; the test file checks these counts and checks every partition against a pairwise comparison of the stacks.
No value of is right for every program. Here works because the bug and the failure are three frames apart; in another program they are not. On a real benchmark, Klees et al. bucketed the crashing inputs of cxxfilt with and compared the buckets with the bugs found by matching each input to the commit that fixed it: 595 stack hashes corresponded to 9 bugs, and about 16 percent of the hashes matched inputs of more than one bug. These are measurements on one program.
Correctness
Statement. BUCKET-CRASHES returns a partition of the crashes in which two crashes share a bucket exactly when they have the same kind and the same first kept frames (up to hash collisions of the short names). Moreover, the partition for refines the partition for , and a key with exact line numbers refines a key with coarse line numbers, which refines a key without them.
Key invariant. After each pass of line L5, every crash seen so far is in exactly one bucket, the bucket of its own key. The refinement holds because the key for determines the key for : if two crashes agree on their first kept frames, they agree on their first . The proof file has the details.
What the algorithm does not promise is that buckets are bugs. That is a measurement for each program and each , and the only reliable check is ground truth, for example the set of fixes that remove the crashes.
Proof: Correctness of stack hash bucketingfull
Fix the ignore set and the kind of line handling. For a crash let be the list of its kept frames, innermost first (line L3), and for let
where maps a frame to its (module, function) pair, or to (module, function, line div ) when lines are used with divisor . Line L4 computes and names it by a hash . We assume that is injective on the keys that occur; the page bounds the chance that it is not.
Claim 1 (partition). BUCKET-CRASHES returns a partition of the crashes, and crashes and share a bucket if and only if .
Proof. Invariant: after the loop has handled the first crashes, each of them is in exactly one list, namely the list of of its own key, and no list holds anything else. This holds for after line L1. Line L5 adds crash to exactly one list, the one named by its key, and changes nothing else. At line L6 all crashes are handled, so the lists are disjoint, nonempty and cover all crashes. Two crashes are in the same list if and only if their names are equal, which by injectivity of means their keys are equal.
Claim 2 (refinement in N). If , then . Hence every bucket for lies inside one bucket for .
Proof. Equal keys for have the same kind and the same length , with equal entries in positions 1 to . If , then and the keys for are the same tuples. If , then both stacks have at least kept frames, the keys for are the first entries, and they are equal. By Claim 1, a bucket for is a set of crashes with one key for , hence with one key for , so it lies inside one bucket for .
Claim 3 (refinement in the line handling). Let be a multiple of . Equal keys with lines divided by give equal keys with lines divided by , and equal keys with any lines give equal keys without lines.
Proof. For integers , if then , by the identity for positive integers and . Dropping the third component of every frame maps equal tuples to equal tuples. The refinement of buckets follows as in Claim 2.
Claim 4 (order). The partition does not depend on the order of the crashes.
Proof. By Claim 1 the partition is the set of classes of the relation "equal keys", which is defined crash by crash. Only the names of the lists in the order of first appearance depend on the order.
The claims say nothing about bugs. A bug is not a function of the stack, so no key can be right for every program; the example of the page shows a merge for and a split for .
Complexity
Line L3 reads the whole stack, , and line L4 hashes names; with a hash map for the buckets, each crash costs expected time, so all crashes take with . The extra space is one key of names per bucket and one entry per crash, at most. Getting the stack is the expensive part in practice: it needs a debugger or a sanitizer report for each crash, and symbols for the names.
Properties
- Deterministic. The same stacks give the same buckets.
- Monotone in N. Larger gives more, smaller buckets; trades merging against splitting.
- No ground truth. Buckets can merge distinct bugs and split one bug.
- Order-independent. The partition does not depend on the order of the crashes; only the names of the buckets in order of first appearance do.
Variants and improvements
- Coverage-based uniqueness. AFL calls a crash unique if its trace has an edge tuple that no earlier crash had, or lacks a tuple that every earlier crash had. This needs no stack, but it counts paths, not bugs, and Klees et al. measured that it overcounts.
- Fuzzy matching. Instead of exact equality of the top frames, compare stacks by an edit distance or a weighted similarity, so that a frame that differs deep in the stack counts less than one on top.
- Semantic bucketing. van Tonder, Kotheimer and Le Goues (2018) apply candidate fixes, such as a bounds check inserted at the failing site, and group crashes that the same fix removes; this approximates the definition of a bug as a fix.
- Minimize first. Shrinking each crashing input with delta debugging before bucketing removes noise from the paths and makes stacks of the same bug more alike.
- Sanitizer reports. A memory or undefined-behavior sanitizer reports the kind of error and the stack where it happened, which is often closer to the bug than the place where the program finally fails.
When to use it
Use it as the first triage step after any campaign that produces more crashes than a person can read, and to count findings while the campaign runs. Pick small (a few frames), use an ignore list for allocators, copy helpers and error handlers, and look at one crash from each bucket. When the number of bugs matters, for example to compare two fuzzers, do not report buckets or unique crashes as bugs: Klees et al. recommend counting bugs by ground truth, such as distinct fixes.
Pitfalls
- Reading the stack from the wrong end. Writing line L3 as "the frames of , outermost first" makes the key start with
mainand the dispatch functions, so nearly all crashes fall into a few buckets by their entry point. The right line takes the innermost frames first. - Hashing addresses or line numbers. Writing line L4 with code addresses gives a new key whenever the build changes, and line numbers give a new key after each edit; the same bug then shows up as new. The right line uses module and function names, and line numbers only within one build.
- No ignore list. A crash inside a copy helper or an abort handler has that helper on top. With line L3 written as "g <- all frames of c", every such crash shares the first frame. The right line drops a list of known helper functions.
- Counting buckets as bugs. A bucket count is a measurement of stacks, not of bugs, and it moves with .
- Truncated or missing stacks. Stack overflow, corrupted memory and missing symbols give short or wrong stacks; put such crashes in a bucket of their own kind and look at them separately.
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/crash-bucketing/. The authors are listed in prov/HT3WNS.jsonl.
"""Crash bucketing by a hash of the top frames of the call stack.
A crash record holds the kind of failure and a call stack, innermost frame
first. Frames whose function is in an ignore list (for example a helper
that copies bytes, or the frames of an error handler) are dropped, and the
key of the crash is the kind of failure with the (module, function) pairs
of the first N remaining frames. Crashes with equal keys go into the same
bucket. The key is hashed with SHA-256 to a short name for display.
That one bucket is one bug is a heuristic: a small N can merge different
bugs that fail in the same function, and a large N can split one bug that
is reached on different paths. The stacks here are simulated lists of
frames built by the caller; nothing reads the frames of a real process.
"""
import hashlib
from dataclasses import dataclass
from typing import Sequence
@dataclass(frozen=True)
class Frame:
"""One frame of a simulated call stack."""
module: str
function: str
line: int = 0
@dataclass(frozen=True)
class CrashRecord:
"""A crash: the kind of failure and the stack, innermost frame first."""
kind: str
stack: tuple[Frame, ...]
def stack_key(crash: CrashRecord, n: int, ignore: frozenset[str] = frozenset(),
line_div: int = 0) -> tuple:
"""Return the key of a crash: its kind and the top n kept frames.
A frame is kept if its function is not in ignore. With line_div = 0 the
key of a frame is (module, function). With line_div >= 1 it also holds
line // line_div: 1 keeps the exact line, and 10 drops the last digit,
as in the fuzzy stack hash of Molnar, Li and Wagner (2009).
Precondition: n >= 1 and line_div >= 0. Cost: O(m) for m frames.
"""
if n < 1 or line_div < 0:
raise ValueError("need n >= 1 and line_div >= 0")
kept = [f for f in crash.stack if f.function not in ignore] # @line L3
top = kept[:n]
if line_div:
frames = tuple((f.module, f.function, f.line // line_div) for f in top)
else:
frames = tuple((f.module, f.function) for f in top)
return (crash.kind, frames) # @line L4
def key_name(key: tuple) -> str:
"""Return a short stable name for a key: the first 16 hex digits of its
SHA-256 hash. Cost: O(size of the key)."""
kind, frames = key
text = kind + "\n" + "\n".join("/".join(str(p) for p in f) for f in frames)
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
def bucket_crashes(crashes: Sequence[CrashRecord], n: int, ignore: frozenset[str] = frozenset(),
line_div: int = 0) -> dict[str, list[int]]:
"""Group crashes by stack_key and return a map from the bucket name to
the indices of its crashes, in the order of first appearance.
Precondition: n >= 1. Cost: O(c m) for c crashes of at most m frames.
"""
buckets: dict[str, list[int]] = {} # @line L1
for i, c in enumerate(crashes): # @line L2
name = key_name(stack_key(c, n, ignore, line_div))
buckets.setdefault(name, []).append(i) # @line L5
return buckets # @line L6
def partition(buckets: dict[str, list[int]]) -> list[frozenset[int]]:
"""Return the buckets as a list of sets of crash indices, in order.
Cost: O(c)."""
return [frozenset(v) for v in buckets.values()]
test_crash_bucketing.py 219 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/crash-bucketing/. The authors are listed in prov/HT3WNS.jsonl.
import itertools
import random
import pytest
from crash_bucketing import CrashRecord, Frame, bucket_crashes, key_name, partition, stack_key
IGNORE = frozenset({"copy_bytes"})
def toy_program(x: bytes):
"""A made-up program with three bugs, run on a simulated stack.
It returns None, or (bug id, CrashRecord). The stack is a list that the
toy pushes to and pops from; it is not the stack of the Python process.
Bug 1 is in format (a bad length) and fails later in output, reached
from f or from g. Bug 2 is a failed check in check. Bug 3 is in h, which
calls output with bad data.
"""
stack: list[Frame] = []
def fail(bug, kind):
return bug, CrashRecord(kind, tuple(reversed(stack)))
def call(name, line, body, module="app"):
stack.append(Frame(module, name, line))
out = body()
stack.pop()
return out
def copy_bytes(bad):
return ("fault",) if bad else None
def output(bad, bug):
r = call("copy_bytes", 12, lambda: copy_bytes(bad), module="lib")
if r is not None:
stack.append(Frame("lib", "copy_bytes", 12))
res = fail(bug, "index out of range")
stack.pop()
return res
return None
def prepare():
return call("output", 40, lambda: output(True, 1))
def fmt():
if len(x) >= 2 and x[1] == 2:
return call("prepare", 30, prepare)
return None
def check():
return fail(2, "assertion")
def h():
if len(x) >= 2 and x[1] == 1:
return call("check", 50, check)
if len(x) >= 2 and x[1] == 2:
return call("output", 60, lambda: output(True, 3))
return None
def main():
if len(x) == 0:
return None
if x[0] == 0:
return call("f", 10, lambda: call("format", 20, fmt))
if x[0] == 1:
return call("g", 11, lambda: call("format", 21, fmt))
return call("h", 12, h)
return call("main", 1, main)
EXAMPLE_INPUTS = [bytes([0, 2]), bytes([1, 2]), bytes([2, 1]), bytes([2, 2]), bytes([0, 2, 1]), bytes([1, 2, 0])]
def example_crashes():
out = [toy_program(x) for x in EXAMPLE_INPUTS]
assert all(o is not None for o in out)
return [o[1] for o in out], [o[0] for o in out]
def labels(buckets, count):
"""Name the buckets b1, b2, ... in order of first appearance, per crash."""
lab = [""] * count
for k, idx in enumerate(buckets.values()):
for i in idx:
lab[i] = "b" + str(k + 1)
return lab
def test_page_example_stacks():
crashes, bugs = example_crashes()
assert bugs == [1, 1, 2, 3, 1, 1]
names = [[f.function for f in c.stack] for c in crashes]
assert names[0] == ["copy_bytes", "output", "prepare", "format", "f", "main"]
assert names[1] == ["copy_bytes", "output", "prepare", "format", "g", "main"]
assert names[2] == ["check", "h", "main"]
assert names[3] == ["copy_bytes", "output", "h", "main"]
def test_page_example_buckets():
crashes, bugs = example_crashes()
got = {n: labels(bucket_crashes(crashes, n, IGNORE), 6) for n in (1, 2, 3, 5)}
assert got[1] == ["b1", "b1", "b2", "b1", "b1", "b1"]
assert got[2] == ["b1", "b1", "b2", "b3", "b1", "b1"]
assert got[3] == ["b1", "b1", "b2", "b3", "b1", "b1"]
assert got[5] == ["b1", "b2", "b3", "b4", "b1", "b2"]
# Without the ignore list, N = 1 sees only copy_bytes for bugs 1 and 3.
assert labels(bucket_crashes(crashes, 1), 6) == ["b1", "b1", "b2", "b1", "b1", "b1"]
assert labels(bucket_crashes(crashes, 2), 6) == ["b1", "b1", "b2", "b1", "b1", "b1"]
def test_key_and_name_edge_cases():
c = CrashRecord("assertion", ())
assert stack_key(c, 3) == ("assertion", ())
with pytest.raises(ValueError):
stack_key(c, 0)
only_ignored = CrashRecord("x", (Frame("lib", "copy_bytes"),))
assert stack_key(only_ignored, 2, IGNORE) == ("x", ())
a = CrashRecord("k", (Frame("m", "f", 1),))
b = CrashRecord("k", (Frame("m", "f", 2),))
assert stack_key(a, 1) == stack_key(b, 1)
assert stack_key(a, 1, line_div=1) != stack_key(b, 1, line_div=1)
# Dropping the last digit of the line, as the fuzzy stack hash does.
c41 = CrashRecord("k", (Frame("m", "f", 41),))
c48 = CrashRecord("k", (Frame("m", "f", 48),))
c52 = CrashRecord("k", (Frame("m", "f", 52),))
assert stack_key(c41, 1, line_div=10) == stack_key(c48, 1, line_div=10)
assert stack_key(c41, 1, line_div=10) != stack_key(c52, 1, line_div=10)
with pytest.raises(ValueError):
stack_key(a, 1, line_div=-1)
assert key_name(stack_key(a, 1)) == key_name(stack_key(b, 1))
assert len(key_name(stack_key(a, 1))) == 16
assert bucket_crashes([], 3) == {}
# The kind is part of the key.
assert stack_key(CrashRecord("j", a.stack), 1) != stack_key(a, 1)
def all_crashes(max_len):
out = []
for n in range(max_len + 1):
for t in itertools.product(range(3), repeat=n):
r = toy_program(bytes(t))
if r is not None:
out.append(r)
return out
def brute_force_groups(crashes, n, ignore):
"""Group by comparing every pair of crashes frame by frame."""
def same(a, b):
if a.kind != b.kind:
return False
fa = [(f.module, f.function) for f in a.stack if f.function not in ignore][:n]
fb = [(f.module, f.function) for f in b.stack if f.function not in ignore][:n]
return fa == fb
groups = []
for i, c in enumerate(crashes):
for g in groups:
if same(crashes[g[0]], c):
g.append(i)
break
else:
groups.append([i])
return [frozenset(g) for g in groups]
def test_all_small_inputs_against_brute_force():
found = all_crashes(3)
crashes = [c for _, c in found]
bugs = [b for b, _ in found]
# Inputs of length 2 and 3 over 0, 1, 2: bug 1 from 0 2 and 1 2, bug 2 from 2 1, bug 3 from 2 2.
assert len(crashes) == 16
counts = {}
for n in range(1, 7):
p = partition(bucket_crashes(crashes, n, IGNORE))
assert p == brute_force_groups(crashes, n, IGNORE)
counts[n] = len(p)
pure = all(len({bugs[i] for i in g}) == 1 for g in p)
whole = all(len([g for g in p if any(bugs[i] == b for i in g)]) == 1 for b in set(bugs))
if n == 1:
assert not pure and whole
elif n in (2, 3):
assert pure and whole
else:
assert pure and not whole
assert counts == {1: 2, 2: 3, 3: 3, 4: 4, 5: 4, 6: 4}
def refines(fine, coarse):
return all(any(g <= h for h in coarse) for g in fine)
def random_crash(rng):
funcs = ["a", "b", "c", "d", "skip"]
m = rng.randint(0, 6)
stack = tuple(Frame(rng.choice(["m1", "m2"]), rng.choice(funcs), rng.randint(1, 3)) for _ in range(m))
return CrashRecord(rng.choice(["k1", "k2"]), stack)
def test_random_refinement_and_brute_force():
rng = random.Random(8)
ignore = frozenset({"skip"})
for _ in range(600):
crashes = [random_crash(rng) for _ in range(rng.randint(0, 8))]
prev = None
for n in range(1, 8):
p = partition(bucket_crashes(crashes, n, ignore))
assert p == brute_force_groups(crashes, n, ignore)
assert sorted(i for g in p for i in g) == list(range(len(crashes)))
if prev is not None:
assert refines(p, prev)
prev = p
exact = partition(bucket_crashes(crashes, 3, ignore, line_div=1))
fuzzy = partition(bucket_crashes(crashes, 3, ignore, line_div=2))
plain = partition(bucket_crashes(crashes, 3, ignore))
assert refines(exact, fuzzy) and refines(fuzzy, plain)
History
Earlier test generation work, such as the SAGE whitebox fuzzer, already reported bugs by a stack hash. Molnar, Li and Wagner (2009) found that a plain stack hash split bugs that developers saw as one, and introduced a fuzzy stack hash over the top three frames for the bug reports of their test generation system; they chose three as a trade-off and accepted that it can merge distinct bugs. AFL (2013) chose a coverage-based rule instead, and its whitepaper explains why it does not use stack hashes. Klees et al. (2018) compared both rules with ground truth from fixes on cxxfilt and measured that both count one bug many times, the coverage rule far more, and that stack hashes also merge inputs of different bugs. van Tonder, Kotheimer and Le Goues (2018) proposed bucketing by fixes.
References
- George Klees, Andrew Ruef, Benji Cooper, Shiyi Wei and Michael Hicks, Evaluating fuzz testing, Proceedings of CCS 2018, pp. 2123 to 2138, the subsection on stack hashes with Figure 7 and Table 3 (stack hashing results for cxxfilt)
- David Molnar, Xue Cong Li and David A. Wagner, Dynamic test generation to find integer bugs in x86 binary Linux programs, USENIX Security 2009, pp. 67 to 82, the discussion of bug bucketing and the fuzzy stack hash
- Michal Zalewski, Technical whitepaper for afl-fuzz, section 8, De-duping crashes
- Rijnard van Tonder, John Kotheimer and Claire Le Goues, Semantic crash bucketing, Proceedings of ASE 2018, pp. 612 to 622, grouping crashes by the fix that removes them
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 | W2 basic |
|
Tag HT3WNS Edit this page History Report an error Markdown