Algorithm Search⌘K

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
Properties
deterministicofflineiterative
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 PP of the toy IR with kk integer parameters, a set D⊆ZkD \subseteq \mathbb{Z}^k of allowed inputs, a seed in DD and a solver. The output is a list of tests, one for each path that some input of DD 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 DD, it finds every path of DD once and stops. On this page DD is the box [−8,8]k[-8, 8]^k 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 c0,…,cm−1c_0, \dots, c_{m-1}, numbered from 0, with the implicit conditions of divisions and shifts. Each run rr carries a bound b(r)b(r): the search negates only the conditions at positions b(r)b(r) 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.

  1. GENERATIONAL-SEARCH(P, v0, SOLVE)
  2. 1r0 <- RUN(P, v0); output r0; covered <- the blocks of r0
  3. 2W <- {r0}, with b(r0) = 0
  4. 3while W is not empty do
  5. 4remove from W the run r with the highest score (the oldest on ties)
  6. 5let c_0 ... c_(m-1) be the conditions of r
  7. 6for j <- b(r) to m - 1 do
  8. 7v' <- SOLVE(c_0 and ... and c_(j-1) and not c_j), with the input of r as the hint
  9. 8if there is no v' then continue
  10. 9r' <- RUN(P, v'); output r'
  11. 10score(r') <- the number of blocks of r' not in covered; add them to covered
  12. 11b(r') <- j + 1; add r' to W

The bound on line L11 is the key. The child r′r' agrees with rr on the positions before jj and is opposite at jj. Flipping r′r' at a position before jj would ask for an input that agrees with rr before that position and differs there, which rr itself, or one of its other children, already covers. Flipping r′r' at jj would give back the side of rr. So r′r' is expanded only at positions j+1j + 1 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 aa, bb and cc, with the symbols α\alpha, β\beta and γ\gamma. 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, nn is a constant, so the last branch has a constant condition and RUN does not record it. Each run records three conditions, α=7\alpha = 7, β=5\beta = 5 and γ=3\gamma = 3, 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 a=7a = 7 from run 2.

Correctness

The full proof is in the proof file. Assume that SOLVE is exact over a finite DD, the seed is in DD, and RUN tracks every operation exactly. Let TDT_D be the tree of the decision sequences of the inputs of DD, as in the proof for concolic testing; its leaves are the paths of DD.

  1. A child follows its query. The input from line L7 satisfies c0,…,cj−1,¬cjc_0, \dots, c_{j-1}, \neg c_j, so its run records the same first jj conditions and then ¬cj\neg c_j.
  2. Descendants keep the prefix. A run made by flipping position jj has bound j+1j + 1, and its own children flip at positions j+1j + 1 or later. By induction, every descendant of r′r' agrees with r′r' at the positions 00 to jj.
  3. No path twice. Take two different runs and their lowest common ancestor zz in the tree of parents. If zz is one of them, the other one is opposite to zz at the position where its chain leaves zz. Otherwise the two chains leave zz by flips at two different positions j1<j2j_1 < j_2; the first run is opposite to zz at j1j_1 and the second agrees with zz there. In both cases the paths differ.
  4. Every path. Take a leaf ℓ\ell and follow a chain of runs that agree with ℓ\ell at all positions below their bound, starting at the seed, whose bound is 0. If the current run rr is not ℓ\ell, let jj be the first position where they differ; then j≥b(r)j \ge b(r). An input that follows ℓ\ell satisfies the query at position jj, so the exact solver returns a model, and rr gets a child that agrees with ℓ\ell at the positions 0 to jj, below its bound j+1j + 1. The first difference grows at each step, so after at most ∣ℓ∣|\ell| steps the run is ℓ\ell.
  5. The end. Each run is a new leaf and TDT_D has at most ∣D∣|D| leaves, and each run is expanded once.

Exactly R−1R - 1 solver calls succeed, and the total number of calls is ∑r(m(r)−b(r))\sum_r (m(r) - b(r)), where m(r)m(r) is the number of conditions of rr.

Proof: Generational search finds every feasible path once under an exact solverfull

Setting. PP is a program of the toy IR with kk integer parameters and only constants, copies and binary operations. D⊆ZkD \subseteq \mathbb{Z}^k is a set of inputs that contains the seed. SOLVE is exact over DD: for a list of conditions it returns an input of DD 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 D=ZkD = \mathbb{Z}^k; 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) PP is loop-free, and DD is any set, for example Zk\mathbb{Z}^k; or
  • (B) DD is finite and every run of PP on an input of DD ends.

A condition is a pair (e,s)(e, s); an input uu satisfies it when "e(u)≠0e(u) \ne 0" has the truth value ss and e(u)e(u) does not trap. For an input uu, dec(u)=(c0,…,cm−1)\mathrm{dec}(u) = (c_0, \dots, c_{m-1}) is the list of conditions that RUN records, its decision sequence.

Lemma 1: the record is a function of the decisions

Claim. If u′u' satisfies the first ii conditions c0,…,ci−1c_0, \dots, c_{i-1} of dec(u)\mathrm{dec}(u), then dec(u′)\mathrm{dec}(u') starts with the same ii conditions, and after them both runs reach the same point with the same symbolic store.

