Algorithm Search⌘K

Algorithmcore

Concolic testing

Also called dynamic symbolic execution, DART.

Runs the program on concrete input while recording the symbolic path condition, then negates a branch and solves for input to a new path.

Time
O(R (T + m C)) worst
Space
O(T) extra
Where
C = the cost of one solver call; R = the number of feasible paths explored; T = the largest number of steps of one run; m = the largest number of recorded conditions on one run
Properties
deterministicofflineiterative
Origin
Patrice Godefroid, Nils Klarlund, Koushik Sen, 2005

Concolic testing runs the program on a concrete input and, at the same time, keeps a symbolic expression for each value, so that each run gives its own path condition. It then negates one condition of that path, asks a solver for an input that satisfies the new formula, and runs the program on that input. The name joins "concrete" and "symbolic". The concrete run decides the path, so the tool never forks states, and when an operation is too hard for the solver it can use the concrete value in its place. This page gives the depth-first search of DART, which explores the symbolic execution tree one run at a time. The method that it implements is symbolic execution; generational search is a different order over the same runs.

In plain words

Run the program once on any input, for example all zeros. While it runs, write down every test it passes and which way each test went, in terms of the inputs: "y times 2 was equal to x", "y plus 3 was not less than x". Now take the last test on that list and ask: is there an input that goes the same way at every earlier test but the other way at this one? A solver finds such an input, or says there is none. Run the program on the new input, write down its list, and repeat, always flipping the deepest test that has not been flipped yet. Each new input goes down a new way through the program. Inputs that random testing would almost never hit, such as "x is exactly twice y", come out of the solver at once.

The problem

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, and a solver for the conditions of the program. The output is a list of tests, one input for each path of PP that some input of DD follows, where a path is the sequence of blocks together with the outcome (a return or a trap at a given instruction).

The goal "a test for every feasible path" cannot be met in general. The number of paths can be infinite (see path explosion), and over unbounded integers with products of inputs, the feasibility of one path condition is undecidable by Hilbert's tenth problem. The algorithm is complete relative to its solver: if the solver is exact over DD, it finds every path that an input of DD follows, and it stops when DD is finite. On this page DD is the box [−8,8]k[-8, 8]^k, and the solver tries every point of the box, in place of an SMT solver. A real tool uses an SMT solver for bit vectors, which is a decision procedure for machine integers.

The algorithm

The concolic run. RUN executes PP on the input vv and keeps two stores: the concrete values and the symbolic expressions over the input symbols α1,…,αk\alpha_1, \dots, \alpha_k. An operation on two constants is folded to a constant. Each run records a list of conditions. A condition is a pair (e,s)(e, s): the run went the way on which "e≠0e \ne 0" has the truth value ss.

  • At br a L1 L2, the run records (σ(a),s)(\sigma(a), s), where ss tells whether it went to L1L_1.
  • At a division or a remainder by bb, the run records (σ(b),s)(\sigma(b), s), where ss tells whether b≠0b \ne 0. At a shift by bb, it records the condition 0≤σ(b)≤630 \le \sigma(b) \le 63. If the check fails, the run stops with a trap. These are the implicit conditions of the path condition page.
  • A condition whose expression is a constant is not recorded: no input can change it.

The conditions c1,…,cmc_1, \dots, c_m of a run, joined by "and", are its path condition. Write ¬(e,s)\neg(e, s) for (e,¬s)(e, \neg s).

The search. SS is a stack of pairs (condition, done). Entry ii of the stack is the ii-th condition of the current path. The flag done says that the other side of that condition has been dealt with.

  1. CONCOLIC(P, SOLVE)
  2. 1v <- any input, for example all zeros
  3. 2S <- an empty stack of pairs (condition, done)
  4. 3loop
  5. 4(outcome, c_1 ... c_m) <- RUN(P, v)
  6. 5for i <- |S| + 1 to m do push (c_i, false) on S
  7. 6output the test (v, outcome)
  8. 7repeat
  9. 8if S is empty then return
  10. 9(c, done) <- the top of S; let d_1 ... d_(j-1) be the conditions below it
  11. 10if done then pop S and continue
  12. 11v' <- SOLVE(d_1 and ... and d_(j-1) and not c)
  13. 12if there is no v' then pop S and continue
  14. 13replace the top of S by (not c, true); v <- v'; leave the repeat

