Algorithm Search⌘K

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.

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
Properties
deterministiciterativesoundterminates
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, 12\tfrac12, 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 00 (false), 11 (true) and 12\tfrac12 (unknown). Kleene's strong connectives are a∧b=min⁡(a,b)a \wedge b = \min(a, b), a∨b=max⁡(a,b)a \vee b = \max(a, b) and ¬a=1−a\neg a = 1 - a. So 12∧0=0\tfrac12 \wedge 0 = 0 and 12∨1=1\tfrac12 \vee 1 = 1, and an unknown input makes the result unknown only when the result depends on it. The information order is a⊑ba \sqsubseteq b if a=ba = b or b=12b = \tfrac12: the value 12\tfrac12 is weaker than both 00 and 11. 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 x(v)x(v) for each variable xx ("xx points to vv") and n(v,w)n(v, w) ("the field of vv is ww"). There is also a summary flag sm(v)sm(v), which is 12\tfrac12 when vv may stand for several cells. A heap is a structure with only the values 00 and 11. This version also stores instrumentation predicates, whose values are fixed by the core ones in every heap: rx(v)r_x(v) ("vv is reachable from xx") and c(v)c(v) ("vv is on a cycle"). They cost space, but they keep facts that a summary node would otherwise blur.

A map ff from the nodes of SS onto the nodes of S′S' embeds SS into S′S' if every value of SS is ⊑\sqsubseteq 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 yy must be definite. Focus replaces a structure of NN nodes by up to 2N+12N + 1 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 = y with xx at aa, rz′(v)=rz(v)∨(rz(a)∧ry(v))r_z'(v) = r_z(v) \vee (r_z(a) \wedge r_y(v)).
  • 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 xx is reachable from xx, 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 A[p]A[p] 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.

  1. TVLA-SHAPE-ANALYSIS(P, entry)
  2. 1for each structure S in entry do add blur(coerce(S)) to A[start] and push it on W
  3. 2while W is not empty do
  4. 3take a point p and a structure S from W
  5. 4for each edge from p to q, with statement st, of P do
  6. 5R <- post(S, st): focus if st reads a field, then update, then coerce
  7. 6if st dereferences a variable that has no node in S then report p
  8. 7for each structure T in R do
  9. 8K <- blur(T)
  10. 9if K is not in A[q] then add K to A[q] and push (q, K) on W
  11. 10return 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 X0X_0 for the cell of x, XX for the summary node of the other cells reachable from x, and Y0Y_0, YY for the same on the y side. The most general structure at point 2 is:

node variables rxr_x ryr_y cc smsm edges out
Y0Y_0 y 0 1 0 0 to YY: 12\tfrac12
YY none 0 1 0 12\tfrac12 to YY: 12\tfrac12
X0X_0 x, t 1 0 0 0 to XX: 12\tfrac12
XX none 1 0 0 12\tfrac12 to XX: 12\tfrac12

No node has both rx=1r_x = 1 and ry=1r_y = 1, so the two lists are disjoint. c=0c = 0 everywhere, so both are acyclic.

