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
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 of the toy IR with integer parameters, a set 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 that some input of 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 , it finds every path that an input of follows, and it stops when is finite. On this page is the box , 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 on the input and keeps two stores: the concrete values and the symbolic expressions over the input symbols . An operation on two constants is folded to a constant. Each run records a list of conditions. A condition is a pair : the run went the way on which "" has the truth value .
- At
br a L1 L2, the run records , where tells whether it went to . - At a division or a remainder by , the run records , where tells whether . At a shift by , it records the condition . 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 of a run, joined by "and", are its path condition. Write for .
The search. is a stack of pairs (condition, done). Entry of the stack is the -th condition of the current path. The flag done says that the other side of that condition has been dealt with.
CONCOLIC(P, SOLVE)- 1
v <- any input, for example all zeros - 2
S <- an empty stack of pairs (condition, done) - 3
loop - 4
(outcome, c_1 ... c_m) <- RUN(P, v) - 5
for i <- |S| + 1 to m do push (c_i, false) on S - 6
output the test (v, outcome) - 7
repeat - 8
if S is empty then return - 9
(c, done) <- the top of S; let d_1 ... d_(j-1) be the conditions below it - 10
if done then pop S and continue - 11
v' <- SOLVE(d_1 and ... and d_(j-1) and not c) - 12
if there is no v' then pop S and continue - 13
replace 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 and , with the symbols and . 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 in lexicographic order of .
| run | input | conditions recorded | outcome | stack after the search step |
|---|---|---|---|---|
| 1 | (0, 0) | , | ret 2 | , |
| 2 | (8, 4) | the same two, the second one true | ret 1 | , flipped and done |
| 3 | (-8, -8) | ret 0 | empty |
After run 1, the top entry is not done, so line L11 asks for . This means and , so the only model in the box is , and run 2 reaches the bug. After run 2, the top entry is done and is popped. The next entry asks for , and the first point of the box, , 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 with probability about , 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 (it returns a model in whenever one exists) and the start input is in , the search stops, and it outputs one test for each path that some input of follows, each path exactly once.
- 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 form the leaves of a binary tree , the symbolic execution tree cut down to .
- 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.
- 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.
- The end. When the stack is empty, the invariant says that every leaf of has been output. Each run outputs a leaf that is new, by the invariant, and has at most leaves, so the loop stops. The successful solver calls are one fewer than the runs.
With an exact solver over all of 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. is a program of the toy IR with integer parameters and only constants, copies and binary operations. is a finite set of inputs, and the start input is in . SOLVE is exact over : given a list of conditions, it returns an input of 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 on an input of ends; the programs of the tests satisfy this.
A condition is a pair , and an input satisfies it when "" has the truth value and the evaluation of does not trap. For an input , let be the list of conditions that RUN records on , and let 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 and be inputs, and suppose the first conditions of are and satisfies all of them. Then the first conditions of are also . After the -th condition, the two runs reach the same point with the same symbolic store, so the next event, either the condition 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 . At the start, both runs are at the entry with the store . 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 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 , both runs record a condition with the same expression . If it is one of , then satisfies it, so and 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.
Consequences. Call , the conditions with their senses, the decision sequence of . Let be the set of the decision sequences of the inputs of and of all their prefixes.
- (a) is a binary tree: a prefix fixes the expression of by Lemma 1, so a node has at most two children, and .
- (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 .
- (c) The leaves are in one-to-one correspondence with the paths . Two inputs with the same decision sequence have the same path by Lemma 1. Two different leaves first differ at a condition against . 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 of , let be the leaves below . Then an input of satisfies all conditions of if and only if its decision sequence lies in . This is Lemma 1 in one direction; in the other, a run whose decision sequence extends satisfies the conditions of by definition.
Lemma 2: the invariant
Write the stack as from the bottom, and for , the other side at depth . Let be the set of the decision sequences of the runs output so far.
Claim. The following hold.
- (I1) At line L3, the input is in and satisfies , and .
- (I2) At line L8, is a node of and .
Proof. Initially the stack is empty, is empty, and is the start input, in . So (I1) holds.
From line L3 to line L8. By (I1), satisfies , which are the first conditions of the run of some earlier input (or ). By Lemma 1 its record starts with , so line L5 pushes exactly the rest with the flag false, and line L6 adds the leaf to . The new entries have false flags, so the union over the done entries is unchanged. By (b), is a leaf, so , and (I2) holds with the new stack.
Line L10. The top entry is popped. Every leaf below lies below or below , and both sets are in by (I2). After the pop, (I2) holds with .
Line L12. The solver is exact, so no input of satisfies , and by (d) is empty. After the pop, (I2) holds as in the previous case.
Line L13. The solver returns that satisfies , and the top becomes . Its other side is , all of whose leaves are in by (I2), and the flag was false, so the union over the done entries now covers exactly what (I2) covered. So with the new stack, and satisfies the new stack. (I1) holds.
Theorem
Claim. The search stops. The runs that it outputs have pairwise different paths, and their paths are exactly . Exactly solver calls succeed, where is the number of runs.
Proof. Each run is new. At line L3, by (I1), satisfies , so by (d) its leaf lies below the current stack. Each set is disjoint from , because their sequences differ at depth . So the new leaf is not in .
Termination. Each pass of the outer loop outputs a new leaf of , and has at most leaves, since each leaf is the decision sequence of an input of . So the outer loop runs at most 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 , all the leaves of . By (c), the paths output are exactly the paths of the inputs of , 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.
Remarks. The finiteness of is used only for termination. With a solver that is exact over all of , 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 be the number of paths explored, the largest number of conditions on one run, the largest number of steps of a run and the cost of one solver call. Each run costs , 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 calls, and exactly of them succeed. The total is . The stack and the expressions take space, because shared subterms are stored once.
The cost dominates in practice. The brute-force solver of this page costs evaluations of a formula of size . An SMT solver for bit vectors solves an NP-complete problem in each call, see bit-vector satisfiability. 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 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 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 < ngives one run for each from 0 to 8, and then the solver finds no 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.
# 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
- 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)
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag C4AWCW Edit this page History Report an error Markdown