علوم الحاسوب · الكتاب 5 · السنة الجامعية 3

University Computer Science — Year 3

هذا الكتاب غير متوفر بعد باللغة العربية. النسخ المتوفرة: English.

University Computer Science — Year 3 · السنة الجامعية 3

20Program Verification: Hoare Logic and Model Checking

Tests show that a program works on the inputs tried. Verification shows that it works on all of them, or produces an input on which it fails. This chapter builds two kinds of verifier and runs them. The first is deductive: a program carries assertions, Hoare logic turns it into formulas called verification conditions, and the CDCL solver of Chapter 18 decides them over 8-bit machine integers; on binary search it finds the classic overflow of the midpoint, with the values that cause it. The second is model checking: a finite-state system is explored state by state and a temporal formula is decided on its state graph; on Peterson’s algorithm it confirms mutual exclusion, and on a broken variant it prints the run that breaks it. The chapter closes on what limits both: invariants have to be found, and states multiply.

You already know

A precondition and a postcondition specify a program; it is partially correct when every run started in the precondition that terminates ends in the postcondition, and totally correct when it also always terminates. A loop invariant holds before the loop and is kept by every iteration; a variant is a natural number that decreases at each iteration (Year 1 volume). A proof system is sound when everything it proves is true (Year 2 volume). Big-step semantics relates a program and a starting state to its final state (Definition 5.13). A least fixed point is computed by iterating from the bottom (Definition 8.3). Peterson’s algorithm gives two threads mutual exclusion with two flags and a turn variable (Year 2 volume).

20.1 Hoare triples

The programs of this chapter are written in a small while-language with Python’s syntax: integer variables, assignment, if, while, assert and pass. Integers are 8-bit and unsigned, so 255+1=0255 + 1 = 0, as in a machine register. A loop may open with invariant(...) and variant(...), which do nothing when run, and unknown() is a condition outside the program’s control, such as the comparison with an array element that binary search makes. The big-step interpreter run executes it.

def run(statements, env, choose=lambda: False, fuel=10_000):
    """Big-step execution; returns the final environment. A failed assert raises."""
    for s in statements:
        match s:
            case ast.Assign(targets=[ast.Name(id=x)], value=e):
                env[x] = value(e, env, choose)
            case ast.If(test=b, body=yes, orelse=no):
                env = run(yes if value(b, env, choose) else no, env, choose, fuel)
            case ast.While(test=b):
                _, _, body = annotations(s)
                while value(b, env, choose):
                    fuel -= 1
                    if fuel < 0:
                        raise RuntimeError("out of fuel")
                    env = run(body, env, choose, fuel)
            case ast.Assert(test=b):
                if not value(b, env, choose):
                    raise AssertionError(f"{ast.unparse(b)}, with {env}")
            case ast.Pass() | ast.Expr():
                pass
    return env
Listing 20.1. Big-step execution of the while-language; value evaluates expressions with 8-bit wrap-around. code/bachelor-3/20-program-verification/listings/whilelang.py

Definition 20.1 (Hoare triple, Hoare logic, assignment axiom, rule of consequence)

