Verifying assembly programs in Lean: separation logic and a verified VCG
This post is a guided tour of a small Lean 4 development that I use as a tutorial: the formalization of a toy assembly language, a separation logic to reason about its programs, and a verification condition generator (VCG) that is proved sound. The whole development has fewer than 600 lines of Lean (using Mathlib) and contains no sorry.
The goal is not to build a realistic verifier, but to show, in a setting small enough to fit in one’s head, how the classic pieces of program verification fit together inside a proof assistant:
- Syntax — registers, instructions and programs;
- Operational semantics — what one step of the machine does;
- Separation logic — assertions about registers and ownership of memory cells, and Hoare triples defined as an inductive proof system;
- Weakest preconditions and a VCG — functions that compute the precondition of a piece of code, together with theorems stating that what they compute is derivable in the logic.
The code is organized as follows:
| File | Content |
|---|---|
Asm/Instr.lean | registers, instructions and programs |
Asm/Semantics.lean | heaps, machine states and the step relation Eval |
Asm/SepLogic.lean | assertions, separation connectives and Hoare triples |
Asm/VcGen.lean | weakest preconditions, the VCG and wp_sound |
Asm/VcGenSound.lean | blockWP_sound, vcg_core_sound and vcg_sound |
Asm/IncrMem.lean | a worked example: load, increment and store |
The repository is rodrigogribeiro/tutorial-asm-lean.
1. Syntax
Registers are just named by natural numbers. We derive decidable equality because the semantics needs to compare registers (for instance, when updating one register and leaving the others untouched):
inductive Reg : Type where
| Name : ℕ → Reg
deriving DecidableEq
The instruction set is deliberately minimal, yet it contains the three ingredients that make assembly verification interesting: arithmetic on registers, access to memory through addresses stored in registers, and unstructured control flow (a conditional jump).
inductive Instr : Type where
-- Arithmetic
| ADD (src dest : Reg) : Instr -- dest := dest + src
| MUL (src dest : Reg) : Instr -- dest := dest * src
-- Register transfer
| MOV (src dest : Reg) : Instr -- dest := src
| MOVI (dest : Reg)(val : ℕ) : Instr
-- Memory
| LOAD (dst addr : Reg) : Instr -- dst := mem[reg[addr]]
| STORE (src addr : Reg) : Instr -- mem[reg[addr]] := reg[src]
-- Control flow
| JNZ (cond : Reg) (target : ℕ) : Instr -- if reg[cond] ≠ 0 then pc := target
deriving DecidableEq
abbrev Code := List Instr
A program is simply a list of instructions, and the program counter (pc) is an index into that list. Fetching the instruction at pc is done with a small get? function returning an Option: none means that pc points past the end of the program, which we will interpret as the program having halted.
def List.get? {a} (xs : List a) (n : ℕ) : Option a :=
match xs, n with
| [] , _ => .none
| y :: _, 0 => .some y
| _ :: ys , m + 1 => ys.get? m
Defining get? by hand (instead of using a library function) has a pleasant consequence: equations such as (i :: rest).get? 0 = some i hold by rfl, which simplifies the proofs later.
2. Machine states and heaps
A machine state has two components: a register file, which maps every register to a value, and a heap. The heap is a partial map from addresses to values:
abbrev Heap := ℕ → Option ℕ
structure State where
regs : Reg → ℕ
mem : Heap
Partiality is the key design decision. In separation logic, mem a = none does not mean “address a contains garbage”; it means that the current program does not own address a. Splitting and joining heaps then models the transfer of ownership between parts of a program. Three operations on heaps support this view:
/-- Two heaps are disjoint when their domains do not overlap. -/
def disjoint (h₁ h₂ : Heap) : Prop :=
∀ a, h₁ a = none ∨ h₂ a = none
/-- Left-biased union of two heaps.
Well-behaved (commutative on values) when
the heaps are disjoint. -/
def union (h₁ h₂ : Heap) : Heap :=
fun a => (h₁ a).orElse (fun _ => h₂ a)
/-- Update a single cell of a heap. -/
def update (h : Heap) (a : ℕ) (v : ℕ) : Heap :=
Function.update h a (some v)
Finally, two functions update a register or a memory cell of a state:
def State.updateReg (s : State) (r : Reg) (v : ℕ) : State :=
match s with
| State.mk _ m =>
State.mk (fun r1 => if r = r1 then v else s.regs r1)
m
def State.updateMem (s : State) (addr : ℕ) (v : ℕ) : State :=
State.mk s.regs (s.mem.update addr v)
3. Operational semantics
The behaviour of each instruction is given by a small-step relation. Informally, writing \(\langle pc, s\rangle \to \langle pc', s'\rangle\) for “the machine at program counter \(pc\) in state \(s\) moves to \(pc'\) and state \(s'\)”, the rules are:
-
ADD src dest,MUL src dest,MOV src dest: compute the new value ofdestand go topc + 1; -
LOAD dst addr: if the cell at addressregs[addr]is owned and holdsv, setdst := vand go topc + 1; -
STORE src addr: writeregs[src]into addressregs[addr]and go topc + 1; -
JNZ cond target: ifregs[cond] ≠ 0jump totarget, otherwise go topc + 1.
Note that LOAD gets stuck when the address is not owned (mem a = none): there is no rule for that case. In Lean the relation is the inductive predicate Eval. Here are three of its seven constructors:
inductive Eval (code : Code) : ℕ → State → State → Prop where
/-- ADD: dest := dest + src -/
| add : ∀ {pc : ℕ}
{s : State}
{src dest : Reg}
{v : ℕ},
code.get? pc = .some (.ADD src dest) →
v = (lookupReg s src) + (lookupReg s dest) →
Eval code (pc + 1) s (updateReg s dest v)
/-- LOAD: dst := mem[regs[addr]] -/
| load : ∀ {pc : ℕ}
{s : State}
{dst addr : Reg}
{v val},
code.get? pc = some (.LOAD dst addr) →
v = lookupReg s addr →
.some val = s.mem v →
Eval code (pc + 1) s (updateReg s dst val)
/-- JNZ (taken): if regs[cond] ≠ 0, jump to target. -/
| jnz_taken : ∀ {pc : ℕ}
{s : State}
{cond : Reg}
{target : ℕ},
code.get? pc = some (.JNZ cond target) →
s.regs cond ≠ 0 →
Eval code target s s
-- ... mul, mov, store and jnz_not_taken are analogous
The natural-number index of Eval code pc' s s' is the program counter after the step: each rule fetches the instruction at some pc and concludes with the successor (pc + 1 or target). We will come back to the operational semantics at the end of the post, when discussing what the development proves and what it leaves for future work.
4. Separation logic
4.1 Assertions
An assertion is simply a predicate over machine states — a shallow embedding: we reuse Lean’s own logic (∧, ∃, →, …) instead of defining a syntax of formulas.
abbrev Assert := State → Prop
On top of that we define the usual connectives of separation logic:
def emp : Assert :=
fun s => ∀ a, s.mem a = none
def pointsTo (a v : ℕ) : Assert :=
fun s => s.mem a = some v ∧ ∀ b, b ≠ a → s.mem b = none
def sep (P Q : Assert) : Assert :=
fun s => ∃ h₁ h₂,
h₁.disjoint h₂ ∧
s.mem = h₁.union h₂ ∧
P (State.mk s.regs h₁) ∧
Q (State.mk s.regs h₂)
def wand (P Q : Assert) : Assert :=
fun s => ∀ h', s.mem.disjoint h' →
P (State.mk s.regs h') →
Q (State.mk s.regs (s.mem.union h'))
-
empholds when the program owns no memory; -
a ↦ v(points-to) holds when the program owns exactly one cell, at addressa, holdingv; -
P ∗ Q(separating conjunction) holds when the heap can be split into two disjoint parts, one satisfyingPand the other satisfyingQ. The registers are shared by both sides: only memory is subject to ownership; -
P -∗ Q(magic wand) holds when, whatever disjoint heap satisfyingPwe add to the current one, the result satisfiesQ.
The separating conjunction is what makes local reasoning possible. For example, the assertion (a ↦ 1) ∗ (b ↦ 2) implies a ≠ b, because the two cells must live in disjoint heaps — an aliasing fact that, in plain Hoare logic, would have to be stated and maintained by hand.
The development also defines entailment, a conjunction and, most importantly for what follows, a register substitution P[r ↦ᵣ v], which evaluates P in the state where r has been updated to v:
def entails (P Q : Assert) : Prop :=
∀ s, P s → Q s
def updateReg (P : Assert) (r : Reg) (v : ℕ) : Assert :=
fun s => P (State.updateReg s r v)
notation:50 a " ↦ " v => Assert.pointsTo a v
notation:35 P " ∗ " Q => Assert.sep P Q
notation:25 P " -∗ " Q => Assert.wand P Q
notation:50 P " ⊢ₐ " Q => Assert.entails P Q
notation:50 P "[" r "↦ᵣ" v "]" => Assert.updateReg P r v
4.2 Hoare triples as an inductive proof system
The central definition is the Hoare triple ⦃ P ⦄ code @ pc ⦃ Q ⦄. It is defined as an inductive proposition, with one constructor per inference rule. A proof of a triple is therefore a finite derivation tree that Lean’s kernel checks — the same style used for Hoare logic in Concrete Semantics (Nipkow & Klein) and in the VST project (Appel et al.).
The rules come in two groups. The structural rules do not depend on the instruction being executed:
\[\frac{P' \vdash P \quad \{P\}\ c\ @\ pc\ \{Q\} \quad Q \vdash Q'}{\{P'\}\ c\ @\ pc\ \{Q'\}}\ (\text{Consequence}) \qquad \frac{\{P\}\ c\ @\ pc\ \{Q\}}{\{P * R\}\ c\ @\ pc\ \{Q * R\}}\ (\text{Frame})\] \[\frac{\{P\}\ c\ @\ pc\ \{R\} \quad \{R\}\ c\ @\ pc'\ \{Q\}}{\{P\}\ c\ @\ pc\ \{Q\}}\ (\text{Seq}) \qquad \frac{\{P_1\}\ c\ @\ pc\ \{Q\} \quad \{P_2\}\ c\ @\ pc\ \{Q\}}{\{P_1 \lor P_2\}\ c\ @\ pc\ \{Q\}}\ (\text{Disj}) \qquad \frac{c[pc] = \bot}{\{Q\}\ c\ @\ pc\ \{Q\}}\ (\text{Halt})\]The frame rule is the hallmark of separation logic: a triple proved for the part of the heap an instruction uses remains valid when we add any disjoint piece R of the heap, which the instruction does not touch. Halt says that when there is no instruction at pc the machine does not move, so whatever holds now still holds.
The instruction rules are written in backward style: the postcondition Q is arbitrary and the precondition is exactly what must hold before the instruction so that Q holds after it. For register instructions, this is a substitution:
For memory instructions, the precondition also demands ownership of the accessed cell. This is the existential ∃ v, mem[regs[addr]] = some v, which rules out reading or writing an address the program does not own:
| load {prog : List Instr}
{pc : ℕ}
{P : Assert}
{dst addr : Reg}
(hfetch : prog.get? pc = some (Instr.LOAD dst addr)) :
Triple (fun s => ∃ val, s.mem (s.regs addr) = some val ∧
P (State.updateReg s dst val)) prog pc P
| store {prog : List Instr}
{pc : ℕ}
{P : Assert}
{src addr : Reg}
(hfetch : prog.get? pc = some (Instr.STORE src addr)) :
Triple (fun s => ∃ old, s.mem (s.regs addr) = some old ∧
P (State.updateMem s (s.regs addr) (s.regs src))) prog pc P
The conditional jump does not change the state; its two rules simply record which way the branch goes:
| jnz_taken {prog : List Instr} {pc : ℕ} {P : Assert} {cond : Reg} {target : ℕ}
(hfetch : prog.get? pc = some (Instr.JNZ cond target)) :
Triple (fun s => s.regs cond ≠ 0 ∧ P s) prog pc P
| jnz_not_taken {prog : List Instr} {pc : ℕ} {P : Assert} {cond : Reg} {target : ℕ}
(hfetch : prog.get? pc = some (Instr.JNZ cond target)) :
Triple (fun s => s.regs cond = 0 ∧ P s) prog pc P
4.3 A note on notation
The triple is written with the notation
notation:25 "⦃" P "⦄" prog:arg "@" pc:arg "⦃" Q "⦄" => Triple P prog pc Q
The :arg annotations are not decoration: they restrict prog and pc to argument precedence, so that the parser reads a single atomic term in each position instead of trying to extend prog @ pc ⦃ … into a larger expression. Small details like this one are a good reminder that, in a proof assistant, even notation has to be designed with care.
5. Weakest preconditions
Since the instruction rules are written backward, the precondition of each rule is a function of the postcondition. Making that function explicit gives Dijkstra’s weakest precondition transformer:
def wp (i : Instr) (Q : Assert) : Assert :=
match i with
| .MOVI dest val => fun s => Q (State.updateReg s dest val)
| .ADD src dest => fun s => Q (State.updateReg s dest (s.regs dest + s.regs src))
| .MUL src dest => fun s => Q (State.updateReg s dest (s.regs dest * s.regs src))
| .MOV src dest => fun s => Q (State.updateReg s dest (s.regs src))
| .LOAD dst addr => fun s => ∃ v, s.mem (s.regs addr) = some v ∧ Q (State.updateReg s dst v)
| .STORE src addr => fun s => ∃ old, s.mem (s.regs addr) = some old ∧
Q (State.updateMem s (s.regs addr) (s.regs src))
| .JNZ _ _ => Q -- state-preserving; loop structure handled by VCG
For a straight-line block of instructions, the WP is obtained by folding wp from the last instruction to the first — the postcondition flows backward through the code:
def blockWP (instrs : List Instr) (Q : Assert) : Assert :=
instrs.foldr wp Q
that is, \(\texttt{blockWP}\ [i_1, \ldots, i_n]\ Q = \texttt{wp}\ i_1\ (\texttt{wp}\ i_2\ (\cdots\ (\texttt{wp}\ i_n\ Q)))\).
The first soundness result states that wp really computes a valid precondition:
theorem wp_sound
(prog : List Instr) (pc : ℕ) (i : Instr) (Q : Assert)
(hfetch : prog.get? pc = some i) :
⦃ wp i Q ⦄ prog @ pc ⦃ Q ⦄
For every instruction except JNZ, the proof is a single constructor: the instruction rules were designed so that their preconditions are literally wp i Q. The JNZ case is the interesting one. Here wp returns Q itself, so we must show ⦃ Q ⦄ prog @ pc ⦃ Q ⦄ from rules that only talk about cond ≠ 0 ∧ Q and cond = 0 ∧ Q. The trick is a case split packaged as a disjunction: by consequence, Q implies (cond ≠ 0 ∧ Q) ∨ (cond = 0 ∧ Q), and the disjunction rule combines the two jump rules:
| .JNZ cond target =>
change ⦃ Q ⦄ prog @ pc ⦃ Q ⦄
apply Triple.consequence
(P := fun s => (s.regs cond ≠ 0 ∧ Q s) ∨ (s.regs cond = 0 ∧ Q s))
· intro s hQs
by_cases h : s.regs cond = 0
· exact Or.inr ⟨h, hQs⟩
· exact Or.inl ⟨h, hQs⟩
· exact Triple.disj (Triple.jnz_taken hfetch) (Triple.jnz_not_taken hfetch)
· intro s h
exact h
The second result lifts this to blocks. A list instrs is aligned with the program at offset pc when the k-th instruction of the list is the instruction at pc + k in the program:
theorem blockWP_sound (instrs : List Instr) (code : Code) (pc : ℕ) (Q : Assert)
(hcode : ∀ k, instrs.get? k = code.get? (pc + k)) :
⦃ blockWP instrs Q ⦄ code @ pc ⦃ Q ⦄
The proof is by induction on instrs. For the empty list, blockWP [] Q = Q, and alignment at k = 0 tells us that there is no instruction at pc, so the Halt rule applies. For i :: rest, alignment gives the instruction i at pc and shows that rest is aligned at pc + 1; wp_sound handles i, the induction hypothesis handles rest, and the sequence rule glues them:
exact Triple.seq (wp_sound code pc i (blockWP rest Q) hfetch) (ih (pc + 1) hrest)
6. A worked example: increment a memory cell
Before dealing with jumps, let us use what we have on a concrete program. incrMem reads the value at the address held in r0, adds one to it, and writes the result to the address held in r1:
def incrMem : Code :=
[ Instr.LOAD (Reg.Name 2) (Reg.Name 0) -- r2 := mem[r0]
, Instr.MOVI (Reg.Name 3) 1 -- r3 := 1
, Instr.ADD (Reg.Name 3) (Reg.Name 2) -- r2 := r2 + r3
, Instr.STORE (Reg.Name 2) (Reg.Name 1) -- mem[r1] := r2
]
The specification says: if the cell at r0 holds v and we own the cell at r1, then after the program the cell at r1 holds v + 1.
theorem incrMem_correct (v : ℕ) :
⦃ fun s => s.mem (s.regs (Reg.Name 0)) = some v ∧
∃ old, s.mem (s.regs (Reg.Name 1)) = some old ⦄
incrMem @ 0
⦃ fun s => s.mem (s.regs (Reg.Name 1)) = some (v + 1) ⦄
It is instructive to compute blockWP incrMem Q by hand, going backward from the postcondition Q = (mem[r1] = v + 1):
| Before… | the precondition is |
|---|---|
| (end of program) | mem[r1] = v + 1 |
STORE r2, r1 | ∃ old, mem[r1] = old ∧ r2 = v + 1 |
ADD r3, r2 | ∃ old, mem[r1] = old ∧ r2 + r3 = v + 1 |
MOVI r3, 1 | ∃ old, mem[r1] = old ∧ r2 + 1 = v + 1 |
LOAD r2, r0 | ∃ w, mem[r0] = w ∧ ∃ old, mem[r1] = old ∧ w + 1 = v + 1 |
Each line is obtained from the one above by the corresponding case of wp: STORE adds the ownership obligation for r1 and replaces the updated cell by r2; ADD and MOVI substitute registers; LOAD adds the ownership obligation for r0 and introduces the loaded value w. The last line is implied by the specification’s precondition by choosing w := v, which is exactly what the Lean proof does:
apply Triple.consequence
(P := blockWP incrMem (fun s => s.mem (s.regs (Reg.Name 1)) = some (v + 1)))
· -- Show user precondition implies blockWP
intro s ⟨hmem0, old, hmem1⟩
simp only [blockWP, incrMem, List.foldr, wp,
State.updateReg, State.updateMem, Heap.update,
Reg.Name.injEq,
show (2 : ℕ) ≠ 1 from by decide,
show (3 : ℕ) ≠ 2 from by decide,
show (3 : ℕ) ≠ 1 from by decide,
↓reduceIte, Function.update_self]
exact ⟨v, hmem0, old, hmem1, rfl⟩
· -- Core triple from blockWP_sound
exact blockWP_sound incrMem incrMem 0 _ (fun k => by simp)
· -- Postcondition is trivially implied
intro s hs; exact hs
The simp call computes the table above symbolically. The facts 2 ≠ 1, 3 ≠ 2 and 3 ≠ 1 are what allow it to simplify register lookups after updates — updating r3 does not change r1, and so on. This is the main source of tedium in assembly verification, and it is exactly the kind of bookkeeping that should be delegated to automation.
7. The verification condition generator
blockWP only handles straight-line code. Real assembly programs jump, and jumps create two new problems: the code is no longer a sequence (a JNZ has two successors), and backward jumps create loops, so naively following the control flow would never terminate.
The VCG solves both problems with two classic ideas.
- Loop invariants as cut-points. The user supplies a map from program counters to assertions, the invariants of the loop headers. When the VCG reaches a jump whose target is annotated, it does not follow the jump: it uses the invariant as the precondition at that point and emits a verification condition (VC) to be proved separately. This is the annotation-based approach of Barnett & Leino for unstructured programs.
- Fuel. To make the function structurally recursive, and hence accepted by Lean without a termination proof, the VCG takes a
fuelargument that decreases at each step. If fuel runs out, the VCG returns the preconditionFalse, which is trivially sound; in practice one passesfuel ≥ |code|.
abbrev InvMap := ℕ → Option Assert
structure VCGResult where
pre : Assert
vcs : List Prop
def vcg (code : Code) (Q : Assert) (inv : InvMap) : ℕ → ℕ → VCGResult
| 0, _ => { pre := fun _ => False, vcs := [] }
| fuel + 1, pc =>
match code.get? pc with
| none =>
-- Past the end of code: the postcondition holds by assumption.
{ pre := Q, vcs := [] }
| some (.JNZ cond target) =>
match inv target with
| some I =>
-- The target is annotated with loop invariant I.
let fallThrough := vcg code Q inv fuel (pc + 1)
let vcFall : Prop := ∀ s, I s → s.regs cond = 0 → fallThrough.pre s
{ pre := I
vcs := vcFall :: fallThrough.vcs }
| none =>
-- No annotation: recurse into both branches (sound for forward jumps).
let taken := vcg code Q inv fuel target
let fallThrough := vcg code Q inv fuel (pc + 1)
let pre : Assert := fun s =>
(s.regs cond ≠ 0 → taken.pre s) ∧ (s.regs cond = 0 → fallThrough.pre s)
{ pre := pre
vcs := taken.vcs ++ fallThrough.vcs }
| some i =>
-- Non-branching instruction: compute wp and continue.
let rest := vcg code Q inv fuel (pc + 1)
{ pre := wp i rest.pre, vcs := rest.vcs }
Reading the cases:
- end of the code — the program has halted, so the precondition is the postcondition itself;
- ordinary instruction — compute the precondition of the rest of the code and apply
wp, as inblockWP; - unannotated jump — compute the preconditions of both successors and combine them with a case analysis on the condition register. This is the right treatment for forward jumps (an
if); - jump to an annotated target — the precondition is the invariant
I, and the VCvcFallsays that, when the loop exits (cond = 0), the invariant implies the precondition of the code that follows the loop.
The entry point adds one more obligation: the user’s precondition P must imply the precondition computed for the whole program:
def vcgCheck (fuel : ℕ) (code : Code) (P Q : Assert) (inv : InvMap) : List Prop :=
let result := vcg code Q inv fuel 0
(∀ s, P s → result.pre s) :: result.vcs
For straight-line code, vcg emits no VCs and its precondition is exactly blockWP code Q. The only obligation left is then the implication P → pre, which is what we discharged by hand in the incrMem example.
8. Soundness of the VCG
The main theorem says that proving all VCs is enough to obtain the triple:
theorem vcg_sound (fuel : ℕ) (code : Code) (P Q : Assert) (inv : InvMap)
(hVCs : ∀ vc ∈ vcgCheck fuel code P Q inv, vc)
(hInvs : ∀ t I, inv t = some I → ⦃ I ⦄ code @ t ⦃ Q ⦄) :
⦃ P ⦄ code @ 0 ⦃ Q ⦄
It follows from a core lemma about vcg at an arbitrary pc, proved by induction on fuel:
theorem vcg_core_sound (fuel : ℕ) (code : Code) (Q : Assert) (inv : InvMap) (pc : ℕ)
(hInvs : ∀ t I, inv t = some I → ⦃ I ⦄ code @ t ⦃ Q ⦄)
(hVCs : ∀ vc ∈ (vcg code Q inv fuel pc).vcs, vc) :
⦃ (vcg code Q inv fuel pc).pre ⦄ code @ pc ⦃ Q ⦄
The proof follows the structure of vcg exactly, which is a good sign that the definition is well organized:
- fuel = 0: the precondition is
False; any triple with preconditionFalseis obtained by consequence (ex falso) from some existing triple atpc(Halt orwp_sound); - no instruction at
pc: the Halt rule; - ordinary instruction:
wp_soundfor the instruction, the induction hypothesis forpc + 1, and the sequence rule — exactly as inblockWP_sound; - unannotated jump: by consequence, the precondition
(cond ≠ 0 → taken.pre) ∧ (cond = 0 → ft.pre)implies(cond ≠ 0 ∧ taken.pre) ∨ (cond = 0 ∧ ft.pre); each disjunct is handled by a jump rule followed (via Seq) by the induction hypothesis attargetor atpc + 1; - annotated jump: same shape, but now the precondition is the invariant
I. The consequence step uses the VCvcFallto show thatIimplies the disjunction; the fall-through branch uses the induction hypothesis atpc + 1; and for the taken branch we cannot use the induction hypothesis (we did not recurse into the loop!), so we use the hypothesishInvsinstead:
· exact Triple.disj
(Triple.seq (Triple.jnz_taken h) (hInvs target I hinv))
(Triple.seq (Triple.jnz_not_taken h) (ih (pc + 1) hVCs_ft))
vcg_sound is then a two-line consequence: the head of vcgCheck gives P ⊢ₐ pre, the tail gives the hypotheses of vcg_core_sound, and the consequence rule combines them.
9. Why the hypothesis hInvs?
The most instructive part of the development is the hypothesis
hInvs : ∀ t I, inv t = some I → ⦃ I ⦄ code @ t ⦃ Q ⦄
which says that every annotated loop header is already known to be correct. Why can the VCG not establish this by itself?
Because Triple is an inductive definition: every proof is a finite derivation tree. A loop may execute an unbounded number of times, and there is no constructor in Triple that packages an arbitrary number of iterations into a single step — there is no analogue of Hoare’s while rule,
which is exactly the rule that turns a fact about one iteration into a fact about all of them. Without such a rule, proving the triple at a loop header would require unfolding the loop forever. The VCG therefore cuts the cycle at the annotated points and makes the remaining obligation explicit in the type of the theorem.
This is the same division of labour found in tools such as Why3, KeY or Frama-C/WP: the user provides invariants, the tool generates the VCs of the acyclic paths between them, and the correctness of the annotated points is a separate obligation. There are other possible designs, each with its own trade-offs:
- add a loop rule to
Triple— loops become part of the logic, at the cost of a more complex set of rules and soundness argument; - fuel-bounded unrolling — prove correctness for executions of at most
ksteps, which is weaker than partial correctness; - circular (assume-guarantee) reasoning — assume the invariant at the back-edge and justify it afterwards, which requires coinduction or a step-indexed/modal fixpoint.
Keeping hInvs as an explicit hypothesis is the most transparent choice for a tutorial: it does not change the logic and it shows precisely where the user’s insight (the invariant) is needed.
10. What is proved, and what comes next
It is worth being precise about the guarantees. The theorems wp_sound, blockWP_sound, vcg_core_sound and vcg_sound state that what the WP calculus and the VCG compute is derivable in the proof system Triple. In other words, the VCG is sound with respect to the Hoare logic. The development does not contain a theorem relating Triple to the operational semantics Eval — a statement of the form “if ⦃ P ⦄ code @ pc ⦃ Q ⦄ is derivable and the machine runs from a state satisfying P, then every final state satisfies Q”.
That semantic soundness theorem is the natural next step, and working it out is an excellent exercise. It also forces several design decisions to be revisited:
-
Evalhas no rule forMOVI, so the instruction exists in the syntax and in the logic but not in the semantics; - the index of
Evalrecords the program counter after a step but not the one before it, so the relation, as stated, cannot express “a step frompc”; - the meaning of a triple must be given in terms of executions — for instance, reachability of the end of the program — and then the rules
Seq(which accepts an arbitrarypc') andHaltmust be justified against that meaning; - the frame rule is only sound for instructions that are local — that touch only the memory owned by the precondition — so the memory rules need to be stated in terms of the footprint of the instruction (
a ↦ v) rather than of the whole heap.
These points are the classic difficulties of program logics for low-level code, and they are exactly what the papers in the references below address in realistic settings. The small size of this development makes it a good playground to experiment with them.
References
- C. A. R. Hoare. An Axiomatic Basis for Computer Programming. CACM, 1969.
- E. W. Dijkstra. A Discipline of Programming. Prentice-Hall, 1976.
- J. C. Reynolds. Separation Logic: A Logic for Shared Mutable Data Structures. LICS, 2002.
- P. O’Hearn, J. Reynolds and H. Yang. Local Reasoning about Programs that Alter Data Structures. CSL, 2001.
- M. Myreen and M. Gordon. Hoare Logic for Realistically Modelled Machine Code. TACAS, 2007.
- M. Barnett and K. R. M. Leino. Weakest-Precondition of Unstructured Programs. PASTE, 2005.
- T. Nipkow and G. Klein. Concrete Semantics with Isabelle/HOL. Springer, 2014.
- A. W. Appel et al. Program Logics for Certified Compilers. Cambridge University Press, 2014.
- J.-C. Filliâtre and A. Paskevich. Why3 — Where Programs Meet Provers. ESOP, 2013.