Line L5 keeps the entries that the stack already holds. The new input satisfies the conditions of the stack, so its run agrees with them, and only its later conditions are new. The implementation checks this agreement and reports a divergence if it fails; with exact symbolic tracking it never fails. Lines L8 to L13 find the deepest condition whose other side is still open, exactly as a depth-first search backtracks. A flipped entry is marked done at once: the side that the earlier run took is finished, and the new run explores the other.

Each query on line L11 is the previous path condition with its last condition negated. A solver with incremental solving keeps the shared prefix between calls.

Example

The parameters are xx and yy, with the symbols α\alpha and β\beta. The return of 1 stands for a bug.

entry:
  z = y * 2
  t = z == x
  br t then miss
then:
  w = y + 3
  u = w < x
  br u bug near
miss:
  ret 0
bug:
  ret 1
near:
  ret 2

The solver tries the points of [−8,8]2[-8, 8]^2 in lexicographic order of (x,y)(x, y).

run input conditions recorded outcome stack after the search step
1 (0, 0) (2β=α,true)(2\beta = \alpha, \text{true}), (β+3<α,false)(\beta + 3 < \alpha, \text{false}) ret 2 (2β=α,false)(2\beta = \alpha, \text{false}), (β+3<α,true)(\beta + 3 < \alpha, \text{true})
2 (8, 4) the same two, the second one true ret 1 (2β=α,false)(2\beta = \alpha, \text{false}), flipped and done
3 (-8, -8) (2β=α,false)(2\beta = \alpha, \text{false}) ret 0 empty

After run 1, the top entry is not done, so line L11 asks for 2β=α∧β+3<α2\beta = \alpha \wedge \beta + 3 < \alpha. This means β>3\beta > 3 and α=2β≤8\alpha = 2\beta \le 8, so the only model in the box is (8,4)(8, 4), and run 2 reaches the bug. After run 2, the top entry is done and is popped. The next entry asks for 2β≠α2\beta \ne \alpha, and the first point of the box, (−8,−8)(-8, -8), satisfies it. After run 3, the stack holds only done entries, and the search ends.

Three runs and two solver calls find all three paths. Of the 289 inputs of the box, 280 return 0, 8 return 2 and only one returns 1. Over pairs of 32-bit integers, a random input satisfies x=2yx = 2y with probability about 2−322^{-32}, so random testing almost never reaches then.

Correctness

The full proof is in the proof file. The claim is: if SOLVE is exact over a finite set DD (it returns a model in DD whenever one exists) and the start input is in DD, the search stops, and it outputs one test for each path that some input of DD follows, each path exactly once.

  1. The record is a function of the path so far. By induction along a run, the symbolic store after a sequence of decisions does not depend on the input. So the next recorded condition, or the end of the run, is fixed by the earlier decisions. The sequences of senses of the runs on DD form the leaves of a binary tree TDT_D, the symbolic execution tree cut down to DD.
  2. No divergence. The input from line L11 satisfies all the conditions of the stack, so its run makes the same decisions, and line L5 keeps the stack.
  3. The invariant. At line L8, the tests output so far are exactly the leaves below the other side of each done entry, together with all the leaves below the current stack. At line L3 (after line L13), they are exactly the leaves below the other side of each done entry. Popping a done entry, popping an entry whose other side is empty (the solver says so, and it is exact), and flipping an entry all keep this.
  4. The end. When the stack is empty, the invariant says that every leaf of TDT_D has been output. Each run outputs a leaf that is new, by the invariant, and TDT_D has at most ∣D∣|D| leaves, so the loop stops. The successful solver calls are one fewer than the runs.

With an exact solver over all of Zk\mathbb{Z}^k the same argument shows that no path is output twice. If the tree is infinite, the search may never stop, and a depth-first search may stay in one infinite branch.

Proof: The depth-first concolic search finds every path of the domain oncefull

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 finite set of inputs, and the start input is in DD. SOLVE is exact over DD: given a list of conditions, it returns an input of DD that satisfies all of them if there is one, and reports that there is none otherwise. RUN tracks every operation symbolically, as described on the page, and records no condition whose expression is a constant. We assume that every run of PP on an input of DD ends; the programs of the tests satisfy this.