Proof. Induction over the steps of the run of uu. Both runs start at the entry with the store xj↦αjx_j \mapsto \alpha_j, 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 ee records a condition with the same ee in both runs; if it is ctc_t with t<it < i, then u′u' satisfies it, so e(u)e(u) and e(u′)e(u') 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. □\square

Consequences. Let TDT_D be the set of the decision sequences of the inputs of DD and their prefixes.

  • (a) After a prefix, the expression of the next condition, or the end of the run, is fixed. So TDT_D is a binary tree, and no decision sequence is a proper prefix of another: the decision sequences are the leaves of TDT_D.
  • (b) An input satisfies the conditions of a node qq if and only if its decision sequence lies below qq.
  • (c) Different leaves correspond to different paths, and the same leaf to the same path: two leaves first differ at (e,s)(e, s) against (e,¬s)(e, \neg s), 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) TDT_D has finitely many leaves. In case (B) there are at most ∣D∣|D|. In case (A) a run of a loop-free program with nn blocks visits at most nn blocks, each block records at most a fixed number of conditions, so every leaf has length at most some LL, and a binary tree of depth LL has at most 2L2^L leaves.

Lemma 2: a child follows its query

Claim. Let rr have the decision sequence (c0,…,cm−1)(c_0, \dots, c_{m-1}), and let r′r' be the child made at position jj on line L9. Then dec(r′)\mathrm{dec}(r') starts with c0,…,cj−1,¬cjc_0, \dots, c_{j-1}, \neg c_j.

Proof. The input of r′r' satisfies c0,…,cj−1c_0, \dots, c_{j-1}, so by Lemma 1 its run records these conditions and then reaches the point of cjc_j with the same store, where it records a condition with the expression of cjc_j. The input satisfies ¬cj\neg c_j, so the recorded sense is that of ¬cj\neg c_j. □\square

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 r′r' was made at position jj, then every descendant of r′r' (including r′r') has a decision sequence that agrees with dec(r′)\mathrm{dec}(r') at the positions 0,…,j0, \dots, j.

