Hoare Logic. COMP2600 Formal Methods for Software Engineering. Rajeev Goré

Similar documents
Lecture 5 - Axiomatic semantics

An Annotated Language

Lectures 20, 21: Axiomatic Semantics

Introduction to Axiomatic Semantics

6. Hoare Logic and Weakest Preconditions

Separation Logic. COMP2600 Formal Methods for Software Engineering. Rajeev Goré. Australian National University Semester 2, 2016

CITS5501 Software Testing and Quality Assurance Formal methods

Introduction to Axiomatic Semantics (1/2)

Introduction to Axiomatic Semantics (1/2)

Warm-Up Problem. Let be a set of well-formed Predicate logic formulas. Let be well-formed Predicate logic formulas. Prove or disprove the following.

Part II. Hoare Logic and Program Verification. Why specify programs? Specification and Verification. Code Verification. Why verify programs?

Programming Languages Third Edition

Semantics. There is no single widely acceptable notation or formalism for describing semantics Operational Semantics

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

Reasoning About Imperative Programs. COS 441 Slides 10

Program Verification. Program Verification 307/434

AXIOMS OF AN IMPERATIVE LANGUAGE PARTIAL CORRECTNESS WEAK AND STRONG CONDITIONS. THE AXIOM FOR nop

Warm-Up Problem. 1. What is the definition of a Hoare triple satisfying partial correctness? 2. Recall the rule for assignment: x (assignment)

Software Quality Assurance

The Formal Semantics of Programming Languages An Introduction. Glynn Winskel. The MIT Press Cambridge, Massachusetts London, England

Computation Club: Gödel s theorem

Proving the Correctness of Distributed Algorithms using TLA

Chapter 3. Describing Syntax and Semantics ISBN

The Rule of Constancy(Derived Frame Rule)

3.4 Deduction and Evaluation: Tools Conditional-Equational Logic

Verification Condition Generation

Chapter 3 (part 3) Describing Syntax and Semantics

Lecture 4. First order logic is a formal notation for mathematics which involves:

CSE 307: Principles of Programming Languages

Hoare triples. Floyd-Hoare Logic, Separation Logic

! Use of formal notations. ! in software system descriptions. ! for a broad range of effects. ! and varying levels of use. !

Specification and Verification I

Software Engineering Lecture Notes

Chapter 3. Describing Syntax and Semantics

Chapter 1. Introduction

Static semantics. Lecture 3-6: Semantics. Attribute grammars (2) Attribute grammars. Attribute grammars example. Dynamic semantics

Chapter 3. Semantics. Topics. Introduction. Introduction. Introduction. Introduction

Proving Theorems with Athena

Proof Carrying Code(PCC)

Part I Logic programming paradigm

Context Free Languages

Formal Methods. CITS5501 Software Testing and Quality Assurance

Shared Variables and Interference

Com S 541. Programming Languages I

P1 Engineering Computation

CMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics

Induction and Semantics in Dafny

Section 2.4: Arguments with Quantified Statements

Chapter 3. Describing Syntax and Semantics ISBN

Chapter 3. Describing Syntax and Semantics

Introduction to dependent types in Coq

Principles of Program Analysis. Lecture 1 Harry Xu Spring 2013

COSC252: Programming Languages: Semantic Specification. Jeremy Bolton, PhD Adjunct Professor

Programming Languages and Compilers Qualifying Examination. Answer 4 of 6 questions.

The semantics of a programming language is concerned with the meaning of programs, that is, how programs behave when executed on computers.

COMP 507: Computer-Aided Program Design

Propositional Logic Formal Syntax and Semantics. Computability and Logic

Denotational Semantics of a Simple Imperative Language Using Intensional Logic

Intro to semantics; Small-step semantics Lecture 1 Tuesday, January 29, 2013

CS 11 Haskell track: lecture 1

Lecture 11 Lecture 11 Nov 5, 2014

Hoare logic. WHILE p, a language with pointers. Introduction. Syntax of WHILE p. Lecture 5: Introduction to separation logic

Program Verification. Aarti Gupta

Hoare Logic: Proving Programs Correct