A condition is a pair (e,s)(e, s), and an input uu satisfies it when "e(u)≠0e(u) \ne 0" has the truth value ss and the evaluation of e(u)e(u) does not trap. For an input uu, let rec(u)=(c1,…,cm)\mathrm{rec}(u) = (c_1, \dots, c_m) be the list of conditions that RUN records on uu, and let path(u)\mathrm{path}(u) be the blocks, the kind of outcome and the trapping instruction of its run.

Lemma 1: the record is a function of the decisions

Claim. Let uu and u′u' be inputs, and suppose the first ii conditions of rec(u)\mathrm{rec}(u) are c1,…,cic_1, \dots, c_i and u′u' satisfies all of them. Then the first ii conditions of rec(u′)\mathrm{rec}(u') are also c1,…,cic_1, \dots, c_i. After the ii-th condition, the two runs reach the same point with the same symbolic store, so the next event, either the condition ci+1c_{i+1} or the end of the run with a given outcome kind and position, is the same in both runs up to its sense.

Proof. Induction over the steps of the run of uu. At the start, both runs are at the entry with the store xj↦αjx_j \mapsto \alpha_j. A constant, a copy or an operation updates the store in a way that does not depend on the input, so the stores stay equal. An operation on two constants is folded, and it traps in both runs or in neither. At a check or a branch whose expression ee is a constant, both runs take the same side, because the value of a constant does not depend on the input. At a check or a branch with a symbolic expression ee, both runs record a condition with the same expression ee. If it is one of c1,…,cic_1, \dots, c_i, then u′u' satisfies it, so e(u′)e(u') and e(u)e(u) are both nonzero or both zero, and the runs take the same side: the same successor block at a branch, the same "go on" or "trap" at a check. Here we use that the symbolic store gives the true value of each name as a function of the input, which holds by the same induction: each symbolic operation is the concrete operation applied to the symbolic operands. □\square

Consequences. Call dec(u)=rec(u)\mathrm{dec}(u) = \mathrm{rec}(u), the conditions with their senses, the decision sequence of uu. Let TDT_D be the set of the decision sequences of the inputs of DD and of all their prefixes.

  • (a) TDT_D is a binary tree: a prefix (c1,…,ci)(c_1, \dots, c_i) fixes the expression of ci+1c_{i+1} by Lemma 1, so a node has at most two children, (c1,…,ci,(e,true))(c_1, \dots, c_i, (e, \mathit{true})) and (c1,…,ci,(e,false))(c_1, \dots, c_i, (e, \mathit{false})).
  • (b) No decision sequence of an input is a proper prefix of another: by Lemma 1, after the same prefix both runs either end or record a further condition. So the decision sequences are exactly the leaves of TDT_D.
  • (c) The leaves are in one-to-one correspondence with the paths {path(u):u∈D}\{\mathrm{path}(u) : u \in D\}. Two inputs with the same decision sequence have the same path by Lemma 1. Two different leaves first differ at a condition (e,s)(e, s) against (e,¬s)(e, \neg s). At a branch, the two runs go to different blocks, because a branch with equal targets records nothing. At a check, one run traps there and the other goes on, so the two paths differ in their outcome, in their blocks or in the trapping instruction.
  • (d) For a node qq of TDT_D, let Leaves(q)\mathrm{Leaves}(q) be the leaves below qq. Then an input of DD satisfies all conditions of qq if and only if its decision sequence lies in Leaves(q)\mathrm{Leaves}(q). This is Lemma 1 in one direction; in the other, a run whose decision sequence extends qq satisfies the conditions of qq by definition.

Lemma 2: the invariant

Write the stack as (d1,f1),…,(dj,fj)(d_1, f_1), \dots, (d_j, f_j) from the bottom, and diˉ\bar{d_i} for (d1,…,di−1,¬di)(d_1, \dots, d_{i-1}, \neg d_i), the other side at depth ii. Let OO be the set of the decision sequences of the runs output so far.

