3.5. Operational Semantics of Assembly

In the previous chapters we studied the semantics of high-level languages, such as arithmetic expressions and the imperative language IMP. In these languages variables have names, commands are composed in a structured way (sequencing, conditionals, loops), and there is no explicit notion of addressable memory. Real programs, however, are ultimately executed by a processor, which understands only a much poorer language: the assembly language of its instruction set (its ISA, short for Instruction Set Architecture).

In this chapter we define, in Lean, a small ISA inspired by real architectures. It has registers, arithmetic flags, an addressable memory, and jump instructions. We give this language a small-step operational semantics in the form of an executable step function, together with a reachability relation, which is the propositional counterpart of multi-step execution. This lets us both run programs inside Lean and prove properties about them.

There are at least two good reasons to study a semantics of this kind. The first is that it is the destination of every compiler: to prove a compiler correct we need a precise semantics of the target language. The second is that low-level programs manipulate memory directly, and reasoning about memory is precisely the problem that motivates separation logic, the subject of the next chapter, which is built on top of the definitions presented here.

3.5.1. Syntax of the language

Our machine has eight general-purpose registers, named R0 through R7. Registers are the processor's "fast memory": every arithmetic operation reads and writes registers. Since the set of registers is finite and fixed, we model registers as an enumerated type.

namespace Ch21 /-- General-purpose registers -/ inductive Reg : Type where | R0 | R1 | R2 | R3 | R4 | R5 | R6 | R7 deriving DecidableEq, Repr

Besides registers, real processors maintain a set of flags: bits that summarize the result of the last arithmetic operation. The ZF flag (zero flag) indicates that the result was zero; SF (sign flag), that the result was negative; CF and OF signal carry and overflow, respectively. Conditional jump instructions inspect these flags to decide whether or not to divert the flow of execution.

/-- Flags of the arithmetic unit -/ inductive Flag : Type where | ZF -- Zero Flag | SF -- Sign Flag | CF -- Carry Flag | OF -- Overflow Flag deriving DecidableEq, Repr

Many instructions accept as their source either a register or a constant embedded in the instruction itself (an immediate). To avoid duplicating each instruction, we introduce a type of operands:

/-- Operand: register or immediate -/ inductive Operand : Type where | reg : Reg → Operand | imm : Int → Operand deriving Repr

In real assembly, jump targets are symbolic labels that the assembler translates into addresses. To keep things simple, a label will be directly the index of the target instruction in the program.

/-- A label is an index into the instruction list -/ abbrev Label := Nat

The instruction set contains data-transfer operations (MOV), arithmetic operations (ADD, SUB, MUL, NEG), memory-access operations (LOAD and STORE), control-flow operations (JMP, JZ, JNZ, JLT), and the HALT instruction, which ends execution. We follow the Intel syntax convention, in which the first argument is the destination: ADD R0 (reg R1) means R0 ← R0 + R1.

/-- Instruction set -/ inductive Instr : Type where | MOV : Reg → Operand → Instr -- dst ← src | ADD : Reg → Operand → Instr -- dst ← dst + src | SUB : Reg → Operand → Instr -- dst ← dst - src | MUL : Reg → Operand → Instr -- dst ← dst * src | NEG : Reg → Instr -- dst ← -dst | LOAD : Reg → Reg → Instr -- dst ← mem[src] | STORE : Reg → Reg → Instr -- mem[dst] ← src | JMP : Label → Instr -- PC ← lbl (unconditional) | JZ : Label → Instr -- PC ← lbl if ZF | JNZ : Label → Instr -- PC ← lbl if ¬ZF | JLT : Label → Instr -- PC ← lbl if SF ≠ OF | HALT : Instr deriving Repr

Note that LOAD and STORE use indirect addressing: the memory address being accessed is the contents of a register. Thus LOAD R2 R1 reads the memory location whose address is stored in R1 and puts the value read into R2, while STORE R1 R0 writes the contents of R0 into the location whose address is stored in R1.

A program is simply a list of instructions. The program counter (PC) is an index into this list and points to the next instruction to be executed.

/-- A program is a list of instructions; the PC is an index into it -/ abbrev Program := List Instr

3.5.2. Machine state