Lecture 2: Analyzing Algorithms: The 2-d Maxima Problem

(a) (4 pts) Prove that if a and b are rational, then ab is rational. Since a and b are rational they can be written as the ratio of integers a 1

Hoare logic. Lecture 5: Introduction to separation logic. Jean Pichon-Pharabod University of Cambridge. CST Part II 2017/18

What if current foundations of mathematics are inconsistent? Vladimir Voevodsky September 25, 2010

Hardware versus software

Shared Variables and Interference

Logic and Computation

MSO Lecture Design by Contract"

Fundamental Concepts. Chapter 1

A Small Interpreted Language

Proving Properties on Programs From the Coq Tutorial at ITP 2015

Hoare logic. A proof system for separation logic. Introduction. Separation logic

Why. an intermediate language for deductive program verification

Lee Pike. June 3, 2005

Logic and Computation Lecture 20 CSU 290 Spring 2009 (Pucella) Thursday, Mar 12, 2009

Formal Verification. Lecture 10

A CRASH COURSE IN SEMANTICS

Propositional Logic. Andreas Klappenecker

6.001 Notes: Section 1.1

How invariants help writing loops Author: Sander Kooijmans Document version: 1.0

Lecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning

6.001 Notes: Section 6.1

SEQUENCES, MATHEMATICAL INDUCTION, AND RECURSION

CIS 500 Software Foundations. Final Exam. May 3, Answer key

Critical Analysis of Computer Science Methodology: Theory

Lambda Calculus and Type Inference

Symbolic Execution and Proof of Properties

COMP 410 Lecture 1. Kyle Dewey

Mathematical Logic Prof. Arindama Singh Department of Mathematics Indian Institute of Technology, Madras. Lecture - 37 Resolution Rules

Overview. CS389L: Automated Logical Reasoning. Lecture 6: First Order Logic Syntax and Semantics. Constants in First-Order Logic.

Outline. Introduction. 2 Proof of Correctness. 3 Final Notes. Precondition P 1 : Inputs include

Abstract Interpretation

Advances in Programming Languages

LOGIC AND DISCRETE MATHEMATICS

This is already grossly inconvenient in present formalisms. Why do we want to make this convenient? GENERAL GOALS

Basic Verification Strategy

Transcription:

Hoare Logic COMP2600 Formal Methods for Software Engineering Rajeev Goré Australian National University Semester 2, 2016 (Slides courtesy of Ranald Clouston) COMP 2600 Hoare Logic 1

Australian Capital Territory Election Software Australian Capital Territory elections use Single Transferable Voting If we have C candidates for S < C vacancies you rank all candidates in order of your preference: Gough, Vladimir,..., Tony Counting such ballots proceeds in rounds where in each round we count up the votes for each candidate, elect or eliminate one candidate and then transfer the surplus votes to the next preferred candidate COMP 2600 Hoare Logic 2

Australian Capital Territory Election Software Australian Capital Territory elections use Single Transferable Voting If we have C candidates for S < C vacancies you rank all candidates in order of your preference: John, Mary,..., Tony Counting such ballots proceeds in rounds where in each round we count up the votes for each candidate, elect or eliminate one candidate and then transfer the surplus votes to the next preferred candidate The ACT Electoral Commission uses a computer program to count the votes cast for elections Is it safe? COMP 2600 Hoare Logic 3

Australian Capital Territory Election Software Australian Capital Territory elections use Single Transferable Voting If we have C candidates for S < C vacancies you rank all candidates in order of your preference: John, Mary,..., Tony Counting such ballots proceeds in rounds where in each round we count up the votes for each candidate, elect or eliminate one candidate and then transfer the surplus votes to the next preferred candidate The ACT Electoral Commission uses a computer program to count the votes cast for elections Is it safe? Bugs? We have found three: all could have changed the outcome! Verification COMP 2600 Hoare Logic 4

What gets verified? Hardware Compilers Programs Specifications, too... How do we do it? Informally analysing the code Testing: Program testing can be used to show the presence of bugs, but never to show their absence! - Edsger Dijkstra Formal verification COMP 2600 Hoare Logic 5