Claim. The following hold.

  • (I1) At line L3, the input vv is in DD and satisfies d1,…,djd_1, \dots, d_j, and O=⋃i:fiLeaves(diˉ)O = \bigcup_{i : f_i} \mathrm{Leaves}(\bar{d_i}).
  • (I2) At line L8, (d1,…,dj)(d_1, \dots, d_j) is a node of TDT_D and O=⋃i:fiLeaves(diˉ)∪Leaves(d1,…,dj)O = \bigcup_{i : f_i} \mathrm{Leaves}(\bar{d_i}) \cup \mathrm{Leaves}(d_1, \dots, d_j).

Proof. Initially the stack is empty, OO is empty, and vv is the start input, in DD. So (I1) holds.

From line L3 to line L8. By (I1), vv satisfies d1,…,djd_1, \dots, d_j, which are the first jj conditions of the run of some earlier input (or j=0j = 0). By Lemma 1 its record starts with d1,…,djd_1, \dots, d_j, so line L5 pushes exactly the rest dj+1,…,dmd_{j+1}, \dots, d_m with the flag false, and line L6 adds the leaf ℓ=(d1,…,dm)\ell = (d_1, \dots, d_m) to OO. The new entries have false flags, so the union over the done entries is unchanged. By (b), ℓ\ell is a leaf, so Leaves(ℓ)={ℓ}\mathrm{Leaves}(\ell) = \{\ell\}, and (I2) holds with the new stack.

Line L10. The top entry (dj,true)(d_j, \mathit{true}) is popped. Every leaf below (d1,…,dj−1)(d_1, \dots, d_{j-1}) lies below (d1,…,dj)(d_1, \dots, d_j) or below djˉ\bar{d_j}, and both sets are in OO by (I2). After the pop, (I2) holds with Leaves(d1,…,dj−1)\mathrm{Leaves}(d_1, \dots, d_{j-1}).

Line L12. The solver is exact, so no input of DD satisfies d1,…,dj−1,¬djd_1, \dots, d_{j-1}, \neg d_j, and by (d) Leaves(djˉ)\mathrm{Leaves}(\bar{d_j}) is empty. After the pop, (I2) holds as in the previous case.

Line L13. The solver returns v′∈Dv' \in D that satisfies d1,…,dj−1,¬djd_1, \dots, d_{j-1}, \neg d_j, and the top becomes (¬dj,true)(\neg d_j, \mathit{true}). Its other side is (d1,…,dj)(d_1, \dots, d_j), all of whose leaves are in OO by (I2), and the flag was false, so the union over the done entries now covers exactly what (I2) covered. So O=⋃i:fiLeaves(diˉ)O = \bigcup_{i : f_i} \mathrm{Leaves}(\bar{d_i}) with the new stack, and v′v' satisfies the new stack. (I1) holds. □\square

Theorem

Claim. The search stops. The runs that it outputs have pairwise different paths, and their paths are exactly {path(u):u∈D}\{\mathrm{path}(u) : u \in D\}. Exactly R−1R - 1 solver calls succeed, where RR is the number of runs.

Proof. Each run is new. At line L3, by (I1), vv satisfies d1,…,djd_1, \dots, d_j, so by (d) its leaf lies below the current stack. Each set Leaves(diˉ)\mathrm{Leaves}(\bar{d_i}) is disjoint from Leaves(d1,…,dj)\mathrm{Leaves}(d_1, \dots, d_j), because their sequences differ at depth ii. So the new leaf is not in OO.

Termination. Each pass of the outer loop outputs a new leaf of TDT_D, and TDT_D has at most ∣D∣|D| leaves, since each leaf is the decision sequence of an input of DD. So the outer loop runs at most ∣D∣|D| times. Each pass of the inner loop pops an entry or leaves the loop, and each pass of the outer loop pushes finitely many entries, so the inner loop stops too.

Completeness. The search returns at line L8 with an empty stack. Then (I2) gives O=Leaves(ε)O = \mathrm{Leaves}(\varepsilon), all the leaves of TDT_D. By (c), the paths output are exactly the paths of the inputs of DD, and since the leaves output are pairwise different, so are the paths.

Solver calls. Every run but the first follows exactly one successful call on line L13, and every successful call is followed by a run. □\square

Remarks. The finiteness of DD is used only for termination. With a solver that is exact over all of Zk\mathbb{Z}^k, the invariant and the argument "each run is new" still hold, so no path is output twice, but on a program with an infinite tree the search need not stop, and it can stay forever in one infinite branch. If RUN replaces a symbolic subterm by its concrete value, Lemma 1 fails, a run can leave the predicted prefix, and the implementation reports the divergence.