The state of a real machine consists of the contents of the registers, the flags, the memory, and the program counter. We choose functional representations for each component. The register file is a total function from registers to integers: every register always holds some value. The same goes for the flags, which are Booleans.

Memory, on the other hand, is modeled as a partial function from addresses (natural numbers) to integers, using Option Int. The value none represents an unallocated address: trying to read it is a runtime error. This distinction between allocated and unallocated addresses will be fundamental in the next chapter, when we talk about ownership of portions of memory.

/-- Register file: total map -/ abbrev RegFile := Reg → Int /-- Flag file: total map -/ abbrev FlagFile := Flag → Bool /-- Memory: partial map from addresses to values -/ abbrev Memory := Nat → Option Int /-- Complete machine state -/ structure MachineState : Type where regs : RegFile flags : FlagFile mem : Memory pc : Nat

Since the components of the state are functions, updating them means building a new function that differs from the old one at a single point. This pattern, which we already used for IMP states, shows up three times:

/-- Updates a register -/ def updateReg (rf : RegFile) (r : Reg) (v : Int) : RegFile := fun r' => if r' = r then v else rf r' /-- Updates a flag -/ def updateFlag (ff : FlagFile) (f : Flag) (v : Bool) : FlagFile := fun f' => if f' = f then v else ff f' /-- Updates an address in memory -/ def updateMem (m : Memory) (a : Nat) (v : Int) : Memory := fun a' => if a' = a then some v else m a'

The initial state has every register set to zero, every flag cleared, a completely empty memory, and the PC pointing to the first instruction.

/-- Initial state: everything zero, empty memory -/ def initState : MachineState := { regs := fun _ => 0 , flags := fun _ => false , mem := fun _ => none , pc := 0 }

Because it is made of functions, MachineState cannot automatically derive a Repr instance. To inspect states with #eval, we write functions that convert the relevant parts into text.

def showRegs (rf : RegFile) : String := let rs := [("R0", Reg.R0), ("R1", Reg.R1), ("R2", Reg.R2), ("R3", Reg.R3), ("R4", Reg.R4), ("R5", Reg.R5), ("R6", Reg.R6), ("R7", Reg.R7)] String.intercalate ", " (rs.map fun (n, r) => s!"{n}={rf r}") def showState (s : MachineState) : String := s!"pc={s.pc}, [{showRegs s.regs}], ZF={s.flags .ZF}"

3.5.3. Operands and flags

Evaluating an operand is simple: a register is read from the register file, and an immediate is its own value.

def evalOperand (rf : RegFile) : Operand → Int | .reg r => rf r | .imm n => n

After each arithmetic operation, the ZF and SF flags are updated according to the result. Since our arithmetic is over mathematical integers (with no bit limit), there is no carry and no overflow; the CF and OF flags exist only to keep the resemblance with real architectures and are never modified.On a 64-bit machine, ADD would operate on BitVec 64 and would need to compute CF and OF. Here we choose Int to keep the proofs simple.

-- Updates ZF and SF based on the arithmetic result def setArithFlags (ff : FlagFile) (result : Int) : FlagFile := updateFlag (updateFlag ff .ZF (result == 0)) .SF (result < 0)

3.5.4. Operational semantics

Machine execution follows the fetch–execute cycle: the processor fetches the instruction pointed to by the PC and executes it, producing a new state. Fetching may fail if the PC is outside the bounds of the program.

/-- Fetches the instruction at the current PC -/ def fetch (prog : Program) (pc : Nat) : Option Instr := prog[pc]?

Unlike what we did for IMP, we define the step semantics as a function rather than as an inductive relation. This is possible because executing an instruction is deterministic and always terminates, and it has the advantage of making the semantics directly executable. The result is an Option MachineState: the value none indicates that the machine has stopped, either because it executed HALT or because of a memory access fault.

Writing the state as a quadruple (R, F, M, pc) and P[pc] for the instruction at position pc of program P, the rules for some instructions can be presented in the usual style. For MOV we have

\frac{P[pc] = \mathtt{MOV}\ r\ o}{(R, F, M, pc) \longrightarrow (R[r \mapsto \llbracket o \rrbracket_R], F, M, pc + 1)}

where \llbracket o \rrbracket_R is the value of operand o in register file R. Arithmetic instructions also update the flags; for instance, for ADD, with v = R(r) + \llbracket o \rrbracket_R:

\frac{P[pc] = \mathtt{ADD}\ r\ o \qquad v = R(r) + \llbracket o \rrbracket_R}{(R, F, M, pc) \longrightarrow (R[r \mapsto v], \mathit{flags}(F, v), M, pc + 1)}

The LOAD instruction can take a step only if the address being read is allocated:

\frac{P[pc] = \mathtt{LOAD}\ d\ s \qquad M(R(s)) = \mathsf{some}\ v}{(R, F, M, pc) \longrightarrow (R[d \mapsto v], F, M, pc + 1)}

STORE, in contrast, always succeeds and may even allocate a fresh location:

\frac{P[pc] = \mathtt{STORE}\ d\ s}{(R, F, M, pc) \longrightarrow (R, F, M[R(d) \mapsto R(s)], pc + 1)}

Finally, conditional jumps only change the PC. For JZ, for example, there are two rules:

\frac{P[pc] = \mathtt{JZ}\ \ell \qquad F(\mathtt{ZF}) = \mathsf{true}}{(R, F, M, pc) \longrightarrow (R, F, M, \ell)} \qquad \frac{P[pc] = \mathtt{JZ}\ \ell \qquad F(\mathtt{ZF}) = \mathsf{false}}{(R, F, M, pc) \longrightarrow (R, F, M, pc + 1)}

The following function implements all of these rules. Note that addresses are natural numbers, whereas registers hold integers; we use Int.toNat to convert between them (negative addresses are treated as zero).

/-- Executes one instruction from state s. Returns none on a memory fault or on HALT. -/ def stepInstr (s : MachineState) : Instr → Option MachineState | .MOV dst op => let v := evalOperand s.regs op some { s with regs := updateReg s.regs dst v, pc := s.pc + 1 } | .ADD dst op => let v := s.regs dst + evalOperand s.regs op some { s with regs := updateReg s.regs dst v , flags := setArithFlags s.flags v , pc := s.pc + 1 } | .SUB dst op => let v := s.regs dst - evalOperand s.regs op some { s with regs := updateReg s.regs dst v , flags := setArithFlags s.flags v , pc := s.pc + 1 } | .MUL dst op => let v := s.regs dst * evalOperand s.regs op some { s with regs := updateReg s.regs dst v , flags := setArithFlags s.flags v , pc := s.pc + 1 } | .NEG dst => let v := -(s.regs dst) some { s with regs := updateReg s.regs dst v , flags := setArithFlags s.flags v , pc := s.pc + 1 } | .LOAD dst src => match s.mem (s.regs src).toNat with | none => none -- fault: unallocated address | some v => some { s with regs := updateReg s.regs dst v , pc := s.pc + 1 } | .STORE dst src => some { s with mem := updateMem s.mem (s.regs dst).toNat (s.regs src) , pc := s.pc + 1 } | .JMP lbl => some { s with pc := lbl } | .JZ lbl => some { s with pc := if s.flags .ZF then lbl else s.pc + 1 } | .JNZ lbl => some { s with pc := if !s.flags .ZF then lbl else s.pc + 1 } | .JLT lbl => some { s with pc := if s.flags .SF != s.flags .OF then lbl else s.pc + 1 } | .HALT => none -- normal termination

A machine step composes fetching with execution. Since both may fail, we use the bind of the Option monad: if fetching returns none, the whole step returns none.

/-- Single machine step: fetch and execute the instruction at the PC -/ def step (prog : Program) (s : MachineState) : Option MachineState := (fetch prog s.pc).bind (stepInstr s)

To execute several steps, we iterate step a fixed number of times. The parameter n acts as "fuel" that guarantees termination of the function even for programs that enter an infinite loop.

/-- Executes n steps -/ def stepN (prog : Program) : Nat → MachineState → Option MachineState | 0, s => some s | n + 1, s => (step prog s).bind (stepN prog n)

A subtle detail: since the machine returns none when it stops, stepN with more fuel than the number of steps until HALT yields none. To observe the final state, we must supply exactly the number of steps preceding the HALT, or use the reachability relation of the next section.

3.5.5. Reachability