Formal Program Verification Formal program verification is about proving properties of programs using logic and mathematics. In particular, it is about proving they meet their specifications proving that requirements are satisfied COMP 2600 Hoare Logic 6

Why verify formally? Proofs guarantee (partial) correctness of program. Formal proofs are mechanically checkable. Good practice for ordinary programming. Why not verify formally? Time consuming. Expensive. COMP 2600 Hoare Logic 7

Formal or Informal? The question of whether to verify formally or not ultimately comes down to how disastrous occasional failure would be. The website of UK-based formal software engineers Altran Praxis http:// www.altran-praxis.com showcases many of the industries that are most likely to take the formal route. COMP 2600 Hoare Logic 8

Verification for Functional Languages Haskell is a pure functional language, so: Equations defining functions really are equations Therefore, we can prove properties of Haskell programs using standard mathematical techniques such as: substitution of equal terms arithmetic structural induction, etc. We saw some of this last week. COMP 2600 Hoare Logic 9

Verification for Imperative Languages Imperative languages are built around a program state (data stored in memory). Imperative programs are sequences of commands that modify that state. To prove properties of imperative programs, we need A way of expressing assertions about program states. Rules for manipulating and proving those assertions. These will be provided by Hoare Logic. COMP 2600 Hoare Logic 10

C. A. R. (Tony) Hoare The inventor of this week s logic is also famous for inventing the Quicksort algorithm in 1960 - when he was just 26! A quote: Computer programming is an exact science in that all the properties of a program and all the consequences of executing it in any given environment can, in principle, be found out from the text of the program itself by means of purely deductive reasoning. COMP 2600 Hoare Logic 11

Logic = Syntax and (Semantics or Calculus) Syntax: special language from which we build formulae Semantics: the way in which we assign truth to formulae via models Validity: fundamental notion from semantics Calculus: symbol manipulation rules which allows us to construct proofs Provable: fundamental notion from calculus Soundness and Completeness: provable if and only if valid CPL Syntax: connectives,,, and atomic formulae p,q,r CPL Semantics: model assigns true/false to each atomic formula and truth tables allow us to lift this to truth value of larger formulae ND calculus: a finite set of rules, and regulations on how to use them COMP 2600 Hoare Logic 12

Classical Prop Logic = Syntax and (Semantics or Calculus) Syntax Semantics Calculus atomic formulae truth values Natural Deduc- p,q,r {true, f alse} tion connectives,,, truth tables rules of inference formulae A,B,C satisfiable rule instance validity proof Soundness and Completeness: formula A provable if and only if A valid COMP 2600 Hoare Logic 13

Hoare Logic = Syntax and (Semantics or Calculus) Syntax Semantics Calculus CPL f ormulae CPL semantics (ND) if pre-state satisfies P Hoare Triple {P} S {Q} and program S terminates then post-state satisfies Q rules of proof {x = 1} x := x + 1 {x = 2} if pre-state satisfies x = 1 and program x := x + 1 terminates then post-state satisfies x = 2 proo f rule? COMP 2600 Hoare Logic 14

Hoare Logic: A Simple Imperative Programming Language Syntax of the programming language component S from a Hoare triple To prove things about programs, we first need to fix a programming language. For this we ll define a little language with four different kinds of statement. Assignment x := e where x is a variable, and e is an expression built from variables and arithmetic that returns a number, e.g. 2 + 3, x y + 1... Sequencing S 1 ;S 2 Conditional if b then S 1 else S 2 where b is an expression built from variables, arithmetic and logic that returns a boolean (true or false), e.g. y < 0, x y z = 0... While while b do S COMP 2600 Hoare Logic 15

A Note on (the lack of) Aliasing Suppose we had the code fragment x := y This looks up the number value of y and copies it into the piece of memory pointed to by x. Now they both have the same number value. It does not make the variables x and y point to the same piece of memory. So if the next line of the program is x := x + 1 then after that it is no longer the case that x = y. COMP 2600 Hoare Logic 16