Proof. Induction on the distance from r′r'. For r′r' it is trivial. A child of a descendant ss is made at a position j′≥b(s)j' \ge b(s). Every descendant ss of r′r' other than r′r' was itself made at a position at least bb of its parent, and bounds only grow along a chain: b(s)=js+1b(s) = j_s + 1 where js≥b(parent(s))j_s \ge b(\mathrm{parent}(s)). So j′≥b(s)≥b(r′)=j+1j' \ge b(s) \ge b(r') = j + 1. By Lemma 2, the child agrees with ss at the positions below j′j', which include 0,…,j0, \dots, j, and ss agrees with r′r' there by induction. □\square

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 DD. Exactly R−1R - 1 solver calls succeed, where RR is the number of runs, and the number of calls is ∑r(m(r)−b(r))\sum_r (m(r) - b(r)).

Proof. No path twice. Let x≠yx \ne y be two nodes and zz their lowest common ancestor.

  • If z=xz = x, let x′x' be the child of xx on the chain to yy, made at position jj. By Lemma 2, dec(x′)\mathrm{dec}(x') has ¬cj\neg c_j at position jj, where dec(x)\mathrm{dec}(x) has cjc_j, and by Lemma 3, yy agrees with x′x' at position jj. So dec(y)≠dec(x)\mathrm{dec}(y) \ne \mathrm{dec}(x).
  • Otherwise let x′x' and y′y' be the children of zz on the two chains, made at positions jxj_x and jyj_y. Line L6 makes at most one child per position, so jx≠jyj_x \ne j_y; say jx<jyj_x < j_y. By Lemma 2, x′x' has ¬cjx\neg c_{j_x} at position jxj_x, and y′y' agrees with zz at every position below jyj_y, so it has cjxc_{j_x} there. By Lemma 3, xx and yy agree with x′x' and y′y' at position jxj_x. So dec(x)≠dec(y)\mathrm{dec}(x) \ne \mathrm{dec}(y).

By (c) the paths differ as well.

Termination. Each node is a leaf of TDT_D (its input is in DD), and different nodes are different leaves, so by (d) there are finitely many nodes. Each node enters WW once and is expanded once, with finitely many calls, so the loop stops.

Every path. Let ℓ\ell be a leaf of TDT_D. We build a chain of nodes r0,r1,…r_0, r_1, \dots such that each rtr_t agrees with ℓ\ell at every position below b(rt)b(r_t). Take r0r_0 as the seed, with b(r0)=0b(r_0) = 0. If dec(rt)=ℓ\mathrm{dec}(r_t) = \ell, stop. Otherwise the two sequences are different leaves, so neither is a prefix of the other, and they first differ at some position jj, with j≥b(rt)j \ge b(r_t) by the property of rtr_t. When rtr_t is expanded (it is, since the loop runs until WW is empty), line L6 reaches jj. An input that follows ℓ\ell satisfies c0,…,cj−1,¬cjc_0, \dots, c_{j-1}, \neg c_j of rtr_t, by (b), so the exact solver returns a model and line L9 makes a child rt+1r_{t+1} at position jj. By Lemma 2, rt+1r_{t+1} agrees with ℓ\ell at the positions 0,…,j0, \dots, j, which are the positions below b(rt+1)=j+1b(r_{t+1}) = j + 1. The first position of difference with ℓ\ell grows strictly along the chain and is at most the length of ℓ\ell, so the chain reaches ℓ\ell.

Solver calls. The expansion of rr makes one call for each jj from b(r)b(r) to m(r)−1m(r) - 1, which gives the total. Each successful call makes one run, and every run but the seed comes from one successful call. □\square

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 D=ZkD = \mathbb{Z}^k 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 j+1j + 1 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 RR be the number of runs, mm the largest number of conditions on a run, TT the largest number of steps of a run and CC the cost of a solver call. Each run is made once at cost O(T)O(T) and expanded once with at most mm calls. The priority queue costs O(log⁡R)O(\log R) per run. The total is O(R(T+mC+log⁡R))O(R (T + m C + \log R)), 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, O(RT)O(R T) in total. SAGE keeps only the input of each run in the worklist, O(Rk)O(R k), and runs the program again symbolically when it expands a run. Depth-first search needs only one stack of O(m)O(m) entries.

In SAGE, mm 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 mm new tests.

Properties

  • Complete relative to the solver, with no repeats. With exact tracking and an exact solver over a finite DD, every path of DD 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 m−b(r)m - b(r).
  • 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 jj instead of j+1j + 1, it flips position jj again, and the solver returns an input of its parent's path. If the bound is too large, paths are lost. With the bound j+1j + 1 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.

generational_search.pyI0RawGitHub
# 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

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • 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)
WritingW2 basic
  • a scene preset for the example