Verifying and attacking programs with solvers: IC3, Horn clauses and symbolic execution
Solvers can prove a program never reaches an error state or find an input that reaches it. Starting from bounded verification and k-induction from m01, study IC3/PDR, which constructs inductive invariants without unrolling; its generalization to programs as constrained Horn clauses solved by Z3 Spacer; and symbolic and concolic execution (KLEE, SAGE, angr), which generates failure-triggering inputs, together with its main enemy: path explosion.
After this lesson you can
- Explain IC3/PDR using frames, blocked cubes, relative induction queries and fixed points, and implement a teaching version for small Boolean systems.
- Express verification of a program with loops as constrained Horn clauses and solve it with Z3 Spacer.
- Build a symbolic executor that generates failure-triggering inputs for a 32-bit bit-vector minilanguage.
- Implement concolic execution by negating path conditions and compare its effectiveness with random fuzzing.
- Choose path-explosion techniques (state merging, summaries, search heuristics and limits) for a given program.
Before you start
Motivation: prove it cannot fail or find an input that fails
Given a program and a property (“never two processes in the critical section”, “the index is always within the buffer”), there are two distinct questions, and this lesson’s tools divide between them:
- Can it ever fail? Answering “no” requires an argument covering all executions, including arbitrarily long ones. That argument is an inductive invariant: a set of states containing the initial states, closed under a step and excluding bad states. IC3 and Horn clause solvers construct it.
- Which input makes it fail? Answering “this one” only requires a witness: a concrete input that leads to a violated assertion. Symbolic and concolic execution search for it by asking the solver about the condition defining each path.
Both questions are undecidable in general. Deciding whether a program reaches the error line contains the halting problem (put the error just after code whose termination you want to know), and Rice’s theorem extends the impossibility to every nontrivial property of what a program computes. Each technique pays that price differently. IC3 on a finite system always terminates, but on programs with unbounded integers (Spacer) it may not; symbolic execution never reports a false positive if the solver and environment model are exact, but gives up completeness: finding no bug proves nothing. The lesson covers both sides with a common thread, the SMT solver from preceding lessons (DPLL(T), bit-blasting and incremental solving), and three labs: a symbolic and concolic executor from scratch, IC3 on Peterson’s algorithm and loop verification with Z3’s Spacer engine.
What you already know: BMC and k-induction
A transition system is a pair of formulas over a vector of state variables : the initial predicate and transition relation , where are next-state variables. A safety property is invariant if it holds in every reachable state. Bounded model checking (BMC, Biere, Cimatti, Clarke and Zhu, 1999) unrolls steps and asks whether a trace reaches a bad state:
If is satisfiable, the model is a counterexample of exactly steps; trying makes the first one the shortest. If unsatisfiable for all , you only know there are no failures of length . To close the gap, k-induction adds an inductive step: if no trace of consecutive good states can step to a bad state,
and is also unsatisfiable for , then is invariant. The issue is that the inductive step concerns any good state, reachable or not. If a cycle of unreachable good states can reach a bad state, the step fails for every even though the property is true. The classic solution is strengthening the hypothesis: prove an invariant stronger than . Finding it by hand is the hard work, which is exactly what IC3 automates.
The running example is Peterson’s mutual exclusion algorithm for two processes. Each process visits four positions: (outside), (flag set: on arrival it does ), (turn yielded: on arrival it does , with ) and (critical section, entered from if or ; on exit, ). With each process position in two bits, two flags and the turn, the state has 7 bits: 128 states. The buggy variant swaps the first two writes (turn before flag), a classic error breaking mutual exclusion. The next cell explores both models explicitly.
from collections import deque
from itertools import product
# Estado: (pc0, pc1, f0, f1, t); pc ∈ {0 fuera, 1 bandera, 2 turno, 3 crítica}
ESTADOS = list(product(range(4), range(4), (0, 1), (0, 1), (0, 1))) # 2^7 = 128
INICIAL = (0, 0, 0, 0, 0)
malo = lambda s: s[0] == 3 and s[1] == 3
def sucesores(s, fallo=False):
out = []
for i in (0, 1):
j = 1 - i
pc, f, t = list(s[:2]), list(s[2:4]), s[4]
if pc[i] == 0:
if fallo: t = j # el fallo: el turno antes que la bandera
else: f[i] = 1
pc[i] = 1
elif pc[i] == 1:
if fallo: f[i] = 1
else: t = j
pc[i] = 2
elif pc[i] == 2:
if f[j] == 1 and t != i:
continue # espera activa: este proceso no puede avanzar
pc[i] = 3
else:
f[i], pc[i] = 0, 0
out.append((pc[0], pc[1], f[0], f[1], t))
return out
def alcanzables(fallo):
dist, cola = {INICIAL: 0}, deque([INICIAL])
while cola:
s = cola.popleft()
for y in sucesores(s, fallo):
if y not in dist:
dist[y] = dist[s] + 1
cola.append(y)
return dist
for fallo in (False, True):
d = alcanzables(fallo)
malos = [k for s, k in d.items() if malo(s)]
print(f"{'con el fallo' if fallo else 'correcto '}: {len(d)} estados alcanzables; "
f"contraejemplo más corto (lo que encuentra BMC): {min(malos) if malos else 'no hay'}")
# Paso de k-inducción: ¿hay un camino s0 … sk con s0 … s(k-1) buenos y sk malo?
# B_k = estados buenos desde los que un camino de k pasos por estados buenos llega a uno malo.
alc = set(alcanzables(False))
B, tam = {s for s in ESTADOS if malo(s)}, []
for k in range(1, 130):
B = {s for s in ESTADOS if not malo(s) and any(y in B for y in sucesores(s))}
tam.append(len(B))
print("\nPeterson correcto, |B_k| para k = 1 … 8:", tam[:8], " |B_129| =", tam[-1])
print("¿Algún estado de B_129 es alcanzable?", bool(B & alc))
print("Un camino de 129 estados buenos entre 128 posibles repite alguno: hay un ciclo de estados")
print("inalcanzables que lleva al error, y el paso de k-inducción falla para todo k.")The output summarizes the problem. Correct Peterson reaches 20 of the 128 states and none is bad; the buggy version reaches 32, and the shortest counterexample has 6 steps, which BMC would find at . But the k-induction step for correct Peterson always fails: , the set of good states from which steps through good states lead to a bad state, never empties (it has 16 states at ), and none of its states is reachable. A path of 129 good states must repeat one, so an unreachable cycle feeds the induction counterexample for any . The lab shows that the k-induction variant requiring paths without repeated states does terminate, but needs .
IC3/PDR: inductive invariants without unrolling
IC3 (Bradley, 2011), also called PDR (property directed reachability, the name Eén, Mishchenko and Brayton gave their 2011 implementation), never unrolls . None of its solver queries contains more than one copy of : the typical one is “a frame, at most one clause, and a primed cube”. The formulas are small, numerous and almost all unsatisfiable. The idea is to maintain a sequence of overapproximations of reachability and refine them only where needed to exclude bad states.
Frames and their four invariants
The invariants read directly. Call the set of states reachable in at most steps. By induction on , : , and if , a state of is in (invariant 2) or succeeds one in , so it is in (invariant 3). Each frame is an overapproximation of states reachable in steps, and invariant 4 says these overapproximations are already safe through . IC3 does not yet guarantee long traces; it gets that when the sequence stabilizes.
Relative-induction queries
The central ingredient is a weak form of induction.
If for a cube (a conjunction of literals; a concrete state is a cube over all variables), the check is the SAT query
If unsatisfiable, no state in outside reaches in one step, and can be added to without breaking the invariants. Notice on the left: this makes the query relative, not simply . A state reachable only from itself (a loop) does not prevent blocking it. If satisfiable, the model gives a predecessor of that must also be blocked one level down.
The algorithm
With frames in delta form (each clause stored once, at the highest frame where it holds), the main loop is:
- Blocking. While is satisfiable, take the bad state from the model and create obligation . Process lowest-level obligations first:
- if is already excluded from by subsequently learned clauses, discard it;
- if yields predecessor , create obligation and retain ; if is an initial state (always when , but possibly earlier), the chain of obligations is a counterexample. Check at every level: blocking an initial state would break ;
- if unsatisfiable, generalize to a shorter cube , add to at the greatest where it remains relatively inductive, and requeue if .
- New frame. When contains no bad states, open without clauses (all states) and move to .
- Propagation. For and each clause of (not in ): if , push it to . If a layer is left with no clauses of its own, and is an inductive invariant implying .
You will prove this in the guided exercise: with , invariant 3 says (consecution), the chain of 1 and 2 gives (initiation) and 4 gives (safety).
Why the trace is real. Each obligation carries a complete state and each predecessor comes from a model of , so consecutive obligations have a concrete transition between them. When one reaches level 0, its state satisfies : the chain is an execution of the system. Its length need not be , or minimal: obligations requeued at higher levels lengthen the chain. In the interactive, with the bug, IC3 finds the counterexample with and a 6-step trace, also minimal in this case.
Proof
After propagation, consecutive frames and with that were semantically equal (same states) would also be syntactically equal: for each clause of , , so would have been pushed to and IC3 would have stopped. Thus while it has not stopped, as state sets (inclusion is invariant 2 and is strict by the above). A strictly increasing chain of nonempty subsets (all contain ) of a set of states has at most links, so . That each blocking phase terminates follows similarly: each clause learned at level excludes from at least one state previously included (the obligation’s state), frames only lose states and there are finitely many.
∎The bound is terrible, but only a bound: in practice IC3 converges in few frames because generalized clauses exclude entire regions. On Peterson, with 7 variables, it stops at .
Generalization: from one state to a region
Blocking state by state would enumerate the space. Generalization removes literals from cube while the clause remains valid: for each literal , it tries and accepts it if
- is unsatisfiable (clause excludes no initial states), and
- is unsatisfiable ( remains relatively inductive).
Each removed literal doubles the excluded region. In the interactive’s first step, the bad 7-literal state is generalized to (process 1 is at or , the positions with low bit 1, but its flag is down), which has 2 literals and excludes states. Clause is a protocol property any person would write: “at and my flag is set”. Later its companion appears for and . Bradley calls this inductive generalization and searches for a minimal inductive subclause (none of its proper subclauses is relatively inductive); this lesson’s single literal-by-literal pass is a cheap approximation, because relative induction is not monotone (removing a literal may make another previously rejected literal removable). Serious implementations also use the query’s unsatisfiable core to remove all literals unused in the refutation at once.
Lab: from BMC to IC3 on Peterson
The lab models Peterson as a Boolean transition system in Z3, searches for the counterexample with BMC, measures k-induction and implements a teaching version of IC3 using Z3 as a SAT oracle. It is deliberately simple: a new solver per query, frames as lists of cubes and literal-by-literal generalization. Production implementations (ABC, nuXmv, Z3’s PDR engine) use one incremental solver per frame with activation literals, core-based generalization and ternary simulation to enlarge predecessors.
import time
from z3 import *
# pc_i ∈ {0 fuera, 1 bandera, 2 turno, 3 crítica} con dos bits (a_i alto, b_i bajo); banderas f0, f1; turno t.
NOMBRES = ['a0', 'b0', 'a1', 'b1', 'f0', 'f1', 't']
def variables(sufijo=''):
return {n: Bool(n + sufijo) for n in NOMBRES}
def pc_es(x, i, v):
return And(x[f'a{i}'] == bool(v >> 1), x[f'b{i}'] == bool(v & 1))
def init(x):
return And([Not(x[n]) for n in NOMBRES])
def malo(x):
return And(pc_es(x, 0, 3), pc_es(x, 1, 3))
def trans(x, y, fallo=False):
"""y es sucesor de x: avanza el proceso 0 o el 1 (entrelazado)."""
pasos = []
for i in (0, 1):
j = 1 - i
fi, fj, a, b = f'f{i}', f'f{j}', f'a{i}', f'b{i}'
igual = lambda *cambian: And([y[n] == x[n] for n in NOMBRES if n not in cambian])
turno_a_j = y['t'] == bool(j)
if fallo: # el fallo: escribe el turno antes que la bandera
pasos.append(And(pc_es(x, i, 0), pc_es(y, i, 1), turno_a_j, igual(a, b, 't')))
pasos.append(And(pc_es(x, i, 1), pc_es(y, i, 2), y[fi], igual(a, b, fi)))
else:
pasos.append(And(pc_es(x, i, 0), pc_es(y, i, 1), y[fi], igual(a, b, fi)))
pasos.append(And(pc_es(x, i, 1), pc_es(y, i, 2), turno_a_j, igual(a, b, 't')))
puede = Or(Not(x[fj]), x['t'] == bool(i))
pasos.append(And(pc_es(x, i, 2), puede, pc_es(y, i, 3), igual(a, b)))
pasos.append(And(pc_es(x, i, 3), pc_es(y, i, 0), Not(y[fi]), igual(a, b, fi)))
return Or(pasos)
def estado(m, x):
v = {n: is_true(m.eval(x[n], model_completion=True)) for n in NOMBRES}
pc = [2 * v[f'a{i}'] + v[f'b{i}'] for i in (0, 1)]
return f"pc=(L{pc[0]},L{pc[1]}) f=({int(v['f0'])},{int(v['f1'])}) t={int(v['t'])}"
def bmc(fallo, kmax):
for k in range(kmax + 1):
xs = [variables(f'_{s}') for s in range(k + 1)]
s = Solver()
s.add(init(xs[0]), malo(xs[k]), *[trans(xs[i], xs[i + 1], fallo) for i in range(k)])
if s.check() == sat:
return k, [estado(s.model(), x) for x in xs]
return None, None
k, traza = bmc(fallo=True, kmax=12)
print(f"BMC, Peterson con el fallo: contraejemplo de longitud {k}")
for i, e in enumerate(traza):
print(f" {i}: {e}")
print(f"BMC, Peterson correcto: contraejemplo hasta k = 12: {bmc(fallo=False, kmax=12)[0]}")
def paso_inductivo(k, camino_simple):
"""¿Es UNSAT P(x0) ∧ T ∧ … ∧ P(x_{k-1}) ∧ T ∧ ¬P(x_k)? (Peterson correcto)"""
xs = [variables(f'_{s}') for s in range(k + 1)]
s = Solver()
s.add(*[Not(malo(xs[i])) for i in range(k)], malo(xs[k]))
s.add(*[trans(xs[i], xs[i + 1]) for i in range(k)])
if camino_simple: # todos los estados del camino distintos dos a dos
s.add(*[Or([xs[i][n] != xs[j][n] for n in NOMBRES]) for i in range(k + 1) for j in range(i + 1, k + 1)])
return s.check() == unsat
for simple in (False, True):
ks = [k for k in range(1, 21) if paso_inductivo(k, simple)]
print(f"k-inducción {'con caminos simples' if simple else 'simple '}: "
f"primer k que funciona entre 1 y 20: {ks[0] if ks else 'ninguno'}")npm run lab and open the connection link.X, Xp = variables(), variables("'")
lit = lambda x, n, v: x[n] if v else Not(x[n])
como_formula = lambda cubo, x: And([lit(x, n, v) for n, v in cubo])
texto_cubo = lambda c: ' ∧ '.join(('' if v else '¬') + n for n, v in c)
def cubo_de(m):
"""Cubo completo (las 7 variables) del estado actual de un modelo."""
return tuple((n, is_true(m.eval(X[n], model_completion=True))) for n in NOMBRES)
class IC3:
def __init__(self, fallo, generalizar_bien=True):
self.fallo, self.bien = fallo, generalizar_bien
self.T = trans(X, Xp, fallo)
self.delta = [[], []] # delta[i]: cubos bloqueados cuyo marco más alto es i
self.consultas = 0
def F(self, i):
if i == 0:
return init(X)
return And([Not(como_formula(c, X)) for j in range(i, len(self.delta)) for c in self.delta[j]])
def sat(self, *fs):
self.consultas += 1
s = Solver()
s.add(*fs)
return s.model() if s.check() == sat else None
def relativa(self, cubo, i):
"""¿F_i ∧ ¬c ∧ T ∧ c'? Devuelve un modelo (con el predecesor) o None."""
return self.sat(self.F(i), Not(como_formula(cubo, X)), self.T, como_formula(cubo, Xp))
def generaliza(self, cubo, i):
g = list(cubo)
for l in cubo:
h = [m for m in g if m != l]
if not h or self.sat(init(X), como_formula(h, X)) is not None:
continue # ¬h debe valer en el estado inicial
if not self.bien or self.relativa(tuple(h), i - 1) is None:
g = h # sin la consulta relativa, la cláusula puede ser falsa
return tuple(g)
def bloquea(self, cubo, k):
cola = [(k, cubo, None)]
while cola:
cola.sort(key=lambda o: o[0])
nivel, c, padre = cola.pop(0)
if nivel == 0 or all(not v for _, v in c): # un estado inicial: la cadena es un contraejemplo
traza = [c]
while padre:
traza.append(padre[1]); padre = padre[2]
return traza
if self.sat(self.F(nivel), como_formula(c, X)) is None:
continue # ya bloqueado por cláusulas posteriores
m = self.relativa(c, nivel - 1)
if m is not None:
ob = (nivel, c, padre)
cola += [(nivel - 1, cubo_de(m), ob), ob]
else:
g = self.generaliza(c, nivel)
j = nivel
while j < k and self.relativa(g, j) is None:
j += 1
for jj in range(1, j + 1): # quita los cubos que g subsume
self.delta[jj] = [d for d in self.delta[jj] if not set(g) <= set(d)]
self.delta[j].append(g)
if j < k:
cola.append((j + 1, c, padre))
return None
def run(self):
k = 1
while True:
while (m := self.sat(self.F(k), malo(X))) is not None:
traza = self.bloquea(cubo_de(m), k)
if traza:
return 'contraejemplo', traza, k
k += 1
self.delta.append([])
for i in range(1, k):
for c in list(self.delta[i]):
if self.relativa(c, i) is None: # F_i ∧ T ⇒ ¬c': la cláusula sube
self.delta[i].remove(c)
self.delta[i + 1].append(c)
if not self.delta[i]: # F_i = F_{i+1}
inv = [c for j in range(i + 1, len(self.delta)) for c in self.delta[j]]
return 'invariante', inv, k
def es_inductivo(inv, fallo):
"""Iniciación, consecución y seguridad, con solvers nuevos y sin mirar los marcos."""
I = And([Not(como_formula(c, X)) for c in inv])
Ip = substitute(I, *[(X[n], Xp[n]) for n in NOMBRES])
res = {}
for nombre, f in [('iniciación', And(init(X), Not(I))),
('consecución', And(I, trans(X, Xp, fallo), Not(Ip))),
('seguridad', And(I, malo(X)))]:
s = Solver(); s.add(f)
res[nombre] = 'ok' if s.check() == unsat else 'FALLA en ' + estado(s.model(), X)
return res
for fallo in (False, True):
ic3 = IC3(fallo)
r, datos, k = ic3.run()
print(f"IC3, Peterson {'con el fallo' if fallo else 'correcto'}: {r} con k = {k}, {ic3.consultas} consultas")
if r == 'invariante':
print(f" {len(datos)} cláusulas:")
for c in datos:
print(f" ¬({texto_cubo(c)})")
print(" comprobación independiente:", es_inductivo(datos, fallo))
else:
print(f" traza de {len(datos) - 1} pasos desde el estado inicial")
ic3 = IC3(fallo=True, generalizar_bien=False)
r, datos, k = ic3.run()
print(f"\nIC3 que generaliza sin la consulta relativa, Peterson CON el fallo: {r}")
if r == 'invariante':
print(" comprobación independiente:", es_inductivo(datos, True))npm run lab and open the connection link.The results, one by one:
- BMC finds the buggy Peterson counterexample exactly at , the minimum distance calculated by the explicit cell. The trace is the classic error: one process yields the turn before setting its flag; the other also yields the turn, sets its flag and enters because the first flag is still down; then the first sets its flag and enters too, because the last yielded turn gives it priority. (There are two symmetric minimal traces depending on which starts; Z3 returns one.) On correct Peterson, BMC finds nothing up to , proving nothing.
- Unrestricted k-induction fails for every between 1 and 20 (and the explicit cell proved it fails for all). Requiring simple paths (all states distinct), the first valid is 17: this finite-system variant always terminates because a simple path cannot exceed the number of states, but query size grows with inequality constraints.
- IC3 proves correct Peterson with and an 8-clause invariant, mostly 2 literals each, confirmed by independent checking (initiation, consecution and safety). The interactive shows exactly those 8 clauses: its oracle enumerates 128 states instead of Z3, but the search policy is the same and both reach the same invariant. With the bug, IC3 finds the counterexample at and returns a 6-step trace.
- The variant generalizing without the relative query declares an invariant for buggy Peterson, and independent checking refutes it on consecution.
From transition systems to programs: constrained Horn clauses
A program with loops is a transition system whose states are code position and variable values, but writing it that way and applying IC3 over bits would be inefficient: variables are integers, and natural invariants are linear inequalities such as , not bit conjunctions. Modern tools’ formulation generalizes both Hoare logic’s verification conditions and propositional Horn-SAT.
To verify a loop, the invariant is the unknown predicate. A bounded copy like this one, in C with 32-bit unsigned integers,
if (off + len > 64) return; // buf tiene 64 bytes
for (i = 0; i < len; i++)
buf[off + i] = src[i];
generates three clauses over a predicate , one per edge of the control-flow graph:
An interpretation of making them valid is exactly a loop invariant implying safety: the first clause is initiation, the second consecution and the third safety. Satisfiable means safe. If the system is unsatisfiable, the refutation is a finite derivation (a hyperresolution tree) that, read as an execution, is a counterexample. Clauses with one predicate in the body (linear) describe transition systems; those with several, such as , arise with procedure calls and recursion, where the predicate summarizes the function.
This formulation separates two previously joined problems: the tool translating the language (C, LLVM, Java, Solidity, Rust) into clauses, and the solver solving them. SeaHorn (Gurfinkel, Kahsai, Komuravelli and Navas, 2015) compiles C to LLVM, simplifies the code and emits CHCs; Spacer (Komuravelli, Gurfinkel and Chaki, 2014), integrated into Z3, solves them. Spacer lifts IC3 to theories: frames are sets of linear arithmetic lemmas instead of Boolean clauses, it simultaneously maintains overapproximations (“may” summaries) and underapproximations (“must” summaries) of each predicate, and generalizes predecessors by model-based projection: instead of a concrete state, a formula containing it and eliminating local variables. Bjørner, Gurfinkel, McMillan and Rybalchenko (2015) give the overview. With unbounded integers the problem is undecidable (linear integer CHCs encode counter machines), so Spacer may not terminate: Rice’s theorem on this side.
Lab: loops verified with Spacer
The cell writes two functions as CHCs and solves them with SolverFor('HORN'), which uses Spacer. Binary search traverses a[0..n) with mid = (lo + hi) / 2 and checks that every access a[mid] is in range; the injected bug is the classic while (lo <= hi) with hi = n. The copy is modeled three ways: ideal arithmetic, the C code’s actual 32-bit addition (written in linear arithmetic as “add, and if it exceeds , subtract ”) and the corrected check.
from z3 import *
def resuelve(nombre, Inv, vs, init, pasos, error, testigo):
"""init ⇒ Inv; Inv ∧ guarda ⇒ Inv(siguiente); Inv ∧ error ⇒ false. Spacer busca Inv."""
s = SolverFor('HORN')
s.set('timeout', 20000)
s.add(ForAll(vs, Implies(init, Inv(*vs))))
for (guarda, extra), sig in pasos:
s.add(ForAll(vs + extra, Implies(And(Inv(*vs), guarda), Inv(*sig))))
s.add(ForAll(vs + error[1], Implies(And(Inv(*vs), error[0]), False)))
r = s.check()
if r == sat:
print(f"{nombre}: seguro. Invariante: {s.model().eval(Inv(*vs))}")
elif r == unsat:
print(f"{nombre}: INSEGURO. {testigo()}")
else:
print(f"{nombre}: unknown ({s.reason_unknown()})")
def busqueda(con_error):
lo, hi, n, mid, r = Ints('lo hi n mid r')
Inv = Function('Inv', IntSort(), IntSort(), IntSort(), BoolSort())
guarda = (lo <= hi) if con_error else (lo < hi)
calc = And(guarda, 2 * mid + r == lo + hi, r >= 0, r <= 1) # mid = (lo + hi) / 2, sin división
pasos = [((calc, [mid, r]), (mid + 1, hi, n)), # a[mid] < clave
((calc, [mid, r]), (lo, mid, n))] # a[mid] >= clave
error = (And(calc, Or(mid < 0, mid >= n)), [mid, r]) # a[mid] fuera de rango
def testigo(): # el contraejemplo más corto, desenrollando como en BMC
for k in range(6):
los, his = Ints(' '.join(f'lo{i}' for i in range(k + 1))), Ints(' '.join(f'hi{i}' for i in range(k + 1)))
M, R, N = Ints(' '.join(f'm{i}' for i in range(k + 1))), Ints(' '.join(f'r{i}' for i in range(k + 1))), Int('N')
c = lambda i: And((los[i] <= his[i]) if con_error else (los[i] < his[i]),
2 * M[i] + R[i] == los[i] + his[i], R[i] >= 0, R[i] <= 1)
s = Solver()
s.add(N >= 0, los[0] == 0, his[0] == N, c(k), Or(M[k] < 0, M[k] >= N))
for i in range(k):
s.add(c(i), Or(And(los[i + 1] == M[i] + 1, his[i + 1] == his[i]),
And(los[i + 1] == los[i], his[i + 1] == M[i])))
if s.check() == sat:
m = s.model()
return f"Contraejemplo: n = {m[N]}, tras {k} iteraciones se lee a[{m[M[k]]}]"
resuelve('búsqueda binaria' + (' con lo <= hi' if con_error else ''), Inv, [lo, hi, n],
And(n >= 0, lo == 0, hi == n), pasos, error, testigo)
W, CAP = 2**32, 64
suma32 = lambda a, b: If(a + b >= W, a + b - W, a + b) # suma de 32 bits sin signo, en aritmética lineal
def copia(modo):
off, ln, i = Ints('off len i')
Inv = Function('Inv', IntSort(), IntSort(), IntSort(), BoolSort())
rango = And(off >= 0, off < W, ln >= 0, ln < W)
if modo == 'ideal': # off + len nunca desborda
guarda, idx = off + ln <= CAP, off + i
elif modo == 'u32': # el código C real
guarda, idx = suma32(off, ln) <= CAP, suma32(off, i)
else: # if (len > 64 || off > 64 - len) return;
guarda, idx = And(ln <= CAP, off <= CAP - ln), suma32(off, i)
def testigo():
s = Solver(); s.add(rango, guarda, 0 < ln, i == 0, idx >= CAP) # falla en la primera iteración
s.check(); m = s.model()
o, l = m[off].as_long(), m[ln].as_long()
return f"Contraejemplo: off = {hex(o)}, len = {hex(l)}; (off + len) mod 2^32 = {(o + l) % W} pasa la comprobación y se escribe buf[{hex(o)}]"
resuelve(f'copia ({modo})', Inv, [off, ln, i], And(rango, guarda, i == 0),
[((i < ln, []), (off, ln, i + 1))], (And(i < ln, idx >= CAP), []), testigo)
busqueda(False)
busqueda(True)
for modo in ('ideal', 'u32', 'corregida'):
copia(modo)npm run lab and open the connection link.Read Spacer’s invariants: they explain why the code is correct:
- In correct binary search, the invariant is . It does not include and need not: inside the loop , so gives . With
while (lo <= hi)the system is unsatisfiable and the counterexample is the smallest possible: , with no iterations, readsa[0]from an empty array. - In the copy, the ideal model is safe with invariant . The 32-bit model is unsafe: with and , the addition wraps to 0, the check passes and the first write lands at
buf[64], one byte past the end. The corrected check never adds two caller-controlled quantities ( first and then , which does not overflow), and Spacer proves it with the same invariant.
The second point explains why low-level code verification uses bit vectors, or linear arithmetic with overflow modeled as here. Ideal integers prove safety of a program other than the one being executed. Spacer also supports bit vectors directly, but reasons about them much worse than linear arithmetic (its lemmas and model-based projection target linear inequalities) and readily returns unknown on timeout; hence the lab encodes overflow using integers. Try it: rewrite the corrected version using BitVec(32), ULE and ULT, and compare.
Symbolic execution
We switch sides: now we seek an input rather than an invariant. King’s idea (1976) is to execute the program with symbols instead of values.
Two properties make the method meaningful. First is King’s theorem: if a concrete input satisfies path condition , concrete execution on follows that path, and each variable’s final value is evaluated at . Thus the solver model is a test case reproducing the bug without false positives, provided the symbolic semantics is exact. Second, conditions of different paths are disjoint (paths diverge at a branch, one taking and the other ), and for a terminating program their union covers every input. Symbolic execution partitions input space into equivalence classes, one per path. Exploration searches a tree of symbolic-state nodes; depth-first traversal needs memory proportional to depth and fits an incremental solver (push on descent, pop on ascent).
Queries. Each branch costs one or two feasibility queries, and formulas are conjunctions of path conditions in the theory of bit vectors: exactly the kind of problem solved by bit-blasting. Real tools make them cheap through optimizations measured in the KLEE paper. Its table 1 shows that, over 5-minute Coreutils runs, going from no optimization to all optimizations reduces the mean from 13,717 queries to 699 and time from 300 s to 20 s. The two main ones are constraint independence (send only constraints sharing variables with the new condition) and the counterexample cache (reuse models and previous query results: if a subset was unsatisfiable, its superset is too; if a subset model satisfies the new constraints, no solver call is needed).
Memory. This lesson’s mini-language has only variables, but real code indexes memory with input-dependent values. There are three responses, most to least precise: model memory as an array in array theory, from 32- or 64-bit addresses to bytes, with select and store (exact but costly); fork the state for every object a symbolic pointer may point to, as KLEE does; or concretize the address, fixing it to the concrete execution’s value and adding equality to the path condition, which is cheap but loses paths where the pointer differs.
Machine integers, not mathematical integers
A symbolic executor for C must use bit vectors of each type’s width. With ideal integers, len + 8 > 64 and len > 56 are the same condition, and the lesson’s bug disappears from the model. With unsigned 32-bit integers they differ: for , addition wraps, the length check passes and the copy writes billions of bytes. The following interactive and lab compare the two models on the same program.
Lab: a symbolic executor for a mini-language
The lab writes an interpreter for a mini-language of assignments, jumps and assertions over 32-bit integers: concrete, symbolic (depth-first, pruning infeasible paths, over BitVec(32) or ideal integers) and, below, concolic. The test program is a header parser with a vulnerable length check: that of the earlier copy, preceded by an 8-byte header.
import random, time
from z3 import *
MASK = 2**32 - 1
# in x | x = a | x = a op b (op: + - * & | ^ << >>) | if a cmp b goto L | goto L | assert a cmp b | halt
# Comparaciones sin signo: == != u< u<= u> u>=. Todo valor es un entero de 32 bits.
def compila(src):
prog, etiquetas = [], {}
for linea in src.strip().splitlines():
l = linea.split('#')[0].strip()
if not l:
continue
if l.endswith(':'):
etiquetas[l[:-1]] = len(prog)
continue
t = l.split()
if t[0] in ('in', 'goto', 'halt'):
prog.append(tuple(t))
elif t[0] == 'if': # if a cmp b goto L
prog.append(('if', t[1], t[2], t[3], t[5]))
elif t[0] == 'assert':
prog.append(('assert', t[1], t[2], t[3]))
elif t[1] == '=':
prog.append(('set', t[0], *t[2:]))
else:
raise SyntaxError(l)
return prog, etiquetas
CMP_C = {'==': lambda a, b: a == b, '!=': lambda a, b: a != b, 'u<': lambda a, b: a < b,
'u<=': lambda a, b: a <= b, 'u>': lambda a, b: a > b, 'u>=': lambda a, b: a >= b}
OPS_C = {'+': lambda a, b: (a + b) & MASK, '-': lambda a, b: (a - b) & MASK, '*': lambda a, b: (a * b) & MASK,
'&': lambda a, b: a & b, '|': lambda a, b: a | b, '^': lambda a, b: a ^ b,
'<<': lambda a, b: (a << b) & MASK if b < 32 else 0, '>>': lambda a, b: a >> b if b < 32 else 0}
es_const = lambda a: a[0].isdigit()
def concreto(P, entradas):
"""Ejecución normal. Devuelve ('fallo', pc) si una aserción falla, o ('fin', entorno)."""
prog, et = P
env, pc, pasos = {}, 0, 0
val = lambda a: int(a, 0) & MASK if es_const(a) else env[a]
while pc < len(prog) and pasos < 100000:
pasos += 1
ins = prog[pc]
if ins[0] == 'in':
env[ins[1]] = entradas[ins[1]] & MASK; pc += 1
elif ins[0] == 'set':
env[ins[1]] = val(ins[2]) if len(ins) == 3 else OPS_C[ins[3]](val(ins[2]), val(ins[4])); pc += 1
elif ins[0] == 'goto':
pc = et[ins[1]]
elif ins[0] == 'if':
pc = et[ins[4]] if CMP_C[ins[2]](val(ins[1]), val(ins[3])) else pc + 1
elif ins[0] == 'assert':
if not CMP_C[ins[2]](val(ins[1]), val(ins[3])):
return 'fallo', pc
pc += 1
else:
break
return 'fin', env
def semantica(ideal):
"""Constructores de Z3: bit-vectores de 32 bits o enteros matemáticos (sin desbordamiento)."""
if ideal:
cmp = {'==': lambda a, b: a == b, '!=': lambda a, b: a != b, 'u<': lambda a, b: a < b,
'u<=': lambda a, b: a <= b, 'u>': lambda a, b: a > b, 'u>=': lambda a, b: a >= b}
ops = {'+': lambda a, b: a + b, '-': lambda a, b: a - b, '*': lambda a, b: a * b}
return Int, IntVal, ops, cmp, lambda x: And(x >= 0, x <= MASK)
cmp = {'==': lambda a, b: a == b, '!=': lambda a, b: a != b, 'u<': ULT, 'u<=': ULE, 'u>': UGT, 'u>=': UGE}
ops = {'+': lambda a, b: a + b, '-': lambda a, b: a - b, '*': lambda a, b: a * b,
'&': lambda a, b: a & b, '|': lambda a, b: a | b, '^': lambda a, b: a ^ b,
'<<': lambda a, b: a << b, '>>': lambda a, b: LShR(a, b)}
return (lambda n: BitVec(n, 32)), (lambda c: BitVecVal(c, 32)), ops, cmp, (lambda x: BoolVal(True))
class Explorador:
"""Ejecución simbólica en profundidad con poda de caminos infactibles y, opcionalmente, fusión de estados."""
def __init__(self, P, ideal=False, fusion=False):
self.P, self.fusion = P, fusion
self.var, self.cte, self.ops, self.cmp, self.dominio = semantica(ideal)
self.consultas, self.entradas = 0, []
def factible(self, camino):
self.consultas += 1
s = Solver(); s.set('timeout', 10000)
s.add(*camino)
return s.model() if s.check() == sat else None
def val(self, env, a):
return self.cte(int(a, 0) & MASK) if es_const(a) else env[a]
def entrada_de(self, m):
return {n: m.eval(self.var(n), model_completion=True).as_long() for n in self.entradas}
def funde(self, env1, cam1, env2, cam2):
"""Un estado para dos: valores con If(guarda, ...) y condición prefijo común ∧ (resto1 ∨ resto2)."""
k = 0
while k < min(len(cam1), len(cam2)) and cam1[k].eq(cam2[k]):
k += 1
g1, g2 = And(cam1[k:]), And(cam2[k:])
env = {n: env1[n] if env1[n].eq(env2[n]) else If(g1, env1[n], env2[n]) for n in env1.keys() & env2.keys()}
return env, cam1[:k] + [simplify(Or(g1, g2))]
def explora(self, max_segundos=30):
prog, et = self.P
t0 = time.perf_counter()
pila, caminos = [(0, {}, [])], 0 # estados (pc, entorno simbólico, condición de camino)
while pila and time.perf_counter() - t0 < max_segundos:
if self.fusion: # el estado de menor pc absorbe a los que estén en su mismo pc
pila.sort(key=lambda e: -e[0])
pc, env, cam = pila.pop()
while pila and pila[-1][0] == pc:
_, env2, cam2 = pila.pop()
env, cam = self.funde(env, cam, env2, cam2)
else:
pc, env, cam = pila.pop()
primero = True
while pc < len(prog):
if self.fusion and not primero and any(p == pc for p, _, _ in pila):
pila.append((pc, env, cam)) # otro estado espera aquí: se fundirán
break
primero = False
ins = prog[pc]
if ins[0] == 'in':
x = self.var(ins[1]); env[ins[1]] = x; cam = cam + [self.dominio(x)]
self.entradas.append(ins[1]); pc += 1
elif ins[0] == 'set':
a = self.val(env, ins[2])
env[ins[1]] = a if len(ins) == 3 else simplify(self.ops[ins[3]](a, self.val(env, ins[4])))
pc += 1
elif ins[0] == 'goto':
pc = et[ins[1]]
elif ins[0] == 'if':
c = simplify(self.cmp[ins[2]](self.val(env, ins[1]), self.val(env, ins[3])))
hijos = []
for cond, destino in ((c, et[ins[4]]), (simplify(Not(c)), pc + 1)):
if is_false(cond):
continue
if is_true(cond) or self.factible(cam + [cond]):
hijos.append((destino, dict(env), cam + ([] if is_true(cond) else [cond])))
if len(hijos) == 1: # una sola rama factible: no se bifurca
pc, env, cam = hijos[0]
continue
pila.extend(reversed(hijos))
break
elif ins[0] == 'assert':
c = simplify(self.cmp[ins[2]](self.val(env, ins[1]), self.val(env, ins[3])))
if not is_true(c):
m = self.factible(cam + [Not(c)])
if m is not None: # una entrada que viola la aserción
return caminos, self.entrada_de(m), time.perf_counter() - t0
cam = cam + [c]
pc += 1
else:
caminos += 1 # halt: fin de un camino
break
else:
caminos += 1
return caminos, None, time.perf_counter() - t0
CABECERA = """
in magic
in ver
in len
if magic != 0x4F52594E goto rechaza
if ver u< 3 goto antigua
if ver u> 9 goto rechaza
if ver == 1 goto depuracion
t = len + 8
if t u> 64 goto rechaza
assert len u<= 56 # copia len bytes en buf + 8; buf tiene 64
goto fin
antigua:
if len u> 64 goto rechaza
assert len u<= 64
goto fin
depuracion:
r = 2
goto fin
rechaza:
r = 1
fin:
halt
"""
cab = compila(CABECERA)
hexd = lambda d: {k: hex(v) for k, v in d.items()} if d else 'ninguno'
for ideal in (False, True):
ex = Explorador(cab, ideal=ideal)
caminos, fallo, dt = ex.explora()
print(f"simbólica, {'enteros ideales' if ideal else 'BitVec(32) '}: {caminos} caminos terminados antes de "
f"{'parar' if fallo else 'agotar el árbol'}, {ex.consultas} consultas, fallo: {hexd(fallo)}")
print("comprobación concreta de la entrada:", concreto(cab, Explorador(cab).explora()[1])[0])npm run lab and open the connection link.With BitVec(32) the explorer finishes 5 paths and finds the bug on the sixth, with 14 queries: an input with the correct header, version 3 and len equal to 0xfffffffc (any value from 0xfffffff8 works; Z3 returns one). Concrete execution confirms the violation. With ideal integers the tree has 6 paths, all traversed with the same 14 queries and no bug: the vulnerable branch does not exist in that model.
Concolic execution
Pure symbolic execution has two practical problems: it keeps many states alive at once, and cannot answer as soon as the program does something the solver cannot model (a system call, cryptographic function, expensive nonlinear arithmetic). Concolic execution, from concrete plus symbolic, avoids them by always executing a real input.
The first tool was DART (Godefroid, Klarlund and Sen, 2005): random input, instrumented execution, negate the last unexplored condition and repeat, equivalent to depth-first traversal of the path tree with one execution in memory. CUTE (Sen, Marinov and Agha, 2005) named it concolic and extended it to pointer inputs. SAGE (Godefroid, Levin and Molnar, 2008) brought it to complete x86 applications reading files, with very long traces, and changed the strategy to generational search: negate all conditions of each execution, not just the last, and each child obtained by negating receives bound , so it only negates conditions after and does not regenerate its siblings. Each execution, expensive with such long traces, thus yields many new cases. The paper reports SAGE had already found over 30 new bugs in shipped Windows applications while still in development, and detected the MS07-017 animated-cursor loader vulnerability without format knowledge.
KLEE (Cadar, Dunbar and Engler, 2008) is the other branch of the family: it is not concolic, but online symbolic execution maintaining every state in memory and forking at each branch, with environment models (about 2500 lines of code for about 40 system calls and a symbolic filesystem). On the 89 GNU Coreutils utilities, its automatically generated tests achieved mean line coverage of 90.9% (median 94.7%), versus 68.4% for the developers’ hand-written suite, and across the 452 applications analyzed found 56 serious bugs, three in Coreutils undetected for over 15 years.
Concretization has a cost. If the program computes h = hash(x) and then compares h == k, concolic execution uses the concrete value of h and branch h == k no longer depends symbolically on x: it cannot negate it, and that path is lost. Worse, if concretization omits the equality from the path condition, the solver’s input may not follow the intended path (a divergence), detected when the new trace differs from the expected prefix. This is the price of never losing the ability to execute: no solver answer is needed to proceed.
The interactive shows three things. The first negation, on len ≤ 56, asks for together with in 32 bits, and the solver returns interval : overflow comes from the solver, not someone thinking of it. Full generational search from the valid header traverses all 7 feasible paths with 7 executions and 8 queries, 2 unsatisfiable (branch ver == 1, dead code because there , and violation of len ≤ 64 in the old branch, impossible with ). Random fuzzing does not get past the first line: with magic uniform over 32 bits, the probability of matching the signature is , and 20,000 inputs traverse one path.
Lab: concolic versus random fuzzing
def concolico(P, semilla, max_segundos=15):
"""Búsqueda generacional (SAGE): de cada ejecución se niegan todas las condiciones por encima de su cota."""
prog, et = P
var, cte, ops, cmp, _ = semantica(False)
t0 = time.perf_counter()
trabajo, vistos, ejecuciones, consultas = [(dict(semilla), 0)], set(), 0, 0
while trabajo and time.perf_counter() - t0 < max_segundos:
entrada, cota = trabajo.pop()
ejecuciones += 1
env_c, env_s, camino, pc = {}, {}, [], 0
vc = lambda a: int(a, 0) & MASK if es_const(a) else env_c[a]
vs = lambda a: cte(int(a, 0) & MASK) if es_const(a) else env_s[a]
while pc < len(prog):
ins = prog[pc]
if ins[0] == 'in':
env_c[ins[1]], env_s[ins[1]] = entrada[ins[1]] & MASK, var(ins[1]); pc += 1
elif ins[0] == 'set':
if len(ins) == 3:
env_c[ins[1]], env_s[ins[1]] = vc(ins[2]), vs(ins[2])
else:
env_c[ins[1]] = OPS_C[ins[3]](vc(ins[2]), vc(ins[4]))
env_s[ins[1]] = simplify(ops[ins[3]](vs(ins[2]), vs(ins[4])))
pc += 1
elif ins[0] == 'goto':
pc = et[ins[1]]
elif ins[0] in ('if', 'assert'):
r = CMP_C[ins[2]](vc(ins[1]), vc(ins[3])) # lo que hace la ejecución concreta
c = simplify(cmp[ins[2]](vs(ins[1]), vs(ins[3]))) # y su condición simbólica
if not (is_true(c) or is_false(c)):
camino.append(c if r else simplify(Not(c)))
if ins[0] == 'assert' and not r:
return dict(fallo=entrada, ejecuciones=ejecuciones, consultas=consultas)
pc = (et[ins[4]] if r else pc + 1) if ins[0] == 'if' else pc + 1
else:
break
for j in range(cota, len(camino)): # niega cada condición por encima de la cota
consultas += 1
s = Solver(); s.add(*camino[:j], Not(camino[j]))
if s.check() == sat:
m = s.model()
nueva = {n: m.eval(var(n), model_completion=True).as_long() for n in entrada}
if tuple(sorted(nueva.items())) not in vistos:
vistos.add(tuple(sorted(nueva.items())))
trabajo.append((nueva, j + 1))
return dict(fallo=None, ejecuciones=ejecuciones, consultas=consultas)
def fuzz(P, nombres, max_segundos=10, semilla=0):
rnd, t0, n = random.Random(semilla), time.perf_counter(), 0
while time.perf_counter() - t0 < max_segundos:
n += 1
entrada = {v: rnd.getrandbits(32) for v in nombres}
if concreto(P, entrada)[0] == 'fallo':
return n, entrada
return n, None
r = concolico(cab, {'magic': 0x4F52594E, 'ver': 3, 'len': 16})
print(f"concólica desde una cabecera válida: {r['ejecuciones']} ejecuciones, {r['consultas']} consultas, fallo: {hexd(r['fallo'])}")
n, f = fuzz(cab, ['magic', 'ver', 'len'], max_segundos=10)
print(f"fuzzing aleatorio durante 10 s: {n} entradas, fallo: {hexd(f)}")
print(f"probabilidad por entrada de que el fuzzing dispare el fallo: 2^-32 · 7/2^32 · 8/2^32 = {7 * 8 / 2**96:.1e}")npm run lab and open the connection link.Concolic execution starts with a valid input whose path has 6 conditions; generational search negates all 6 (6 queries) and the second execution already violates the assertion. Random fuzzing runs on the order of millions of inputs in 10 s (the exact number depends on the machine) and none fails: it needs the exact signature (), a version from 3 to 9 () and one of the 8 overflowing lengths () simultaneously, total per input. This is ideal for the solver: few conditions, each very narrow.
Path explosion
The downside appears as soon as there are loops. A loop of iterations with branches each has paths: with and , over four billion. No path enumeration, symbolic or concolic, can traverse them, and if the bug requires a particular combination of branches in every iteration, on average a constant fraction of the tree must be traversed before finding it. It is the technique’s major enemy and a principal challenge Cadar and Sen (2013) analyze in their review of three decades of symbolic execution.
The interactive’s model is small but exact. With depth-first search and random child order, on average complete subtrees are explored before the progress child, and expected iterations satisfy , with internal nodes in a subtree of height ; breadth-first traverses all earlier levels and half the last. Both expectations are . Techniques for taming the explosion attack it from four sides.
State merging. When two states reach the same program point, replace them with one with condition and values . Merging at the loop header gives one state per iteration instead of , moving the explosion from paths to formulas: the interactive actually builds the merged formula with shared subexpressions (a hash-consed DAG) and measures its size. As a DAG it grows linearly with (65 nodes with and ); written as a tree without sharing, it grows as (7216 nodes with the same parameters), because each iteration uses the previous value twice. Merging transfers work to the solver, and queries on formulas with many nested ite can be much more expensive than many small queries. Tools therefore merge selectively: Kuznetsov, Kinder, Bucur and Candea (2012) estimate how many future queries depend on each variable before merging, and Avgerinos, Rebert, Cha and Brumley’s veritesting (2014) merges only statically selected loop-free regions.
Summaries. A function called from many places is analyzed once and its summary saved: a disjunction of (precondition, postcondition) pairs over its parameters, reusable at each call. The concolic version is compositional dynamic execution (SMART, Godefroid, 2007). For loops, infer relationships between iteration count and variables (for example ) rather than unrolling.
Search heuristics. Exploration order does not change tree size, but changes time to the first bug. KLEE alternates two heuristics: random path selection, traversing the binary state tree from the root and choosing each branch with probability , favoring shallow states and preventing a tight loop from monopolizing search; and coverage-oriented search, weighting states likely to cover new code soon more heavily. The interactive shows when the latter works: in the uniform loop all iterations execute the same lines, after the first nothing new remains to cover and the heuristic degenerates to depth-first; in a stage machine, where each advance enters new code, the progress branch always covers something new and cost becomes linear in (about iterations with ).
Limits. No strategy prevents an occasional very expensive query or nonterminating path. Real executors impose a per-solver-query timeout (treating unknown as “unexplored branch”), maximum depth, maximum live states and a global budget, and prioritize coverage achievable within it.
Lab: when fuzzing wins and when merging wins
The second program has a “bug” depending on all 32 bits at once: it fails if exactly half the bits of are 1. It counts bits with a 32-iteration loop and one branch per bit, so it has paths, but about one in seven random inputs triggers it: the probability is .
MITAD = """
in x
c = 0
i = 0
bucle:
if i == 32 goto fin
b = x >> i
b = b & 1
if b == 0 goto sigue
c = c + 1
sigue:
i = i + 1
goto bucle
fin:
assert c != 16 # «fallo» si exactamente la mitad de los bits están a 1
halt
"""
mitad = compila(MITAD)
n, f = fuzz(mitad, ['x'], max_segundos=10)
print(f"fuzzing aleatorio: fallo en la entrada número {n}: x = {hex(f['x'])}")
ex = Explorador(mitad)
caminos, fallo, dt = ex.explora(max_segundos=15)
print(f"simbólica en profundidad, 15 s: {caminos} caminos terminados, {ex.consultas} consultas, fallo: {hexd(fallo)}")
r = concolico(mitad, {'x': 0}, max_segundos=15)
print(f"concólica desde x = 0, 15 s: {r['ejecuciones']} ejecuciones, {r['consultas']} consultas, fallo: {hexd(r['fallo'])}")
ex = Explorador(mitad, fusion=True)
caminos, fallo, dt = ex.explora()
x = fallo['x']
print(f"simbólica con fusión de estados: {ex.consultas} consultas, fallo: x = {hex(x)} con {bin(x).count('1')} bits a 1")npm run lab and open the connection link.The roles reverse. Random fuzzing finds the bug in a few inputs (expected attempts: ). Depth-first symbolic execution finishes on the order of thousands of paths in 15 s without finding it: the tree has leaves and, because the explorer tries the 0-bit branch first and the last iterations change first, leaves come in integer order with bit 0 as the most significant; the first with 16 ones has bits 16 through 31 set, number . Generational concolic execution from does not get there either: it too discovers paths one at a time in the same tree, and each execution contributes only its path’s 32 conditions. With state merging at the loop header, however, counter becomes a single expression with 32 nested ite, the final assertion is one query and the executor needs 65 queries (two feasibility checks per iteration and the assertion) to return an input with 16 bits set. Exact path and execution counts vary with the machine; the conclusion does not.
Security applications
These techniques are everyday defensive tools: they run on one’s own code before release, in continuous integration or during patch review. Four typical uses share the same “formula plus solver” pattern:
- Inputs reaching a bug. Every assertion, memory access with its implicit bounds check and division (zero divisor) is a query . If satisfiable, the model is a test case reproducing the problem and can join the regression suite after the fix. SAGE did this with Windows format parsers and KLEE with Coreutils.
- Overflow with bit vectors. This lesson’s length check is the pattern of many real bugs: adding two attacker-controlled quantities wraps before comparison. With correctly sized bit vectors the solver finds the wrapping combination; ideal integers hide it. The fix can also be verified: Spacer or an unsatisfiable query proves the rewritten check that never adds two external quantities.
- Function equivalence. To check that optimized
gdoes the same as referencef, ask over bit vectors: if unsatisfiable, they are equivalent for all inputs; otherwise the model is an input where they differ. This is the same miter construction as circuit equivalence, used to validate patches (does the change only alter behavior for intended inputs?) and compiler optimizations. - Binary analysis with angr. Without source code, angr (Shoshitaishvili and colleagues’ 2016 SoK) translates machine code into an intermediate representation (VEX, from Valgrind), symbolically executes it using a Z3-based constraint engine (claripy), models memory and the OS, and offers this lesson’s techniques (directed exploration, state merging, veritesting) as composable Python building blocks. It is used to audit one’s own binaries, firmware and third-party components.
Complementing fuzzing. The lab shows this in miniature: fuzzing is unbeatable when the bug occupies a non-negligible fraction of inputs (millions of executions per second, without a solver), and stalls on narrow comparisons like signatures, checksums or exact lengths; symbolic execution solves those comparisons with one query but drowns in path explosion. Hybrid systems alternate them: fuzzing while coverage progresses, then a concolic query to pass the comparison blocking it. SAGE already called itself whitebox fuzzing, and Driller (Stephens and colleagues, 2016) combines a coverage-guided fuzzer with angr’s concolic execution in this way. The same applies at the boundary with language models: autonomous security agents propose hypotheses and inputs, and a symbolic executor or verifier confirms each finding with a reproducible witness. Neural network verification, certified robustness, poses queries of the same form (“is there a small perturbation changing the class?”) with SMT and mixed-integer linear programming.
Common mistakes
The other four design mistakes appeared where relevant: concluding safety because BMC found nothing up to , generalizing in IC3 without the relative query, exploring without limits and careless environment modeling.
Exercises
if (x == 0xDEADBEEF) bug(); with 32-bit x. If fuzzing generates uniformly and independently on every execution, what is the probability of passing it at least once in executions?0xDEADBEEF, how many solver queries are needed to obtain an input entering the bug() branch?len of type uint32_t: if (len + 8 > 64) return; memcpy(buf + 8, src, len); (buf has 64 bytes). How do you model len, and what happens with the other option?Inv(x) ∧ error(x) ⇒ false and SolverFor('HORN').check() returns sat. What have you obtained?Step 1 of 4. How do you prove initiation, ?
is_inductive(estados, init, trans, bad, inv). The arguments describe an explicit finite system: estados is an iterable of all states, init(s), bad(s) and inv(s) return booleans and trans(s) returns an iterable of successors of s. Check, in this order, initiation (every initial state satisfies inv), consecution (every successor of a state in inv satisfies inv) and safety (no state in inv is bad). Return (True, None) if all three hold, or (False, (motivo, testigo)) for the first failure: 'iniciación' with an initial state outside inv; 'consecución' with a pair (s, t), s in inv and successor t of s outside inv; or 'seguridad' with a bad state in inv. There is no Z3 in the browser, so the oracle enumerates states; the IC3 lab function es_inductivo does the same with three Z3 queries, and each counterexample the solver returns is the witness you find here by traversal.def is_inductive(estados, init, trans, bad, inv):
"""Iniciación, consecución y seguridad, en ese orden. Devuelve (True, None) o (False, (motivo, testigo))."""
estados = list(estados)
# tu código
return True, NoneSummary
- BMC finds bounded-length counterexamples; k-induction can fail for every because its step concerns unreachable states. An invariant stronger than the property is needed.
- IC3 maintains frames overapproximating reachability, blocks bad cubes with relative queries , generalizes each cube to a short clause (checking it remains relatively inductive) and propagates until , an inductive invariant. On Peterson: 8 clauses with .
- Constrained Horn clauses separate language from solver: initiation, consecution and safety are clauses, the invariant is the unknown predicate, and sat means safe. Spacer (in Z3) is IC3 over theories.
- Symbolic execution partitions inputs by path and obtains an input traversing each path from its condition; concolic execution follows real inputs, negates conditions (generational search in SAGE) and concretizes what it cannot model.
- Use bit vectors of the actual width: ideal integers make overflow disappear, precisely the security bugs.
- Path explosion () is fought with state merging (which moves it into formulas), summaries, search heuristics depending on program structure, and strict limits. Fuzzing and symbolic execution complement each other: one sweeps broad regions, the other crosses narrow comparisons.