The stepN function is great for testing programs, but not very convenient for proofs: we need to know in advance how many steps will be taken. To reason about arbitrary executions, we define the reflexive–transitive closure of the step relation as an inductive predicate: s \longrightarrow^{*} s'' holds if s'' = s, or if s takes a step to some s' from which s'' is reachable.

\frac{}{s \longrightarrow^{*} s}\,(\mathsf{refl}) \qquad \frac{\mathit{step}(s) = \mathsf{some}\ s' \qquad s' \longrightarrow^{*} s''}{s \longrightarrow^{*} s''}\,(\mathsf{next})

The recursive constructor is called next rather than step to avoid confusion with the step function defined above.

/-- s'' is reachable from s in zero or more steps -/ inductive Reaches (prog : Program) : MachineState → MachineState → Prop where | refl : ∀ s, Reaches prog s s | next : ∀ s s' s'', step prog s = some s' → Reaches prog s' s'' → Reaches prog s s''

A state s' such that Reaches prog s s' and step prog s' = none is a final state of the execution starting at s: the machine stopped (normally or due to an error) upon reaching s'.

3.5.6. Execution examples

Let us look at three small programs. The first computes 3 + 4 and stores the result in R0.

-- Program: computes 3 + 4 in R0 def prog_add : Program := [ .MOV .R0 (.imm 3) -- 0: R0 ← 3 , .MOV .R1 (.imm 4) -- 1: R1 ← 4 , .ADD .R0 (.reg .R1) -- 2: R0 ← R0 + R1 , .HALT ] -- 3: stop

Running three steps from the initial state, we reach the state immediately before the HALT:

some "pc=3, [R0=7, R1=4, R2=0, R3=0, R4=0, R5=0, R6=0, R7=0], ZF=false"#eval (stepN prog_add 3 initState).map showState
some "pc=3, [R0=7, R1=4, R2=0, R3=0, R4=0, R5=0, R6=0, R7=0], ZF=false"

With four steps, the fourth one is the HALT, which returns none:

none#eval (stepN prog_add 4 initState).map showState
none

The second program is a countdown loop. The SUB instruction decrements R0 and sets the ZF flag when the result is zero; JNZ jumps back to instruction 1 as long as ZF is cleared.

-- Program: countdown from R0 = 3 to 0 def prog_loop : Program := [ .MOV .R0 (.imm 3) -- 0: R0 ← 3 , .SUB .R0 (.imm 1) -- 1: R0 ← R0 - 1 (ZF set when 0) , .JNZ 1 -- 2: if ¬ZF, go back to 1 , .HALT ] -- 3: stop

The loop executes the MOV instruction once and the SUB/JNZ pair three times, for a total of seven steps before the HALT:

some "pc=3, [R0=0, R1=0, R2=0, R3=0, R4=0, R5=0, R6=0, R7=0], ZF=true"#eval (stepN prog_loop 7 initState).map showState
some "pc=3, [R0=0, R1=0, R2=0, R3=0, R4=0, R5=0, R6=0, R7=0], ZF=true"

The third program writes a value to memory and reads it back. The STORE instruction allocates address 100, which was empty in the initial state; then LOAD reads it successfully.

-- Program: writes a value to memory and reads it back def prog_loadstore : Program := [ .MOV .R0 (.imm 42) -- 0: R0 ← 42 , .MOV .R1 (.imm 100) -- 1: R1 ← 100 (address) , .STORE .R1 .R0 -- 2: mem[100] ← 42 , .LOAD .R2 .R1 -- 3: R2 ← mem[100] , .HALT ] -- 4: stop some "R2=42, mem[100]=(some 42)"#eval (stepN prog_loadstore 4 initState).map (fun s => s!"R2={s.regs .R2}, mem[100]={s.mem 100}")
some "R2=42, mem[100]=(some 42)"

If we omit the STORE, the LOAD tries to read an unallocated address and the machine stops with an error as early as the second step:

none#eval (stepN [.MOV .R1 (.imm 100), .LOAD .R2 .R1, .HALT] 2 initState).map showState
none

3.5.7. Fundamental lemmas

We now turn to proving properties of the semantics. We begin with lemmas describing the update functions. They are the "read-after-write equations": reading the location that was just written returns the value written, and reading any other location returns the old value. All the proofs go through by simplification, unfolding the definition of the update.

