Algorithmresearch
Three-valued logic shape analysis
Also called Sagiv-Reps-Wilhelm shape analysis, TVLA.
Represents heaps by logical structures with a third value for unknown and merges nodes by abstraction predicates, for shape properties.
- Solves
- Shape analysis
- Time
- O(E M v^2 N^5) worst
- Space
- O(L M v N^2) extra
- Where
- E = the number of edges of the program; L = the number of program points; M = the largest number of canonical structures at one point; N = the largest number of nodes in one structure; v = the number of pointer variables
- Model
- Word RAM
- Properties
- deterministiciterativesoundterminates
- Evidence
- Full proofCode in 1 languages
- Origin
- Mooly Sagiv, Thomas Reps, Reinhard Wilhelm, 1999
Three-valued logic shape analysis is an abstract interpretation for shape analysis. It describes a heap as a logical structure: its cells are the individuals, and its pointers are predicates. To get a finite description of heaps of any size, it merges cells that the chosen abstraction predicates cannot tell apart into one summary node. A fact that is not the same for all the merged cells gets a third truth value, , for "unknown". The embedding theorem gives soundness: a formula that is true or false on the abstract structure has that value in every heap that the structure describes. Sagiv, Reps and Wilhelm (1999, 2002) gave the method, and the TVLA system (2000) made the predicates a parameter that the user sets.
In plain words
Draw the heap as boxes and arrows. Keep a few yes or no facts about each box: which variable points to it, which variables can reach it, and whether it is on a loop. Boxes that agree on all those facts are merged into one fuzzy box that may stand for many boxes. Some facts are then no longer yes or no. An arrow from a fuzzy box may be there for some of its boxes and missing for others, so its value is "maybe". A program step first splits a fuzzy box when it needs to know one box exactly, then updates the facts, then throws away pictures that no heap can match, and then merges again. Since there are only so many ways to label boxes, the pictures at each point stop changing, and every real heap at that point matches one of them.
The problem
Programs work on cells with one pointer field n. They have pointer variables, and statements x = null, x = new, x = y, x = y.n, x.n = null, x.n = y, and tests whether a variable is null or whether two variables are equal. The question is the shape problem: find a sound description of all heaps that reach each point, precise enough to show that no null pointer is dereferenced and that lists stay acyclic.
Three-valued logic. The values are (false), (true) and (unknown). Kleene's strong connectives are , and . So and , and an unknown input makes the result unknown only when the result depends on it. The information order is if or : the value is weaker than both and . The connectives are monotone in this order. If you replace an input by a weaker one, the result can only get weaker.
Structures. A structure has nodes and a value for each predicate on them. The core predicates are for each variable (" points to ") and ("the field of is "). There is also a summary flag , which is when may stand for several cells. A heap is a structure with only the values and . This version also stores instrumentation predicates, whose values are fixed by the core ones in every heap: (" is reachable from ") and (" is on a cycle"). They cost space, but they keep facts that a summary node would otherwise blur.
A map from the nodes of onto the nodes of embeds into if every value of is the value of its image, and two nodes go to the same image only if that image is a summary node. A structure stands for all heaps that embed into it.
The algorithm
Every unary predicate is an abstraction predicate. Blur (canonical abstraction) merges all nodes that agree on every unary predicate. It keeps their unary values, joins the binary values, and marks a merged node as a summary. So a canonical structure has at most one node per vector of unary values, and there are finitely many canonical structures. A statement is done in four steps, as in TVLA:
- Focus. Before
x = y.n, the successor of the node of must be definite. Focus replaces a structure of nodes by up to structures: one with no successor, one per candidate node that is the successor as a whole, and, for a summary candidate, one in which a single cell is split off as the successor. - Update. Each predicate gets its new value from a Kleene formula over the old values. For example, after
x.n = ywith at , . - Coerce. Facts that hold in every heap make values sharper, or show that no heap fits: a variable points to at most one cell, a cell has one successor, the successor of a cell reachable from is reachable from , and an edge back into a cell that is not on a cycle cannot exist. A structure that no heap fits is dropped.
- Blur again, so the result is canonical.
The analysis keeps a set of canonical structures at each point and iterates to a fixed point with a worklist. It does not join structures. The union of the sets is the join.
TVLA-SHAPE-ANALYSIS(P, entry)- 1
for each structure S in entry do add blur(coerce(S)) to A[start] and push it on W - 2
while W is not empty do - 3
take a point p and a structure S from W - 4
for each edge from p to q, with statement st, of P do - 5
R <- post(S, st): focus if st reads a field, then update, then coerce - 6
if st dereferences a variable that has no node in S then report p - 7
for each structure T in R do - 8
K <- blur(T) - 9
if K is not in A[q] then add K to A[q] and push (q, K) on W - 10
return A and the reported points
Example
In-place reversal of the list at x into y. The loop head is point 1.
0: y = null
1: while x != null:
2: t = x.n
3: x.n = y
4: y = x
5: x = t
6: exit
The input is a list of any length. Canonical abstraction gives 4 entry structures: the empty list, one cell, two cells, and a head cell that points into a summary node. All lists of three or more cells map to that last one. Write for the cell of x, for the summary node of the other cells reachable from x, and , for the same on the y side. The most general structure at point 2 is:
| node | variables | edges out | ||||
|---|---|---|---|---|---|---|
y |
0 | 1 | 0 | 0 | to : | |
| none | 0 | 1 | 0 | to : | ||
x, t |
1 | 0 | 0 | 0 | to : | |
| none | 1 | 0 | 0 | to : |
No node has both and , so the two lists are disjoint. everywhere, so both are acyclic.
t = x.n needs the successor of , and focus gives three structures. In the first, has no successor. The update then sets to on while t is null, and coerce drops the structure. In the second, is one cell and is the successor. In the third, one cell is split off as the successor, and keeps the rest. x.n = y points at , so now reaches the old y list. y = x and x = t move the variables, and blur merges the old into . The result is again one of the structures at point 1. The worklist stops with 13 structures at point 1, and at most 13 at any point.
At the exit, x is null and there are 4 structures: no cell, y alone, y with one successor, and y with a summary of the rest. On all four, is and is . By the embedding theorem, in every run on every input list, y is an acyclic list that holds every cell, so no cell is lost. No point is reported, so the loop never dereferences null.
Correctness
The embedding theorem is proved by induction on formulas. Atomic values are by the definition of embedding. The connectives are monotone. A quantifier is a maximum or minimum over all nodes, and the map is onto, so both sides range over the same values. Each step then keeps every heap of the input inside the output. Blur is itself an embedding. Coerce changes a value only to the one that every embedded heap has. Focus splits a structure into cases that together cover its heaps. The update formulas, read by the theorem, give values -above the new concrete values. Where the new value cannot be computed from the predicates, as for reachability after a cycle is cut, the formula uses the constant . By induction on runs, every reached heap embeds into a structure at its point: , with the empty set of states. The proof file has the details.
Proof: The embedding theorem, and why the fixed point over canonical structures covers every reachable heapfull
Setting. Truth values are , and . The information order is if or . Kleene's connectives are , and .
A structure has a finite set of nodes , a value for each unary predicate and node , a value for each pair of nodes, and a flag . The unary predicates are (" points here") and ("reachable from by zero or more steps") for each variable , and ("on a cycle of "). Equality is not stored. Its value is for , for with , and for with . A heap is a structure with all values in and everywhere, and whose predicates have their intended meaning: each variable holds at most one cell, each cell has at most one successor, and and are the reachability and the cycle sets of that graph.
Formulas are built from , , , , , , , and the constants . is the value of in under an assignment of nodes to its free variables. The quantifiers are the maximum and the minimum over .
Embedding. A map embeds into , written , if:
- is onto;
- for every unary , and ;
- . That is, if two distinct nodes or one summary node map to , then .
Two embeddings compose into an embedding. The concretization is the set of heaps that embed into , and for a set of structures .
1. The embedding theorem
Lemma 1. Kleene's connectives are monotone in : if and , then , and . If for in a finite set , then and .
Proof. For : . For , assume is definite, since otherwise there is nothing to prove. If , one of is , so the same one of is , and . If , both are , so . is the dual. The finite cases follow by induction on .
Theorem 1 (embedding theorem). If , then for every formula and assignment .
Proof. By induction on . Constants have the same value on both sides. For , and the claim is conditions 2 and 3. For , and it follows from the induction hypothesis and Lemma 1. For , the left side is . By the induction hypothesis, each term is . By Lemma 1 the maximum of the left terms is the maximum of the right terms over . Since is onto, that maximum runs over all of , which is the right side. is the same with the minimum.
So a formula that has a definite value on a structure has that value on every heap in its concretization. A value of says nothing.
2. The three steps
Lemma 2 (blur). Let map each node of to its class of nodes with the same unary values. Then , so .
Proof. is onto. A class keeps the common unary values of its members, so condition 2 holds for unary predicates with equality. The value of between two classes is the join of the values between their members, and each member value is the join. A class gets if it has two members or a summary member, which is condition 3. Every heap then embeds into by .
Two nodes of always differ on some unary value, and the code orders the nodes by those values. So the result does not depend on the names of the nodes of , and a set of blurred structures can be stored as a set of keys.
Lemma 3 (variables stay definite). In every structure that the analysis builds, for every variable and node .
Proof. from_heap gives definite values. null and new write and . copy copies a definite row. load copies the row of the node of after the focus step, which makes that row definite (Lemma 5). The other steps do not write variable predicates. Blur and coerce keep unary values or make them definite.
So "the node of " is well defined, and is null in a heap of exactly when no node of has . The analysis reports a null dereference at a point exactly when the dereferenced variable has no node, and that is then true in every heap of .
Lemma 4 (coerce). If , then is not None, and with the same .
Proof. Each rule changes a value only to the one that every heap with an embedding into must have, or it reports that no heap can embed. We check each rule against and . Write for the cells of at node . These sets are not empty, because is onto.
- Some node has . Then every cell in has . Since holds at most one cell, is that one cell, so setting keeps condition 3. Two such nodes would give two cells, which is not possible. The cell is reachable from , so cannot be , and it may be set to .
- No node has . By Lemma 3 every cell has , so is null and no cell is reachable from . So everywhere, and a value is a contradiction.
- . Then every cell of has every cell of as successor. A cell has at most one successor, so is one cell, and is correct. Every other node holds no successor of these cells, so a value of may become . Two nodes with are a contradiction.
- and . The successor of a cell on a cycle is on the same cycle, so no cell of points to a cell of . So may be set to , and a value is a contradiction. The rule for and is the same: the successor of a cell reachable from is reachable from .
- , and either with , or and for a variable . In the first case is one cell , and an edge from to would put on a cycle. In the second case is the one cell of , and every cell of is reachable from . An edge from to would put on a cycle. Both contradict , so may be set to , and a value is a contradiction.
In each case keeps conditions 1 to 3 against the changed structure. The loop repeats the rules until nothing changes, and the claim holds after each round.
Lemma 5 (focus). Let be the node of a variable in . Every heap embeds into some structure returned by focus_succ(S, u), and in each returned structure the row is definite.
Proof. By Lemma 4, embeds into . In the node is one cell . Let be the set of nodes with . If is empty, the row is definite and is returned. Otherwise there are three cases for the successor of in .
- is null, or . Then for every cell with . embeds by into the structure that sets for all .
- and . embeds by into the structure with and for the other .
- and has other cells. Then by condition 3, and the split structure is built. It has a new node that copies all values of , with , , and the other values of row set to . The map that sends to , and every other cell as does, is an embedding: is onto because keeps a cell; is the only cell at ; the copied values are -above those of as they were for ; and in row the only is the edge from to .
Each result is coerced again, and survives that by Lemma 4.
3. The update of each statement
Lemma 6. Let , and let be the heap after a statement. If the statement dereferences a variable that is null in , the analysis reports the point. Otherwise embeds into some structure in post(S, st).
Proof. assume tests only whether variables are null or equal. By Lemma 3 the test has the same value in and in , so is kept exactly when passes. For null, copy and new the new predicate values are the old values of other predicates, or , in both and . So the same , sending the new cell to the new node for new, is still an embedding. For the other statements, the new value of each predicate in is a formula over , and the code computes the same formula over , so Theorem 1 gives condition 2. Here is the cell of (for load, of ), and .
load, after focus on (Lemma 5). . For reachability, . Proof in : the cells reachable from the successor of are the cells reachable from , without itself unless is on a cycle.cut. Let . In a functional graph the path from is unique. If is not on a cycle and , then comes after on that path. It cannot come before , because then and would be on a cycle. So loses reachability from . If , the path from to does not use the edge of , and stays. If is on a cycle and , then is on that cycle, and whether it stays depends on where the path from enters the cycle. So the new value is , where is a definite value when , and otherwise. The code uses in place of . That is in the first case and in the second, so it is in both, and Lemma 1 with Theorem 1 gives condition 2. For cycles, : cutting an edge of a cycle breaks exactly that cycle, which is the set reachable from .link, done ascutand then the new edge on the result, where has no successor. Then , and . A cycle forms exactly when reaches , and then it consists of the cells on the path from to , which are all the cells reachable from . So .
In each case the result is coerced, and survives that by Lemma 4. Dereferences: load, cut and link report the point exactly when the dereferenced variable has no node, which by Lemma 3 means that it is null in .
4. Soundness of the analysis
Let be the concrete transfer on sets of states at the program points, from the given initial heaps. The reachable states are , and assigns no states to any point. Let be the abstract transfer on sets of canonical structures that analyze iterates: blur of coerce of the entry heaps at the start point, and blur of post along each edge.
Theorem 2 (soundness). . That is, every heap that the program reaches at point embeds into some structure in . Every null dereference that happens in a run is at a point that the analysis reports.
Proof. analyze stops only when its worklist is empty. Every key added to is pushed once, and its successors are computed when it is popped. So at the end, is closed under , and it is the least closed family that contains the entry. Now take a run and use induction on . For , embeds into the blur of its own coerced structure, by Lemmas 2 and 4. For the step from to , let with in . By Lemma 6, embeds into some in post(S, st), or the dereference is reported. By Lemma 2, embeds into , which is in because is closed.
By Theorem 1, a formula with value on every structure of holds in every heap at . This is how the page example reads off "acyclic" and "every cell is reachable from ".
5. Termination and cost
Theorem 3. analyze terminates.
Proof. Let be the number of unary predicates for variables. A blurred structure has nodes with pairwise different unary values, so it has at most nodes, since the variable predicates are definite (Lemma 3). Its values are drawn from finite sets. So there are finitely many canonical structures, at most doubly exponential in . Each only grows, and a key is pushed only when it is new. So the worklist empties. Inside one step, the loop of coerce ends because each round that changes something turns a into a definite value, or a flag into , and there are at most such values. focus_succ returns at most structures.
Cost. Let bound the nodes of a structure, bound the number of canonical structures at a point, be the number of variables, and be the number of edges of the program. One round of coerce costs , and there are rounds, so coerce costs . A transfer focuses into structures and coerces each one. Blur costs . Every structure at a point is popped once, and each of its out edges is processed once. So the total time is , which is within . The sets take space for points. Since can be doubly exponential in , the bound is useful only because, in practice, the sets of structures that a program reaches are small. In the page example, at most 13 structures reach any point. This holds for input lists of any length, because all lists of three or more cells have the same canonical abstraction.
Complexity
A canonical structure has at most nodes, since the variable predicates are always or . The number of canonical structures is finite but can be doubly exponential in . One coerce costs . A transfer focuses into structures, so the whole run takes time and space. These bounds are far above what real runs see. In practice the cost depends on how many distinct structures reach each point.
Properties
- Sound. Every reached heap embeds into a structure at its point, and every possible null dereference is reported.
- Terminating without widening. The set of canonical structures is finite, so no widening is needed.
- Parametric. The precision is set by the choice of predicates. Adding an instrumentation predicate, such as reachability or "is shared", splits nodes that it tells apart and keeps the facts it records exact.
- Disjunctive. A set of structures per point keeps cases apart. Joining the structures into one would lose, for example, the case split between a list of one cell and a longer list.
Variants and improvements
- TVLA. Lev-Ami and Sagiv (2000) made predicates, update formulas and integrity rules user input, so one engine runs many analyses. Bogudlov, Lev-Ami, Reps and Sagiv (2007) made the engine up to 50 times faster.
- Single structure per point. An analysis can join all structures at a point into one. It is faster but less precise.
- Verification by stronger predicates. With predicates for sortedness and order, Lev-Ami, Reps, Sagiv and Wilhelm (2000) showed that correct versions of bubble sort and insertion sort on lists return sorted lists.
- Separation logic. The separation logic analyses and bi-abduction describe heaps with list segment formulas instead of logical structures. Bi-abduction computes a summary for each procedure on its own, and this makes the analysis compositional.
When to use it
Use it when the property is about the shape of linked data, such as acyclicity, sharing, reachability or disjointness, and when it needs a precise case split, as in destructive updates of lists and trees. It fits small and mid-sized code and research tools that need to state new properties as predicates. For whole programs, use a compositional method such as bi-abduction.
Pitfalls
- Too few predicates. With only the core predicates, a summary node loses which cells are reachable from which variable, and the analysis can report null dereferences that cannot happen. The instrumentation predicates keep this information.
- Wrong update formulas. An update formula that is not sound for some heap breaks the theorem, and nothing in the method detects it. Test each formula against real heaps.
- No focus before a field read. Without focus,
x = y.non a summary successor givesxthe value on several nodes, and the next steps can tell almost nothing. - Too many structures. Each unary predicate can multiply the bound on the number of nodes by 3, and the number of structures at a point can grow very fast. Use few abstraction predicates.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/three-valued-logic-shape-analysis/. The authors are listed in prov/BGQ8GB.jsonl.
"""Shape analysis with three-valued logical structures, after Sagiv, Reps
and Wilhelm, for programs over singly linked cells with one field n.
Truth values are 0, 1 and HALF (unknown), with and = min, or = max and
not v = 1 - v (Kleene's logic). A structure has nodes 0 .. k-1 and:
u[x][v] x points to v (one predicate per variable)
u["r:x"][v] v is reachable from x by n-steps (zero steps included)
u["c"][v] v lies on a cycle of n
n[v][w] the field n of v is w
sm[v] 0, or HALF if v may stand for more than one cell
All unary predicates are abstraction predicates: canonical abstraction
(blur) merges the nodes that agree on all of them. A program is a dict from
point to a list of (statement, successor point). Statements:
("null", x) x = null
("new", x) x = new cell
("copy", x, y) x = y
("load", x, y) x = y.n
("cut", x) x.n = null
("link", x, y) x.n = y
("assume", t, x[, y]) keep the states where the test holds, t one of
"null", "nonnull", "eq", "neq"
analyze(prog, vars_, entry) returns the set of canonical structures at each
point and the points where a null dereference may happen.
"""
HALF = 0.5
def join(a, b):
return a if a == b else HALF
def leq(a, b):
"""The information order: a is at least as definite as b."""
return a == b or b == HALF
def predicates(vars_):
return tuple(vars_) + tuple("r:" + x for x in vars_) + ("c",)
class Struct:
def __init__(self, preds, u, sm, n):
self.preds = preds
self.u = u
self.sm = sm
self.n = n
def size(self):
return len(self.sm)
def copy(self):
return Struct(self.preds, {p: list(vs) for p, vs in self.u.items()}, list(self.sm), [list(r) for r in self.n])
def key(self):
"""A hashable form. After blur it is canonical, since blur sorts the
nodes by their unary values and no two nodes share them."""
vec = tuple(tuple(self.u[p][v] for p in self.preds) for v in range(self.size()))
return (vec, tuple(self.sm), tuple(tuple(r) for r in self.n))
def thaw(preds, key):
vec, sm, n = key
u = {p: [vec[v][i] for v in range(len(vec))] for i, p in enumerate(preds)}
return Struct(preds, u, list(sm), [list(r) for r in n])
def from_heap(vars_, env, nxt):
"""The two-valued structure of a concrete heap: env maps each variable
to a cell or None, nxt maps each cell to its successor or None."""
cells = sorted(nxt)
idx = {c: i for i, c in enumerate(cells)}
preds = predicates(vars_)
k = len(cells)
u = {p: [0] * k for p in preds}
for x in vars_:
c = env.get(x)
seen = set()
if c is not None:
u[x][idx[c]] = 1
while c is not None and c not in seen:
seen.add(c)
u["r:" + x][idx[c]] = 1
c = nxt[c]
for c in cells:
d, steps = nxt[c], 0
while d is not None and d != c and steps <= k:
d, steps = nxt[d], steps + 1
u["c"][idx[c]] = int(d == c)
n = [[0] * k for _ in range(k)]
for c in cells:
if nxt[c] is not None:
n[idx[c]][idx[nxt[c]]] = 1
return Struct(preds, u, [0] * k, n)
def node_of(S, x):
"""The node that x points to, or None. Variables are always definite."""
hits = [v for v in range(S.size()) if S.u[x][v] == 1]
assert all(S.u[x][v] != HALF for v in range(S.size()))
return hits[0] if hits else None
# ----------------------------------------------------------- the three steps
def blur(S):
"""Canonical abstraction: merge the nodes with equal unary values."""
preds = S.preds
vec = [tuple(S.u[p][v] for p in preds) for v in range(S.size())]
keys = sorted(set(vec))
g = {key: i for i, key in enumerate(keys)}
m = len(keys)
members = [[] for _ in range(m)]
for v in range(S.size()):
members[g[vec[v]]].append(v)
u = {p: [keys[i][j] for i in range(m)] for j, p in enumerate(preds)}
sm = [HALF if len(members[i]) > 1 or any(S.sm[v] == HALF for v in members[i]) else 0 for i in range(m)]
n = [[None] * m for _ in range(m)]
for v in range(S.size()):
for w in range(S.size()):
a, b = g[vec[v]], g[vec[w]]
n[a][b] = S.n[v][w] if n[a][b] is None else join(n[a][b], S.n[v][w])
return Struct(preds, u, sm, n)
def coerce(S, vars_):
"""Sharpen S with facts true of every heap, or return None if no heap
fits it. The facts: a variable points to at most one cell, and its
reachability set is empty exactly when it is null; a cell has at most
one successor; the successor of a cell reachable from x is reachable
from x; the successor of a cell on a cycle is on a cycle; a cell that
is not on a cycle has no edge from itself or from a cell it reaches."""
S = S.copy()
k = S.size()
changed = True
while changed:
changed = False
for x in vars_:
hits = [v for v in range(k) if S.u[x][v] == 1]
rx = S.u["r:" + x]
if len(hits) > 1:
return None
for v in range(k):
if hits and v == hits[0]:
if S.sm[v] != 0:
S.sm[v] = 0
changed = True
if rx[v] == 0:
return None
if rx[v] == HALF:
rx[v] = 1
changed = True
elif not hits and rx[v] != 0:
if rx[v] == 1:
return None
rx[v] = 0
changed = True
for v in range(k):
ones = [w for w in range(k) if S.n[v][w] == 1]
if len(ones) > 1:
return None
if ones:
w = ones[0]
if S.sm[w] != 0:
S.sm[w] = 0
changed = True
for w2 in range(k):
if w2 != w and S.n[v][w2] == HALF:
S.n[v][w2] = 0
changed = True
for v in range(k):
for w in range(k):
if S.n[v][w] == 0:
continue
bad = S.u["c"][v] == 1 and S.u["c"][w] == 0
bad = bad or any(S.u["r:" + z][v] == 1 and S.u["r:" + z][w] == 0 for z in vars_)
# An edge back to a cell that reaches v closes a cycle.
bad = bad or (v == w and S.sm[v] == 0 and S.u["c"][v] == 0)
bad = bad or (S.u["c"][w] == 0 and any(S.u[z][w] == 1 and S.u["r:" + z][v] == 1 for z in vars_))
if bad:
if S.n[v][w] == 1:
return None
S.n[v][w] = 0
changed = True
return S
def _split(S, w, u):
"""Copy the summary node w into a new node that is the one successor of
u; w keeps the other cells."""
T = S.copy()
k = T.size()
for p in T.preds:
T.u[p].append(T.u[p][w])
T.sm.append(0)
for r in T.n:
r.append(r[w])
T.n.append(list(T.n[w]))
T.n[k][k] = T.n[w][w]
for j in range(k + 1):
if j != k:
T.n[u][j] = 0 if T.n[u][j] == HALF else T.n[u][j]
T.n[u][k] = 1
T.n[u][w] = 0
return T
def focus_succ(S, u, vars_):
"""Structures that together stand for the same heaps as S, in each of
which the n-successor of node u is definite."""
S = coerce(S, vars_)
if S is None:
return []
cand = [w for w in range(S.size()) if S.n[u][w] == HALF]
if not cand:
return [S]
out = []
none = S.copy()
for w in cand:
none.n[u][w] = 0
out.append(none)
for w in cand:
whole = S.copy()
for w2 in cand:
whole.n[u][w2] = 0
whole.n[u][w] = 1
out.append(whole)
if S.sm[w] == HALF:
out.append(_split(S, w, u))
return [T for T in (coerce(T, vars_) for T in out) if T is not None]
def _cut(S, x, vars_):
"""x.n = null on a structure where x is not null."""
u = node_of(S, x)
k = S.size()
cu = S.u["c"][u]
rx = S.u["r:" + x]
xs = S.u[x]
T = S.copy()
for z in vars_:
rz = S.u["r:" + z]
for v in range(k):
a = min(rz[u], rx[v], 1 - xs[v])
# When u is not on a cycle, the cells after u are reachable from
# z only through u. When it is, they may also come before u.
T.u["r:" + z][v] = min(rz[v], 1 - min(a, 1 - cu), 1 - min(a, cu, HALF))
for v in range(k):
T.u["c"][v] = min(S.u["c"][v], 1 - min(cu, rx[v]))
for w in range(k):
T.n[u][w] = 0
return T
def post(S, st, vars_):
"""The structures after statement st, and whether st may dereference
null. Each result is focused, updated and coerced, not yet blurred."""
kind = st[0]
k = S.size()
if kind == "assume":
t, x = st[1], st[2]
a = node_of(S, x)
if t == "null":
ok = a is None
elif t == "nonnull":
ok = a is not None
else:
b = node_of(S, st[3])
ok = (a == b) == (t == "eq")
return ([S] if ok else []), False
if kind == "null":
T = S.copy()
T.u[st[1]] = [0] * k
T.u["r:" + st[1]] = [0] * k
return [T], False
if kind == "new":
x = st[1]
T = S.copy()
for p in T.preds:
T.u[p].append(0)
T.u[x] = [0] * k + [1]
T.u["r:" + x] = [0] * k + [1]
T.sm.append(0)
for r in T.n:
r.append(0)
T.n.append([0] * (k + 1))
return [T], False
if kind == "copy":
x, y = st[1], st[2]
T = S.copy()
T.u[x] = list(S.u[y])
T.u["r:" + x] = list(S.u["r:" + y])
return [T], False
if kind == "load":
x, y = st[1], st[2]
u = node_of(S, y)
if u is None:
return [], True
out = []
for F in focus_succ(S, u, vars_):
T = F.copy()
T.u[x] = [F.n[u][v] for v in range(F.size())]
T.u["r:" + x] = [max(min(F.u["r:" + y][v], 1 - F.u[y][v]), min(F.u[y][v], F.u["c"][v])) for v in range(F.size())]
T = coerce(T, vars_)
if T is not None:
out.append(T)
return out, False
if kind == "cut":
if node_of(S, st[1]) is None:
return [], True
T = coerce(_cut(S, st[1], vars_), vars_)
return ([T] if T is not None else []), False
if kind == "link":
x, y = st[1], st[2]
if node_of(S, x) is None:
return [], True
C = _cut(S, x, vars_)
u = node_of(C, x)
T = C.copy()
ryu = C.u["r:" + y][u]
for z in vars_:
for v in range(k):
T.u["r:" + z][v] = max(C.u["r:" + z][v], min(C.u["r:" + z][u], C.u["r:" + y][v]))
for v in range(k):
T.u["c"][v] = max(C.u["c"][v], min(ryu, C.u["r:" + y][v]))
T.n[u][v] = max(C.n[u][v], C.u[y][v])
T = coerce(T, vars_)
return ([T] if T is not None else []), False
raise ValueError("bad statement: %r" % (st,))
def analyze(prog, vars_, entry, start=0):
"""The least fixed point over sets of canonical structures. entry is a
list of structures for the start point. Returns (A, errors): A maps each
point to a set of keys (use thaw to read them), errors is the set of
points whose statement may dereference null."""
preds = predicates(vars_)
A = {p: set() for p in prog}
errors = set()
work = []
for S in entry: # @line L1
C = coerce(S, vars_)
if C is not None:
key = blur(C).key()
if key not in A[start]:
A[start].add(key)
work.append((start, key))
while work: # @line L2
p, key = work.pop() # @line L3
S = thaw(preds, key)
for st, q in prog[p]: # @line L4
outs, err = post(S, st, vars_) # @line L5
if err:
errors.add(p) # @line L6
for T in outs: # @line L7
new = blur(T).key() # @line L8
if new not in A[q]: # @line L9
A[q].add(new)
work.append((q, new))
return A, errors # @line L10
# ------------------------------------------------------------- formulas
def evaluate(S, phi, env=None):
"""Kleene value of a formula on S. Formulas are tuples: ("p", name, v),
("n", v, w), ("eq", v, w), ("not", f), ("and", f, g), ("or", f, g),
("exists", v, f), ("forall", v, f), ("const", value); v and w are
names of logical variables bound in env."""
env = env or {}
op = phi[0]
if op == "const":
return phi[1]
if op == "p":
return S.u[phi[1]][env[phi[2]]]
if op == "n":
return S.n[env[phi[1]]][env[phi[2]]]
if op == "eq":
a, b = env[phi[1]], env[phi[2]]
if a != b:
return 0
return 1 if S.sm[a] == 0 else HALF
if op == "not":
return 1 - evaluate(S, phi[1], env)
if op == "and":
return min(evaluate(S, phi[1], env), evaluate(S, phi[2], env))
if op == "or":
return max(evaluate(S, phi[1], env), evaluate(S, phi[2], env))
if op in ("exists", "forall"):
vals = [evaluate(S, phi[2], dict(env, **{phi[1]: v})) for v in range(S.size())]
if op == "exists":
return max(vals, default=0)
return min(vals, default=1)
raise ValueError("bad formula: %r" % (phi,))
test_three_valued_logic_shape_analysis.py 364 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/three-valued-logic-shape-analysis/. The authors are listed in prov/BGQ8GB.jsonl.
import itertools
import random
from three_valued_logic_shape_analysis import HALF, analyze, blur, evaluate, from_heap, leq, node_of, predicates, thaw
V = ("x", "y", "t")
P = predicates(V)
# In-place reversal of the list at x into y.
REV = {
0: [(("null", "y"), 1)],
1: [(("assume", "nonnull", "x"), 2), (("assume", "null", "x"), 6)],
2: [(("load", "t", "x"), 3)],
3: [(("link", "x", "y"), 4)],
4: [(("copy", "y", "x"), 5)],
5: [(("copy", "x", "t"), 1)],
6: [],
}
# Append a new cell at the end of the list at x.
APPEND = {
0: [(("assume", "null", "x"), 8), (("assume", "nonnull", "x"), 1)],
1: [(("copy", "y", "x"), 2)],
2: [(("load", "t", "y"), 3)],
3: [(("assume", "nonnull", "t"), 4), (("assume", "null", "t"), 5)],
4: [(("copy", "y", "t"), 2)],
5: [(("new", "t"), 6)],
6: [(("link", "y", "t"), 7)],
7: [],
8: [(("new", "x"), 7)],
}
# Remove the second cell of the list at x.
DELETE = {
0: [(("assume", "nonnull", "x"), 1), (("assume", "null", "x"), 6)],
1: [(("load", "t", "x"), 2)],
2: [(("assume", "nonnull", "t"), 3), (("assume", "null", "t"), 6)],
3: [(("load", "y", "t"), 4)],
4: [(("link", "x", "y"), 5)],
5: [(("cut", "t"), 6)],
6: [],
}
# Walk the list with no null test: it must fail at the end of an acyclic list.
WALK = {
0: [(("copy", "y", "x"), 1)],
1: [(("load", "t", "y"), 2)],
2: [(("copy", "y", "t"), 1)],
}
# ------------------------------------------------------- concrete semantics
def step(st, env, nxt):
"""Successor states of one statement, or "err" on a null dereference."""
kind = st[0]
env, nxt = dict(env), dict(nxt)
if kind == "assume":
a = env[st[2]]
if st[1] == "null":
ok = a is None
elif st[1] == "nonnull":
ok = a is not None
else:
ok = (a == env[st[3]]) == (st[1] == "eq")
return [(env, nxt)] if ok else []
if kind == "null":
env[st[1]] = None
elif kind == "new":
c = len(nxt)
nxt[c] = None
env[st[1]] = c
elif kind == "copy":
env[st[1]] = env[st[2]]
else:
base = env[st[2] if kind == "load" else st[1]]
if base is None:
return "err"
if kind == "load":
env[st[1]] = nxt[base]
elif kind == "cut":
nxt[base] = None
else:
nxt[base] = env[st[2]]
return [(env, nxt)]
def canon(env, nxt):
"""A form of a heap that is equal for two heaps exactly when they are
the same up to renaming of cells."""
marks = {c: tuple(sorted(v for v in env if env[v] == c)) for c in nxt}
kids = {c: [] for c in nxt}
for d, c in nxt.items():
if c is not None:
kids[c].append(d)
oncyc = set()
for c in nxt:
d, steps = nxt[c], 0
while d is not None and d != c and steps <= len(nxt):
d, steps = nxt[d], steps + 1
if d == c:
oncyc.add(c)
def shape(c):
return (marks[c], tuple(sorted(shape(d) for d in kids[c] if d not in oncyc)))
roots = tuple(sorted(shape(c) for c in nxt if nxt[c] is None))
cycles, done = [], set()
for c in sorted(oncyc):
if c in done:
continue
seq, d = [], c
while d not in done:
done.add(d)
seq.append(shape(d))
d = nxt[d]
cycles.append(min(tuple(seq[i:] + seq[:i]) for i in range(len(seq))))
return (tuple(sorted(v for v in env if env[v] is None)), roots, tuple(sorted(cycles)))
def heaps(maxk, free=("x",)):
"""One heap of each shape with at most maxk cells. Variables in free
point anywhere, the others are null. Renaming cells shows that the
first free variable that is not null can point to cell 0."""
out = {}
for k in range(maxk + 1):
for nx in itertools.product([None] + list(range(k)), repeat=k):
for targets in itertools.product([None] + list(range(k)), repeat=len(free)):
if [c for c in targets if c is not None][:1] not in ([], [0]):
continue
env = {v: None for v in V}
env.update(zip(free, targets))
nxt = dict(enumerate(nx))
out.setdefault(canon(env, nxt), (env, nxt))
return list(out.values())
# ------------------------------------------------------------- embeddings
def masks(S):
out = []
for v in range(S.size()):
d = b = 0
for i, p in enumerate(S.preds):
if S.u[p][v] != HALF:
d |= 1 << i
b |= (S.u[p][v] == 1) << i
out.append((d, b))
return out
def embedding(C, T, cm=None, tm=None):
"""A surjective map f from the nodes of C onto the nodes of T with
C(p)(v) below T(p)(f v) for every predicate and tuple, and two nodes
of C mapped together only onto a summary node; None if there is none."""
k, m = C.size(), T.size()
if k < m:
return None
cm, tm = cm or masks(C), tm or masks(T)
cand = []
for c in range(k):
cs = [w for w in range(m) if (cm[c][1] ^ tm[w][1]) & tm[w][0] == 0]
if not cs:
return None
cand.append(cs)
f = [None] * k
def go(i):
if i == k:
return len(set(f)) == m
for w in cand[i]:
ok = leq(C.n[i][i], T.n[w][w]) and (C.sm[i] == 0 or T.sm[w] == HALF)
for j in range(i):
if not ok:
break
if f[j] == w and T.sm[w] != HALF:
ok = False
elif not leq(C.n[i][j], T.n[w][f[j]]) or not leq(C.n[j][i], T.n[f[j]][w]):
ok = False
if ok:
f[i] = w
if go(i + 1):
return True
f[i] = None
return False
return list(f) if go(0) else None
def signature(S):
nodes = [node_of(S, v) for v in V]
return tuple(a is None for a in nodes) + tuple(a == b for a, b in itertools.combinations(nodes, 2))
def check_sound(prog, init, cap=6):
"""Run the analysis from the abstraction of init and the concrete
program from every heap in init. Every concrete state must embed into
a structure at its point, and every concrete null dereference must be
reported. A loop around "new" grows the heap without end, so the
concrete run stops at heaps of more than cap cells. Returns (states
checked, analysis result, errors)."""
A, errors = analyze(prog, V, [from_heap(V, e, n) for e, n in init])
index = {}
for p in A:
for key in A[p]:
T = thaw(P, key)
index.setdefault((p, signature(T)), []).append((T, masks(T)))
seen = set()
for env, nxt in init:
work = [(0, env, nxt)]
while work:
p, e, n = work.pop()
if len(n) > cap:
continue
key = (p, canon(e, n))
if key in seen:
continue
seen.add(key)
C = from_heap(V, e, n)
if blur(C).key() not in A[p]:
cm = masks(C)
bucket = index.get((p, signature(C)), [])
hit = next((i for i, (T, tm) in enumerate(bucket) if embedding(C, T, cm, tm)), None)
assert hit is not None, (p, e, n)
bucket.insert(0, bucket.pop(hit)) # neighbouring states often share a structure
for st, q in prog[p]:
r = step(st, e, n)
if r == "err":
assert p in errors, (p, e, n)
continue
work.extend((q, e2, n2) for e2, n2 in r)
return len(seen), A, errors
def list_heap(length, var="x"):
env = {v: None for v in V}
env[var] = 0 if length else None
return env, {i: (i + 1 if i + 1 < length else None) for i in range(length)}
# ------------------------------------------------------------------ tests
def test_kleene_logic():
vals = (0, HALF, 1)
S = from_heap(V, {"x": None, "y": None, "t": None}, {})
for a in vals:
assert evaluate(S, ("not", ("const", a))) == 1 - a
for b in vals:
assert evaluate(S, ("and", ("const", a), ("const", b))) == min(a, b)
assert evaluate(S, ("or", ("const", a), ("const", b))) == max(a, b)
assert evaluate(S, ("or", ("const", HALF), ("not", ("const", HALF)))) == HALF
assert [b for b in vals if leq(0, b)] == [0, HALF]
assert [b for b in vals if leq(HALF, b)] == [HALF]
def test_page_example():
"""Reversal of lists of up to 4 cells: the exit point has the empty list,
one cell, two cells and a summary; y is an acyclic list that holds every
cell, and no step can dereference null."""
A, errors = analyze(REV, V, [from_heap(V, *list_heap(k)) for k in range(5)])
assert errors == set()
exit_ = [thaw(P, key) for key in A[6]]
assert sorted(S.size() for S in exit_) == [0, 1, 2, 2]
acyclic = ("not", ("exists", "v", ("p", "c", "v")))
owned = ("forall", "v", ("p", "r:y", "v"))
for S in exit_:
assert evaluate(S, acyclic) == 1 and evaluate(S, owned) == 1
assert node_of(S, "x") is None
summary = [S for S in exit_ if HALF in S.sm]
assert len(summary) == 1
S = summary[0]
h = node_of(S, "y")
w = 1 - h
assert S.sm == [HALF if v == w else 0 for v in range(2)]
assert S.n[h][w] == HALF and S.n[w][w] == HALF and S.n[w][h] == 0
assert {p: len(keys) for p, keys in A.items()} == {0: 4, 1: 13, 2: 9, 3: 12, 4: 12, 5: 9, 6: 4}
longer, _ = analyze(REV, V, [from_heap(V, *list_heap(k)) for k in range(9)])
assert longer == A
def test_blur_is_canonical():
rng = random.Random(1)
for _ in range(300):
k = rng.randint(0, 6)
nxt = {c: rng.choice([None] + list(range(k))) for c in range(k)}
env = {v: rng.choice([None] + list(range(k))) for v in V}
B = blur(from_heap(V, env, nxt))
assert blur(B).key() == B.key()
perm = list(range(k))
rng.shuffle(perm)
nxt2 = {perm[c]: (None if d is None else perm[d]) for c, d in nxt.items()}
env2 = {v: (None if c is None else perm[c]) for v, c in env.items()}
assert blur(from_heap(V, env2, nxt2)).key() == B.key()
assert embedding(from_heap(V, env, nxt), B) is not None
def test_embedding_theorem():
"""A formula has a value on the blurred structure that is at least as
weak as its value on the heap."""
formulas = [
("exists", "v", ("p", "c", "v")),
("forall", "v", ("or", ("p", "r:x", "v"), ("p", "r:y", "v"))),
("exists", "v", ("exists", "w", ("and", ("n", "v", "w"), ("n", "w", "v")))),
("exists", "v", ("exists", "w", ("and", ("not", ("eq", "v", "w")), ("and", ("p", "r:x", "v"), ("p", "r:x", "w"))))),
("forall", "v", ("forall", "w", ("or", ("not", ("n", "v", "w")), ("p", "r:t", "w")))),
("exists", "v", ("and", ("p", "x", "v"), ("p", "y", "v"))),
("exists", "v", ("exists", "w", ("and", ("p", "y", "w"), ("n", "v", "w")))),
]
rng = random.Random(2)
weak = 0
for _ in range(400):
k = rng.randint(0, 6)
nxt = {c: rng.choice([None] + list(range(k))) for c in range(k)}
env = {v: rng.choice([None] + list(range(k))) for v in V}
C = from_heap(V, env, nxt)
B = blur(C)
for phi in formulas:
a, b = evaluate(C, phi), evaluate(B, phi)
assert a in (0, 1) and leq(a, b)
weak += b == HALF
assert weak > 60
def test_reversal_sound_for_all_heaps_up_to_5_cells():
init = heaps(5)
assert len(init) == 818
states, A, errors = check_sound(REV, init)
assert states > 10000
assert errors == set()
def test_other_programs_sound_for_all_heaps_up_to_4_cells():
init = heaps(4)
for prog in (APPEND, DELETE, WALK):
check_sound(prog, init)
_, _, errors = check_sound(WALK, [list_heap(k) for k in range(5)])
assert errors == {1}
_, A, errors = check_sound(APPEND, [list_heap(k) for k in range(5)])
assert errors == set()
for key in A[7]:
S = thaw(P, key)
assert evaluate(S, ("not", ("exists", "v", ("p", "c", "v")))) == 1
assert evaluate(S, ("forall", "v", ("p", "r:x", "v"))) == 1
def test_random_programs_sound_for_all_heaps_up_to_3_cells():
pool = [("null", "x"), ("new", "y"), ("copy", "t", "x"), ("copy", "x", "y"), ("load", "x", "y"), ("load", "t", "t"), ("load", "y", "x"), ("cut", "x"), ("cut", "t"), ("link", "x", "y"), ("link", "y", "x"), ("link", "t", "t"), ("link", "x", "t")]
tests = [("assume", "null", "x"), ("assume", "nonnull", "y"), ("assume", "eq", "x", "t"), ("assume", "neq", "x", "y")]
init = heaps(3, free=V)
rng = random.Random(3)
for _ in range(10):
prog = {}
for p in range(6):
succ = [(rng.choice(pool), p + 1)]
if rng.random() < 0.3:
succ.append((rng.choice(tests), rng.randrange(6)))
prog[p] = succ
prog[6] = []
check_sound(prog, init)
History
Jones and Muchnick (1979) and later analyses described the heap with graphs of a bounded size. Sagiv, Reps and Wilhelm (TOPLAS 1998) analyzed destructive updates with shape graphs. They then recast shape analysis in Kleene's three-valued logic (1952), with summary nodes, abstraction by predicates and the embedding theorem, at POPL 1999 and in TOPLAS 2002. Lev-Ami and Sagiv built TVLA (SAS 2000), and Lev-Ami, Reps, Sagiv and Wilhelm used it to verify sorting programs (ISSTA 2000). Reps, Sagiv and Wilhelm surveyed the line of work at CAV 2004. Bogudlov and others revamped TVLA in 2007.
References
- Mooly Sagiv, Thomas Reps and Reinhard Wilhelm, Parametric shape analysis via 3-valued logic, Proceedings of the 26th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL '99), 1999, pages 105-118, the first version of the method, with Kleene's logic, summary nodes and the embedding theorem
- Mooly Sagiv, Thomas Reps and Reinhard Wilhelm, Parametric shape analysis via 3-valued logic, ACM Transactions on Programming Languages and Systems 24(3), 2002, pages 217-298, the embedding theorem, canonical abstraction, instrumentation predicates, and the focus and coerce operations
- Tal Lev-Ami and Mooly Sagiv, TVLA, A System for Implementing Static Analyses, Static Analysis Symposium (SAS 2000), LNCS 1824, pages 280-301, the TVLA system, which builds an analysis from predicates and update formulas written by the user
- Tal Lev-Ami, Thomas Reps, Mooly Sagiv and Reinhard Wilhelm, Putting static analysis to work for verification, A case study, Proceedings of the 2000 ACM SIGSOFT International Symposium on Software Testing and Analysis (ISSTA '00), pages 26-38, the analysis applied to sorting programs on linked lists, which shows that correct versions produce sorted lists
- Thomas Reps, Mooly Sagiv and Reinhard Wilhelm, Static program analysis via 3-valued logic, Computer Aided Verification (CAV 2004), pages 15-30, an invited survey of the method and of later work on it
- Igor Bogudlov, Tal Lev-Ami, Thomas Reps and Mooly Sagiv, Revamping TVLA, Making parametric shape analysis competitive, Computer Aided Verification (CAV 2007), LNCS 4590, pages 221-225, the TVLA transformer as focus, update, coerce and blur, and the speedups of the new implementation
- Stephen Cole Kleene, Introduction to Metamathematics, North-Holland, 1952, the section on the strong three-valued logic, where an unknown value is neither true nor false
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag BGQ8GB Edit this page History Report an error Markdown