Complexity

Let RR be the number of paths explored, mm the largest number of conditions on one run, TT the largest number of steps of a run and CC the cost of one solver call. Each run costs O(T)O(T), since each step adds at most one node to an expression. Each stack entry is pushed once and causes at most one solver call, so there are at most RmR m calls, and exactly R−1R - 1 of them succeed. The total is O(R(T+mC))O(R (T + m C)). The stack and the expressions take O(T)O(T) space, because shared subterms are stored once.

The cost CC dominates in practice. The brute-force solver of this page costs ∣D∣|D| evaluations of a formula of size O(T)O(T). An SMT solver for bit vectors solves an NP-complete problem in each call, see bit-vector satisfiability. RR can be exponential in the number of branches.

Properties

  • No false alarms. Every test is a real run of the program, so every failure it reports is real. This holds even when the symbolic part is wrong or incomplete; a wrong symbolic part only makes the search miss paths or diverge.
  • Complete relative to the solver. With an exact solver and exact tracking, every feasible path is found once and only once. With an incomplete solver or with concretization, some paths are missed, and the method gives no guarantee about them.
  • Concrete values help the solver. When a condition contains an operation that the solver does not handle, such as a nonlinear product or a hash function, the tool can replace that subterm by its value in the current run. The query then stays solvable, at the price of completeness.
  • Depth-first and anytime. Each run gives a test, so the tool can stop at any time and keep what it has. The stack has at most mm entries.

Variants and improvements

  • CUTE. Sen, Marinov and Agha extend the method to C programs with pointers and dynamic data. They keep a logical input map, approximate constraints on pointers by equalities and disequalities, and named the method concolic.
  • Concretization. DART falls back to the concrete value when a condition leaves the theory of the solver, for example a product of two inputs with a linear solver. CUTE does the same. If the fall-back makes a run leave the predicted prefix, DART detects it and starts again from a random input.
  • Bounded depth. A depth bound on the stack makes the search stop on programs with an infinite tree. The paths below the bound are lost.
  • Generational search. Generational search negates every condition of a run at once, and picks the next run by the new coverage it gives. It suits long runs with thousands of conditions, where depth-first search spends its budget in one corner of the tree.
  • Hybrid fuzzing. A coverage-guided fuzzer finds most easy paths quickly. A concolic engine is called on the inputs of the fuzzer when coverage stops growing, to solve the narrow conditions such as "x is twice y".
  • Pure symbolic execution with concrete help. EXE and KLEE fork symbolic states at each feasible branch and keep many states in memory at once, instead of rerunning the program. They use concrete values for the operations that have no symbolic input.

When to use it

Use concolic testing to generate tests for programs with narrow conditions that random inputs do not hit: parsers with magic numbers, checksums, arithmetic relations between inputs. It needs a way to observe the program as it runs, such as instrumentation of the code. Prefer pure symbolic execution when the program state is small and forking is cheap, and a fuzzer when the conditions are wide and runs are cheap. For proofs of absence of bugs, use a verifier: a concolic tool proves nothing about the paths that it does not reach.

Pitfalls

  • Leaving out the implicit conditions. If the run does not record b≠0b \ne 0 at a division, the search never generates the input that traps there, and a solver may give a model in which the division by zero has an arbitrary value. See the path condition page.
  • A mismatch of semantics. The solver must use the same arithmetic as the program. Unbounded integers in the solver and 32-bit words in the program give models that take a different path on the machine, because of integer overflow. Toy IR division truncates toward zero, so the solver must too.
  • Divergence. Concretization, calls to code that is not instrumented, and nondeterminism such as time or threads make a run leave the predicted prefix. A tool that does not detect this explores the same path twice or marks a side as done that it never saw.
  • Recording constant conditions. A branch on a value that does not depend on the input gives a condition with no symbols. Negating it always fails, so RUN does not record such conditions.
  • Expecting termination. A loop whose trip count is an input gives an infinite tree, and the search follows it forever. On the box of this page, the counted loop while i < n gives one run for each nn from 0 to 8, and then the solver finds no n>8n > 8 in the box.

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.