theorem updateReg_same (rf : RegFile) (r : Reg) (v : Int) : (updateReg rf r v) r = v := rf:RegFiler:Regv:ℤ⊢ updateReg rf r v r = v All goals completed! 🐙 theorem updateReg_other (rf : RegFile) (r r' : Reg) (v : Int) (h : r' ≠ r) : (updateReg rf r v) r' = rf r' := rf:RegFiler:Regr':Regv:ℤh:r' ≠ r⊢ updateReg rf r v r' = rf r' All goals completed! 🐙 theorem updateMem_same (m : Memory) (a : Nat) (v : Int) : (updateMem m a v) a = some v := m:Memorya:ℕv:ℤ⊢ updateMem m a v a = some v All goals completed! 🐙 theorem updateMem_other (m : Memory) (a a' : Nat) (v : Int) (h : a' ≠ a) : (updateMem m a v) a' = m a' := m:Memorya:ℕa':ℕv:ℤh:a' ≠ a⊢ updateMem m a v a' = m a' All goals completed! 🐙

3.5.7.1. Determinism and the effect of instructions

Since step is a function, determinism of the semantics is immediate: if a state steps both to s_1 and to s_2, then s_1 = s_2. In a semantics given by an inductive relation, this fact would require a proof by case analysis on both derivations.

theorem step_deterministic (prog : Program) (s s1 s2 : MachineState) (h1 : step prog s = some s1) (h2 : step prog s = some s2) : s1 = s2 := prog:Programs:MachineStates1:MachineStates2:MachineStateh1:step prog s = some s1h2:step prog s = some s2⊢ s1 = s2 prog:Programs:MachineStates1:MachineStates2:MachineStateh1:step prog s = some s1h2:some s1 = some s2⊢ s1 = s2 All goals completed! 🐙

The next lemmas describe, declaratively, the effect of specific instructions. They are the bridge between the computational definition of stepInstr and the inference rules presented above: given that the fetched instruction is a MOV (or an ADD), the next state is exactly the one described by the corresponding rule.

-- Effect of the MOV instruction theorem step_MOV (prog : Program) (s : MachineState) (dst : Reg) (op : Operand) (hf : fetch prog s.pc = some (.MOV dst op)) : step prog s = some { s with regs := updateReg s.regs dst (evalOperand s.regs op), pc := s.pc + 1 } := prog:Programs:MachineStatedst:Regop:Operandhf:fetch prog s.pc = some (Instr.MOV dst op)⊢ step prog s = some { regs := updateReg s.regs dst (evalOperand s.regs op), flags := s.flags, mem := s.mem, pc := s.pc + 1 } All goals completed! 🐙 -- Effect of the ADD instruction theorem step_ADD (prog : Program) (s : MachineState) (dst : Reg) (op : Operand) (hf : fetch prog s.pc = some (.ADD dst op)) : step prog s = some { s with regs := updateReg s.regs dst (s.regs dst + evalOperand s.regs op), flags := setArithFlags s.flags (s.regs dst + evalOperand s.regs op), pc := s.pc + 1 } := prog:Programs:MachineStatedst:Regop:Operandhf:fetch prog s.pc = some (Instr.ADD dst op)⊢ step prog s = some { regs := updateReg s.regs dst (s.regs dst + evalOperand s.regs op), flags := setArithFlags s.flags (s.regs dst + evalOperand s.regs op), mem := s.mem, pc := s.pc + 1 } All goals completed! 🐙

3.5.7.2. Memory frame properties

The following two lemmas are especially important because they anticipate the central idea of separation logic. They state which parts of memory an instruction does not modify. A STORE writes to a single address; all the others remain unchanged. A LOAD, in turn, does not change memory at all. Properties of this kind are called frame properties: they describe the "frame" that stays fixed during execution.