t = x.n needs the successor of X0X_0, and focus gives three structures. In the first, X0X_0 has no successor. The update then sets rtr_t to 11 on XX while t is null, and coerce drops the structure. In the second, XX is one cell and is the successor. In the third, one cell X1X_1 is split off XX as the successor, and XX keeps the rest. x.n = y points X0X_0 at Y0Y_0, so X0X_0 now reaches the old y list. y = x and x = t move the variables, and blur merges the old Y0Y_0 into YY. 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, ∀v. ry(v)\forall v.\ r_y(v) is 11 and ∃v. c(v)\exists v.\ c(v) is 00. 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 ⊑\sqsubseteq 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 ⊑\sqsubseteq-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 12\tfrac12. By induction on runs, every reached heap embeds into a structure at its point: lfp F⊆γ(lfp F#)\mathrm{lfp}\, F \subseteq \gamma(\mathrm{lfp}\, F^\#), with ⊥\bot 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 00, 12\tfrac12 and 11. The information order is a⊑ba \sqsubseteq b if a=ba = b or b=12b = \tfrac12. Kleene's connectives are a∧b=min⁡(a,b)a \wedge b = \min(a, b), a∨b=max⁡(a,b)a \vee b = \max(a, b) and ¬a=1−a\neg a = 1 - a.

A structure SS has a finite set of nodes USU^S, a value pS(u)p^S(u) for each unary predicate pp and node uu, a value nS(u,w)n^S(u, w) for each pair of nodes, and a flag smS(u)∈{0,12}sm^S(u) \in \{0, \tfrac12\}. The unary predicates are xx ("xx points here") and rxr_x ("reachable from xx by zero or more nn steps") for each variable xx, and cc ("on a cycle of nn"). Equality is not stored. Its value is eqS(u,w)=0eq^S(u, w) = 0 for u≠wu \ne w, 11 for u=wu = w with smS(u)=0sm^S(u) = 0, and 12\tfrac12 for u=wu = w with smS(u)=12sm^S(u) = \tfrac12. A heap is a structure with all values in {0,1}\{0, 1\} and sm=0sm = 0 everywhere, and whose predicates have their intended meaning: each variable holds at most one cell, each cell has at most one successor, and rxr_x and cc are the reachability and the cycle sets of that graph.

Formulas are built from p(v)p(v), n(v,w)n(v, w), v=wv = w, ¬\neg, ∧\wedge, ∨\vee, ∃v\exists v, ∀v\forall v and the constants 0,12,10, \tfrac12, 1. [ ⁣[φ] ⁣]S(Z)[\![\varphi]\!]^S(Z) is the value of φ\varphi in SS under an assignment ZZ of nodes to its free variables. The quantifiers are the maximum and the minimum over USU^S.

Embedding. A map f:US→US′f : U^S \to U^{S'} embeds SS into S′S', written S⊑fS′S \sqsubseteq^f S', if:

  1. ff is onto;
  2. pS(u)⊑pS′(f(u))p^S(u) \sqsubseteq p^{S'}(f(u)) for every unary pp, and nS(u,w)⊑nS′(f(u),f(w))n^S(u, w) \sqsubseteq n^{S'}(f(u), f(w));
  3. eqS(u,w)⊑eqS′(f(u),f(w))eq^S(u, w) \sqsubseteq eq^{S'}(f(u), f(w)). That is, if two distinct nodes or one summary node map to u′u', then smS′(u′)=12sm^{S'}(u') = \tfrac12.

Two embeddings compose into an embedding. The concretization γ(S)\gamma(S) is the set of heaps that embed into SS, and γ(X)=⋃S∈Xγ(S)\gamma(\mathcal{X}) = \bigcup_{S \in \mathcal{X}} \gamma(S) for a set of structures X\mathcal{X}.

1. The embedding theorem

Lemma 1. Kleene's connectives are monotone in ⊑\sqsubseteq: if a⊑a′a \sqsubseteq a' and b⊑b′b \sqsubseteq b', then ¬a⊑¬a′\neg a \sqsubseteq \neg a', a∧b⊑a′∧b′a \wedge b \sqsubseteq a' \wedge b' and a∨b⊑a′∨b′a \vee b \sqsubseteq a' \vee b'. If ai⊑bia_i \sqsubseteq b_i for ii in a finite set II, then max⁡Iai⊑max⁡Ibi\max_I a_i \sqsubseteq \max_I b_i and min⁡Iai⊑min⁡Ibi\min_I a_i \sqsubseteq \min_I b_i.

Proof. For ¬\neg: 1−12=121 - \tfrac12 = \tfrac12. For ∧\wedge, assume a′∧b′a' \wedge b' is definite, since otherwise there is nothing to prove. If a′∧b′=0a' \wedge b' = 0, one of a′,b′a', b' is 00, so the same one of a,ba, b is 00, and a∧b=0a \wedge b = 0. If a′∧b′=1a' \wedge b' = 1, both are 11, so a=b=1a = b = 1. ∨\vee is the dual. The finite cases follow by induction on ∣I∣|I|. □\square

Theorem 1 (embedding theorem). If S⊑fS′S \sqsubseteq^f S', then [ ⁣[φ] ⁣]S(Z)⊑[ ⁣[φ] ⁣]S′(f∘Z)[\![\varphi]\!]^S(Z) \sqsubseteq [\![\varphi]\!]^{S'}(f \circ Z) for every formula φ\varphi and assignment ZZ.

Proof. By induction on φ\varphi. Constants have the same value on both sides. For p(v)p(v), n(v,w)n(v, w) and v=wv = w the claim is conditions 2 and 3. For ¬\neg, ∧\wedge and ∨\vee it follows from the induction hypothesis and Lemma 1. For ∃v. ψ\exists v.\, \psi, the left side is max⁡u∈US[ ⁣[ψ] ⁣]S(Z[v↦u])\max_{u \in U^S} [\![\psi]\!]^S(Z[v \mapsto u]). By the induction hypothesis, each term is ⊑[ ⁣[ψ] ⁣]S′(f∘Z[v↦f(u)])\sqsubseteq [\![\psi]\!]^{S'}(f \circ Z[v \mapsto f(u)]). By Lemma 1 the maximum of the left terms is ⊑\sqsubseteq the maximum of the right terms over u∈USu \in U^S. Since ff is onto, that maximum runs over all of US′U^{S'}, which is the right side. ∀\forall is the same with the minimum. □\square

So a formula that has a definite value on a structure has that value on every heap in its concretization. A value of 12\tfrac12 says nothing.

2. The three steps

Lemma 2 (blur). Let gg map each node of SS to its class of nodes with the same unary values. Then S⊑gblur(S)S \sqsubseteq^g \mathrm{blur}(S), so γ(S)⊆γ(blur(S))\gamma(S) \subseteq \gamma(\mathrm{blur}(S)).

Proof. gg is onto. A class keeps the common unary values of its members, so condition 2 holds for unary predicates with equality. The value of nn between two classes is the join of the values between their members, and each member value is ⊑\sqsubseteq the join. A class gets sm=12sm = \tfrac12 if it has two members or a summary member, which is condition 3. Every heap H⊑fSH \sqsubseteq^f S then embeds into blur(S)\mathrm{blur}(S) by g∘fg \circ f. □\square

Two nodes of blur(S)\mathrm{blur}(S) 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 SS, 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, xS(u)∈{0,1}x^S(u) \in \{0, 1\} for every variable xx and node uu.

Proof. from_heap gives definite values. null and new write 00 and 11. copy copies a definite row. load copies the row n(u,⋅)n(u, \cdot) of the node uu of yy 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. □\square

So "the node of xx" is well defined, and xx is null in a heap of γ(S)\gamma(S) exactly when no node of SS has x=1x = 1. 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 γ(S)\gamma(S).

Lemma 4 (coerce). If H⊑fSH \sqsubseteq^f S, then coerce(S)\mathrm{coerce}(S) is not None, and H⊑fcoerce(S)H \sqsubseteq^f \mathrm{coerce}(S) with the same ff.

Proof. Each rule changes a value only to the one that every heap with an embedding into SS must have, or it reports that no heap can embed. We check each rule against HH and ff. Write f−1(u)f^{-1}(u) for the cells of HH at node uu. These sets are not empty, because ff is onto.

  • Some node uu has x(u)=1x(u) = 1. Then every cell in f−1(u)f^{-1}(u) has x=1x = 1. Since xx holds at most one cell, f−1(u)f^{-1}(u) is that one cell, so setting sm(u)=0sm(u) = 0 keeps condition 3. Two such nodes would give two cells, which is not possible. The cell is reachable from xx, so rx(u)r_x(u) cannot be 00, and it may be set to 11.
  • No node has x=1x = 1. By Lemma 3 every cell has x=0x = 0, so xx is null and no cell is reachable from xx. So rx=0r_x = 0 everywhere, and a value 11 is a contradiction.
  • n(v,w)=1n(v, w) = 1. Then every cell of f−1(v)f^{-1}(v) has every cell of f−1(w)f^{-1}(w) as successor. A cell has at most one successor, so f−1(w)f^{-1}(w) is one cell, and sm(w)=0sm(w) = 0 is correct. Every other node w′w' holds no successor of these cells, so a value 12\tfrac12 of n(v,w′)n(v, w') may become 00. Two nodes with n(v,⋅)=1n(v, \cdot) = 1 are a contradiction.
  • c(v)=1c(v) = 1 and c(w)=0c(w) = 0. The successor of a cell on a cycle is on the same cycle, so no cell of f−1(v)f^{-1}(v) points to a cell of f−1(w)f^{-1}(w). So n(v,w)n(v, w) may be set to 00, and a value 11 is a contradiction. The rule for rz(v)=1r_z(v) = 1 and rz(w)=0r_z(w) = 0 is the same: the successor of a cell reachable from zz is reachable from zz.
  • c(w)=0c(w) = 0, and either w=vw = v with sm(v)=0sm(v) = 0, or z(w)=1z(w) = 1 and rz(v)=1r_z(v) = 1 for a variable zz. In the first case f−1(v)f^{-1}(v) is one cell ee, and an edge from ee to ee would put ee on a cycle. In the second case f−1(w)f^{-1}(w) is the one cell bb of zz, and every cell ee of f−1(v)f^{-1}(v) is reachable from bb. An edge from ee to bb would put bb on a cycle. Both contradict c=0c = 0, so n(v,w)n(v, w) may be set to 00, and a value 11 is a contradiction.

In each case HH keeps conditions 1 to 3 against the changed structure. The loop repeats the rules until nothing changes, and the claim holds after each round. □\square

Lemma 5 (focus). Let uu be the node of a variable in SS. Every heap H⊑fSH \sqsubseteq^f S embeds into some structure returned by focus_succ(S, u), and in each returned structure the row n(u,⋅)n(u, \cdot) is definite.

Proof. By Lemma 4, HH embeds into S0=coerce(S)S_0 = \mathrm{coerce}(S). In S0S_0 the node uu is one cell aa. Let WW be the set of nodes ww with n(u,w)=12n(u, w) = \tfrac12. If WW is empty, the row is definite and S0S_0 is returned. Otherwise there are three cases for the successor dd of aa in HH.

  • dd is null, or f(d)∉Wf(d) \notin W. Then nH(a,e)=0n^H(a, e) = 0 for every cell ee with f(e)∈Wf(e) \in W. HH embeds by ff into the structure that sets n(u,w)=0n(u, w) = 0 for all w∈Ww \in W.
  • f(d)=w∈Wf(d) = w \in W and f−1(w)={d}f^{-1}(w) = \{d\}. HH embeds by ff into the structure with n(u,w)=1n(u, w) = 1 and n(u,w′)=0n(u, w') = 0 for the other w′∈Ww' \in W.
  • f(d)=w∈Wf(d) = w \in W and f−1(w)f^{-1}(w) has other cells. Then sm(w)=12sm(w) = \tfrac12 by condition 3, and the split structure is built. It has a new node kk that copies all values of ww, with sm(k)=0sm(k) = 0, n(u,k)=1n(u, k) = 1, n(u,w)=0n(u, w) = 0 and the other 12\tfrac12 values of row uu set to 00. The map f′f' that sends dd to kk, and every other cell as ff does, is an embedding: f′f' is onto because ww keeps a cell; dd is the only cell at kk; the copied values are ⊑\sqsubseteq-above those of dd as they were for ff; and in row uu the only 11 is the edge from aa to dd.

Each result is coerced again, and HH survives that by Lemma 4. □\square

3. The update of each statement

Lemma 6. Let H⊑fSH \sqsubseteq^f S, and let H′H' be the heap after a statement. If the statement dereferences a variable that is null in HH, the analysis reports the point. Otherwise H′H' 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 SS and in HH, so SS is kept exactly when HH passes. For null, copy and new the new predicate values are the old values of other predicates, 00 or 11, in both HH and SS. So the same ff, 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 H′H' is a formula over HH, and the code computes the same formula over SS, so Theorem 1 gives condition 2. Here aa is the cell of xx (for load, of yy), and u=f(a)u = f(a).

  • load x=y.nx = y.n, after focus on uu (Lemma 5). x′(v)=n(a,v)x'(v) = n(a, v). For reachability, rx′(v)=(ry(v)∧¬y(v))∨(y(v)∧c(v))r_x'(v) = (r_y(v) \wedge \neg y(v)) \vee (y(v) \wedge c(v)). Proof in HH: the cells reachable from the successor of aa are the cells reachable from aa, without aa itself unless aa is on a cycle.
  • cut x.n=nullx.n = \mathrm{null}. Let A(v)=rz(a)∧rx(v)∧¬x(v)A(v) = r_z(a) \wedge r_x(v) \wedge \neg x(v). In a functional graph the path from zz is unique. If aa is not on a cycle and A(v)=1A(v) = 1, then vv comes after aa on that path. It cannot come before aa, because then aa and vv would be on a cycle. So vv loses reachability from zz. If A(v)=0A(v) = 0, the path from zz to vv does not use the edge of aa, and rz(v)r_z(v) stays. If aa is on a cycle and A(v)=1A(v) = 1, then vv is on that cycle, and whether it stays depends on where the path from zz enters the cycle. So the new value is min⁡(rz(v), ¬(A(v)∧¬c(a)), β)\min(r_z(v),\ \neg(A(v) \wedge \neg c(a)),\ \beta), where β\beta is a definite value when A(v)∧c(a)=1A(v) \wedge c(a) = 1, and β=1\beta = 1 otherwise. The code uses ¬(A(v)∧c(a)∧12)\neg(A(v) \wedge c(a) \wedge \tfrac12) in place of β\beta. That is 12\tfrac12 in the first case and 11 in the second, so it is ⊒β\sqsupseteq \beta in both, and Lemma 1 with Theorem 1 gives condition 2. For cycles, c′(v)=c(v)∧¬(c(a)∧rx(v))c'(v) = c(v) \wedge \neg(c(a) \wedge r_x(v)): cutting an edge of a cycle breaks exactly that cycle, which is the set reachable from aa.
  • link x.n=yx.n = y, done as cut and then the new edge on the result, where aa has no successor. Then rz′(v)=rz(v)∨(rz(a)∧ry(v))r_z'(v) = r_z(v) \vee (r_z(a) \wedge r_y(v)), and n′(a,v)=y(v)n'(a, v) = y(v). A cycle forms exactly when yy reaches aa, and then it consists of the cells on the path from yy to aa, which are all the cells reachable from yy. So c′(v)=c(v)∨(ry(a)∧ry(v))c'(v) = c(v) \vee (r_y(a) \wedge r_y(v)).

In each case the result is coerced, and H′H' 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 HH. □\square

4. Soundness of the analysis

Let FF be the concrete transfer on sets of states at the program points, from the given initial heaps. The reachable states are R=lfp FR = \mathrm{lfp}\, F, and ⊥\bot assigns no states to any point. Let F#F^\# 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). lfp F⊆γ(lfp F#)\mathrm{lfp}\, F \subseteq \gamma(\mathrm{lfp}\, F^\#). That is, every heap that the program reaches at point pp embeds into some structure in A[p]A[p]. 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 A[q]A[q] is pushed once, and its successors are computed when it is popped. So at the end, AA is closed under F#F^\#, and it is the least closed family that contains the entry. Now take a run (p0,H0),(p1,H1),…(p_0, H_0), (p_1, H_1), \ldots and use induction on ii. For i=0i = 0, H0H_0 embeds into the blur of its own coerced structure, by Lemmas 2 and 4. For the step from ii to i+1i + 1, let Hi⊑SH_i \sqsubseteq S with SS in A[pi]A[p_i]. By Lemma 6, Hi+1H_{i+1} embeds into some TT in post(S, st), or the dereference is reported. By Lemma 2, Hi+1H_{i+1} embeds into blur(T)\mathrm{blur}(T), which is in A[pi+1]A[p_{i+1}] because AA is closed. □\square

By Theorem 1, a formula with value 11 on every structure of A[p]A[p] holds in every heap at pp. This is how the page example reads off "acyclic" and "every cell is reachable from yy".

5. Termination and cost

Theorem 3. analyze terminates.

Proof. Let U=2v+1U = 2v + 1 be the number of unary predicates for vv variables. A blurred structure has nodes with pairwise different unary values, so it has at most N≤2v3v+1N \le 2^v 3^{v + 1} 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 vv. Each A[p]A[p] 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 12\tfrac12 into a definite value, or a flag into 00, and there are at most N2+vN+NN^2 + vN + N such values. focus_succ returns at most 2N+12N + 1 structures. □\square

Cost. Let NN bound the nodes of a structure, MM bound the number of canonical structures at a point, vv be the number of variables, and EE be the number of edges of the program. One round of coerce costs O(vN2)O(vN^2), and there are O(N2+vN)O(N^2 + vN) rounds, so coerce costs O(vN4+v2N3)O(vN^4 + v^2 N^3). A transfer focuses into O(N)O(N) structures and coerces each one. Blur costs O(N2+vNlog⁡N)O(N^2 + vN \log N). Every structure at a point is popped once, and each of its out edges is processed once. So the total time is O(EM(vN5+v2N4))O(E M (v N^5 + v^2 N^4)), which is within O(EMv2N5)O(E M v^2 N^5). The sets A[p]A[p] take O(LM(N2+vN))O(L M (N^2 + vN)) space for LL points. Since MM can be doubly exponential in vv, 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 N≤2v3v+1N \le 2^v 3^{v+1} nodes, since the variable predicates are always 00 or 11. The number MM of canonical structures is finite but can be doubly exponential in vv. One coerce costs O(vN4+v2N3)O(v N^4 + v^2 N^3). A transfer focuses into O(N)O(N) structures, so the whole run takes O(EMv2N5)O(E M v^2 N^5) time and O(LMvN2)O(L M v N^2) 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.n on a summary successor gives x the value 12\tfrac12 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.

three_valued_logic_shape_analysis.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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
  7. 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.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/BGQ8GB/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example