concolic_testing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/concolic-testing/. The authors are listed in prov/C4AWCW.jsonl.
"""Concolic testing with the depth-first search of DART, on the toy IR.

concolic_run(prog, args) runs prog on concrete arguments and keeps, next to
each concrete value, a symbolic expression over the input symbols. It
returns a Run: the arguments, the outcome, the labels of the blocks visited,
the index of the instruction that trapped (or None) and the list of
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 the implicit condition "divisor != 0", and a shift adds
"0 <= amount <= 63". A condition whose expression is a constant is not
recorded, since no input can change it.

Expressions are tuples: ("in", i) for input i, ("k", c) for a constant and
("op", op, a, b). Operations on two constants are folded.

brute_force_solver(lo, hi) returns a solver that tries every input in the
box [lo, hi]^k in a fixed order. It is exact over the box: it finds a model
in the box whenever one exists. concolic(prog, solve) runs the depth-first
search and returns the list of runs, one per path that it explores.
"""

import itertools

import toyir

_DIV = ("/", "%")
_SHIFT = ("<<", ">>")


class Run:
    __slots__ = ("args", "outcome", "labels", "trap_at", "conds")

    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

    def path(self):
        """The identity of the path: the blocks, the kind of outcome and
        the instruction that trapped, if any."""
        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 run on concrete args, 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 expression e on the inputs. Raises toyir._Trap on a
    division by zero or a bad 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 condition whose
    evaluation traps 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 brute_force_solver(lo=-8, hi=8):
    """A solver that tries every input in [lo, hi]^k, in lexicographic order."""

    def solve(conds, k):
        for v in itertools.product(range(lo, hi + 1), repeat=k):
            if holds(conds, v):
                return list(v)
        return None

    return solve


def negate(cond):
    e, sense = cond
    return (e, not sense)


def concolic(prog, solve=None, start=None, fuel=10000, max_runs=100000):
    """The DART search. Returns the list of runs, one per explored path.
    Raises RuntimeError if a run does not follow the prefix that the solver
    was asked for (a divergence); with exact symbolic tracking this does not
    happen."""
    if solve is None:
        solve = brute_force_solver()
    k = len(prog.params)
    v = list(start) if start is not None else [0] * k  # @line L1
    stack = []  # @line L2
    runs = []
    while len(runs) < max_runs:  # @line L3
        r = concolic_run(prog, v, fuel)  # @line L4
        if [c for c, _ in stack] != r.conds[: len(stack)]:
            raise RuntimeError("divergence: the run left the expected prefix")
        for c in r.conds[len(stack):]:  # @line L5
            stack.append((c, False))
        runs.append(r)  # @line L6
        while True:  # @line L7
            if not stack:  # @line L8
                return runs
            c, done = stack[-1]  # @line L9
            if done:  # @line L10
                stack.pop()
                continue
            prefix = [d for d, _ in stack[:-1]]
            model = solve(prefix + [negate(c)], k)  # @line L11
            if model is None:  # @line L12
                stack.pop()
                continue
            stack[-1] = (negate(c), True)  # @line L13
            v = model
            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_concolic_testing.py 225 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/concolic-testing/. The authors are listed in prov/C4AWCW.jsonl.

import collections
import itertools
import random

import toyir
from concolic_testing import brute_force_solver, concolic, concolic_run, holds

LO, HI = -8, 8

PAGE = """
# params: x, y
entry:
  z = y * 2
  t = z == x
  br t then miss
then:
  w = y + 3
  u = w < x
  br u bug near
miss:
  ret 0
bug:
  ret 1
near:
  ret 2
"""

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 that records the path, written apart from the
    concolic 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 check_complete(prog):
    runs = concolic(prog)
    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 r in runs:
        assert all(LO <= a <= HI for a in r.args)
        assert r.outcome == toyir.run(prog, r.args)
    return runs


def test_page_example():
    prog = toyir.parse(PAGE)
    runs = check_complete(prog)
    assert [r.args for r in runs] == [[0, 0], [8, 4], [-8, -8]]
    assert [r.outcome for r in runs] == [("ret", 2), ("ret", 1), ("ret", 0)]
    counts = collections.Counter(toyir.run(prog, v) for v in box(2))
    assert counts == {("ret", 0): 280, ("ret", 2): 8, ("ret", 1): 1}