-- STORE does not touch other memory addresses theorem step_STORE_frame (prog : Program) (s : MachineState) (dst src : Reg) (hf : fetch prog s.pc = some (.STORE dst src)) : ∀ a, a ≠ (s.regs dst).toNat → (step prog s).map (·.mem a) = some (s.mem a) := prog:Programs:MachineStatedst:Regsrc:Reghf:fetch prog s.pc = some (Instr.STORE dst src)⊢ ∀ (a : ℕ), a ≠ (s.regs dst).toNat → Option.map (fun x => x.mem a) (step prog s) = some (s.mem a) intro a prog:Programs:MachineStatedst:Regsrc:Reghf:fetch prog s.pc = some (Instr.STORE dst src)a:ℕha:a ≠ (s.regs dst).toNat⊢ Option.map (fun x => x.mem a) (step prog s) = some (s.mem a) All goals completed! 🐙

For LOAD, the proof has to consider both possible outcomes of the read. If the address is not allocated, the step returns none, contradicting the hypothesis hstep. Otherwise, the new state differs from the old one only in the registers and the PC.

-- LOAD does not modify memory theorem step_LOAD_mem (prog : Program) (s s' : MachineState) (dst src : Reg) (hf : fetch prog s.pc = some (.LOAD dst src)) (hstep : step prog s = some s') : s'.mem = s.mem := prog:Programs:MachineStates':MachineStatedst:Regsrc:Reghf:fetch prog s.pc = some (Instr.LOAD dst src)hstep:step prog s = some s'⊢ s'.mem = s.mem prog:Programs:MachineStates':MachineStatedst:Regsrc:Reghf:fetch prog s.pc = some (Instr.LOAD dst src)hstep:stepInstr s (Instr.LOAD dst src) = some s'⊢ s'.mem = s.mem cases hm : s.mem (s.regs src).toNat with prog:Programs:MachineStates':MachineStatedst:Regsrc:Reghf:fetch prog s.pc = some (Instr.LOAD dst src)hstep:stepInstr s (Instr.LOAD dst src) = some s'hm:s.mem (s.regs src).toNat = none⊢ s'.mem = s.mem All goals completed! 🐙 prog:Programs:MachineStates':MachineStatedst:Regsrc:Reghf:fetch prog s.pc = some (Instr.LOAD dst src)hstep:stepInstr s (Instr.LOAD dst src) = some s'v:ℤhm:s.mem (s.regs src).toNat = some v⊢ s'.mem = s.mem prog:Programs:MachineStates':MachineStatedst:Regsrc:Reghf:fetch prog s.pc = some (Instr.LOAD dst src)v:ℤhm:s.mem (s.regs src).toNat = some vhstep:{ regs := updateReg s.regs dst v, flags := s.flags, mem := s.mem, pc := s.pc + 1 } = s'⊢ s'.mem = s.mem; prog:Programs:MachineStatedst:Regsrc:Reghf:fetch prog s.pc = some (Instr.LOAD dst src)v:ℤhm:s.mem (s.regs src).toNat = some v⊢ { regs := updateReg s.regs dst v, flags := s.flags, mem := s.mem, pc := s.pc + 1 }.mem = s.mem; All goals completed! 🐙

3.5.7.3. Properties of reachability

Reachability is transitive: if s_1 \longrightarrow^{*} s_2 and s_2 \longrightarrow^{*} s_3, then s_1 \longrightarrow^{*} s_3. The proof is by induction on the first derivation. In the base case, s_1 = s_2 and the second derivation is already the answer. In the inductive case, s_1 takes a step to some s' and, by the induction hypothesis, s' \longrightarrow^{*} s_3; it then suffices to reapply the next constructor.

theorem Reaches.trans (prog : Program) {s1 s2 s3 : MachineState} (h12 : Reaches prog s1 s2) (h23 : Reaches prog s2 s3) : Reaches prog s1 s3 := prog:Programs1:MachineStates2:MachineStates3:MachineStateh12:Reaches prog s1 s2h23:Reaches prog s2 s3⊢ Reaches prog s1 s3 induction h12 with prog:Programs1:MachineStates2:MachineStates3:MachineStates:MachineStateh23:Reaches prog s s3⊢ Reaches prog s s3 All goals completed! 🐙 prog:Programs1:MachineStates2:MachineStates3:MachineStates:MachineStates':MachineStates'':MachineStatehs:step prog s = some s'a:Reaches prog s' s''ih:Reaches prog s'' s3 → Reaches prog s' s3h23:Reaches prog s'' s3⊢ Reaches prog s s3 All goals completed! 🐙

It is also useful to know that a single step is an execution:

theorem Reaches.one (prog : Program) {s s' : MachineState} (h : step prog s = some s') : Reaches prog s s' := Reaches.next s s' s' h (Reaches.refl s')

3.5.8. Correctness of a program

We close the chapter by proving that prog_add really computes 3 + 4. The statement says that there is a final state s_f, reachable from the initial state, in which the machine stops and R0 contains 7:

\exists s_f.\ \mathit{initState} \longrightarrow^{*} s_f \ \land\ \mathit{step}(s_f) = \mathsf{none} \ \land\ s_f.\mathit{regs}(\mathtt{R0}) = 7

The strategy is to build each intermediate state of the execution explicitly and check each step separately. Since all states are concrete, each step can be checked by pure computation, with rfl: Lean evaluates step and compares the results.

-- Intermediate states computed explicitly def s0 := initState def s1 := { s0 with regs := updateReg s0.regs .R0 3, pc := 1 } def s2 := { s1 with regs := updateReg s1.regs .R1 4, pc := 2 } def s3 := { s2 with regs := updateReg s2.regs .R0 (s2.regs .R0 + s2.regs .R1) , flags := setArithFlags s2.flags (s2.regs .R0 + s2.regs .R1) , pc := 3 } -- Each step checked by reflexivity theorem hstep0 : step prog_add s0 = some s1 := ⊢ step prog_add s0 = some s1 All goals completed! 🐙 theorem hstep1 : step prog_add s1 = some s2 := ⊢ step prog_add s1 = some s2 All goals completed! 🐙 theorem hstep2 : step prog_add s2 = some s3 := ⊢ step prog_add s2 = some s3 All goals completed! 🐙 theorem hhalt3 : step prog_add s3 = none := ⊢ step prog_add s3 = none All goals completed! 🐙 theorem hR0_7 : s3.regs .R0 = 7 := ⊢ s3.regs Reg.R0 = 7 All goals completed! 🐙

With these facts in hand, the proof of the theorem is just the assembly of a Reaches derivation with three applications of next followed by refl.

/-- After running prog_add from the initial state, there is a final state with R0 = 7 -/ theorem prog_add_correct : ∃ sf, Reaches prog_add initState sf ∧ step prog_add sf = none ∧ sf.regs .R0 = 7 := ⟨s3, Reaches.next _ _ _ hstep0 (Reaches.next _ _ _ hstep1 (Reaches.next _ _ _ hstep2 (Reaches.refl _))), hhalt3, hR0_7⟩

This style of proof, although completely rigorous, does not scale: for a program with loops or with symbolic inputs we cannot enumerate the states. We need a program logic, in the style of Hoare logic, adapted to assembly language. Moreover, since low-level programs manipulate memory through computed addresses, this logic must deal well with the aliasing problem: knowing when two addresses may or may not coincide. This is the role of separation logic, which we study in the next chapter.

end Ch21

3.5.9. Exercises

1. Write a program prog_mul that computes 6 * 7 in R0 using the
   MUL instruction, and use #eval with stepN to check the result.
2. Write a program that computes the factorial of 5 using a loop
   (instructions MUL, SUB and JNZ). How many steps are needed until
   HALT? Check with stepN.
3. Prove the analogue of step_MOV for the SUB instruction:
   theorem step_SUB (prog : Program) (s : MachineState) (dst : Reg)
       (op : Operand) (hf : fetch prog s.pc = some (.SUB dst op)) :
       step prog s = some { s with
         regs  := updateReg s.regs dst (s.regs dst - evalOperand s.regs op),
         flags := setArithFlags s.flags (s.regs dst - evalOperand s.regs op),
         pc    := s.pc + 1 }
4. Prove that jump instructions do not change registers:
   if fetch prog s.pc = some (.JNZ l) and step prog s = some s',
   then s'.regs = s.regs.
5. Prove that HALT is indeed terminal:
   fetch prog s.pc = some .HALT → step prog s = none.
6. Prove that stepN is compatible with Reaches:
   stepN prog n s = some s' → Reaches prog s s'.
   (Hint: induction on n, generalizing s.)
7. Prove the correctness of prog_loadstore in the same style as
   prog_add_correct: there is a final state, reachable from
   initState, in which R2 = 42.