Maps to: Stanford CS 257 Introduction to Automated Reasoning (Winter 2026), Lecture 13 · Tue 02/17/2026 · Decision procedures for arrays, strings and sequences (guest lecture by Clark Barrett). Reading: none listed on the course page. Basis: The Stanford slides are on Canvas. The public Iowa decks cover two of the three topics:
- First-Order Theories: the theory of arrays , its axioms and examples;
- Theory Solvers III: the theory of strings, the proof system with L-INTRO, L-VALID, C-SPLIT and friends, extended functions as macros, regular-expression reasoning and the inclusion rules.
The rest comes from:
- Bradley and Manna, The Calculus of Computation, Chapter 11: arrays and the array property fragment;
- Kroening and Strichman, Decision Procedures, Chapter 7: arrays;
- Stump, Barrett, Dill and Levitt (2001), extensional arrays;
- Brummayer and Biere (2009), lemmas on demand for arrays;
- de Moura and Bjørner (2009), generalized arrays;
- Liang, Reynolds, Tinelli, Barrett and Deters (CAV 2014), the DPLL(T) string solver behind the slides;
- Brzozowski (1964), derivatives of regular expressions;
- Backes et al. (FMCAD 2018), Zelkova;
- Sheng et al. (IJCAR 2022), sequences.
These notes add two modules:
arrays.py: eager and lazy decision procedures for arrays, with array models as certificates;strings.py: regular expressions by derivatives, the slides’ inclusion rules, and the slides’ string calculus with memberships and an optional letter-count abstraction.The experiments were designed for these notes and do not reflect what was said in class. Sequences get an overview (§10) without code. Code:
code/lecture13/(4 scripts + 2 modules; Python standard library only; under a second to 23 seconds each) Reading time: 3 hours including running the code
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- State the axioms of the theory of arrays, explain what extensionality adds, and describe an array model as a finite map with a default.
- Reduce a quantifier-free array formula to EUF eagerly (write elimination, index-set instantiation, extensionality witnesses), and explain why the index set suffices.
- Explain lemmas on demand: which axiom instances a model can violate, and why the loop terminates.
- Say why string constraints are hard (the decidability map) and how the slides’ proof system works: L-INTRO, L-VALID, C-SPLIT, A-CONF, CONST-CONF.
- Explain why the calculus does not terminate on some inputs, and how finer abstractions (letter counts) and fair search help.
- Use Brzozowski derivatives for membership, emptiness and inclusion, and compare them with the slides’ incomplete inclusion rules.
- Turn a security question (sanitizers, access patterns) into string constraints and read the answer.
0.2 Prerequisites and scope
| Assumed | Introduced here | Developed later |
|---|---|---|
| EUF, congruence closure, CDCL(T) (Lecture 10) | the theory of arrays; eager and lazy procedures | theory combination (Lecture 18) |
| quantifier instantiation as an idea (Lecture 8) | index-set instantiation | quantifier instantiation in SMT (Lecture 17) |
| branch and bound, the gcd test (Lecture 12) | length and letter-count abstractions | — |
| regular expressions (informally) | derivatives, inclusion, length sets | — |
| — | symbolic execution (motivation) | symbolic execution (Lecture 14) |
0.3 Map
§1 why arrays and strings
§2 the theory of arrays: axioms, models, extensionality ← code 01
§3 the eager approach: write elimination + index set ← code 01, 02
§4 the lazy approach: lemmas on demand ← code 01, 02
§5 certificates for array answers ← code 01, 02
§6 strings: the theory and its difficulty
§7 the slides' proof system for word equations ← code 03
§8 regular expressions: derivatives, inclusion, memberships ← code 04
§9 applications: sanitizers, access policies ← code 04
§10 sequences (overview)
§11 summary §12 common pitfalls §13 exercises §14 further reading §15 next lecture
0.4 Notation
| Symbol | Meaning |
|---|---|
| = read | the element of array at index |
| = write | the array equal to except that it holds at |
| the default value of an array model (a fresh element) | |
| , , | concatenation, the empty word, length |
| the number of occurrences of the letter in | |
| , | membership; the language of the regular expression |
| , | the derivative of by ; ” accepts ” |
| A, [0..9], ~R, R & S | any character, a range, complement, intersection (the slides’ notation, plus ~ and &) |
| ⟨S; A⟩ | a proof state: string constraints S, arithmetic constraints A |
0.5 The code of this lecture
Two modules.
arrays.py:
- sort inference
array_termsand the printershow; ArrayValueandArrayModel(array semantics);- the eager reduction
reduce_to_euf/solve_eager; - the lazy loop
violated_lemmas/solve_lazy; - certificates
model_from_euf,check_model_arrays,lemma_kind,check_unsat_arrays,certify; - benchmarks
swaps,store_commute,ALIASING,BM_EXAMPLE,random_array_formula.
strings.py:
- regex smart constructors,
deriv/rderiv/nullable,witness,included,word_of_length,length_set; - the slides’ inclusion rules
rule_proof; - the parser
parse_constraints(with the macros),check_modeland the independent matchernaive_match; - the solver
StringSolver/solve_strings, withlia_checkfor the arithmetic part; brute_forcefor bounded ground truth.
1. Why arrays and strings
Lecture 10’s slides already showed the pipeline of symbolic execution for security (the Iowa deck repeats it for strings):
code + security policy → symbolic execution → SMT formula → SMT solver → "unsafe: here is an input"
or "safe"
Lecture 14 builds the left half. This lecture is about what the formulas contain once programs do more than arithmetic:
- Memory is an array. A heap, a stack frame, a hash table or a C array is a function from addresses to values.
*p = 1is a write,*qis a read, and the question “can a write throughqchange whatppoints to?” is a question about arrays (script 01, Part 4). - Strings are everywhere in security. Queries, paths, URLs and policies are built by concatenation and checked by regular expressions. Bugs look like “some input makes this string look like that” (script 04, Parts 4–5).
Both theories have a feature that EUF and arithmetic do not: their natural axioms talk about all indices or all positions. The decision procedures in this lecture are, at heart, clever ways of instantiating those universal statements only where needed.
2. The theory of arrays
2.1 Signature and axioms
The slides’ has three sorts: A (arrays), I (indices) and E (elements). It has two function symbols, read : A × I → E and write : A × I × E → A, and these axioms:
- Read-over-write, same index:
- Read-over-write, other index:
- Extensionality:
Dropping axiom 3 gives the theory without extensionality.
Decidability. Full first-order is undecidable. The quantifier-free fragment, with arbitrary Boolean structure, is decidable: NP-complete, like SAT itself. A larger decidable fragment allows some universal quantifiers over indices, guarded by index ranges: Bradley and Manna’s array property fragment. It can say ” is sorted between and ”:
That needs integer indices, i.e. arrays combined with arithmetic, which is Lecture 18’s topic. This lecture’s code keeps indices uninterpreted (one scalar sort for indices and elements, so is allowed).
2.2 What an array model is
An array is a function from indices to elements. A quantifier-free formula mentions only finitely many indices, though, so every array we ever need is
a default value everywhere, except at finitely many places.
ArrayValue stores exactly that: a finite map and a default δ (a fresh element). Two array values are equal when their maps and defaults are equal, which is equality as functions: entries equal to the default are dropped.
Script 01, Part 1 evaluates terms in the model , , , :
| term | value |
|---|---|
| δ | |
| δ | |
| (equal to ) |
2.3 What extensionality buys
The slides ask whether two formulas are valid. We check validity by showing the negation unsatisfiable:
| claim | negation | claim is |
|---|---|---|
| read(write(a, i, e), i) = e (slides’ Ex. 1) | UNSAT | valid |
| write(a, i, a[i]) = a, with extensionality | UNSAT | valid |
| write(a, i, a[i]) = a, without extensionality | SAT | not valid |
Why. and agree at every index: at by axiom 1, everywhere else by axiom 2. But “equal at every index” becomes “equal” only through axiom 3. Without it, the solver may keep the two arrays apart. Its “countermodel” (, with the write in another class) is then no array model in the intended sense: the certificate check, which compares arrays as functions, rejects it.
The slides’ Ex. 2, , is axiom 3 itself. It is valid in and not in the theory without extensionality.
3. The eager approach: instantiate the axioms up front
3.1 The idea
Lecture 10’s eager approach to EUF (Ackermann) replaced functions by constants plus consistency constraints. Here we do the same with arrays: turn the array formula into an EUF formula in which read is an ordinary binary function and arrays are constants. reduce_to_euf has three steps.
- Write elimination. Replace each write term , innermost first, by a fresh array constant . What the formula needs to know about is axioms 1 and 2:
- Extensionality witnesses. For every equality between arrays, add with a fresh index : if two arrays differ, they differ somewhere (axiom 3, Skolemized). The other direction, , is congruence, which EUF already knows.
- Index-set instantiation. Instantiate the ∀j of step 1 for every term used as an index: the index set, witnesses included. For each write this adds for each index term .
3.2 Why the index set is enough
A model has to get right only the reads that the formula actually performs, and every read uses an index from the set. Two reads at indices outside the set never meet, so the universally quantified axiom can be “true elsewhere” for free.
Bradley and Manna prove this for the whole array property fragment. arrays.py checks it empirically:
- every SAT model is turned into an array model and evaluated on the original formula with array semantics;
- eager and lazy answers are compared on random formulas.
That check caught a real bug in the first version (§5).
3.3 The example
Script 01, Part 2, on an example in the style of Bradley and Manna:
write elimination: A1 stands for a⟨i1◁e1⟩
write elimination: A2 stands for A1⟨i2◁e2⟩
index set: {j, i1, i2}
instances added:
A1[i1] = e1
i1 = j ∨ A1[j] = a[j]
i1 = i2 ∨ A1[i2] = a[i2]
A2[i2] = e2
i2 = j ∨ A2[j] = A1[j]
i2 = i1 ∨ A2[i1] = A1[i1]
EUF result: UNSAT; 6 instances, 11 EUF atoms, 1 conflict(s), 0 decisions; refutation ok
Reading the refutation. (because ), so . Also by congruence (), so , contradicting the last conjunct.
3.4 The cost
There are (number of writes) × (size of the index set) instances, a quadratic number, all added before the search starts, needed or not. Each is a case split for the SAT solver.
Run it:
python3 01_arrays.py(under a second).
4. The lazy approach: lemmas on demand
4.1 The idea
Treat read and write as uninterpreted functions and solve the formula in EUF. The EUF solver knows nothing about arrays, so its model may be nonsense. For example, it may say . Then:
repeat:
solve formula ∧ lemmas in EUF (read, write uninterpreted)
UNSAT → UNSAT (the lemmas are valid in T_A, so the formula is T_A-unsatisfiable)
SAT → look for axiom instances the model VIOLATES
none → the model is an array model: SAT
some → add them as lemmas, and go round again
This is the Lecture 10 story again: the very lazy loop, with theory lemmas that are axiom instances. Boolector’s “lemmas on demand” for arrays (Brummayer and Biere 2009) and the array solvers in Z3 and cvc5 work this way, but online: they add the lemmas inside one CDCL(T) run. Our loop restarts CDCL(T) each round, because Lecture 5’s SAT solver cannot grow new variables mid-search.
4.2 Which instances can a model violate?
violated_lemmas reads the EUF model as arrays. For each array class , the reads with give a finite map from index classes to element classes. Then for every write , with in class and in class :
| axiom | what the model must satisfy | lemma added if not |
|---|---|---|
| (1) | ||
| (2) | for every index class read in or | ( a term of ) |
| (3) | for every array equality that is false in the model: and differ somewhere | , fresh |
Two details matter.
- The lemma speaks about the write term , not about the array that was actually read. Congruence carries it to every array equal to , which is how lemmas reach both down (from a read of a write to its base) and up (from a read of the base to the write).
- Termination. Every lemma is built from the input’s writes, its index terms and one witness per array equality, so there are finitely many. A lemma, once added, holds in every later model.
Why “no violation” means “array model”. Define each array class’s value as with default δ elsewhere. Then:
- axiom 1 holds at ;
- axiom 2 holds at every index read in or , and at all other indices both sides are δ;
- axiom 3 holds because unequal classes differ somewhere.
So reads, writes and equalities all evaluate as EUF said. model_from_euf builds exactly this model, and check_model_arrays verifies it.
4.3 The example, round by round
Script 01, Part 3, on the same :
round 1: EUF says SAT
add lemma a⟨i1◁e1⟩[i1] = e1
add lemma a⟨i1◁e1⟩⟨i2◁e2⟩[i2] = e2
add lemma i2 = j ∨ a⟨i1◁e1⟩⟨i2◁e2⟩[j] = a⟨i1◁e1⟩[j]
round 2: EUF says UNSAT
UNSAT after 2 rounds and 3 lemmas (eager: 6 instances); refutation ok
The lazy approach never adds or the instances at : no model ever violated them.
4.4 Memory and aliasing
Script 01, Part 4 asks whether *p = c1; *q = c2; assert(*p == c1) can fail (with ):
| case | procedure | result | EUF calls | lemmas |
|---|---|---|---|---|
| no assumption about p, q | lazy | SAT | 2 | 3 |
| no assumption about p, q | eager | SAT | 1 | 10 |
| assume p ≠ q | lazy | UNSAT | 2 | 3 |
| assume p ≠ q | eager | UNSAT | 1 | 10 |
The failing execution is m1 = [p ↦ c1, else δ]; m2 = [p ↦ c2, else δ]; p = q: the assertion fails exactly when the pointers alias. Program verifiers and symbolic executors ask such questions constantly.
4.5 Eager vs lazy, measured
Script 02 compares the two on three families, with every answer certified.
Swaps. random swaps followed by the same swaps in reverse restore the array. As a formula: , which is UNSAT. Each step is a named array, as a symbolic executor would produce.
| formula | indices | approach | instances / lemmas | EUF calls | conflicts | time |
|---|---|---|---|---|---|---|
| swaps(16) | 3 | eager | 2,337 | 1 | 24 | 1.23 s |
| swaps(16) | 3 | lazy | 257 | 34 | 44 | 0.73 s |
| swaps(4) | 6 | eager | 233 | 1 | 134 | 0.29 s |
| swaps(4) | 6 | lazy | 97 | 10 | 177 | 0.14 s |
| swaps(8) | 6 | eager | 753 | 1 | 408 | 5.41 s |
| swaps(8) | 6 | lazy | 225 | 18 | 363 | 1.01 s |
With 6 distinct indices, the eager formula carries many useless case splits that the SAT solver explores anyway. At the lazy approach is about 5 times faster, and the gap grows with (see figures/02_eager_vs_lazy.png).
Store commutation (the SMT-LIB “storecomm” family). Writes at pairwise different indices commute:
| formula | approach | instances / lemmas | EUF calls | time |
|---|---|---|---|---|
| storecomm(8) | eager | 145 | 1 | 0.02 s |
| storecomm(8) | lazy | 89 | 10 | 0.06 s |
| storecomm(16) | eager | 545 | 1 | 0.20 s |
| storecomm(16) | lazy | 305 | 18 | 0.80 s |
Here almost every instance is needed: the extensionality witness must be compared with every index, through every write. The lazy loop rediscovers them over rounds, restarting each time, so eager wins on this family. Without the assumption the formula is SAT, and the counterexample has .
Random formulas. On 100 random array formulas (61 SAT, 39 UNSAT):
- the approaches agree on all 100, and 200/200 answers are certified;
- lazy adds 982 lemmas against 2,454 eager instances, but its 257 EUF calls make it slower on these small inputs (0.42 s vs 0.27 s).
The lesson. Neither approach dominates. Real solvers mix them, for instance adding axiom (1) eagerly and (2)–(3) lazily, and they add lemmas online. Later refinements avoid most instances altogether, by reasoning about “weak equivalence” of arrays (Christ and Hoenicke 2015).
Run it:
python3 02_array_benchmarks.py(about 23 s), withfigures/02_eager_vs_lazy.png.
5. Certificates for array answers
As in Lectures 10–12, no answer is reported on trust.
-
SAT.
model_from_eufbuilds an array model from the EUF classes.check_model_arraysevaluates the original formula in it, with array semantics: reads look up, writes update, arrays are equal iff they are the same function. This shares no code with congruence closure. -
UNSAT. Every added lemma must be an instance of an axiom.
lemma_kindchecks the shape:- row1 is for ;
- row2 is ;
- ext is , with a that occurs nowhere else and serves one pair only.
The final EUF refutation is then checked by Lecture 10’s
check_unsat: its theory lemmas are re-checked by an independent congruence procedure, and the propositional part by DRUP.
A bug the certificate caught. The first eager reduction built the index set from the reads that remain after write elimination. In , the read disappears from the formula together with the write, so the index was forgotten. The EUF model was then not an array model, and the array-semantics evaluation failed on random formula 19. The fix collects index terms from the eliminated writes’ arguments too.
6. Strings: the theory and its difficulty
6.1 The basic theory
The slides’ basic theory of strings has:
- sorts: String, Int, RegEx;
- constants: a fixed finite alphabet (here printable ASCII), the empty string ε, character strings, numerals;
- operators: concatenation , length , membership , plus integer and .
The decidability map (the slides):
| constraints | status | reference |
|---|---|---|
| concatenation + equality (word equations) | decidable, in PSPACE | Makanin 1977; Plandowski 2004; Jeż 2016 |
| + length constraints | decidability open | — |
| + replace-all | undecidable | Lin and Barceló 2016 |
Even the decidable case is far too expensive to implement directly: Makanin’s algorithm is famously complicated.
6.2 The pragmatic approach
The slides’ answer, which is cvc5’s and Z3’s:
- a rule-based proof system, whose rules are each easy to check;
- the existing arithmetic solver for everything about lengths;
- embrace incompleteness: the procedure may run forever on some unsatisfiable inputs, and real solvers return “unknown” at a budget.
strings.py implements this for conjunctions of constraints. In cvc5 the same rules run as a theory solver inside DPLL(T), and the case splits become new literals for the SAT solver.
7. The proof system for word equations
7.1 Proof states
A proof state is SAT, UNSAT, or a pair ⟨S; A⟩:
- S holds the string constraints, flattened so that every literal is simple;
- A holds the arithmetic constraints;
- every string variable has a length variable .
The length normalization is
7.2 The rules
Core rules (the slides, with the names StringSolver logs):
| rule | when | effect |
|---|---|---|
| L-INTRO | an equation in S | add to A |
| L-VALID | a variable | branch: | |
| A-CONF | A is unsatisfiable (over ) | close: UNSAT |
| S-CONF / CONST-CONF | S is contradictory; two different characters must be equal | close: UNSAT |
| A-PROP | A entails an equality between length terms | add it to S (here: gives ) |
| S-PROP | S entails an equality between length terms | add it to A (here: an equation with is solved by substitution) |
| SAT | no other rule applies | a model exists |
Concatenation rules.
- C-EQ: two variables that expand to the same concatenation are equal.
- C-SPLIT: two expansions of one variable, and , agree up to and then meet different variables and . Compare their lengths, in three branches:
- : for a fresh ;
- : ;
- : .
StringSolver works on equations between words rather than variable expansions; after substitution and stripping of common prefixes, the two views coincide. A variable meeting a character, , is split with L-VALID: or .
One deviation from the slides. The solver adds for every variable up front. That is the arithmetic content of L-VALID, and it saves branches.
7.3 The slides’ derivation
The slides derive UNSAT for . L-INTRO gives and , so . The slides then split with L-VALID ( | ) and close both branches by A-CONF. Script 03 prints:
x = y·x·z ∧ y = "a"
S-PROP y := "a"
A-CONF the arithmetic constraints are unsatisfiable
-> UNSAT after 1 proof states
The same argument with non-negativity built in closes the root at once.
C-SPLIT at work ():
S-PROP x := u·z
C-SPLIT |u| = |v|: u := v
S-PROP z := w
A-CONF the arithmetic constraints are unsatisfiable
C-SPLIT |u| > |v|: u := v·_k1
S-PROP w := _k1·z
SAT x = 'aa', u = 'aa', z = '', v = 'a', w = 'a'
Every model is checked on the input (check_model, with an independent regex matcher) before it is reported.
7.4 Properties: sound, but not terminating
The slides: the system is
- refutation sound (easy: check each rule);
- solution sound (hard to prove; we check every model anyway);
- not terminating (“for pathological unsat cases, C-SPLIT can be applied infinitely often”);
- hence incomplete.
Script 03, Part 2 shows non-termination on :
L-VALID x = ε
CONST-CONF "a" = "b"
L-VALID |x| > 0: x := "b"·_k1
L-VALID _k1 = ε
CONST-CONF "a" = "b"
L-VALID |_k1| > 0: _k1 := "b"·_k2
...
| state budget | result | states | depth |
|---|---|---|---|
| 25 | UNKNOWN | 26 | 13 |
| 50 | UNKNOWN | 51 | 17 |
| 100 | UNKNOWN | 101 | 33 |
| 200 | UNKNOWN | 201 | 49 |
Why it loops. fails, so . After removing the common b, the equation is : the same equation again. Length reasoning cannot help, because always holds.
7.5 A finer abstraction: counting letters
Length is one number per variable. A finer abstraction keeps one number per letter: , the Parikh image of the word. Every equation gives one linear equation per letter, and length is their sum, so the new abstraction is never weaker. On the a-count says : A-CONF at the root (counts=True).
Script 03, Part 3, on 100 random word equations (2 variables, alphabet {a, b}, budget 200 states):
| abstraction | SAT | UNSAT | UNKNOWN | states | UNSAT confirmed by brute force |
|---|---|---|---|---|---|
| lengths only | 52 | 45 | 3 | 774 | 45/45 |
| letter counts | 52 | 48 | 0 | 163 | 48/48 |
“Confirmed by brute force” means no solution with words of length ≤ 4 over {a, b}: bounded evidence, not a proof. String solvers do not yet produce checkable UNSAT certificates the way SAT solvers do; cvc5’s string proof rules are recent research.
Counting is not enough either. Part 4 shows . The counts force , but the search splits only at the left end: each fails, and can always grow. It is UNKNOWN after 101 states; brute force finds no solution up to length 5. Reading from the right would end it: the left side ends in b, so would have to end in b, but has no b. Real solvers compare both ends and much more (cvc5’s normal forms), and still remain incomplete.
7.6 Lengths are integers
Script 03, Part 5:
| constraints | result | why |
|---|---|---|
| UNSAT at the root | : the gcd test (Lecture 12) | |
| SAT: , | commuting words are powers of one word (Lyndon–Schützenberger) | |
| SAT: , | A-PROP: is entailed, so |
The first row would be satisfiable over the reals: the arithmetic part must be integer arithmetic.
Equality elimination. lia_check first eliminates every equality with a coefficient ±1, by substitution. Branch and bound alone runs forever on : it is Lecture 12’s endless strip again. After eliminating , the gcd test sees at once. That is the first step of the Omega test (Lecture 12, §5).
7.7 Fair search
A plain depth-first search can dive forever into one branch (, , …) and never look at the branch that has the solution. StringSolver uses iterative deepening: depth limit 16, then 32, 64, and so on. Every branch is reached eventually, so every satisfiable input is eventually solved; only unsatisfiable inputs can still run forever.
Run it:
python3 03_word_equations.py(about 3 s).
8. Regular expressions
8.1 Derivatives
The slides note that the automata-based approach to must build , and that complement and intersection of automata are expensive (a product and a subset construction).
Brzozowski derivatives (1964) avoid building automata up front. The derivative is the language of what may follow : It is again a regular expression, computed by structural rules:
| ∅, ε | ∅ |
| a character class | ε if , else ∅ |
| , , | , , |
Here (“nullable”) says whether . Membership is a loop: iff .
Script 04, Part 1, on :
| read | derivative | ν |
|---|---|---|
| ‘1’ | no | |
| ‘2’ | no | |
| ‘a’ | yes | |
| ’!’ | yes |
The word ‘12b’ dies at ‘b’ (the derivative becomes ∅).
Why derivatives are finite. The derivatives are the states of an automaton built on demand. Brzozowski proved that, up to simplification (associativity, commutativity and idempotence of |), there are finitely many. The smart constructors in strings.py keep regexes in such a normal form.
- Emptiness:
witnessexplores derivatives breadth first and returns a shortest word of the language, or None. - Inclusion: iff , so the same search decides it and returns a counterexample when it fails.
- Finite alphabet: the alphabet (95 characters) is cut into minterms, pieces on which every character class agrees, and only one representative per piece is explored.
8.2 The slides’ inclusion rules
The slides propose proving with a “fast, incomplete procedure”, using rules such as:
- (1) ;
- (4) ;
- (6) from infer ;
- (8) concatenation, componentwise;
- (9) ranges: when and .
rule_proof searches with all of them except (7), transitivity, which needs a guessed intermediate expression. It reproduces the slides’ exercise:
L([0..1]*·A*·"b"·A*) ⊆ L([0..9]*·A*) by (8)
L([0..1]*) ⊆ L([0..9]*) by (6)
L([0..1]) ⊆ L([0..9]) by (9)
L(A*·"b"·A*) ⊆ L(A*) by (4)
Script 04, Part 2 compares it with the exact check:
| slides’ rules | ? | counterexample | ||
|---|---|---|---|---|
| [0..1]*·A*·“b”·A* | [0..9]*·A* | proved | yes | — |
| A*·“ab”·A* | A*·“b”·A* | proved | yes | — |
| (A·A)* | A* | proved | yes | — |
| [a..b]* | (“a”*·“b”*)* | no proof | yes | — |
| [0..9]·[0..9]* | [0..9]* | no proof | yes | — |
| “a”·(“ba”)* | (“ab”)*·“a” | no proof | yes | — |
| [0..9]* | [0..9]·[0..9]* | no proof | no | ε |
| A*·“ab”·A* | A*·“ba”·A* | no proof | no | “ab” |
Why the rules fail. They have no rule for:
- an alternative on the left ( is the class , and needs one);
- ;
- regrouping as .
They are sound and cheap, and a solver uses them first. The exact check is the fallback.
8.3 Memberships in the string solver
Memberships enter StringSolver through these rules:
| rule | effect |
|---|---|
| M-DERIV | becomes ; uses the right derivative |
| M-EMPTY | the memberships of one variable intersect to ∅: close the branch |
| M-APPROX | is impossible even with every variable of replaced by (or its own regex): close the branch |
| M-UNFOLD | with several variables: branch | for each first character of (the slides’ “unfolding”, which may not terminate) |
| M-LEN | the set of lengths of is ultimately periodic; when it is one progression , tell the arithmetic solver |
| M-PICK | at the end, a variable needs a word of the chosen length; if there is none, branch | |
Script 04, Part 3:
| constraints | result | model |
|---|---|---|
| SAT | ||
| SAT | ||
| has at most one digit | SAT | |
| UNSAT | — | |
| the same without M-LEN | UNKNOWN after 61 states | — |
Why M-LEN matters. The lengths of a regular language form an ultimately periodic set: a unary automaton, the subset sequence of length_set. For they are , and the gcd test refutes . Without M-LEN, the solver tries length 1, 3, 5, …, excludes each and tries the next, forever.
8.4 Extended functions as macros
The slides extend the theory with substr, contains, index_of and replace, and implement them by reduction to the core. For example, is . parse_constraints implements the simplest such macros:
- positive occurrences: contains becomes (fresh ), and prefixof and suffixof likewise;
- negations with a constant needle become memberships: contains is .
A negated contains with a variable needle would need a universal quantifier, so it is rejected.
Performance. The slides’ later sections show that cvc5 keeps the extended functions and simplifies them as knowledge accumulates: contains when the constant does not contain . It also uses length-based conditional rewrites, such as when . These notes do not implement those rewrites.
Run it:
python3 04_regex_and_security.py(about half a second).
9. Applications
9.1 Does a sanitizer stop an injection?
A query is built as q = "SELECT * FROM t WHERE name='" · x · "'" from an input . Say the query is injected when:
- the string literal (no quote inside: ) ends at the first quote;
- what follows () starts a new OR condition.
Script 04, Part 4 adds candidate sanitizers:
| sanitizer | injection possible? | input |
|---|---|---|
| none | SAT | 'or |
| blacklist OR | SAT | 'or |
| blacklist OR, or | SAT | 'oR |
| blacklist all four spellings | UNSAT | — |
| no quote in | UNSAT | — |
| letters and digits only | UNSAT | — |
Reading the answers.
- SAT is a concrete input that gets through, checked on the constraints. Blacklisting spellings falls to the next spelling.
- UNSAT is relative to this one pattern. Blocking the four spellings of OR leaves other injections open (AND, semicolons, …).
- The robust fixes. Forbidding the quote, or allowing only letters and digits, removes any way out of the literal. Better still are parameterized queries, where the input never becomes part of the query text.
9.2 Comparing access patterns (in the style of Zelkova)
Access policies match resource names with wildcards: * is any word, ? is one character. “Does the new policy allow anything the old one did not?” is an inclusion question, and a failed check returns a concrete name (script 04, Part 5):
| P1 | P2 | P1 allows more? | a name only P1 allows |
|---|---|---|---|
| files/public/* | files/* | no | — |
| files/* | files/public/* | yes | files/ |
| files/team-?/report-*.pdf | files/team-*/report-* | no | — |
| files/team-*/report-* | files/team-?/report-*.pdf | yes | files/team-/report- |
| files/*/report-* | files/*report* | no | — |
Amazon’s Zelkova (Backes et al., FMCAD 2018, in the slides’ reading list) answers such questions for real access policies, by translating them to SMT with strings and regular expressions.
9.3 Symbolic execution
The slides open the strings deck with symbolic execution: program inputs become SMT variables, and each path becomes a constraint. Lecture 14 builds a symbolic executor; its path conditions are exactly the kind of formulas this lecture’s procedures decide.
10. Sequences (overview)
A sequence is a string whose elements come from an arbitrary sort (integers, records, other sequences) instead of a finite alphabet. The theory of sequences (as in cvc5; Sheng et al., IJCAR 2022) has:
- concatenation and length, as for strings;
- the array-like operations nth and update.
What it models. It is the natural model of vectors and lists in programming languages. It was motivated by verifying the Move language’s vector operations.
How it is decided. Its solver combines the two halves of this lecture:
- the concatenation and length reasoning of §7, without letter-level tricks (the alphabet is infinite);
- array-style read-over-write reasoning for nth and update.
11. Summary
- Arrays are functions from indices to elements. Their axioms are read-over-write (twice) and extensionality. A quantifier-free formula only needs arrays that are “default everywhere except at finitely many places”.
- Eager: eliminate writes, add extensionality witnesses, and instantiate axiom (2) for every index term. The result is an EUF formula of quadratic size.
- Lazy: treat read and write as uninterpreted, add only the axiom instances a model violates, and repeat. It wins when most instances are useless (swaps over many indices) and loses when nearly all are needed (storecomm), at least with restarts.
- Every array answer is certified: models by array semantics, refutations by axiom-instance checks plus DRUP. The certificate caught a real bug.
- Strings: word equations are decidable but impractical, length makes decidability open, and replace-all makes it undecidable. Solvers use a rule-based calculus with an arithmetic solver for lengths and accept incompleteness.
- The calculus (L-INTRO, L-VALID, C-SPLIT, A-CONF, CONST-CONF) is sound but not terminating: splits forever. Letter counts refute it at once, but not every equation; iterative deepening guarantees that satisfiable inputs are solved.
- Derivatives decide membership, emptiness and inclusion of regular expressions, with witnesses, and make complement and intersection cheap. The slides’ inclusion rules are a fast, incomplete first try.
- String solving answers security questions: whether a sanitizer stops an injection, and whether a policy change opens up anything new.
12. Common pitfalls
- Forgetting extensionality. Without axiom 3, is satisfiable. Decide which theory you mean.
- Computing the index set too late. Indices hidden inside eliminated writes still count (§5).
- Instantiating at index terms only up to syntax. may hold in the model even when and are different terms; the lemma lets the solver decide.
- Expecting termination from string solvers. UNKNOWN is a normal answer; budgets are part of the design.
- Reading UNSAT from a bounded search as a proof. “No solution up to length 4” is evidence, not a refutation.
- Real arithmetic for lengths. is satisfiable over .
- Depth-first search without fairness. One infinite branch can hide a solution in the next one.
- Blacklists as sanitizers. The solver finds the spelling you forgot.
13. Exercises
1. (array semantics) In the model , evaluate and decide whether .
Answer
The read. , and then gives . Its value at 2 is .
The equality. : yes, as functions (extensionality).
2. (eager reduction) Reduce to EUF by hand. How many instances, and why is it UNSAT?
Answer
The reduction. One write, ; the index set is . The instances are and : two in all.
The refutation.
- Since , the second instance gives .
- The formula says , so .
- That contradicts .
3. (lazy lemmas) For the same formula, what does the first EUF model look like, and which lemma does violated_lemmas add?
Answer
The first model. In EUF, (with ) and are unrelated terms, so the model can have with .
The violated instance. The class map of has index class , but while . Lemma: . Possibly also , if ‘s map lacks .
The next round. It is UNSAT.
4. (extensionality) Why is the witness lemma sound even though it is not valid for a fixed ?
Answer
Not valid, but equisatisfiable. For a fixed index the lemma is not valid: two different arrays may agree at that . But is fresh, so the lemma is the Skolemization of , which is axiom 3.
Why that suffices. Adding a Skolemized consequence preserves satisfiability: any model can interpret as an index where and differ, if they differ at all.
The proviso. It holds only if occurs nowhere else, which is why lemma_kind checks that each witness serves one pair only.
5. (eager vs lazy) Explain from the tables of §4.5 why lazy wins on swaps over 6 indices and loses on storecomm.
Answer
Swaps over 6 indices. Most eager instances concern index pairs that never interact, yet each is a case split for the SAT solver: 408 conflicts at . The lazy loop adds 225 of 753, and the time drops about 5×.
Storecomm. Nearly every instance is used by the proof. The lazy loop adds most of them anyway (305 of 545 at ), and it needs restarts to do so.
6. (word equations) Run the calculus by hand on .
Answer
L-VALID on vs b.
- gives : CONST-CONF (a ≠ b).
- gives, after stripping b, . With , A entails , so A-PROP sets .
The rest. That leaves , so (S-PROP). The model is , , which is script 03’s answer.
7. (letter counts) Show that is unsatisfiable using counts, and say whether lengths alone suffice.
Answer
Counts. The a-count gives , i.e. : unsatisfiable.
Lengths alone. They give , which always holds, so they do not suffice.
8. (derivatives) Compute and of . Is ?
Answer
The derivatives. , and .
Membership of aba.
- After a: .
- After b: .
- After a: , which is not nullable.
So .
9. (inclusion rules) Prove and with the slides’ rules, or explain why the second needs a rule the list lacks.
Answer
The first. It follows by (4) directly: anything is in .
The second. (5) gives , and (9) gives . Combining them needs (7), transitivity, which our search does not use. With transitivity: . rule_proof fails here; included succeeds.
10. (programming) Add right-end splitting to StringSolver.branches: when the first equation’s last tokens differ, split there instead of (or before) the left end. Does "aa"·y·"b" = y·"b"·x become UNSAT with counts=True? What happens to the 100 random equations of script 03?
Answer sketch
The split. Mirror the two cases: a variable vs a character at the end gives | ; variable vs variable gives the three C-SPLIT branches with suffixes.
The example. The last tokens are b vs . With , the b-count of becomes 1, contradicting ; with , the lengths fail. So it is UNSAT.
A strategy. Choose the end with a constant first. Expect no regressions and fewer states.
11. (programming) Implement online lemmas on demand: instead of restarting CDCL(T) each round, pre-register the candidate atoms (all and for writes and index terms) in the abstraction, and let a theory solver add violated instances as theory lemmas at final checks. Compare EUF conflicts and time with solve_lazy on script 02’s families.
Answer sketch
The atoms. Pre-registration makes the atom set finite and fixed, which Lecture 5’s solver needs. It is the same set the eager approach uses, but the clauses are not added until violated.
The theory solver. A subclass of EUF whose check(final=True) runs violated_lemmas on the current classes. It returns one violated instance as a conflict clause, which is valid in and therefore a legal theory lemma.
What to expect. A single CDCL(T) run, with the lazy approach’s small lemma count and no restarts. On storecomm it should approach eager’s time.
14. Further reading
- A. R. Bradley, Z. Manna, The Calculus of Computation, Chapter 11 (arrays; the array property fragment).
- D. Kroening, O. Strichman, Decision Procedures, Chapter 7 (arrays).
- A. Stump, C. W. Barrett, D. L. Dill, J. Levitt, “A Decision Procedure for an Extensional Theory of Arrays”, LICS 2001.
- R. Brummayer, A. Biere, “Lemmas on Demand for the Extensional Theory of Arrays”, JSAT 2009.
- L. de Moura, N. Bjørner, “Generalized, Efficient Array Decision Procedures”, FMCAD 2009.
- J. Christ, J. Hoenicke, “Weakly Equivalent Arrays”, FroCoS 2015.
- T. Liang, A. Reynolds, C. Tinelli, C. Barrett, M. Deters, “A DPLL(T) Theory Solver for a Theory of Strings and Regular Expressions”, CAV 2014 (the slides’ calculus), and the later papers in the slides’ list (FMSD 2016, CAV 2017, CAV 2019, CAV 2022).
- J. A. Brzozowski, “Derivatives of Regular Expressions”, JACM 1964; S. Owens, J. Reppy, A. Turon, “Regular-expression derivatives re-examined”, JFP 2009.
- W. Plandowski, “Satisfiability of Word Equations with Constants is in PSPACE”, JACM 2004; A. Jeż, “Recompression: a simple and powerful technique for word equations”, JACM 2016.
- A. W. Lin, P. Barceló, “String Solving with Word Equations and Transducers: Towards a Logic for Analysing Mutation XSS”, POPL 2016.
- J. Backes et al., “Semantic-based Automated Reasoning for AWS Access Policies using SMT”, FMCAD 2018.
- Y. Sheng et al., “Reasoning About Vectors Using an SMT Theory of Sequences”, IJCAR 2022.
15. Next lecture
Lecture 14: symbolic execution (Rachel Cleaveland).
- How a program becomes formulas. Run a program on symbolic inputs; each path gives a path condition, and the solver turns feasible path conditions into concrete test inputs.
- Path explosion and concolic testing. Many paths, and how mixing concrete and symbolic execution (DART, KLEE) gets past what the solver cannot handle.
See Lecture 14 (notes only, no code module).