def test_first_run_conditions():
    run = concolic_run(toyir.parse(PAGE), [0, 0])
    two_y = ("op", "*", ("in", 1), ("k", 2))
    assert run.conds == [
        (("op", "==", two_y, ("in", 0)), True),
        (("op", "<", ("op", "+", ("in", 1), ("k", 3)), ("in", 0)), False),
    ]


def test_implicit_trap_condition():
    prog = toyir.parse(DIVIDE)
    runs = check_complete(prog)
    assert sorted(r.outcome for r in runs) == [("ret", 1), ("ret", 2), ("ret", 3), ("trap",)]
    trap = [r for r in runs if r.outcome == ("trap",)][0]
    assert trap.conds[-1] == (("op", "-", ("in", 0), ("in", 1)), False)


def test_counted_loop_stops_at_the_box():
    runs = check_complete(toyir.parse(COUNT))
    assert [r.args for r in runs] == [[n] for n in range(0, 9)]


def test_random_loop_free_programs():
    rng = random.Random(20261115)
    for _ in range(80):
        prog = toyir.random_program(rng, rng.randint(2, 4), rng.randint(2, 7), acyclic=True)
        check_complete(prog)


def test_random_programs_with_loops():
    rng = random.Random(7)
    for _ in range(30):
        prog = toyir.random_program(rng, rng.randint(2, 4), rng.randint(3, 7), acyclic=False)
        check_complete(prog)


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. Up to 2^k paths, plus the traps."""
    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 = []
    for _ in range(12):
        runs = check_complete(ladder(rng, rng.randint(2, 5)))
        sizes.append(len(runs))
    assert max(sizes) >= 10


def test_path_condition_is_exact():
    rng = random.Random(11)
    for _ in range(40):
        prog = toyir.random_program(rng, 3, rng.randint(2, 6), acyclic=rng.random() < 0.5)
        runs = concolic(prog)
        for v in box(2):
            p = trace(prog, v)
            hits = [r for r in runs if holds(r.conds, v)]
            assert len(hits) == 1 and hits[0].path() == p


def test_solver_calls():
    rng = random.Random(3)
    for _ in range(40):
        prog = toyir.random_program(rng, 3, rng.randint(2, 7), acyclic=True)
        inner = brute_force_solver()
        calls = {"sat": 0, "unsat": 0}

        def solve(conds, k):
            m = inner(conds, k)
            calls["sat" if m is not None else "unsat"] += 1
            return m

        runs = concolic(prog, solve)
        assert calls["sat"] == len(runs) - 1
        assert calls["sat"] + calls["unsat"] <= sum(len(r.conds) for r in runs)


def test_start_input_outside_the_order():
    prog = toyir.parse(PAGE)
    runs = concolic(prog, start=[8, 4])
    assert runs[0].outcome == ("ret", 1)
    assert {r.path() for r in runs} == brute_paths(prog)

History

Godefroid, Klarlund and Sen presented DART at PLDI 2005. It combined random testing of the interface of a C program with a dynamic analysis that records the path condition of each run and directs the next run to a new path. In the same year Sen, Marinov and Agha presented CUTE at ESEC/FSE, which handles pointer inputs and named the method concolic testing. The idea of symbolic execution goes back to King in 1976. Concolic testing made it practical for large programs, because concrete values handle what the solver cannot. Later tools built on it: SAGE at Microsoft with generational search, and hybrid fuzzers that pair a concolic engine with a greybox fuzzer.

References

  1. Patrice Godefroid, Nils Klarlund and Koushik Sen, DART, directed automated random testing, Proceedings of PLDI 2005, pp. 213 to 223, the sections on the execution model, the stack of branch records and the search for a new input (solve_path_constraint)
  2. Koushik Sen, Darko Marinov and Gul Agha, CUTE, a concolic unit testing engine for C, Proceedings of ESEC/FSE 2005, pp. 263 to 272, the sections on concolic execution, the approximation of pointer constraints and the depth-first search
  3. 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 section on concolic testing and the use of concrete values
  4. Roberto Baldoni, Emilio Coppa, Daniele Cono D'Elia, Camil Demetrescu and Irene Finocchi, A survey of symbolic execution techniques, ACM Computing Surveys 51(3), 2018, Article 50, the section on concolic execution and concretization

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.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