Syntax: Three Components of Hoare Triples 1. A precondition 2. A code fragment 3. A postcondition The precondition is an assertion saying something of interest about the state before the code is executed. The postcondition is an assertion saying something of interest about the state after the code is executed. COMP 2600 Hoare Logic 17

Semantics: notion of a state A state is determined by the values given to the program variables In this course all our variables will store numbers only. COMP 2600 Hoare Logic 18

Syntax of Preconditions and Postconditions So all our assertions about the state will be built out of variables, numbers, and basic arithmetic relations: x = 3; x = y; x y; x > 0; x (y 2 + 1 3 4 ); etc... COMP 2600 Hoare Logic 19

Syntax of Preconditions and Postconditions ctd. We may want to make complicated claims about several different variables, so we will use propositional logic to combine the simple assertions, e.g. x = 4 y = 2; x < 0 y < 0; x > y x = 2 y; True; False. The last two logical constructions - True and False - will prove particularly useful, as we ll later see. COMP 2600 Hoare Logic 20

A Rough Guide to Hoare Logic Semantics Hoare logic will allow us to make claims such as: If (x > 0) is true before y := 0-x is executed then (y < 0 x y) is true afterwards. In this example, (x > 0) is a precondition; y := 0-x is a code fragment; (y < 0 x y) is a postcondition. This particular assertion is intuitively true; we will need to learn Hoare logic before we can prove this, though! COMP 2600 Hoare Logic 21

Hoare s Notation the Definition The Hoare triple: {P} S {Q} means: If P is true in the initial state and S terminates then Q will hold in the final state. Examples: 1. {x = 2} x := x+1 {x = 3} 2. {x = 2} x := x+1 {x = 5000} 3. {x > 0} y := 0-x {y < 0 x y} COMP 2600 Hoare Logic 22

A Larger Hoare Triple {n 0} fact := 1; while (n >0) fact := fact * n; n := n -1 {fact = n!} Question - what if n < 0? COMP 2600 Hoare Logic 23

Partial Correctness Hoare logic expresses partial correctness. We say a program is partially correct if it gives the right answer whenever it terminates. It never gives a wrong answer, but it may give no answer at all. {P} S {Q} does NOT imply that S terminates, even if P holds initially. For example {x = 1} while x=1 do y:=2 {x = 3} is true in Hoare logic semantics ie if pre-state satisfies x = 1 *and* the while loop terminates then the poststate satisfies x = 3 (but the while loop does not terminate) COMP 2600 Hoare Logic 24

Partial Correctness is OK Why not insist on termination? We may not want termination. It simplifies the logic. If necessary, we can prove termination separately. We will come back to termination next week with the Weakest Precondition Calculus. COMP 2600 Hoare Logic 25

There s not much point writing stuff down unless you can do something with it... We can use pre- and postconditions to specify the effect of a code fragment on the state, but how do we prove or disprove a Hoare Triple specification? Is {P} S {Q} true? We need a calculus: a collection of rules and procedures for (formally) manipulating the (language of) triples. (Just like ND for classical propositional logic... ) We will now turn to developing and applying a basic version of Hoare Logic. COMP 2600 Hoare Logic 26

The Assignment Axiom (Rule 1/6) We will have one rule for each of our four kinds of statement (plus two other rules, as we ll see). First, we look at assignment. Assignments change the state so we expect Hoare triples for assignments to reflect that change. Suppose Q(x) is a predicate involving a variable x, and that Q(e) indicates the same formula with all occurrences of x replaced by the expression e. The assignment axiom of Hoare Logic: one line proof {Q(e)} x := e {Q(x)} COMP 2600 Hoare Logic 27

The Assignment Axiom Intuition {Q(e)} x := e {Q(x)} If we want x to have some property Q after the assignment, then that property must hold for the value (e) assigned to x - before the assignment is executed. You might ask if this rule is backwards and should be {Q(x)} x := e {Q(e)} But this is wrong: if we tried to apply this axiom to the precondition x = 0 and code fragment x := 1 we d get {x = 0} x := 1 {1 = 0} which says if x = 0 initially and x := 1 terminates then 1 = 0 finally COMP 2600 Hoare Logic 28

