Algorithmadvanced
Generational search
Also called whitebox fuzzing, SAGE search.
Expands each concolic run by negating every branch condition on its path at once, producing a generation of new inputs to test.
- Time
- O(R (T + m C + log R)) worst
- Space
- O(R T) extra
- Where
- C = the cost of one solver call; R = the number of runs; T = the largest number of steps of one run; m = the largest number of recorded conditions on one run
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Patrice Godefroid, Michael Y. Levin, David Molnar, 2008
Generational search is the search order of SAGE, the whitebox fuzzer of Godefroid, Levin and Molnar. Like concolic testing, it runs the program on concrete inputs and records the path condition of each run. Unlike the depth-first search of DART, it negates every condition of a run, not only the deepest open one, and so turns one run into a whole generation of new inputs. A bound stored with each input stops the search from producing the same path twice, and a score by new code coverage picks the run to expand next. The design fits long runs on large input files, where one symbolic run is expensive and should pay for many new tests.
In plain words
Run the program on a seed input and write down every test it passes on the way, in terms of the input. A depth-first tool would now flip only the last test. Generational search flips each test in turn: for the first test, find an input that goes the other way there; for the second test, find an input that goes the same way at the first test and the other way at the second; and so on to the end. Each answer is a new input, a child of the seed. Then run all the children, see which ones reach code not seen before, and expand the best one next in the same way. A child does not flip the tests that its parent already handled, so the search never makes the same input path twice.
The problem
The problem is the one of concolic testing. The input is a program of the toy IR with integer parameters, a set of allowed inputs, a seed in and a solver. The output is a list of tests, one for each path that some input of follows, or as many as a budget allows.
What is decidable is also the same. A path can have an undecidable condition over unbounded integers with products, and a program can have infinitely many paths (see path explosion). The algorithm is complete relative to its solver: with a solver that is exact over a finite , it finds every path of once and stops. On this page is the box and the solver tries the points of the box. SAGE uses an SMT solver on bit vectors, and in a real use the search stops at a time budget, with no claim about the paths that it did not reach.
The algorithm
RUN is the concolic run of concolic testing: it returns the outcome, the blocks visited and the conditions , numbered from 0, with the implicit conditions of divisions and shifts. Each run carries a bound : the search negates only the conditions at positions and later. SOLVE takes a hint, the input of the parent run, and changes only the inputs that occur in the query, as SAGE does: its new input is the old one with the solved bytes replaced.
GENERATIONAL-SEARCH(P, v0, SOLVE)- 1
r0 <- RUN(P, v0); output r0; covered <- the blocks of r0 - 2
W <- {r0}, with b(r0) = 0 - 3
while W is not empty do - 4
remove from W the run r with the highest score (the oldest on ties) - 5
let c_0 ... c_(m-1) be the conditions of r - 6
for j <- b(r) to m - 1 do - 7
v' <- SOLVE(c_0 and ... and c_(j-1) and not c_j), with the input of r as the hint - 8
if there is no v' then continue - 9
r' <- RUN(P, v'); output r' - 10
score(r') <- the number of blocks of r' not in covered; add them to covered - 11
b(r') <- j + 1; add r' to W
The bound on line L11 is the key. The child agrees with on the positions before and is opposite at . Flipping at a position before would ask for an input that agrees with before that position and differs there, which itself, or one of its other children, already covers. Flipping at would give back the side of . So is expanded only at positions and later.
The score is the number of new blocks that a run covers when it is made, SAGE's measure of incremental coverage. Ties go to the older run. The score changes only the order of the runs; without a budget, the set of runs is the same for every order.
Example
The parameters are , and , with the symbols , and . The bug is reached when at least two of the three tests hold. It is a smaller form of the four-byte example of the SAGE paper, in which a counter grows for each byte that has a given value.
entry:
n = 0
t = a == 7
br t i1 j1
i1:
n = n + 1
jump j1
j1:
t = b == 5
br t i2 j2
i2:
n = n + 1
jump j2
j2:
t = c == 3
br t i3 j3
i3:
n = n + 1
jump j3
j3:
u = 2 <= n
br u bad ok
bad:
ret 1
ok:
ret 0
On every path, is a constant, so the last branch has a constant condition and RUN does not record it. Each run records three conditions, , and , each true or false.
| run | input | parent, flipped position | bound | outcome | score |
|---|---|---|---|---|---|
| 1 | (0, 0, 0) | seed | 0 | ret 0 | 5 |
| 2 | (7, 0, 0) | run 1, position 0 | 1 | ret 0 | 1 (i1) |
| 3 | (0, 5, 0) | run 1, position 1 | 2 | ret 0 | 1 (i2) |
| 4 | (0, 0, 3) | run 1, position 2 | 3 | ret 0 | 1 (i3) |
| 5 | (7, 5, 0) | run 2, position 1 | 2 | ret 1 | 1 (bad) |
| 6 | (7, 0, 3) | run 2, position 2 | 3 | ret 1 | 0 |
| 7 | (0, 5, 3) | run 3, position 2 | 3 | ret 1 | 0 |
| 8 | (7, 5, 3) | run 5, position 2 | 3 | ret 1 | 0 |
The seed gives the first generation, runs 2 to 4, from three queries. Run 2 is expanded next, at positions 1 and 2 only, and its first child reaches the bug. Run 4 has bound 3 and three conditions, so it has no children. The search makes 8 runs for the 8 paths, with 7 solver calls that all succeed, and no path appears twice. Each child keeps the inputs of its parent that its query does not mention: run 5 keeps from run 2.
Correctness
The full proof is in the proof file. Assume that SOLVE is exact over a finite , the seed is in , and RUN tracks every operation exactly. Let be the tree of the decision sequences of the inputs of , as in the proof for concolic testing; its leaves are the paths of .
- A child follows its query. The input from line L7 satisfies , so its run records the same first conditions and then .
- Descendants keep the prefix. A run made by flipping position has bound , and its own children flip at positions or later. By induction, every descendant of agrees with at the positions to .
- No path twice. Take two different runs and their lowest common ancestor in the tree of parents. If is one of them, the other one is opposite to at the position where its chain leaves . Otherwise the two chains leave by flips at two different positions ; the first run is opposite to at and the second agrees with there. In both cases the paths differ.
- Every path. Take a leaf and follow a chain of runs that agree with at all positions below their bound, starting at the seed, whose bound is 0. If the current run is not , let be the first position where they differ; then . An input that follows satisfies the query at position , so the exact solver returns a model, and gets a child that agrees with at the positions 0 to , below its bound . The first difference grows at each step, so after at most steps the run is .
- The end. Each run is a new leaf and has at most leaves, and each run is expanded once.
Exactly solver calls succeed, and the total number of calls is , where is the number of conditions of .
Proof: Generational search finds every feasible path once under an exact solverfull
Setting. is a program of the toy IR with integer parameters and only constants, copies and binary operations. is a set of inputs that contains the seed. SOLVE is exact over : for a list of conditions it returns an input of that satisfies all of them if one exists, and reports that there is none otherwise. (A decision procedure for the theory of the conditions is exact over ; the brute-force solver of the page is exact over the box.) RUN tracks every operation symbolically and records no condition with a constant expression. We assume one of two cases:
- (A) is loop-free, and is any set, for example ; or
- (B) is finite and every run of on an input of ends.
A condition is a pair ; an input satisfies it when "" has the truth value and does not trap. For an input , is the list of conditions that RUN records, its decision sequence.
Lemma 1: the record is a function of the decisions
Claim. If satisfies the first conditions of , then starts with the same conditions, and after them both runs reach the same point with the same symbolic store.
Proof. Induction over the steps of the run of . Both runs start at the entry with the store , and each constant, copy and operation changes the store in a way that does not depend on the input. A branch or check on a constant expression goes the same way in both runs. A branch or check on a symbolic expression records a condition with the same in both runs; if it is with , then satisfies it, so and are both zero or both nonzero, and both runs take the same side. The symbolic store gives the true value of each name as a function of the input, by the same induction.
Consequences. Let be the set of the decision sequences of the inputs of and their prefixes.
- (a) After a prefix, the expression of the next condition, or the end of the run, is fixed. So is a binary tree, and no decision sequence is a proper prefix of another: the decision sequences are the leaves of .
- (b) An input satisfies the conditions of a node if and only if its decision sequence lies below .
- (c) Different leaves correspond to different paths, and the same leaf to the same path: two leaves first differ at against , which at a branch sends the runs to different blocks (a branch with equal targets records nothing) and at a check makes one run trap and the other go on.
- (d) has finitely many leaves. In case (B) there are at most . In case (A) a run of a loop-free program with blocks visits at most blocks, each block records at most a fixed number of conditions, so every leaf has length at most some , and a binary tree of depth has at most leaves.
Lemma 2: a child follows its query
Claim. Let have the decision sequence , and let be the child made at position on line L9. Then starts with .
Proof. The input of satisfies , so by Lemma 1 its run records these conditions and then reaches the point of with the same store, where it records a condition with the expression of . The input satisfies , so the recorded sense is that of .
Lemma 3: descendants keep the prefix
Call the runs made by the search nodes, and the relation "made on line L9 while expanding" the parent relation; the seed is the root.
Claim. If was made at position , then every descendant of (including ) has a decision sequence that agrees with at the positions .
Proof. Induction on the distance from . For it is trivial. A child of a descendant is made at a position . Every descendant of other than was itself made at a position at least of its parent, and bounds only grow along a chain: where . So . By Lemma 2, the child agrees with at the positions below , which include , and agrees with there by induction.
Theorem
Claim. In case (A) or (B), the search stops; the paths of the runs it outputs are pairwise different; and they are exactly the paths of the inputs of . Exactly solver calls succeed, where is the number of runs, and the number of calls is .
Proof. No path twice. Let be two nodes and their lowest common ancestor.
- If , let be the child of on the chain to , made at position . By Lemma 2, has at position , where has , and by Lemma 3, agrees with at position . So .
- Otherwise let and be the children of on the two chains, made at positions and . Line L6 makes at most one child per position, so ; say . By Lemma 2, has at position , and agrees with at every position below , so it has there. By Lemma 3, and agree with and at position . So .
By (c) the paths differ as well.
Termination. Each node is a leaf of (its input is in ), and different nodes are different leaves, so by (d) there are finitely many nodes. Each node enters once and is expanded once, with finitely many calls, so the loop stops.
Every path. Let be a leaf of . We build a chain of nodes such that each agrees with at every position below . Take as the seed, with . If , stop. Otherwise the two sequences are different leaves, so neither is a prefix of the other, and they first differ at some position , with by the property of . When is expanded (it is, since the loop runs until is empty), line L6 reaches . An input that follows satisfies of , by (b), so the exact solver returns a model and line L9 makes a child at position . By Lemma 2, agrees with at the positions , which are the positions below . The first position of difference with grows strictly along the chain and is at most the length of , so the chain reaches .
Solver calls. The expansion of makes one call for each from to , which gives the total. Each successful call makes one run, and every run but the seed comes from one successful call.
Remarks. The order of line L4 is not used anywhere, so every order of the worklist gives the same set of runs. Case (A) with needs a decision procedure for the conditions; with products of inputs over unbounded integers there is none, by the negative answer to Hilbert's tenth problem, and the result then holds only relative to whatever the solver can decide. The bound is used twice: in Lemma 3, to keep the prefix of descendants fixed, which gives "no path twice"; and in the chain of "every path", which shows that the bound never hides a leaf.
Complexity
Let be the number of runs, the largest number of conditions on a run, the largest number of steps of a run and the cost of a solver call. Each run is made once at cost and expanded once with at most calls. The priority queue costs per run. The total is , the same order as depth-first concolic testing; the difference is the order of the runs, not their number.
The space is larger. The worklist can hold every run made so far, and this implementation keeps the conditions of each, in total. SAGE keeps only the input of each run in the worklist, , and runs the program again symbolically when it expands a run. Depth-first search needs only one stack of entries.
In SAGE, is large: a run on a file of thousands of bytes can record many thousands of conditions, and the symbolic run takes much longer than a concrete one. Generational search turns that one symbolic run into up to new tests.
Properties
- Complete relative to the solver, with no repeats. With exact tracking and an exact solver over a finite , every path of is found exactly once.
- The order does not change the result without a budget. Any choice on line L4 explores the same set of runs. With a budget, the order decides which paths are found, which is why SAGE scores by new coverage.
- Each symbolic run pays for many tests. Depth-first search gets one new input per run. Generational search gets up to .
- Children of one run are independent. The queries of one expansion share nothing but the parent's path condition, so a tool can solve them in parallel and run the children in parallel.
- No false alarms. Every test is a real run, so a crash that the search finds is a real crash, as in all concolic methods.
Variants and improvements
- Depth-first and breadth-first orders. The depth-first search of concolic testing expands only the deepest open condition and keeps one stack. Generational search with a first-in, first-out worklist instead of the score is a breadth-first search over the generations of the search tree.
- Query optimizations in SAGE. The SAGE paper drops the conditions that share no input with the negated one, skips a condition that is already in the path condition, limits how often the conditions of one branch are flipped, and drops a condition of a loop that a later condition of the same branch implies. The solver of this page does the first in a weak form: it changes only the inputs that occur in the query.
- Grammar-based whitebox fuzzing. Godefroid, Kiezun and Levin (2008) replace the bytes of the input by the tokens of a grammar, so that the generated inputs pass the parser of the program. See grammar-based fuzzing.
- Hybrid fuzzing. A coverage-guided fuzzer does the cheap exploration, and a generational expansion of selected inputs gets past the narrow checks such as magic numbers and checksums.
When to use it
Use generational search for concolic testing of programs whose runs are long and whose inputs are large, such as parsers of file formats, media decoders and network protocol handlers. It suits a fixed time budget, because it spreads the search over the whole tree instead of the deepest corner. For short runs, depth-first concolic testing is simpler and needs less memory. For a proof that a program has no bug, use a verifier instead: whitebox fuzzing proves nothing about the paths that it does not reach.
Pitfalls
- The wrong bound. If a child gets the bound instead of , it flips position again, and the solver returns an input of its parent's path. If the bound is too large, paths are lost. With the bound each path appears once, under the conditions of the proof.
- Divergence. A child whose run does not follow its query, because of concretization or calls to code that is not instrumented, can repeat a path or leave a subtree out. The implementation stops with an error; SAGE detects divergences and counts them.
- Memory. A worklist of complete runs grows with the number of tests. Store inputs and recompute the conditions.
- A greedy score. Scoring by new blocks favors runs that found new code early. A deep bug behind code that is already covered gets a low score and waits. The score helps under a budget; it is not a guarantee.
- Overflow and the solver. As in all concolic methods, the solver must use the arithmetic of the machine, or its inputs follow other paths than predicted.
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/generational-search/. The authors are listed in prov/WF74QR.jsonl.
"""Generational search, the search of SAGE, on the toy IR.
concolic_run(prog, args) runs prog on concrete arguments and keeps a
symbolic expression over the input symbols next to each value. It returns a
Run with the arguments, the outcome, the labels of the blocks visited, the
index of the instruction that trapped (or None) and the conditions. A
condition is a pair (e, sense): the run went the way on which
(value of e != 0) equals sense. A br adds its condition, a division or a
remainder adds "divisor != 0", and a shift adds "0 <= amount <= 63".
Conditions with a constant expression are not recorded.
Expressions are tuples: ("in", i), ("k", c) and ("op", op, a, b).
brute_force_solver(lo, hi) returns a solver that is exact over the box
[lo, hi]^k. It changes only the inputs that occur in the conditions and
keeps the others at the values of a hint, the input of the parent run, as
SAGE does. Among the values of a changed input it tries the hint value
first, then the others in increasing order.
generational(prog, solve) runs the search and returns the runs in the
order in which it made them. Each run carries its bound, its parent (an
index into the list, or None), the position it flipped and its score.
"""
import heapq
import itertools
import toyir
_DIV = ("/", "%")
_SHIFT = ("<<", ">>")
class Run:
__slots__ = ("args", "outcome", "labels", "trap_at", "conds", "bound", "parent", "flip", "score")
def __init__(self, args, outcome, labels, trap_at, conds):
self.args = args
self.outcome = outcome
self.labels = labels
self.trap_at = trap_at
self.conds = conds
self.bound = 0
self.parent = None
self.flip = None
self.score = 0
def path(self):
return (self.labels, self.outcome[0], self.trap_at)
def _mk(op, a, b):
if a[0] == "k" and b[0] == "k":
return ("k", toyir._binop(op, a[1], b[1]))
return ("op", op, a, b)
def concolic_run(prog, args, fuel=10000):
"""One concrete run with the symbolic store next to it. Each instruction
and each terminator uses one unit of fuel, as in toyir.run."""
args = list(args)
if len(args) != len(prog.params):
raise ValueError("expected %d arguments" % len(prog.params))
env = dict(zip(prog.params, args))
sym = {x: ("in", i) for i, x in enumerate(prog.params)}
def val(a):
if isinstance(a, int):
return a
if a not in env:
raise toyir.UndefinedName(a)
return env[a]
def sval(a):
return ("k", a) if isinstance(a, int) else sym[a]
label = prog.entry
labels = [label]
conds = []
while True:
block = prog.blocks[label]
for idx, ins in enumerate(block.instrs):
if fuel <= 0:
return Run(args, ("fuel",), tuple(labels), None, conds)
fuel -= 1
kind = ins[0]
if kind == "const":
env[ins[1]] = ins[2]
sym[ins[1]] = ("k", ins[2])
elif kind == "copy":
env[ins[1]] = val(ins[2])
sym[ins[1]] = sval(ins[2])
elif kind == "op":
_, x, op, a, b = ins
va, vb = val(a), val(b)
sa, sb = sval(a), sval(b)
guard = None
if op in _DIV:
guard, ok = sb, vb != 0
elif op in _SHIFT:
guard = _mk("&", _mk("<=", ("k", 0), sb), _mk("<=", sb, ("k", 63)))
ok = 0 <= vb <= 63
if guard is not None:
if guard[0] != "k":
conds.append((guard, ok))
if not ok:
return Run(args, ("trap",), tuple(labels), idx, conds)
env[x] = toyir._binop(op, va, vb)
sym[x] = _mk(op, sa, sb)
else:
raise ValueError("concolic_run handles const, copy and op only, not %r" % (kind,))
if fuel <= 0:
return Run(args, ("fuel",), tuple(labels), None, conds)
fuel -= 1
t = block.term
if t[0] == "ret":
return Run(args, ("ret", val(t[1])), tuple(labels), None, conds)
if t[0] == "jump":
label = t[1]
else:
taken = val(t[1]) != 0
s = sval(t[1])
if s[0] != "k" and t[2] != t[3]:
conds.append((s, taken))
label = t[2] if taken else t[3]
labels.append(label)
def evaluate(e, inputs):
"""The value of e on the inputs; raises toyir._Trap on a bad division
or shift. Shared subterms are evaluated once."""
memo = {}
def ev(e):
tag = e[0]
if tag == "k":
return e[1]
if tag == "in":
return inputs[e[1]]
key = id(e)
if key not in memo:
memo[key] = toyir._binop(e[1], ev(e[2]), ev(e[3]))
return memo[key]
return ev(e)
def holds(conds, inputs):
"""True when the inputs satisfy every condition; a trap counts as false."""
for e, sense in conds:
try:
v = evaluate(e, inputs)
except toyir._Trap:
return False
if (v != 0) != sense:
return False
return True
def inputs_of(conds):
"""The indices of the inputs that occur in the conditions."""
out = set()
stack = [e for e, _ in conds]
seen = set()
while stack:
e = stack.pop()
if id(e) in seen:
continue
seen.add(id(e))
if e[0] == "in":
out.add(e[1])
elif e[0] == "op":
stack.append(e[2])
stack.append(e[3])
return sorted(out)
def brute_force_solver(lo=-8, hi=8):
"""A solver that is exact over [lo, hi]^k. Inputs that do not occur in
the conditions keep their hint values; a changed input tries its hint
value first. The hint must lie in the box."""
def solve(conds, k, hint):
idx = inputs_of(conds)
orders = [[hint[i]] + [x for x in range(lo, hi + 1) if x != hint[i]] for i in idx]
v = list(hint)
for choice in itertools.product(*orders):
for i, x in zip(idx, choice):
v[i] = x
if holds(conds, v):
return list(v)
return None
return solve
def negate(cond):
e, sense = cond
return (e, not sense)
def generational(prog, solve=None, start=None, fuel=10000, max_runs=100000):
"""The generational search. Raises RuntimeError on a divergence, which
exact symbolic tracking rules out."""
if solve is None:
solve = brute_force_solver()
k = len(prog.params)
v0 = list(start) if start is not None else [0] * k
first = concolic_run(prog, v0, fuel) # @line L1
runs = [first]
covered = set(first.labels)
first.score = len(covered)
work = [(-first.score, 0)] # @line L2
while work and len(runs) < max_runs: # @line L3
_, i = heapq.heappop(work) # @line L4
r = runs[i]
conds = r.conds # @line L5
for j in range(r.bound, len(conds)): # @line L6
query = conds[:j] + [negate(conds[j])]
model = solve(query, k, r.args) # @line L7
if model is None: # @line L8
continue
child = concolic_run(prog, model, fuel) # @line L9
if child.conds[: j + 1] != query:
raise RuntimeError("divergence: the run left the expected prefix")
new = set(child.labels) - covered # @line L10
covered |= new
child.score = len(new)
child.bound = j + 1 # @line L11
child.parent = i
child.flip = j
runs.append(child)
heapq.heappush(work, (-child.score, len(runs) - 1))
if len(runs) >= max_runs:
break
return runs
toyir.py 602 lines
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy IR: three-address code in basic blocks.
A program is Program(params, blocks). blocks is a dict from label to
Block(instrs, term), kept in insertion order, and the first label is the
entry. Instructions are tuples:
("const", x, k) x = k
("copy", x, a) x = y
("op", x, op, a, b) x = a op b
("phi", x, {pred: a}) x = phi [pred: a, ...]
("addr", p, x) p = &x
("load", x, p) x = *p
("store", p, a) *p = a
("alloc", p) p = alloc
("call", x, f, args) x = call f(a, b) (args is a list)
Terminators are ("jump", L), ("br", a, L1, L2) and ("ret", a). An operand a
is a str (a name) or an int. The text form of a copy of an int is the text
form of a constant, so parse always gives ("const", x, k) for "x = k".
"""
from dataclasses import dataclass, field
import re
OPS = ("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", "<=", "==", "!=")
@dataclass
class Block:
instrs: list = field(default_factory=list)
term: tuple = ("ret", 0)
@dataclass
class Program:
params: list
blocks: dict
@property
def entry(self):
return next(iter(self.blocks))
class UndefinedName(Exception):
"""A name was read before any definition."""
# ---------------------------------------------------------------- text form
_NAME = r"[A-Za-z_][A-Za-z0-9_.]*"
_INT = r"-?[0-9]+"
def _operand(tok):
if re.fullmatch(_INT, tok):
return int(tok)
if re.fullmatch(_NAME, tok):
return tok
raise ValueError("bad operand: %r" % tok)
def _name(tok):
if not re.fullmatch(_NAME, tok):
raise ValueError("bad name: %r" % tok)
return tok
def _parse_instr(line):
toks = line.split()
if toks[0] == "jump" and len(toks) == 2:
return "term", ("jump", _name(toks[1]))
if toks[0] == "br" and len(toks) == 4:
return "term", ("br", _operand(toks[1]), _name(toks[2]), _name(toks[3]))
if toks[0] == "ret" and len(toks) == 2:
return "term", ("ret", _operand(toks[1]))
lhs, eq, rhs = line.partition("=")
if not eq:
raise ValueError("bad line: %r" % line)
lhs, rhs = lhs.strip(), rhs.strip()
if lhs.startswith("*"):
return "instr", ("store", _name(lhs[1:].strip()), _operand(rhs))
x = _name(lhs)
if rhs.startswith("phi"):
body = rhs[3:].strip()
if not (body.startswith("[") and body.endswith("]")):
raise ValueError("bad phi: %r" % line)
args = {}
inner = body[1:-1].strip()
if inner:
for part in inner.split(","):
pred, colon, a = part.partition(":")
if not colon:
raise ValueError("bad phi: %r" % line)
args[_name(pred.strip())] = _operand(a.strip())
return "instr", ("phi", x, args)
if rhs.startswith("call "):
m = re.fullmatch(r"call\s+(" + _NAME + r")\s*\((.*)\)", rhs)
if not m:
raise ValueError("bad call: %r" % line)
inner = m.group(2).strip()
args = [_operand(a.strip()) for a in inner.split(",")] if inner else []
return "instr", ("call", x, m.group(1), args)
if rhs == "alloc":
return "instr", ("alloc", x)
if rhs.startswith("&"):
return "instr", ("addr", x, _name(rhs[1:].strip()))
if rhs.startswith("*"):
return "instr", ("load", x, _name(rhs[1:].strip()))
parts = rhs.split()
if len(parts) == 1:
a = _operand(parts[0])
if isinstance(a, int):
return "instr", ("const", x, a)
return "instr", ("copy", x, a)
if len(parts) == 3 and parts[1] in OPS:
return "instr", ("op", x, parts[1], _operand(parts[0]), _operand(parts[2]))
raise ValueError("bad instruction: %r" % line)
def parse(text):
"""Parse the text form. A line "# params: a, b" gives the parameters;
without it, the parameters are the names that are read and never
defined, in the order of their first use."""
params = None
blocks = {}
cur = None
for raw in text.splitlines():
line = raw.strip()
if not line:
continue
if line.startswith("#"):
m = re.fullmatch(r"#\s*params:(.*)", line)
if m:
inner = m.group(1).strip()
params = [_name(p.strip()) for p in inner.split(",")] if inner else []
continue
if line.endswith(":") and re.fullmatch(_NAME, line[:-1]):
label = line[:-1]
if label in blocks:
raise ValueError("duplicate label: %r" % label)
cur = label
blocks[label] = Block([], None)
continue
if cur is None:
raise ValueError("instruction outside a block: %r" % line)
if blocks[cur].term is not None:
raise ValueError("instruction after the terminator in %r" % cur)
kind, item = _parse_instr(line)
if kind == "term":
blocks[cur].term = item
else:
blocks[cur].instrs.append(item)
for label, b in blocks.items():
if b.term is None:
raise ValueError("block %r has no terminator" % label)
if not blocks:
raise ValueError("empty program")
prog = Program([], blocks)
if params is None:
params = _free_names(prog)
prog.params = params
return prog
def _free_names(prog):
defined = set()
for b in prog.blocks.values():
for ins in b.instrs:
d = defs(ins)
if d is not None:
defined.add(d)
out = []
for b in prog.blocks.values():
for ins in b.instrs:
for a in uses(ins):
if a not in defined and a not in out:
out.append(a)
for a in term_uses(b.term):
if a not in defined and a not in out:
out.append(a)
return out
def _show_instr(ins):
k = ins[0]
if k == "const":
return "%s = %d" % (ins[1], ins[2])
if k == "copy":
return "%s = %s" % (ins[1], ins[2])
if k == "op":
return "%s = %s %s %s" % (ins[1], ins[3], ins[2], ins[4])
if k == "phi":
return "%s = phi [%s]" % (ins[1], ", ".join("%s: %s" % (p, a) for p, a in ins[2].items()))
if k == "addr":
return "%s = &%s" % (ins[1], ins[2])
if k == "load":
return "%s = *%s" % (ins[1], ins[2])
if k == "store":
return "*%s = %s" % (ins[1], ins[2])
if k == "alloc":
return "%s = alloc" % ins[1]
if k == "call":
return "%s = call %s(%s)" % (ins[1], ins[2], ", ".join(str(a) for a in ins[3]))
raise ValueError("bad instruction: %r" % (ins,))
def _show_term(t):
if t[0] == "jump":
return "jump %s" % t[1]
if t[0] == "br":
return "br %s %s %s" % (t[1], t[2], t[3])
if t[0] == "ret":
return "ret %s" % (t[1],)
raise ValueError("bad terminator: %r" % (t,))
def show(prog):
lines = ["# params: " + ", ".join(prog.params)]
for label, b in prog.blocks.items():
lines.append(label + ":")
for ins in b.instrs:
lines.append(" " + _show_instr(ins))
lines.append(" " + _show_term(b.term))
return "\n".join(lines) + "\n"
# ---------------------------------------------------------- names and graph
def defs(ins):
"""The name an instruction defines, or None for a store."""
return None if ins[0] == "store" else ins[1]
def uses(ins):
"""The names an instruction reads, in order (phi operands included)."""
k = ins[0]
if k == "const" or k == "alloc" or k == "addr":
ops = []
elif k == "copy":
ops = [ins[2]]
elif k == "op":
ops = [ins[3], ins[4]]
elif k == "phi":
ops = list(ins[2].values())
elif k == "load":
ops = [ins[2]]
elif k == "store":
ops = [ins[1], ins[2]]
elif k == "call":
ops = list(ins[3])
else:
raise ValueError("bad instruction: %r" % (ins,))
return [a for a in ops if isinstance(a, str)]
def term_uses(t):
if t[0] == "br" or t[0] == "ret":
return [t[1]] if isinstance(t[1], str) else []
return []
def succs(prog, label):
"""Successor labels of a block, without repeats, in terminator order."""
t = prog.blocks[label].term
if t[0] == "jump":
return [t[1]]
if t[0] == "br":
return [t[2]] if t[2] == t[3] else [t[2], t[3]]
return []
def edges(prog):
return [(a, b) for a in prog.blocks for b in succs(prog, a)]
def preds(prog):
"""Dict from label to the list of predecessor labels, in block order."""
out = {label: [] for label in prog.blocks}
for a, b in edges(prog):
out[b].append(a)
return out
def is_acyclic(prog):
color = {label: 0 for label in prog.blocks}
for root in prog.blocks:
if color[root]:
continue
color[root] = 1
stack = [(root, iter(succs(prog, root)))]
while stack:
v, it = stack[-1]
w = next(it, None)
if w is None:
color[v] = 2
stack.pop()
elif color[w] == 1:
return False
elif color[w] == 0:
color[w] = 1
stack.append((w, iter(succs(prog, w))))
return True
def paths(prog):
"""Every path from the entry to a ret block, as a list of labels.
The CFG must be acyclic."""
if not is_acyclic(prog):
raise ValueError("paths needs an acyclic CFG")
out = []
def walk(path):
last = path[-1]
s = succs(prog, last)
if not s:
out.append(list(path))
for w in s:
path.append(w)
walk(path)
path.pop()
walk([prog.entry])
return out
# ------------------------------------------------------------------ running
class _Trap(Exception):
pass
class _Fuel(Exception):
pass
def _binop(op, a, b):
if not isinstance(a, int) or not isinstance(b, int):
raise TypeError("arithmetic on a pointer")
if op == "+":
return a + b
if op == "-":
return a - b
if op == "*":
return a * b
if op == "/" or op == "%":
if b == 0:
raise _Trap()
q = abs(a) // abs(b)
if (a < 0) != (b < 0):
q = -q
return q if op == "/" else a - b * q
if op == "&":
return a & b
if op == "|":
return a | b
if op == "^":
return a ^ b
if op == "<<" or op == ">>":
if b < 0 or b > 63:
raise _Trap()
return a << b if op == "<<" else a >> b
if op == "<":
return int(a < b)
if op == "<=":
return int(a <= b)
if op == "==":
return int(a == b)
if op == "!=":
return int(a != b)
raise ValueError("bad operator: %r" % op)
class _Frame:
"""One activation: its program, its variables and its position."""
def __init__(self, prog, args, fid):
if len(args) != len(prog.params):
raise ValueError("expected %d arguments" % len(prog.params))
self.prog = prog
self.env = dict(zip(prog.params, args))
self.fid = fid
self.label = prog.entry
self.prev = None
self.pc = 0 # 0 means: the phis of the block have not run yet
self.dest = None # the name that receives the value of a pending call
def val(self, a):
if isinstance(a, int):
return a
if a not in self.env:
raise UndefinedName(a)
return self.env[a]
def _run(prog, args, fuel, funcs):
"""Run with an explicit stack of frames, so deep recursion in the toy
program does not use Python recursion."""
heap = {}
envs = {}
stack = []
fr = _Frame(prog, args, 0)
envs[0] = fr.env
nframes = 1
def tick():
nonlocal fuel
if fuel <= 0:
raise _Fuel()
fuel -= 1
while True:
block = fr.prog.blocks[fr.label]
instrs = block.instrs
if fr.pc == 0:
# Phis at the top of the block read all operands first, then assign.
incoming = []
i = 0
while i < len(instrs) and instrs[i][0] == "phi":
tick()
ins = instrs[i]
if fr.prev not in ins[2]:
raise ValueError("phi %s has no operand for %r" % (ins[1], fr.prev))
incoming.append((ins[1], fr.val(ins[2][fr.prev])))
i += 1
for x, v in incoming:
fr.env[x] = v
fr.pc = i if i > 0 else -1
start = fr.pc if fr.pc > 0 else 0
called = False
env = fr.env
for j in range(start, len(instrs)):
ins = instrs[j]
tick()
k = ins[0]
if k == "const":
env[ins[1]] = ins[2]
elif k == "copy":
env[ins[1]] = fr.val(ins[2])
elif k == "op":
env[ins[1]] = _binop(ins[2], fr.val(ins[3]), fr.val(ins[4]))
elif k == "addr":
env[ins[1]] = ("var", fr.fid, ins[2])
elif k == "alloc":
cell = ("heap", len(heap))
heap[cell] = None
env[ins[1]] = cell
elif k == "load":
p = fr.val(ins[2])
if p[0] == "var":
if p[2] not in envs[p[1]]:
raise UndefinedName(p[2])
env[ins[1]] = envs[p[1]][p[2]]
else:
if heap[p] is None:
raise UndefinedName(repr(p))
env[ins[1]] = heap[p]
elif k == "store":
p = fr.val(ins[1])
if p[0] == "var":
envs[p[1]][p[2]] = fr.val(ins[2])
else:
heap[p] = fr.val(ins[2])
elif k == "call":
if funcs is None or ins[2] not in funcs:
raise ValueError("unknown function %r" % ins[2])
vals = [fr.val(a) for a in ins[3]]
fr.pc = j + 1
fr.dest = ins[1]
stack.append(fr)
fr = _Frame(funcs[ins[2]], vals, nframes)
envs[nframes] = fr.env
nframes += 1
called = True
break
elif k == "phi":
raise ValueError("phi after a non-phi instruction")
else:
raise ValueError("bad instruction: %r" % (ins,))
if called:
continue
tick()
t = block.term
if t[0] == "jump" or t[0] == "br":
if t[0] == "jump":
nxt = t[1]
else:
nxt = t[2] if fr.val(t[1]) != 0 else t[3]
fr.prev, fr.label, fr.pc = fr.label, nxt, 0
continue
v = fr.val(t[1])
if not stack:
return ("ret", v), fuel
fr = stack.pop()
fr.env[fr.dest] = v
def run(prog, args, fuel=10000, funcs=None):
"""Run prog on args. Returns ("ret", v), ("trap",) or ("fuel",).
Each instruction, phi and terminator uses one unit of fuel. funcs is an
optional dict from function name to Program, used by call; deep
recursion in the toy program is fine, because the frames are kept on an
explicit stack."""
try:
out, _ = _run(prog, list(args), fuel, funcs)
return out
except _Trap:
return ("trap",)
except _Fuel:
return ("fuel",)
# ------------------------------------------------------------ random programs
_SAFE = ("+", "-", "*", "&", "|", "^", "<", "<=", "==", "!=")
_CONST_RIGHT = ("/", "%", "<<", ">>")
def random_program(rng, nvars, nblocks, acyclic):
"""A random program with blocks B0 .. B(nblocks-1) and variables
x0 .. x(nvars-1). x0 and x1 are the parameters; the entry defines the
others, so no run reads an undefined name. A division by a variable can
trap. Every block is reachable from
B0 and B0 has no predecessor. With acyclic=False, each loop has its own
counter c that is set to 0 in B0 and never reset, and the back edge is
taken only while c < m and c < 4, where m is the first parameter. So the
whole run takes each back edge at most 3 times."""
nvars = max(nvars, 1)
nblocks = max(nblocks, 1)
xs = ["x%d" % i for i in range(nvars)]
params = xs[:2]
labels = ["B%d" % i for i in range(nblocks)]
def operand():
if rng.random() < 0.25:
return rng.randint(-3, 9)
return rng.choice(xs)
def instr():
x = rng.choice(xs)
r = rng.random()
if r < 0.15:
return ("const", x, rng.randint(-5, 9))
if r < 0.25:
return ("copy", x, rng.choice(xs))
if r < 0.3:
# A division by a variable may trap.
return ("op", x, rng.choice(("/", "%")), rng.choice(xs), rng.choice(xs))
if r < 0.4:
op = rng.choice(_CONST_RIGHT)
k = rng.randint(1, 5)
return ("op", x, op, rng.choice(xs), k)
return ("op", x, rng.choice(_SAFE), operand(), operand())
blocks = {}
has_pred = [False] * nblocks
has_pred[0] = True
for i in range(nblocks):
instrs = [instr() for _ in range(rng.randint(1, 3))]
if i == 0:
instrs = [("const", x, rng.randint(-5, 9)) for x in xs[len(params):]] + instrs
if i == nblocks - 1:
term = ("ret", rng.choice(xs))
elif has_pred[i + 1] and rng.random() < 0.2:
term = ("ret", rng.choice(xs))
else:
first = i + 1 if not has_pred[i + 1] else rng.randrange(i + 1, nblocks)
if rng.random() < 0.5:
term = ("jump", labels[first])
has_pred[first] = True
else:
second = rng.randrange(i + 1, nblocks)
if second == first:
term = ("jump", labels[first])
else:
term = ("br", rng.choice(xs), labels[first], labels[second])
has_pred[second] = True
has_pred[first] = True
blocks[labels[i]] = Block(instrs, term)
if not acyclic and nblocks > 1:
nloops = rng.randint(1, max(1, nblocks // 3))
for k in range(nloops):
latches = [lab for lab in labels[1:] if blocks[lab].term[0] == "jump"]
if not latches:
break
t = rng.choice(latches)
h = labels[rng.randint(1, labels.index(t))]
c, m, w1, w2, w = "c%d" % k, "m%d" % k, "t%d" % k, "u%d" % k, "w%d" % k
blocks[labels[0]].instrs[0:0] = [("const", c, 0), ("copy", m, params[0])]
out = blocks[t].term[1]
blocks[t].instrs += [
("op", c, "+", c, 1),
("op", w1, "<", c, m),
("op", w2, "<", c, 4),
("op", w, "&", w1, w2),
]
blocks[t].term = ("br", w, h, out)
return Program(list(params), blocks)
test_generational_search.py 241 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generational-search/. The authors are listed in prov/WF74QR.jsonl.
import itertools
import random
import toyir
from generational_search import brute_force_solver, generational, holds
LO, HI = -8, 8
PAGE = """
# params: a, b, c
entry:
n = 0
t = a == 7
br t i1 j1
i1:
n = n + 1
jump j1
j1:
t = b == 5
br t i2 j2
i2:
n = n + 1
jump j2
j2:
t = c == 3
br t i3 j3
i3:
n = n + 1
jump j3
j3:
u = 2 <= n
br u bad ok
bad:
ret 1
ok:
ret 0
"""
DIVIDE = """
# params: x, y
entry:
d = x - y
t = d < 0
br t lt ge
lt:
u = x == y
br u dead r1
ge:
q = 12 / d
v = q == 3
br v r2 r3
dead:
ret 9
r1:
ret 1
r2:
ret 2
r3:
ret 3
"""
COUNT = """
# params: n
entry:
i = 0
jump head
head:
t = i < n
br t body exit
body:
i = i + 1
jump head
exit:
ret i
"""
def trace(prog, args):
"""A plain concrete run, written apart from the search code:
(labels, outcome kind, index of the trapping instruction)."""
env = dict(zip(prog.params, args))
label = prog.entry
labels = [label]
def val(a):
return a if isinstance(a, int) else env[a]
while True:
block = prog.blocks[label]
for idx, ins in enumerate(block.instrs):
if ins[0] == "const":
env[ins[1]] = ins[2]
elif ins[0] == "copy":
env[ins[1]] = val(ins[2])
else:
a, b = val(ins[3]), val(ins[4])
if ins[2] in ("/", "%") and b == 0:
return (tuple(labels), "trap", idx)
if ins[2] in ("<<", ">>") and not 0 <= b <= 63:
return (tuple(labels), "trap", idx)
env[ins[1]] = toyir._binop(ins[2], a, b)
t = block.term
if t[0] == "ret":
return (tuple(labels), "ret", None)
label = t[1] if t[0] == "jump" else (t[2] if val(t[1]) != 0 else t[3])
labels.append(label)
def box(k):
return itertools.product(range(LO, HI + 1), repeat=k)
def brute_paths(prog):
out = set()
for v in box(len(prog.params)):
p = trace(prog, v)
assert p[1] == toyir.run(prog, v)[0]
out.add(p)
return out
def counting_solver():
inner = brute_force_solver()
calls = {"sat": 0, "unsat": 0}
def solve(conds, k, hint):
m = inner(conds, k, hint)
calls["sat" if m is not None else "unsat"] += 1
return m
return solve, calls
def check_complete(prog):
solve, calls = counting_solver()
runs = generational(prog, solve)
found = [r.path() for r in runs]
assert len(found) == len(set(found)), "a path was explored twice"
assert set(found) == brute_paths(prog)
for i, r in enumerate(runs):
assert all(LO <= a <= HI for a in r.args)
assert r.outcome == toyir.run(prog, r.args)
if i > 0:
p = runs[r.parent]
assert p.bound <= r.flip < len(p.conds)
assert r.bound == r.flip + 1
assert r.conds[: r.flip] == p.conds[: r.flip]
assert r.conds[r.flip] == (p.conds[r.flip][0], not p.conds[r.flip][1])
assert calls["sat"] == len(runs) - 1
assert calls["sat"] + calls["unsat"] == sum(len(r.conds) - r.bound for r in runs)
return runs
def test_page_example():
prog = toyir.parse(PAGE)
runs = check_complete(prog)
assert [tuple(r.args) for r in runs] == [
(0, 0, 0),
(7, 0, 0),
(0, 5, 0),
(0, 0, 3),
(7, 5, 0),
(7, 0, 3),
(0, 5, 3),
(7, 5, 3),
]
assert [r.outcome[1] for r in runs] == [0, 0, 0, 0, 1, 1, 1, 1]
assert [r.score for r in runs] == [5, 1, 1, 1, 1, 0, 0, 0]
assert [r.bound for r in runs] == [0, 1, 2, 3, 2, 3, 3, 3]
# The last test of the program is on a constant, so no run records it.
assert all(len(r.conds) == 3 for r in runs)
def test_the_solver_keeps_the_hint():
solve = brute_force_solver()
cond = (("op", "==", ("in", 1), ("k", 5)), True)
assert solve([cond], 3, [4, 0, -2]) == [4, 5, -2]
assert solve([(cond[0], False)], 3, [4, 0, -2]) == [4, 0, -2]
assert solve([cond, (cond[0], False)], 3, [4, 0, -2]) is None
def test_implicit_trap_condition():
runs = check_complete(toyir.parse(DIVIDE))
assert sorted(r.outcome for r in runs) == [("ret", 1), ("ret", 2), ("ret", 3), ("trap",)]
def test_counted_loop_stops_at_the_box():
runs = check_complete(toyir.parse(COUNT))
assert sorted(r.args[0] for r in runs) == list(range(0, 9))
def ladder(rng, k):
"""k tests in a row on linear terms of x, y and the running sum s, with a
division by s at the end."""
lines = ["# params: x, y", "entry:", " s = 0", " jump T0"]
for i in range(k):
a, b, c = rng.randint(-3, 3), rng.randint(-3, 3), rng.randint(-6, 6)
lines += ["T%d:" % i, " e = x * %d" % a, " f = y * %d" % b, " g = e + f", " g = g + s"]
lines += [" t = g < %d" % c, " br t A%d C%d" % (i, i)]
lines += ["A%d:" % i, " s = s + x", " jump T%d" % (i + 1)]
lines += ["C%d:" % i, " s = s - %d" % rng.randint(1, 3), " jump T%d" % (i + 1)]
lines += ["T%d:" % k, " r = 12 / s", " ret r"]
return toyir.parse("\n".join(lines))
def test_random_ladders():
rng = random.Random(5)
sizes = [len(check_complete(ladder(rng, rng.randint(2, 5)))) for _ in range(12)]
assert max(sizes) >= 10
def test_random_loop_free_programs():
rng = random.Random(20261115)
for _ in range(80):
check_complete(toyir.random_program(rng, rng.randint(2, 4), rng.randint(2, 7), acyclic=True))
def test_random_programs_with_loops():
rng = random.Random(7)
for _ in range(30):
check_complete(toyir.random_program(rng, rng.randint(2, 4), rng.randint(3, 7), acyclic=False))
def test_path_condition_is_exact():
rng = random.Random(11)
for _ in range(30):
prog = toyir.random_program(rng, 3, rng.randint(2, 6), acyclic=rng.random() < 0.5)
runs = generational(prog)
for v in box(2):
hits = [r for r in runs if holds(r.conds, v)]
assert len(hits) == 1 and hits[0].path() == trace(prog, v)
def test_budget():
prog = toyir.parse(PAGE)
runs = generational(prog, max_runs=5)
assert len(runs) == 5
assert runs[-1].outcome == ("ret", 1)
History
Godefroid, Levin and Molnar presented SAGE and generational search at NDSS 2008. SAGE worked on x86 binaries: it recorded a trace of a run on an input file, executed the trace symbolically to get the path condition, and expanded it with generational search. They designed the search for long runs with thousands of conditions, where the depth-first search of DART spends a whole budget in one small subtree. In their 2012 article in Communications of the ACM they report that SAGE found about one third of the bugs that file fuzzing found during the development of Windows 7. The NDSS paper calls this approach whitebox fuzzing: fuzzing guided by the path condition of each run, in contrast to blackbox fuzzing, which mutates inputs at random.
References
- Patrice Godefroid, Michael Y. Levin and David Molnar, Automated whitebox fuzz testing, Proceedings of NDSS 2008, Internet Society, the section on generational search (the algorithms Search and ExpandExecution, the bound of each input and the score by incremental block coverage)
- Patrice Godefroid, Michael Y. Levin and David Molnar, SAGE, whitebox fuzzing for security testing, Communications of the ACM 55(3), 2012, pp. 40 to 44, the description of generational search and the results on Windows 7
- Patrice Godefroid, Nils Klarlund and Koushik Sen, DART, directed automated random testing, Proceedings of PLDI 2005, pp. 213 to 223, the depth-first search that generational search replaces
- Cristian Cadar and Koushik Sen, Symbolic execution for software testing, three decades later, Communications of the ACM 56(2), 2013, pp. 82 to 90, the sections on concolic testing and on search heuristics
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 WF74QR Edit this page History Report an error Markdown