A Hoare triple {P} S {Q}\{P\}\,S\,\{Q\} is valid when every run of SS from a state satisfying PP that terminates ends in a state satisfying QQ. Hoare logic derives triples by the rules below, where Q[e/x]Q[e/x] is QQ with ee substituted for xx.

  • The assignment axiom: {Q[e/x]}  x=e  {Q}\{Q[e/x]\}\; x = e\; \{Q\}.
  • Sequence: from {P} S1 {R}\{P\}\,S_1\,\{R\} and {R} S2 {Q}\{R\}\,S_2\,\{Q\}, derive {P} S1;S2 {Q}\{P\}\,S_1; S_2\,\{Q\}.
  • If: from {P∧b} S1 {Q}\{P \wedge b\}\,S_1\,\{Q\} and {P∧¬b} S2 {Q}\{P \wedge \neg b\}\,S_2\,\{Q\}, derive {P}\{P\} if b: S1 else: S2 {Q}\{Q\}.
  • While: from {I∧b} S {I}\{I \wedge b\}\,S\,\{I\}, derive {I}\{I\} while b: S {I∧¬b}\{I \wedge \neg b\}.
  • The rule of consequence: from P⇒P′P \Rightarrow P', {P′} S {Q′}\{P'\}\,S\,\{Q'\} and Q′⇒QQ' \Rightarrow Q, derive {P} S {Q}\{P\}\,S\,\{Q\}.

The assignment axiom runs backwards: for xx to satisfy QQ after x=ex = e, the expression ee must satisfy it before. The while rule says nothing about termination; a variant adds it. Tony Hoare proposed the logic in 1969, building on Robert Floyd’s earlier rules for flowcharts.

Theorem 20.2 (Soundness of Hoare logic)

Every derivable triple is valid for the big-step semantics.

The proof is by induction on the derivation, one case per rule: the assignment axiom because evaluating QQ in the state after x=ex = e is evaluating Q[e/x]Q[e/x] in the state before (Exercise 20.7), the while rule by induction on the number of iterations (Exercise 20.10), the others directly. hoare_check.py checks a derivation node by node, and decides the implications of the rule of consequence with the solver of Section 20.3.

A derivation as a proof tree: each line follows from the one above the bar by the rule named on its right. The two consequence steps need x 10 x < 10 ℝightarrow x + 1 10, which holds for 8-bit integers since x < 10 rules out the wrap, and x 10 (x < 10) ℝightarrow x = 10.
A derivation as a proof tree: each line follows from the one above the bar by the rule named on its right. The two consequence steps need x≤10∧x<10⇒x+1≤10x \le 10 \wedge x < 10 \Rightarrow x + 1 \le 10, which holds for 8-bit integers since x<10x < 10 rules out the wrap, and x≤10∧¬(x<10)⇒x=10x \le 10 \wedge \neg (x < 10) \Rightarrow x = 10.
$ python hoare_check.py
      assign  {x + 1 <= 10} x = x + 1 {x <= 10}
    conseq  {x <= 10 and x < 10} x = x + 1 {x <= 10}
  while   {x <= 10} while x < 10: x = x + 1 {x <= 10 and (not x < 10)}
conseq  {x <= 10} while x < 10: x = x + 1 {x == 10}
  assign  {x + 2 <= 10} x = x + 2 {x <= 10}
rejected: x <= 10 and x < 10 does not imply x + 2 <= 10: {'x': 9}
Output 20.1. The derivation of the figure, checked from the leaves up; then a wrong step, rejected with the value that refutes its implication.

20.2 Weakest preconditions

Definition 20.3 (Weakest precondition, strongest postcondition)

The weakest precondition wp(S,Q)\mathrm{wp}(S, Q) is a formula that holds in exactly the states from which every run of SS terminates in a state satisfying QQ. The strongest postcondition sp(P,S)\mathrm{sp}(P, S) holds in exactly the states that runs of SS from PP can end in.

For loop-free programs, wp is computed backwards, one statement at a time:

wp(x=e,Q)=Q[e/x],wp(S1;S2,Q)=wp(S1,wp(S2,Q)),wp(assert b,Q)=b∧Q,\mathrm{wp}(x = e, Q) = Q[e/x], \quad \mathrm{wp}(S_1; S_2, Q) = \mathrm{wp}(S_1, \mathrm{wp}(S_2, Q)), \quad \mathrm{wp}(\text{\texttt{assert} } b, Q) = b \wedge Q,

and the if gives (b⇒wp(S1,Q))∧(¬b⇒wp(S2,Q))(b \Rightarrow \mathrm{wp}(S_1, Q)) \wedge (\neg b \Rightarrow \mathrm{wp}(S_2, Q)); with unknown() as its test, both branches may run, and wp is the conjunction of the two.

Theorem 20.4 (Weakest preconditions decide triples)

For a loop-free SS, {P} S {Q}\{P\}\,S\,\{Q\} is valid if and only if P⇒wp(S,Q)P \Rightarrow \mathrm{wp}(S, Q) is valid.

By induction on SS, the formula computed holds in a state exactly when every run of SS from it ends in QQ; the triple is then the implication. Edsger Dijkstra introduced weakest preconditions in 1975.

def wp(statements, q):
    for s in reversed(statements):  # wp(S1; S2, Q) = wp(S1, wp(S2, Q))
        match s:
            case ast.Assign(targets=[ast.Name(id=x)], value=e):
                q = Substitute(x, e).visit(copy.deepcopy(q))
            case ast.If(
                test=ast.Call(func=ast.Name(id="unknown")), body=yes, orelse=no
            ):
                q = conj(wp(yes, q), wp(no, q))  # either branch may run
            case ast.If(test=b, body=yes, orelse=no):
                q = conj(
                    implies(b, wp(yes, q)),
                    implies(ast.UnaryOp(op=ast.Not(), operand=b), wp(no, q)),
                )
            case ast.Assert(test=b):
                q = conj(b, q)
            case ast.Pass():
                pass
            case _:
                raise ValueError("wp: loops need an invariant (see vcgen.py)")
    return q
Listing 20.2. Weakest preconditions of loop-free programs. code/bachelor-3/20-program-verification/listings/wp.py
$ python wp.py
program: y = x + 1 | x = y + y
  wp for x < 100:  x + 1 + (x + 1) < 100
program: t = x | x = y | y = t
  wp for x == a and y == b:  y == a and x == b
program: if x < y: | m = y | else: | m = x
  wp for m >= x:  implies(x < y, y >= x) and implies(not x < y, x >= x)
Output 20.2. Three weakest preconditions, not simplified: the swap through t exchanges aa and bb in the postcondition.

A loop has no finite formula for its wp in general; it would be the limit of unrolling the loop again and again. The programmer supplies an invariant instead, and the verifier checks it.

20.3 Verification conditions handed to a solver

Definition 20.5 (Annotated program, verification condition, bit-blasting)

An annotated program carries an invariant on every loop, and optionally a variant. Its verification conditions are formulas without programs, whose validity implies that the program meets its specification. Bit-blasting turns a formula over fixed-width integers into a propositional formula with one variable per bit, adders and comparators being written as Boolean circuits.

The generator computes wp backwards, but takes a loop’s invariant II as its precondition and emits three conditions for it: preserved, I∧b⇒wp(S,I)I \wedge b \Rightarrow \mathrm{wp}(S, I); exit, I∧¬b⇒QI \wedge \neg b \Rightarrow Q; and, with a variant VV, variant, I∧b∧V=v0⇒wp(S,V<v0)I \wedge b \wedge V = v_0 \Rightarrow \mathrm{wp}(S, V < v_0). A final condition, entry, says that the precondition implies what the program needs at its start.

def awp(statements, q, vcs):
    """Like wp, but a loop's precondition is its invariant, and the loop adds its
    own conditions to the list vcs."""
    for s in reversed(statements):
        if isinstance(s, ast.While):
            inv, var, body = annotations(s)
            vcs.append(("preserved", implies(conj(inv, s.test), awp(body, inv, vcs))))
            vcs.append(("exit", implies(conj(inv, neg(s.test)), q)))
            if var is not None:  # the variant decreases: V < v0 after the body
                v0 = ast.Name(id=f"v{len(vcs)}")
                smaller = ast.Compare(left=var, ops=[ast.Lt()], comparators=[v0])
                start = ast.Compare(
                    left=copy.deepcopy(var), ops=[ast.Eq()], comparators=[v0]
                )
                entered = conj(conj(inv, s.test), start)
                vcs.append(("variant", implies(entered, awp(body, smaller, vcs))))
            q = inv
        elif isinstance(s, ast.If) and not isinstance(s.test, ast.Call):
            yes, no = awp(s.body, q, vcs), awp(s.orelse, q, vcs)
            q = conj(implies(s.test, yes), implies(neg(s.test), no))
        elif isinstance(s, ast.If):  # unknown(): both branches
            q = conj(awp(s.body, q, vcs), awp(s.orelse, q, vcs))
        else:
            q = wp([s], q)
    return q
Listing 20.3. The verification conditions of an annotated program. code/bachelor-3/20-program-verification/listings/vcgen.py

Each condition FF is valid exactly when ¬F\neg F is unsatisfiable. The bit-blaster gives each 8-bit variable eight Boolean variables and each operation a circuit: a ripple-carry adder for ++, the same adder on the complement plus one for −-, a shift for halving, and the borrow of a subtraction for <<. Each gate becomes a few clauses (Tseitin’s encoding), and CDCL decides the result. A satisfying assignment of ¬F\neg F is a counterexample: values of the variables that make the condition false.

    def add(self, x, y, carry=-1):  # carry -1 is the constant false
        out = []
        for a, b in zip(x, y):  # ripple-carry, least significant bit first
            t = self.XOR(a, b)
            out.append(self.XOR(t, carry))
            carry = self.OR(self.AND(a, b), self.AND(t, carry))
        return out, carry

    def word(self, e):
        match e:
            case ast.Constant(value=c):
                return [1 if c >> i & 1 else -1 for i in range(BITS)]
            case ast.Name(id=x):
                if x not in self.words:
                    self.words[x] = [self.fresh() for _ in range(BITS)]
                return self.words[x]
            case ast.BinOp(left=a, op=ast.Add(), right=b):
                return self.add(self.word(a), self.word(b))[0]
            case ast.BinOp(left=a, op=ast.Sub(), right=b):  # a + not b + 1
                return self.add(self.word(a), [-v for v in self.word(b)], 1)[0]
            case ast.BinOp(left=a, op=ast.FloorDiv()):  # // 2: shift right
                return self.word(a)[1:] + [-1]
        raise ValueError(ast.unparse(e))

    def less(self, a, b):
        """a < b (unsigned) exactly when a - b borrows: a + not b + 1 has no carry."""
        return -self.add(self.word(a), [-v for v in self.word(b)], 1)[1]

    def equal(self, a, b):
        bit = 1
        for x, y in zip(self.word(a), self.word(b)):
            bit = self.AND(bit, -self.XOR(x, y))
        return bit
Listing 20.4. Words of bits, the adder, and comparison through the borrow. code/bachelor-3/20-program-verification/listings/bitblast.py
The verification pipeline of this section.
The verification pipeline of this section.

Binary search keeps an interval [lo,hi)[lo, hi) of indices and halves it. Its array test is replaced by unknown(), so the proof below covers every array; the assertion checks that the midpoint is a valid index of the interval, and the variant hi−lohi - lo proves termination.

SEARCH = """
lo = 0
hi = n
while lo < hi:
    invariant(INV)
    variant(hi - lo)
    mid = MID
    assert lo <= mid and mid < hi
    if unknown():
        lo = mid + 1
    else:
        hi = mid
"""
Listing 20.5. Binary search, with MID and INV filled in three ways. code/bachelor-3/20-program-verification/listings/verify_bsearch.py
$ python verify_bsearch.py
midpoint (lo + hi) // 2:
  entry        91 variables    280 clauses  valid
  preserved   633 variables   2066 clauses  FAILS, e.g. {'hi': 192, 'lo': 128, 'n': 192}
  exit        205 variables    614 clauses  valid
  variant     656 variables   2119 clauses  FAILS, e.g. {'hi': 192, 'lo': 128, 'n': 192, 'v2': 64}
  run with n = 255, always going right, the assert fails:
    lo <= mid and mid < hi, with {'n': 255, 'lo': 128, 'hi': 255, 'mid': 63}
midpoint lo + (hi - lo) // 2:
  entry        91 variables    280 clauses  valid
  preserved   833 variables   2746 clauses  valid
  exit        205 variables    614 clauses  valid
  variant     816 variables   2663 clauses  valid
invariant lo < hi (wrong):
  entry        91 variables    280 clauses  FAILS, e.g. {'n': 0}
  preserved   833 variables   2746 clauses  FAILS, e.g. {'hi': 2, 'lo': 0, 'n': 194}
  exit        205 variables    614 clauses  valid
  variant     816 variables   2663 clauses  valid
Output 20.3. The midpoint (lo+hi)//2(lo + hi) // 2 fails, with a counterexample that the invariant allows; lo+(hi−lo)//2lo + (hi - lo) // 2 is verified; and a wrong invariant is caught at entry (n=0n = 0) and when kept.

With lo=128lo = 128 and hi=192hi = 192, lo+hi=320lo + hi = 320, which wraps to 64 in 8 bits, and the midpoint 32 lies below lolo. The same failure happens with 32-bit indices on arrays of more than 2302^{30} elements, and the cure, lo+(hi−lo)/2lo + (hi - lo)/2, is the same. That state satisfies the invariant, but no run reaches it: from lo=0lo = 0, hi=192hi = 192 the first move to the right already fails, at lo=97lo = 97. The failure is still not an artefact of the invariant: run on n=255n = 255, always choosing the upper half, the interpreter makes the assertion fail at lo=128lo = 128, hi=255hi = 255.

20.4 Temporal properties

Programs that run forever, such as operating systems, lifts and protocols, are specified by what must hold along their runs: two lifts are never in the shaft together; every request is eventually served.

Definition 20.6 (Kripke structure, temporal logic, computation tree logic, linear temporal logic)

A Kripke structure is a finite set of states, a successor relation in which every state has at least one successor, and for each state the set of atomic propositions true in it. A temporal logic speaks of the runs, infinite paths of states. Computation tree logic (CTL) pairs a path quantifier, E (some path) or A (all paths), with a temporal operator, X (next state), F (some future state), G (every future state) or U (until): E[f U g]\mathrm{E}[f \,\mathrm{U}\, g] holds when some path reaches a gg-state through ff-states. Linear temporal logic (LTL) has the temporal operators without path quantifiers, and a formula holds in a state when it holds on every path from it.

Everything is expressed with EX, EU and EG: EF g=E[true U g]\mathrm{EF}\,g = \mathrm{E}[\mathrm{true} \,\mathrm{U}\, g], AG f=¬EF¬f\mathrm{AG}\,f = \neg \mathrm{EF} \neg f, AF f=¬EG¬f\mathrm{AF}\,f = \neg \mathrm{EG} \neg f. E. M. Clarke and E. A. Emerson proposed CTL in 1981; Amir Pnueli proposed LTL for program verification in 1977.

Theorem 20.7 (Fixed points of CTL)

E[f U g]\mathrm{E}[f \,\mathrm{U}\, g] is the least fixed point of Z↦g∨(f∧EX Z)Z \mapsto g \vee (f \wedge \mathrm{EX}\,Z), and EG f\mathrm{EG}\,f is the greatest fixed point of Z↦f∧EX ZZ \mapsto f \wedge \mathrm{EX}\,Z, sets of states being ordered by inclusion.

For EF, the kk-th iterate from the empty set is the set of states that reach gg in fewer than kk steps, and the iteration stops after at most as many rounds as there are states (Exercise 20.11). The greatest fixed point is computed from the full set downwards. So a CTL formula is checked in time polynomial in the size of the structure, by ctl.py.

    def sat(self, f):
        match f:
            case str(p):
                return {s for s in self.states if p in self.labels[s]}
            case ("not", g):
                return self.states - self.sat(g)
            case ("and", g, h):
                return self.sat(g) & self.sat(h)
            case ("or", g, h):
                return self.sat(g) | self.sat(h)
            case ("EX", g):
                return self.pre(self.sat(g))
            case ("EU", g, h):  # least fixed point of Z = h or (g and EX Z)
                keep, z = self.sat(g), self.sat(h)
                while (bigger := z | (keep & self.pre(z))) != z:
                    z = bigger
                return z
            case ("EG", g):  # greatest fixed point of Z = g and EX Z
                z = self.sat(g)
                while (smaller := z & self.pre(z)) != z:
                    z = smaller
                return z
            case ("EF", g):
                return self.sat(("EU", "true", g))
            case ("AX", g):
                return self.sat(("not", ("EX", ("not", g))))
            case ("AG", g):
                return self.sat(("not", ("EF", ("not", g))))
            case ("AF", g):
                return self.sat(("not", ("EG", ("not", g))))
        raise ValueError(f)
Listing 20.6. A CTL model checker: one case per operator, EU and EG by iteration to a fixed point. code/bachelor-3/20-program-verification/listings/ctl.py
The structure of . The shaded region is EF done; state 1 loops on busy forever, so EG busy holds there, and AF done fails at state 0, whose path to state 1 never reaches done.
The structure of Output 20.4. The shaded region is EF done; state 1 loops on busy forever, so EG busy holds there, and AF done fails at state 0, whose path to state 1 never reaches done.
$ python ctl.py
done             holds in states [3]
EX done          holds in states [2, 3]
EF done          holds in states [0, 2, 3]
AF done          holds in states [2, 3]
EG busy          holds in states [1]
AG EF done       holds in states []
EF AG busy       holds in states [0, 1, 2, 3]
second structure: AF AG p holds in states [1, 2]
Output 20.4. Formulas on the four-state structure; and on a second structure, the formula AF AG p, which fails where the LTL formula F G p holds.

The two logics differ. In the second structure, state 0 loops on pp or moves to state 1 (¬p\neg p) and then to state 2, which loops on pp. Every path eventually stays in pp for ever, so the LTL formula F G pp holds at state 0. But AF AG pp fails there: along the path that stays at state 0, no state satisfies AG pp, since state 1 is still reachable from each of them. Each logic expresses some properties the other cannot; LTL is not built in this chapter.

20.5 Model checking finite-state systems

Definition 20.8 (Model checking, counterexample trace, state explosion)

Model checking decides whether a finite-state system, given as a Kripke structure, satisfies a temporal formula, by exploring its states. When a safety property AG ff fails, a counterexample trace is a path from the start to a state violating ff. State explosion is the growth of the number of reachable states, exponential in the number of components of the system.

Model checking began with the work of Clarke and Emerson and of J. P. Queille and J. Sifakis in the early 1980s; Clarke, Emerson and Sifakis shared the 2007 Turing Award for it.

The state of Peterson’s algorithm for two processes is the two program counters, the two flags and the turn; a step is one process executing one line. Breadth-first search from the start finds the reachable states and builds the Kripke structure, and ctl.py checks mutual exclusion, AG ¬(crit0∧crit1)\neg(\mathit{crit}_0 \wedge \mathit{crit}_1), and that process 0 can always still reach its critical section, AG EF crit0\mathit{crit}_0.

def peterson(state, i):
    """The state after process i takes its next step, or None if it is blocked."""
    pc, flag, turn, j = list(state[:2]), list(state[2:4]), state[4], 1 - i
    match pc[i]:
        case 0:  # IDLE: flag[i] = 1
            flag[i], pc[i] = 1, WANT
        case 1:  # WANT: turn = j
            turn, pc[i] = j, WAIT
        case 2:  # WAIT: until flag[j] == 0 or turn == i
            if not (flag[j] == 0 or turn == i):
                return None
            pc[i] = CRIT
        case 3:  # CRIT: leave, flag[i] = 0
            flag[i], pc[i] = 0, IDLE
    return (*pc, *flag, turn)
Listing 20.7. One step of Peterson’s algorithm. code/bachelor-3/20-program-verification/listings/peterson_mc.py
$ python peterson_mc.py
Peterson: 20 reachable states; AG not (crit0 and crit1): True
Peterson: 20 reachable states; AG EF crit0: True
without turn: 9 reachable states; AG not (crit0 and crit1): False
without turn: 9 reachable states; AG EF crit0: True
  counterexample trace, 4 steps (pc0, pc1, flag0, flag1):
    (0, 0, 0, 0) -> (1, 0, 0, 0) -> (1, 1, 0, 0) -> (3, 1, 1, 0) -> (3, 3, 1, 1)
Output 20.5. Peterson’s algorithm has 20 reachable states and keeps mutual exclusion; without the turn, a process that tests the other’s flag before raising its own lets both in, and breadth-first search finds a shortest trace, of 4 steps.

Breadth-first search finds shortest counterexamples, the easiest to read: both processes see the other’s flag down, then both raise their own and enter. A system of nn processes with kk states each can have up to knk^n states, and the weekend problem measures that growth. Model checkers fight it with symbolic representations of sets of states, and with partial-order reduction, which explores only one order of steps that commute; both are told here, not built.

20.6 Exercises

Exercise 20.1 ★

Compute wp(x=x+y;  y=x−y;  x=x−y,  x=a∧y=b)\mathrm{wp}(x = x + y;\; y = x - y;\; x = x - y,\; x = a \wedge y = b) by hand, and say what the program does, in 8-bit arithmetic too.

Solution

Solution of Exercise 20.1.

Backwards: after x = x - y, x−y=a∧y=bx - y = a \wedge y = b; after y = x - y, x−(x−y)=a∧x−y=bx - (x - y) = a \wedge x - y = b; after x = x + y, (x+y)−((x+y)−y)=a∧(x+y)−y=b(x + y) - ((x + y) - y) = a \wedge (x + y) - y = b, that is y=a∧x=by = a \wedge x = b. The program swaps xx and yy without a third variable. In 8-bit arithmetic every step is modulo 256, where these identities still hold, so it swaps there too, even when x+yx + y wraps.

Exercise 20.2 ★

Is {x<200}  x=x+100  {x≥100}\{x < 200\}\; x = x + 100\; \{x \ge 100\} valid with 8-bit unsigned integers? With unbounded integers?

Solution

Solution of Exercise 20.2.

The weakest precondition is x+100≥100x + 100 \ge 100. With unbounded integers it holds for every x≥0x \ge 0, so the triple is valid. In 8 bits, for 156≤x<200156 \le x < 200 the sum wraps to x−156<100x - 156 < 100: not valid; x=156x = 156 is a counterexample.

Exercise 20.3 ★

Give an invariant that proves {n≤20}\{n \le 20\} s = 0; i = 0; while i < n: i = i + 1; s = s + i {2s=n(n+1)}\{2s = n(n + 1)\} with unbounded integers. What is the largest nn for which the 8-bit loop computes ss without wrapping?

Solution

Solution of Exercise 20.3.

II: 2s=i(i+1)∧i≤n2s = i(i + 1) \wedge i \le n. At entry s=i=0s = i = 0. Kept: from 2s=i(i+1)2s = i(i + 1) and i<ni < n, after i=i+1i = i + 1 and s=s+is = s + i we get 2s′=i(i+1)+2(i+1)=(i+1)(i+2)2s' = i(i + 1) + 2(i + 1) = (i + 1)(i + 2) and i+1≤ni + 1 \le n. At exit i≥ni \ge n and i≤ni \le n, so i=ni = n. In 8 bits, s=n(n+1)/2≤255s = n(n + 1)/2 \le 255 requires n≤22n \le 22 (s=253s = 253); at n=23n = 23, ss would be 276 and wraps. The product n(n+1)n(n + 1) in the postcondition wraps earlier, from n=16n = 16, so an 8-bit proof must state it differently.

Exercise 20.4 ★

States 0 to 3; edges 0→10 \to 1, 1→21 \to 2, 2→12 \to 1, 2→32 \to 3, 3→33 \to 3; pp holds in 1 and 3. Predict what ctl.py prints for EX pp, EG pp, AF pp and E[¬p\neg p U pp].

Solution

Solution of Exercise 20.4.

EX pp: states with a successor in {1,3}\{1, 3\}: {0,2,3}\{0, 2, 3\}. EG pp: from {1,3}\{1, 3\}, state 1’s only successor 2 is not in the set, so {3}\{3\}. AF pp: EG ¬p\neg p starts from {0,2}\{0, 2\} and empties, since 0 leads to 1 and 2 leads to 1 or 3; so AF pp holds everywhere. E[¬p\neg p U pp]: from {1,3}\{1, 3\}, add 0 and 2: all four states.

Exercise 20.5 ★★

exercises/ex5_vcgen.py generates verification conditions for loops but forgets one. Find a wrong program and postcondition it accepts, say which condition is missing, and fix it.

Solution

Solution of Exercise 20.5.

The generator emits no exit condition, I∧¬b⇒QI \wedge \neg b \Rightarrow Q, so the postcondition is never connected to the loop. It accepts x = 0; while x < 10: x = x + 1 with invariant x≤10x \le 10 and postcondition x=11x = 11, which is false (test_exercise_5). The fix appends ("exit", implies(conj(inv, neg(s.test)), q)), as in Listing 20.3; then x=11x = 11 is rejected and x=10x = 10 accepted.

Exercise 20.6 ★★

Write for_vcs, the verification conditions of a counted loop for i in range(a, b) with invariant II, from the rule in the file’s docstring. It is tested on a counting loop and on a wrong one.

Solution

Solution of Exercise 20.6.

exercises/ex6_for.py: entry pre⇒I[a/i]∧a≤b\mathit{pre} \Rightarrow I[a/i] \wedge a \le b; preserved I∧a≤i∧i<b⇒wp(body,I[i+1/i])I \wedge a \le i \wedge i < b \Rightarrow \mathrm{wp}(\mathit{body}, I[i + 1/i]); exit I[b/i]⇒postI[b/i] \Rightarrow \mathit{post}. With c = c + 1, invariant c=i∧n<200c = i \wedge n < 200 and post c=nc = n, all three are valid; with c = c + 2, preserved fails (test_exercise_6).

Exercise 20.7 ★★

Prove the assignment axiom sound: if Q[e/x]Q[e/x] holds in state σ\sigma, then QQ holds in σ[x↦v]\sigma[x \mapsto v], where vv is the value of ee in σ\sigma.

Solution

Solution of Exercise 20.7.

Facts used: evaluating an expression in a state looks only at the values of its variables.

By induction on the formula QQ: evaluating Q[e/x]Q[e/x] in σ\sigma replaces each occurrence of xx by ee, whose value in σ\sigma is vv; evaluating QQ in σ[x↦v]\sigma[x \mapsto v] reads vv for each xx and the same values as σ\sigma for every other variable. The two evaluations agree at every node, so Q[e/x]Q[e/x] holds in σ\sigma exactly when QQ holds in σ[x↦v]\sigma[x \mapsto v], the state after x = e. Wrap-around changes nothing, since both sides use the same 8-bit evaluation.

Exercise 20.8 ★★

Starting from the state (0,0,0,0,0)(0, 0, 0, 0, 0) of Listing 20.7, list by hand the states reachable in one and in two steps. Which of them have a process blocked?

Solution

Solution of Exercise 20.8.

States are (pc0, pc1, flag0, flag1, turn). One step: (1,0,1,0,0)(1, 0, 1, 0, 0) (process 0 raised its flag) and (0,1,0,1,0)(0, 1, 0, 1, 0). Two steps: (2,0,1,0,1)(2, 0, 1, 0, 1), (1,1,1,1,0)(1, 1, 1, 1, 0) and (0,2,0,1,0)(0, 2, 0, 1, 0); the middle one is reached both ways. None has a blocked process: a process at line 2 here sees the other’s flag down.

Exercise 20.9 ★★

Write “every request is eventually granted” in CTL and in LTL, with propositions req and grant. Is AG EF crit0 of Output 20.5 such a property? What does a liveness property of Peterson’s algorithm need that the model lacks?

Solution

Solution of Exercise 20.9.

CTL: AG(req ⇒\Rightarrow AF grant). LTL: G(req ⇒\Rightarrow F grant). AG EF crit0\mathit{crit}_0 is weaker: process 0 can always still get in, on some path, not on all. For a true liveness property the model needs fairness: a scheduler that lets every process that can move eventually move; without it, the path where only process 1 runs refutes AF crit0\mathit{crit}_0.

Exercise 20.10 ★★★

Prove the while rule sound: if every terminating run of SS from I∧bI \wedge b ends in II, then every terminating run of while b: S from II ends in I∧¬bI \wedge \neg b.

Solution

Solution of Exercise 20.10.

Facts used: a terminating run of while b: S is a finite sequence of runs of SS, each from a state where bb holds, ending in a state where bb fails.

Let the run pass through states σ0,σ1,…,σk\sigma_0, \sigma_1, \ldots, \sigma_k, where σj+1\sigma_{j+1} is the result of SS from σj\sigma_j, bb holds in σ0,…,σk−1\sigma_0, \ldots, \sigma_{k-1} and fails in σk\sigma_k. By induction on jj, II holds in σj\sigma_j: in σ0\sigma_0 by assumption, and if II holds in σj\sigma_j with j<kj < k, then I∧bI \wedge b holds there, and the premise gives II in σj+1\sigma_{j+1}. So I∧¬bI \wedge \neg b holds in σk\sigma_k.

Exercise 20.11 ★★★

Prove that EF gg is the least fixed point of Z↦g∨EX ZZ \mapsto g \vee \mathrm{EX}\,Z, and that iteration from the empty set reaches it in at most ∣S∣|S| rounds.

Solution

Solution of Exercise 20.11.

Facts used: F(Z)=g∪EX ZF(Z) = g \cup \mathrm{EX}\,Z is monotone; the subsets of a finite set SS ordered by inclusion have no infinite strictly increasing chain.

EF gg is a fixed point: a state reaches gg if and only if it is in gg or has a successor that reaches gg. It is the least: if F(Z)=ZF(Z) = Z, then by induction on kk every state reaching gg in kk steps is in ZZ (for k=0k = 0, g⊆Zg \subseteq Z; a state reaching gg in k+1k + 1 steps has a successor in ZZ, so it is in EX Z⊆Z\mathrm{EX}\,Z \subseteq Z). Iterating Z0=∅Z_0 = \emptyset, Zk+1=F(Zk)Z_{k+1} = F(Z_k) gives ZkZ_k = the states reaching gg in fewer than kk steps, an increasing chain; it stops growing after at most ∣S∣|S| strict increases, at EF gg.

Exercise 20.12 ★★★

Verify insertion sort on four values below 16, unrolled into compare-exchange steps, by bit-blasting the program itself: each variable a word of gates, each if merged with multiplexers. Prove that the result is sorted and made of the inputs, report the size of the CNF, and break one comparison to see a counterexample. Why not use wp here?

Solution

Solution of Exercise 20.12.

exercises/ex12_sort.py executes the program on words of gates: an assignment rebinds a variable’s word, and an if runs both branches and merges each variable that differs with a multiplexer c?x:yc ? x : y. The verification condition, inputs below 16 implies sorted output each equal to some input and each input equal to some output, gives a CNF of 1,390 variables and 4,538 clauses; the solver finds it valid. Replacing a2 > a3 by a2 < a3 gives a counterexample, b=(0,0,0,8)b = (0, 0, 0, 8) (test_exercise_12). wp duplicates the postcondition at each if, so six compare-exchange steps give 262^6 copies, and the formula, built from substituted expressions, grows far faster than the program; the symbolic execution grows linearly. (Checking that the sums agree instead makes the solver’s work much larger: equivalence of adders is hard for CDCL.)

20.7 Weekend problem

Problem 20.1

Weekend problem — Two lifts and one shaft

A lift tower shares one section of shaft between its lifts; at most one lift may be in it. Each lift goes from idle to waiting, then into the shaft, and back to idle, and a lock bit guards the shaft. In the correct protocol a waiting lift takes a free lock in one atomic step; in the buggy one it tests the lock in one step and takes it in the next. The model is in lifts.py.

def moves(state, atomic):
    """Every state reachable in one step of one lift. A state is (lock, positions)."""
    lock, pos = state
    for i, p in enumerate(pos):

        def at(q, new_lock=lock, i=i):
            return new_lock, pos[:i] + (q,) + pos[i + 1 :]

        if p == IDLE:
            yield i, at(WAIT)
        elif p == WAIT and lock == 0:  # the lock is free
            yield i, at(SHAFT, 1) if atomic else at(READY)
        elif p == READY:  # buggy: takes the lock without testing again
            yield i, at(SHAFT, 1)
        elif p == SHAFT:
            yield i, at(IDLE, 0)
Listing 20.8. One step of one lift. code/bachelor-3/20-program-verification/listings/lifts.py
$ python lifts.py
lifts   states   buggy: fails after
    1        3   never
    2        8   6 steps
    3       20   6 steps
    4       48   6 steps
    5      112   6 steps
    6      256   6 steps
fit: states = 1.33 * 2.426^n
Output 20.6. Reachable states of the correct protocol for 1 to 6 lifts, the length of the shortest run that breaks the buggy one, and a fit of the growth.

Part I — The model.

  1. What is a state, and how many states are there before asking which are reachable, for nn lifts in the correct protocol?
  2. Why is every state’s successor set nonempty, as a Kripke structure requires?
  3. List the reachable states for one lift.
  4. Why does interleaving, one lift moving per step, model lifts that run at the same time?
  5. List the 8 reachable states for two lifts.
  6. Which unreachable states does the lock exclude?

Part II — The properties.

  1. Write mutual exclusion in CTL for two lifts.
  2. Write “a waiting lift can always still get in” in CTL.
  3. Why does “a waiting lift eventually gets in”, AG(wait ⇒\Rightarrow AF shaft), fail in this model?
  4. What assumption about the scheduler would make it true?
  5. Is mutual exclusion a safety or a liveness property, and what does a counterexample to each look like?
  6. Why is AG ff checked by reachability alone?

Part III — The bug.

  1. Give the 6-step trace that breaks the buggy protocol for two lifts.
  2. Why is it the shortest?
  3. Why is it also 6 steps for 3, 4, 5 and 6 lifts?
  4. Would testing many times before taking the lock fix the bug?
  5. Which instruction of a processor makes the correct protocol’s atomic step possible?
  6. Relate the bug to Peterson’s variant without turn.

Part IV — State explosion.

  1. Prove that the correct protocol has (n+2)2n−1(n + 2) 2^{n - 1} reachable states, and check the table.
  2. What growth rate bb does the fit report, and why is it above 2?
  3. How many states for 20 lifts, and for 40?
  4. The search stores each state once. At about 100 bytes per state in Python, what memory do 40 lifts need?
  5. The lifts are identical. How could symmetry reduce the count, and to how many states for nn lifts?
  6. Sum up: what is verified, what failed and in how many steps, and how the work grows with nn.
Solution

Solution of Problem 20.1.

1. The lock bit and the position of each lift, idle, waiting or in the shaft: 2⋅3n2 \cdot 3^n combinations.

2. An idle lift can always move to waiting, and a lift in the shaft can always leave; a state with every lift waiting has the lock free (no lift holds it), so one of them can enter.

3. (0, I), (0, W), (1, S).

4. Moves of different lifts that happen at the same time can be put in either order, and every order is explored.

5. Lock 0: II, IW, WI, WW; lock 1: SI, SW, IS, WS.

6. Lock 0 with a lift in the shaft, lock 1 with none, and two lifts in the shaft.

7. AG ¬(shaft0∧shaft1)\neg(\mathit{shaft}_0 \wedge \mathit{shaft}_1).

8. AG(wait0⇒\mathit{wait}_0 \Rightarrow EF shaft0\mathit{shaft}_0).

9. On the path where lift 1 enters, leaves and enters again for ever, lift 0 waits for ever.

10. Strong fairness for the waiting lift, or a queue; the protocol as modelled has no queue.

11. Safety: a counterexample is a finite trace ending in a bad state. Liveness: a counterexample is an infinite path, in a finite model a lasso, a prefix followed by a loop.

12. AG ff fails exactly when a reachable state violates ff; reaching it is all the counterexample needs.

13. Lift 0 waits, lift 1 waits, lift 0 tests the free lock, lift 1 tests the free lock, lift 0 takes it and enters, lift 1 takes it and enters.

14. Breadth-first search finds states in order of distance; and each lift needs 3 steps of its own to be in the shaft, so two lifts need 6.

15. The same two lifts can do it; the other lifts staying idle does not shorten it.

16. No: between the last test and the take, the other lift can still test and take.

17. An atomic test-and-set or compare-and-swap.

18. Both test a shared flag, then act on it in a later step, so both can pass the test before either acts.

19. With the lock free, no lift is in the shaft and each lift is idle or waiting: 2n2^n states. With the lock taken, exactly one lift is in the shaft, nn choices, and the others are idle or waiting: n2n−1n 2^{n-1}. Each is reachable, and the total is (n+2)2n−1(n + 2) 2^{n - 1}: 3, 8, 20, 48, 112, 256, as in the table.

20. 2.426 per lift, because the factor n+2n + 2 grows too, from 3 to 8 between 1 and 6 lifts, and the fit puts that growth into bb; as nn grows, the rate per lift tends to 2.

21. 22⋅219=11,534,33622 \cdot 2^{19} = 11{,}534{,}336 for 20 lifts; 42⋅239≈2.3×101342 \cdot 2^{39} \approx 2.3 \times 10^{13} for 40.

22. About 2.3×10152.3 \times 10^{15} bytes, more than two thousand terabytes: out of reach.

23. Count only how many lifts are idle, waiting or in the shaft: with the lock free, kk waiting for k=0,…,nk = 0, \ldots, n; with it taken, one in the shaft and kk waiting for k=0,…,n−1k = 0, \ldots, n - 1: 2n+12n + 1 states.

24. The correct protocol keeps AG ¬\neg(two lifts in the shaft) over its (n+2)2n−1(n + 2)2^{n-1} reachable states, 256 for 6 lifts; the buggy one fails after 6 steps for every n≥2n \ge 2; and the state count grows about 2.4 times per lift, which is why model checkers need symmetry and symbolic methods.

المصطلحات المعرَّفة في هذا الفصل

عرض كل المصطلحات (1050) في المسرد