Work from the Goal, Backwards It may seem natural to start at the precondition and reason towards the postcondition, but this is not the best way to do Hoare logic. Instead start with your goal (postcondition) and go backwards. e.g. to apply the assignment axiom {Q(e)} x := e {Q(x)} take the postcondition, copy it across to the precondition, then replace all occurrences of x with e. Note that the postcondition may have no, one, or many occurrences of x in it; all get replaced by e in the precondition. COMP 2600 Hoare Logic 29

Example 1 of {Q(e)} x := e {Q(x)} Consider the code fragment x:=2 and suppose that the desired postcondition is (y = x). Our precondition is found by copying the postcondition y = x over, then replacing our occurrence(s) of the variable x with the expression 2. Formally: {y = 2} x:=2 {y = x} is an instance of the assignment axiom. COMP 2600 Hoare Logic 30

Example 2 of {Q(e)} x := e {Q(x)} Consider the code fragment x:=x+1 and suppose that the desired postcondition is (y = x). We proceed as in the last slide: {y = x + 1} x:=x+1 {y = x} COMP 2600 Hoare Logic 31

Example 3 of {Q(e)} x := e {Q(x)} How might we try to prove {y > 0} x:=y+3 {x > 3}? Start with the postcondition x > 3 and apply the axiom: {y + 3 > 3} x:=y+3 {x > 3} Then use the fact that y + 3 > 3 is equivalent to y > 0 to get our result. You can always replace predicates by equivalent predicates; just label your proof step with precondition equivalence, or postcondition equivalence. COMP 2600 Hoare Logic 32

Proving the Assignment Axiom sound w.r.t. semantics Recall that the assignment axiom of Hoare Logic is: {Q(e)} x := e {Q(x)} Why is it so? Let v be the value of expression e in the initial state. If Q(e) is true initially, then so is Q(v). Since the variable x has value v after the assignment (and nothing else is changed in the state), Q(x) must be true after that assignment. COMP 2600 Hoare Logic 33

The Assignment Axiom is Optimal The Hoare triple in the assignment axiom is as strong as possible. {Q(e)} x := e {Q(x)} That is, if Q(x) holds after the assignment then Q(e) MUST have held before it. Why? Suppose Q(x) is true after the assignment. If v is the value assigned, Q(v) is true after the assignment. Since it is only the value of x that is changed, and the predicate Q(v) does not involve x, Q(v) must also be true before the assignment. Since v was the value of e before the assignment, Q(e) is true initially. COMP 2600 Hoare Logic 34

A non-example What if we wanted to prove {y = 2} x:=y {x > 0}? This is clearly true. But our assignment axiom doesn t get us there: {y > 0} x:=y {x > 0} We cannot just replace y > 0 with y = 2 either - they are not equivalent. We need a new Hoare logic rule that manipulates our preconditions (and while we re at it, a rule for postconditions as well!). COMP 2600 Hoare Logic 35

COMP 2600 Hoare Logic 36

Hoare Logic = Syntax and (Semantics or Calculus) Syntax Semantics Calculus CPL predicates CPL semantics No ND! variables x,y,z arithmetic expressions 1 + 2,x < y, and predicates built from them states map variables and expressions to values and predicates to true/false rules of arithmetic e.g 1 + 2 = 3, 2 2 = 4, 6/3 = 2 etc programming language := ; if.then. while as usual one rule for each (seen rule for :=) Hoare Triple {P} S {Q} if pre-state satisfies P and S terminates then post-state satisfies Q proo f COMP 2600 Hoare Logic 37

Summary of Lecture 1 Hoare triple syntax: {P} S {Q} Proof Rule for Assignment: {Q(e)} x := e {Q(x)} Hoare triple Semantics (meaning): If P is true in the initial state and S terminates then Q will hold in the final state. One line proof: Any triple that looks like this is (defined to be) provable and Soundness: is guaranteed to be true Examples: Hoare triple true? Provable by assignment axiom? {x + 1 = 3} x := x+1 {x = 3} yes yes {y > 2} x := y {x > 2} yes yes {y = 3} x := y {x > 2} yes no... need more rules... COMP 2600 Hoare Logic 38