2. SPARK Ada

184
2. SPARK Ada (a) Architecture of SPARK Ada. (b) Language Restrictions in SPARK Ada. (c) Data Flow Analysis. (d) Information Flow Analysis. (e) Verification Conditions. (f) Example: A railway interlocking system. Remark: Sections (a) - (e) will be heavily based on John Barnes [Ba03a]. CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sect. 2 2-1

Transcript of 2. SPARK Ada

2. SPARK Ada

(a) Architecture of SPARK Ada.

(b) Language Restrictions in SPARK Ada.

(c) Data Flow Analysis.

(d) Information Flow Analysis.

(e) Verification Conditions.

(f) Example: A railway interlocking system.

Remark: Sections (a) - (e) will be heavily based onJohn Barnes [Ba03a].

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sect. 2 2-1

(a) Architecture of SPARK AdaMotivation for Developing Ada:

Original problem of Department of Defence in USA(DOD):

Too many languages used and created for militaryapplications (>450).

Languages largely incompatible and not portable.Often minimal software available.Competition restricted, since often only one vendorof compilers and other tools for one language.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (a) 2-2

AdaExisting languages too primitive.

No modularity.Hard to reuse.

Problems particularly severe in the area ofembedded systems.

56% of the software cost of DOD in 1973 forembedded systems.

Most money spent on maintaining software, notdeveloping it.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (a) 2-3

AdaDecision by DOD: Development of new standardprogramming language for military applications.

Name Ada = name of Ada Lovelace (1815-1852).Wrote programs for Babbage’s computer.Therefore called “the first computer programmer”.

First release: Ada 83(1983 – same year C++ was released).

Ada 95: Revision of Ada, integration ofobject-orientation.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (a) 2-4

Reasons for Using Ada in Crit. SystemsAda is the often required standard for militaryapplications in the US , and has therefore adoptedby the Western military industry.Software for military applications forms a largeportion of critical systems .Therefore lots of tools for critical systems supportAda .

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (a) 2-5

Reasons for Using AdaAda was developed taking into account its use inreal-time critical systems:

It is possible to write efficient code and code close toassembler code, while still using high levelabstractions.Features were built in which prevent errors (e.g.array bound checks, no writing to arbitrary memorylocations).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (a) 2-6

Misc. Language Features of AdaTyping is written as in Haskell

We write x : A for “x has type A” .In Java or C this is written as “A x”.

We have enumeration types. E.g.type Gender is (male,female);

introduces a new type having elements male andfemale.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (a) 2-7

Ranges in AdaAda allows to define ranges.

type year is range 0..2100;defines the type of years as integers between 0 and2100.

We have as well subranges of enumerations:If Day is of type

(Mon, Tue,Wed,Thu,Fri,Sat,Sun) ,then we can form the subrange

Mon . . . Wed

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (a) 2-8

Misc. Language Features of AdaThe basic loop statement is an infinite loop with an exitstatement. E.g.

Answer : Character;loop

Put(“Answer yes (y) or no (no)”);Get(Answer);if Answer = ’y’ then

Put_Line (“You said yes”);exit ;

elsif Answer = ’n’ thenPut_Line (“You said no”);exit ;

elsePut_Line (“You must type y or n”);

end if ;end loop ;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (a) 2-9

Misc. Language Features of Ada“For loops” are written as follows:

for N in 1..20 loopPut (“-”);

end loop ;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (a) 2-10

Record Types in AdaA record is essentially a class without methods.Syntax in Ada: type Person is

recordyearOfBirth : Integergender : Gender

end recordThis example declares a type Person which has twofields yearOfBirth and gender.

If a: Person, then we have that a.yearOfBirth : Integerand a.gender : Gender.

One can make assignments like a.gender = male.

If a : Person one can give a value to its fields by sayinga = (1975,male)or a = (year => 1975,gender => male)

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (a) 2-11

SPARK AdaSubset of Ada.

Original definition by B. Carré and T. Jennings, Univ.of Southampton, 1988.Several revisions carried out by Praxis CriticalSystems Ltd.Adapted to Ada95Commercial tools available from Praxis CriticalSystems.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (a) 2-12

SPARK AdaAnnotations to Ada.

Some required for data and information flowanalysis.Others allow to generate and prove verificationconditions.It is as well possible to integrate unchecked or evenunimplemented Ada code.

SPARK Ada code compiles with standard Adacompilers.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (a) 2-13

Architecture of the SPARK AdaSPARK-examiner.

Verifies the following:Correct Ada syntax.SPARK-subset of Ada chosen, as describedabove.

Carries out three levels of analysis:Data flow analysis .Information flow analysis.Generation of verification conditions.

SPADE-simplifier.Simplifies verification conditions of the examiner.Trivial ones are already proved.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (a) 2-14

Architecture of the SPARK Ada⇓

SPADE-proof-checker.Proof tool for interactively proving verificationconditions.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (a) 2-15

Three Levels of AnalysisData flow analysis.

Checks input/output behaviour of parameters andvariables.Checks initialisation of variables.Checks that changed and imported variables areused later (possibly as output variables).

Information flow analysis.Verifies interdependencies between variables.

Verification conditions.Generation of verification conditions, which allow toprove correctness of programs.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (a) 2-16

Three Levels of AnalysisIdea is that the 3 different levels of analysis are applieddepending on the criticality of the program.

(Some parts of the program might not be checked at all).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (a) 2-17

AnnotationsCertain annotations are added to the programs.

Specific to the 3 levels of analysis.

Written as Ada comments :Ignored by Ada compilers.Used by the SPARK Ada tools.Syntax: start with --#, e.g.--# global in out MyGlobalVariable;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (a) 2-18

(b) Lang. Restrict. in SPARK Ada

Factors for Programming LanguagesAddressed by SPARK Ada

Logical Soundness.Problem: statement like Y:=F(X) + G(X):Order of evaluation not specified.Problem if F(X) and G(X) have side effects.

E.g. F(X) has effect Z:=0,G(X) has effect Z:= 1.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-19

SPARK Ada ConceptsSolution in many languages: define order ofevaluation.Not possible, if SPARK Ada should compile onstandard compilers.Solution in SPARK Ada:Functions are not allowed to have side-effects.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-20

SPARK Ada ConceptsSimplicity of language definition.

Omission of too complex principles.No variant records.· (Dependent types, but no complete compile time

checking).No threads (concurrency).No generic types.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-21

Remark on Variant RecordsVariant record means that we have a record, s.t. the thetype of one field depends on the value of some othertype.

Example:type Gender is (Male, Female);

type Person(Sex: Gender:= Female) isrecord

Birth: Date;case Sex is

when Male =>

Bearded: Boolean;when Female =>

Children: Integer;end case ;

end record;CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-22

Remark on Variant RecordsIn the above example the type Gender is defined as atype having two elements, namely Male and Female.

Person is a type, which has a field Sex, Birth, anddepending on the field Sex either a field Bearded or afield Children.

By default, Person.Gender = Female.

We can have elements of type Person and of typePerson(Male).

If John: Person(Male), then John.Sex=Male.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-23

Remark on Variant RecordsWhether the field of a variant record accessed is in thevariant used cannot always be checked at compiletime .

For instance, if we havea: Person ,

a code which accessesa.Bearded

compiles, even if it is clear thata.Sex=Female .

But this will cause a run time error.In case of

a: Person(Female) ,a warning is issued at compile time if

a.Beardedis accessed.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-24

Remark on Variant RecordsVariant records are a restricted form of dependenttypes (see module on interactive theorem proving).

In dependent type theory, as introduced there,such kind of constructs can be used in a type safeway.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-25

SPARK Ada ConceptsExpressive power.

Hiding of variables allowed.Allows to specify strong assertions about variables(e.g. that a variable is only read but not written, oronly written but not read).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-26

SPARK Ada ConceptsSecurity.

Features already supported by Ada:Array bound are checked.Programs does not stray outside thecomputational model (one cannot jump or write toan arbitrary memory location).

Feature enforced by SPARK Ada:In order to be verifiable at compile-time:· Constraints (array bounds, ranges) have to be

static (determined at compile time).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-27

SPARK Ada ConceptsVerifiability

Support of automated verifiability :Extra annotations

control of data flow,control of information flow,proof annotations (more below).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-28

SPARK Ada ConceptsSupport of Verifiability (Cont.)

Support of verification by hand:Every fragment of code has a single entry point andlimited exit points.

Procedures have no return statements (= exitfrom the procedure).Functions have exactly one return statement,which must be the last statement.One can break out of a loop by the so called exitstatement, but this exit cannot be· inside another loop,· inside nested if-then-elses,· inside another for-loop.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-29

SPARK Ada ConceptsExample:

The following is legal(loop is an infinite loopwhat is in other languages written as while (true) ):

loop· · ·if some_condition then

· · ·exit;

end if;· · ·

end loop;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-30

SPARK Ada ConceptsThe following is illegal:

loop· · ·if some_condition then

if another_condition then· · ·exit;

end if;· · ·

end if;end loop;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-31

SPARK Ada ConceptsExit from loops only possible to innermost loop:The following Ada code is illegal in SPARK Ada:

Outer_Loop:for J in 1 . . . M loop

· · ·for K in 1 . . . M loop

. . .

exit Outer_loop when A = 0;. . .

end loop;· · ·

end loop Outer_Loop;-- when exit statement is executed,-- we continue here

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-32

SPARK Ada ConceptsHowever, the following is legal (if one makes therange more explicit, see later):

for J in 1 . . . M loop· · ·exit when A = 0;· · ·

end loop ;-- when exit statement is executed,-- we continue here

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-33

SPARK Ada ConceptsNo structures which are too complex to grasp.

Almost no subtyping.

Omit Details about Subtyping

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-34

SPARK Ada ConceptsDetails about restrictions on subtyping inSPARK Ada.

No derived types (essentially a new name for anexisting type or a subrange for an existing type).No type extension (extension of a record byadding further components).No class-wide types (see next slide).Therefore no late binding (called dispatching inAda).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-35

Class-Wide TypesIn Ada, when introducing a class MyClass, one obtainstwo types:

MyClassOnly elements of MyClass itself, but not of anyderived type (in other languages called subtype) ofit are elements of this type.This means that we have

::::::

early:::::::::::

binding : theimplementation of a method or function used foran element of this type can be determined atcompile time.In C++ methods which are non-virtual have earlybinding: they cannot be overridden by subtypes.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-36

Class-Wide Typesthe

::::::::::::::

class-wide::::::

type MyClass’Class.Elements of MyClass and of derived types belongto this type.This means that we have

:::::

late::::::::::

binding : theimplementation of a method to be used for anelement of this type depends on the actual type ofthe element and can only be determined atrun-time.In Java we have only class-wide types.In C++ we have as well only class-wide types, butone can control subtyping by using the keywordvirtual :· Only virtual methods have late binding.· Only virtual methods can be overridden.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-37

Class-Wide TypesProblem of inheritance: properties are inheritedremotely, which makes it difficult to verify programs.

If one has a class-wide type A with subtype B, andtwo different functions f(x:A) and f(x:B), then one· might expect that a call of f(a) for a:A refers to

the first definition,· but in fact, if a:B it will refer to the second

definition.· That redefinition could have been done by a

different programmer in a different area of thecode.

However elements of a subtype in the sense of therestriction of the range of a type (e.g. Integerrestricted to 0 . . . 20) can be assigned to elements ofthe full type.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-38

Object-Orientation in AdaAda’s concept of object-orientation is restricted.

Ada allows to form record types (essentially classeswith instance variables but not methods).Ada has the concept of a class wide type, whichallows to form polymorphic functions.So instead of

having a method f of a class C with parametersx1:A1 ,. . ., xn:An, and then writing O.f(x1 ,. . ., xn)for a method call for object O: C,one has to introduce a polymorphic function f witharguments X: C’Class,x1:A1 ,. . ., xn:An, and thento write f(O,x1 ,. . ., xn) for the call of this function.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-39

Object-Orientation in AdaDisadvantage: The definition of the functions can bedefined completely separted from the definition of theclass.

Advantage: More flexibility since one doesn’t have todecide for a function, to which object it belongs to.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-40

SPARK Ada Concepts

Language should be as explicit as possible.No polymorphism (ie. that an operation is definedfor different types):

No overloading of functions.No array sliding :Assignment, comparison, operations on arraysonly allowed on arrays with same array index sets.· Ada behaves in an unexpected way in this case.· No concatenation of arrays allowed.· However, for strings such kind of operations are

allowed.No default parameters, default recordcomponents.However standard +, ∗ are overloaded.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-41

SPARK Ada Concepts(Language should be as explicit as possible, cont.)

No anonymous subtypes.Instead of:type Vector is array (0. . .100) of Integer;one has to writetype Vector_index is range 0. . .100;type Vector is array (Vector_index) of Integer;Exception: In for loops , one can use anonymoussubtypes, but one has to explicitly introduce thetype, one is forming a subtype of:· Instead of

for I in 0. . .100 loopone has to writefor I in Integer range 0. . .100 loop

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-42

SPARK Ada Concepts(Language should be as explicit as possible, cont.)

Unique names of entities at a given place:Package variables have to be used explicitly:A variable X of a package Mypackage has to bereferenced as Mypackage.X

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-43

SPARK Ada ConceptsBounded space and time requirements.

Recursion disallowed.No arrays without bounds or with dynamicallyallocated bounds.

Can be declared, but only subtypes of it can beused.

No pointers (called access types in Ada).The above guarantees bounded space.

The space used is exactly that used by all thevariables declared in all packages involved.No additional space is allocated by pointers,allocation of space for arrays.No additional space is used by recursion.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-44

SPARK Ada ConceptsBounded time difficult to guarantee.

One can theoretically determine whether a programusing bounded space terminates:

Such a program has finitely many states .(Only finite amount of information can be stored inbounded space).If a program doesn’t terminate, it needs to enterthe same state twice .That can be checked.

But this is only a theoretical result .The bounds for termination easily exceed the lifetime of the universe.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-45

SPARK Ada ConceptsOne could guarantee bounded time by allowingonly for-loops.· With some further restrictions one could even

obtain polynomial time bounds.· But in general disallowing unrestricted loops

would be too restricting.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (b) 2-46

(c) Data Flow Analysis

Data Flow Analysis – Parameters

In Ada all parameters have to be labelled asinput parameters; symbol: in ,

The same as a non-var parameter in Pascal.output parameters; symbol: out ,input/output parameters; symbol: in out .

The same as a var parameter in Pascal.

Example:procedure ABC(A: in Float;

B: out Integer;C: in out Colour)

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (c) 2-47

In – Out – In Out Parametersout and in out parameters can only by instantiated byvariables.

Assume for instance a procedureprocedure Myproc(B: out Integer)

is beginB:= 0;end Myproc;

It doesn’t make sense to make a callMyproc(0)

it only makes sense to callMyproc(C)

where C is a variable that can be changed.

We see as well that the variable we instantiate it withcannot be an in parameter itself, because then it cannotbe changed.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (c) 2-48

In – Out – In Out Parametersin parameters can be instantiated by arbitrary terms.

Consider:

procedure Myproc(B: in Integer,C: out Integer)is beginC:= B;end Myproc;

It makes sense to callMyproc(0,D)

where D is a variable that can be changed.It makes as well sense to call

Myproc(3 + 5,D)or

Myproc(f(E,F),D)where f is a function with result type Integer.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (c) 2-49

In – Out – In Out ParametersIn Java

Parameters which have type some object orinterface (including arrays), behave like in outparameters in Ada,Parameters of non-object types (int, float, . . .) arebehave like in parameters.

Rules for instantiation are similar:Object-parameters can only be instantiated byvariables.Non-object parameters can be instantiated byarbitrary terms (of the right type).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (c) 2-50

Data Flow Analysis – ParametersExaminer verifies that

Input parameters arenot modified ,but used at least once ,· not necessarily in every branch of the program;

output parameters arenot read before being initialised ,initialised .· Has to take place in all branches of the program.

input/output parameters areread,and changed.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (c) 2-51

Data Flow Analysis – Global VariablesGlobal variables must be given status as input or outputor input/output variables by annotations .

Syntax examples:--# global in A;--# global out B;--# global in out C;

Data flow analysis carries out the same analysis as forparameters.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (c) 2-52

Data Flow Analysis – FunctionsFunctions can have only input parameters (no keywordrequired).

Functions have only read access to global parameters.Therefore the syntax for global parameters is simply--# global A;or--# global A,B,C;

Neither parameters nor global variables can bechanged.Therefore functions don’t have side effects.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (c) 2-53

Data Flow Analysis – PackagesPackage variables = variables global to a package.

Package variables must be declared by annotations.Syntax example:--# own X,Y;

If a variable is initialised it has to be declared; whether itis initialised will be verified.Syntax example:--#initializes X;

However, even an uninitialised package variable isallowed to be used by a procedure.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (c) 2-54

Data Flow Analysis – PackagesIf a package is used it has to be declared:Syntax example:--#inherits Mypackage;

In Ada a package inherits anything froma package surrounding it,and packages inherited by with · · · .· with is the import statement in Ada.

In SPARK-Ada we have to specify, which ones ofthese are actually used in that package.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (c) 2-55

Example (Data Flow Analysis)Consider the following wrong program, which shouldexchange X and Y:procedure Exchange(X,Y: in out Float)isT:Float;

beginT:= X; X:= Y; Y:= X;

end Exchange;

Mistake: body should be:T:= X; X:= Y; Y:= T;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (c) 2-56

Example (Data Flow Analysis)procedure Exchange(X,Y: in out Float)isT:Float;

beginT:= X; X:= Y; Y:= X;

end Exchange;

Data flow analysis results in 3 error messages:T:= X is an ineffective statement.Import of initial value of X is ineffective.T is neither referenced nor used.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (c) 2-57

Example2 (Data Flow Analysis)Here is another wrong program, which should exchangeX and Y:

procedure Exchange(X,Y: in out Float)isbeginX:= Y; Y:= X;end Exchange;

Data flow analysis results in error message:Importation of initial value of X is ineffective.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (c) 2-58

Example 3Assume a procedure with body

Y := X;Z := Y;

ThenThe value of X is used, but never changed.· So X is an input variable (keyword “in ”).The value of Y is changed, but the original value isnever used· It seems to be used in the 2nd line, but what is

used is actually the value of X.· So Y is an output variable, but not an input

variable (keyword “out ”).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (c) 2-59

Example 3

Y := X;Z := Y;

The value of Z is changed, but not used.So Z is an output variable (keyword “out ”).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (c) 2-60

(d) Information Flow Analysis

Additional annotations on how variables depend oneach other.Syntax examples:--#derives X from Y;or, if we have several dependencies--#derives X from Y &--# Y from X;

or, if X gets a value independent of other variables,--#derives X from ;

Often the new value of a variable depends on its ownvalues, so we have--#derives X from X;or--#derives X from X, Y;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (d) 2-61

Information Flow AnalysisInformation flow verifies that these dependencies arefulfilled

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (d) 2-62

ExampleConsider the following wrong program, which shouldexchange X and Y and count the number of exchangesin Z:

procedure ExchangeAndCount(X,Y,Z: in out Integer)--#derives X from Y &--# Y from X &--# Z from Z;isT: Integer;begin

T:= X; X:= Y; Y:= T; Z:= Z + T;end ExchangeAndCount;

The error is the line Z:= Z + T;should be replaced by Z:= Z + 1;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (d) 2-63

ExampleData flow analysis succeeds without problems.

Information flow analysis gives warning, since Zdepends on Z and X (via T).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (d) 2-64

Example 2Assume as in data flow analysis example 3 a procedurewith body

Y := XZ := Y

X does not derive from anywhere , since it is notchanged (no output variable).Y derives from X .Z derives from X , (not from Y!).Note that

only output and input/output variables can derivefrom somewhere,and they can only derive from input andinput/output variables.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (d) 2-65

2

2-65-1

(e) Verification Conditions.

Verification Conditions for Procedures without Loops

Two kinds of annotations are relevant:Pre-conditions, e.g.:--#pre M >= 0 and N < 0;Post-conditions, e.g.:--#post M = M∼ +1;

Then examiner generates formulas which express:If the pre-conditions hold, and the procedure isexecuted, afterwards the post-condition holds.

If there are no pre-conditions, then the formulaexpresses that the post-condition holds always.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-66

Hoare CalculusThe basic formal system which takes pre- andpost-conditions in an imperative program and generatesverification conditions, is called the

::::::::

Hoare::::::::::::

Calculus

Named after Sir Tony Hoare (Professor emeritus fromOxford and Microsoft Research, Cambridge), ComputerScientist.

Winner of the Turing Award 1980.

Knighted by the Queen for his achievements inComputer Science.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-67

Tony Hoare with his Wife Jill

(After having been knighted by the Queen.)

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-68

Verification ConditionsIn post-conditions,

X∼ stands for the value of X before executing theprocedure,X stands for the value after executing it,e.g. X=X∼+1; expresses:The value of X after executing the procedure is thevalue of X before executing it + 1.

Formulas are built using:Boolean connectives and , or , not , xor , ->, <->

quantifiers for all , for some .

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-69

Remark on X ∼

X∼, Y∼ can only be used if X, Y are input and outputparameters or global in out variables.

If X is only an input variable, it won’t change, so X isalways equal to X∼.If X is only an output variable, then the initial value ofX is undefined.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-70

Example (Verification Conditions)Assume the following wrong program:

procedure Wrongincrement(X: in out Float);--# derives X from X;--# pre X >=0.0;--# post X = X∼ + 1.0;is beginX := X + X;

end Wrongincrement;

The mistake in this program is that the body shouldread X := X + 1.0; instead of X := X + X;.

The post-condition is not fulfilled in general.(The pre-condition has no significance in this exampleand is only used in order to introduce the syntax).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-71

Example (Cont.)procedure Wrongincrement(X: in out Float);--# derives X from X;--# pre X >=0.0;--# post X = X∼ + 1.0;is beginX := X + X;

end Wrongincrement;

When going through the program we see that at the endX = X∼ + X∼.

Therefore, replacing X by X∼ + X∼ the post conditionreads:

X∼ + X∼ = X∼ + 1

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-72

Example (Verification Conditions)Since in the resulting formula, each variable hasattached the symbol ∼, the examienr uniformely omitsthe ∼ and generates the formulaH1: x>=0.H2: true.->

C1: x+x =x + 1.

which is not provable.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-73

Example (Verification Conditions)The statements of the form “true” generated by theexaminer above correspond probably to conditions ofthe variables.

If one has a variable X in a range 0 . . . 10, then forthis variable one would have a pre-condition0 ≤ x and x ≤ 10.

(SPARK-Ada puts variables into lowercase.)Integer variables lie as well in a range, namelybetween the minimum integer and the maximuminteger.

These values are called integer__first andinteger__last.So there we get additionally the conditionsx ≥ integer__first and x ≤ integer__last.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-74

Example (Verification Conditions)For floating point numbers, there are no conditions onthe ranges, so the examiner generates “true”.

In Ada, variables are not case-sensitive. Therefore theexaminer replaces variables by lower case versions, inorder to get a unique form.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-75

Example (Verification Conditions)The above formulae have to be treated as beingimplicitly universally quantified,

so the formula above stands for

∀x.((x ≥ 0.0 ∧ true) → (x + x = x + 1.0))

This corresponds to what the correctness of thefunction means:

For all inputs x, we have that, if x fulfils theprecondition, then after executing the program itfulfils the post condition.

That the above formula is unprovable can be shown bygiving a counter example:

Take x := 0.0. Then (x ≥ 0.0 ∧ true) holds, but not(x + x = x + 1.0).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-76

Example2 (Verification Conditions)Assume the correct program:

procedure Correctincrement(X: in out Float);--# derives X from X;--# pre X >=0.0;--# post X = X∼ + 1.0;isbeginX := X + 1.0;

end Correctincrement;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-77

Example 2 (Cont.)procedure Wrongincrement(X: in out Float);--# derives X from X;--# pre X >=0.0;--# post X = X∼ + 1.0;isbeginX := X + 1.0;

end Wrongincrement;

When going through the program, we see that at theend

X = X∼ + 1.0.

Therefore the post condition readsX∼ + 1.0 = X∼ + 1.0.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-78

Example2 (Verification Conditions)The examiner replaces again X∼, Y∼ by X, Yrespectively and generates the formula:H1: true.H2: true.->

C1: x + 1 = x + 1.

“true” stands again probably for trivial conditions on theranges of the variable (see above).

The simplifier shows that this is provable

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-79

Check ConditionsOne can insert in between the procedures a checkcondition.

Now the formulas express:From the pre-condition follows at that position thecheck-condition.From the pre-condition and the check-condition atthat position follows the post-condition.Check conditions serve therefore as intermediateproof-goals.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-80

Example Check ConditionConsider the program:procedure Onecheckfun(X: in out Integer)--# derives X from X;--# pre X = 0;--# post X = 2;

isbegin

X:= X+1;--# check X = 1;X:= X +1;

end Onecheckfun;

That the pre condition implies the check condition is thefollowing verification condition:X∼ = 0 → X∼+1 = 1;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-81

Example Check ConditionConsider the program:procedure Onecheckfun(X: in out Integer)--# derives X from X;--# pre X = 0;--# post X = 2;

isbegin

X:= X+1;--# check X = 1;X:= X +1;

end Onecheckfun;

That the pre and the check condition implies the postcondition is the following verification condition:(X∼ = 0 ∧ X∼+1 = 1) → (X∼+1) + 1 = 2;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-82

Generated Verification ConditionsThe Examiners generates:

H1: x = 0 .H2: x >= integer__first .H3: x <= integer__last .

− >

C1: x + 1 = 1 .

and

H1:x = 0 .H2:x >= integer__first .H3:x <= integer__last .H4:x + 1 = 1 .

− >

C1:x + 1 + 1 = 2 .

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-83

Check and AssertThere is as well an assert directive with similar syntaxas the check directive.

Syntax --# assert T > 0.0;

The difference is:If one has an assert directive, then the verificationcondition is that

From the pre condition follows the assert condition(taking into account changes to variables inbetween).From the assert condition follows the postcondition.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-84

Check and AssertIf one has a check directive, then the first verificationcondition is as before but the second verificationcondition states instead

From the pre condition and the check conditionfollows the post condition.

So the pre-condition is not lost if one has a checkcondition, which makes it easier to prove this result.

Assert condition should mainly be used in loops (wherereuse of the pre-condition is not possible; see below);

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-85

Return ConditionsIf one has functions, one can either state the result ofthe function:E.g.--# return X+1expresses: the result is X+1.or one can associate with the result a variable and acondition. E.g. one can write:--# return X => X > Y;if Y is a parameter or a global parameter.The example expresses:the returned value is > Y.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-86

Examplefunction Tmpfun (X: Integer) return Integer–# pre X > 0;–# return R => R > 1;isbegin

return X + 1;end Tmpfun;

The generated verification condition isX > 0 → X+1 > 1

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-87

ConditionalsIf we have a conditional (i.e. an “if” clause), one hasseveral paths through the program.

E.g. if we have the following program:procedure Simple(A: in out Float)--# derives A from A;--# pre A <= 0.0;--# post A > 0.0;is beginif A >= 1.0

then A := -1.0;else A := 2.0;end if ;

end Simple;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-88

Conditionalsprocedure Simple(A: in out Float)--# derives A from A;--# pre A <= 0.0; post A > 0.0;is beginif A >= 1.0 then A := -1.0;

else A := 2; end if;end Simple;

Then the verification conditions are:

From the precondition follows the postcondition, in caseA∼ ≥ 1.0, (then A at the end is -1.0):

(A∼ ≤ 0.0 ∧ A∼ ≥ 1.0) → -1.0 > 0.0

From the precondition follows the postcondition, in case¬(A∼ ≥ 1.0), (then A at the end is 2.0):

(A∼ ≤ 0.0 ∧ ¬(A∼ ≥ 1.0)) → 2.0 > 0.0 .

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-89

Generated Verif. Cond.H1: a <= 0 .H2: true .H3: a >= 1 .

− >

C1: -1 > 0 .

H1: a <= 0 .H2: true .H3: not (a >= 1) .

− >

C1: 2 > 0 .

Both formulas (including the first one!) are provable andare proved by the simplifier.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-90

ConditionalsOne can as well have check and assert directives inbranches, e.g.:

procedure Simple2(A: in out Float)--# derives A from A;--# pre A <= 0.0; post A > 0.0;is begin

if A >= 1.0then A := -1.0;

--# check A = 1.0;else

A := 2.0;--# check A = 2.0;

end if;end Simple2;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-91

Conditionalsprocedure Simple2(A: in out Float)--# derives A from A;--# pre A <= 0.0; post A > 0.0;is begin

if A >= 1.0 then A := -1.0;--# check A = 1.0;else A := 2; --# check A = 2.0;

end if; end Simple2;

In this example the verification conditions are thatfrom the pre-condition follows the check condition,provided the if-condition is fulfilled/is not fulfilled,and that from the pre condition, the check condition,and the fact that the if-condition is fulfilled/is notfulfilled, follows the post condition.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-92

Conditionalsprocedure Simple2(A: in out Float)--# derives A from A;--# pre A <= 0.0; post A > 0.0;is begin

if A >= 1.0 then A := -1.0;--# check A = 1.0;else A := 2; --# check A = 2.0;

end if; end Simple2;

So we have the following condition:Precondition implies check condition in branch 1:(A∼ ≤ 0.0 ∧ A∼ ≥ 1.0 )→ -1.0 = 1.0Precondition implies check condition in branch 2:(A∼ ≤ 0.0 ∧¬(A∼ ≥ 1.0)) → 2.0 = 2.0

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-93

Conditionalsprocedure Simple2(A: in out Float)--# derives A from A;--# pre A <= 0.0; post A > 0.0;is begin

if A >= 1.0 then A := -1.0;--# check A = 1.0;else A := 2; --# check A = 2.0;

end if; end Simple2;

From the precondition and the checkcondition inbranch 1 follows the post condition (where A = 1):(A∼ ≤ 0.0 ∧ A∼ ≥ 1.0 ∧ -1.0 = 1.0) → -1.0 > 0.0.From the precondition and the checkcondition inbranch 2 follows the post condition (where A = 1):(A∼ ≤ 0.0 ∧¬(A∼ ≥ 0.0) ∧ 2.0 = 2.0) → 2.0 > 0.0.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-94

Generated Ver. Cond.H1: a <= 0 .H2: true .H3: a >= 1 .

− >

C1: -1 = 1 .

H1: a <= 0 .H2: true .H3: not (a >= 1) .

− >

C1: 2 = 2 .

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-95

Generated Ver. Cond.H1: a <= 0 .H2: true .H3: a >= 1 .H4: -1 = 1 .

− >

C1: -1 > 0 .

H1: a <= 0 .H2: true .H3: not (a >= 1) .H4: 2 = 2 .

− >

C1: 2 > 0 .

All 4 verification conditions are provable and are in factproved by the simplifier.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-96

Procedures with Loops

Verification Conditions for Procedures with Loops

If one has a loop, a loop invariant is required.The syntax is for instance:--# assert X +Y= X∼+Y∼;

If one has one pre-condition, one loop and onepost-condition, the examiner generates verificationconditions expressing:

From the pre-condition follows, when first enteringthe loop, the condition of assert .From assert follows, if exit conditions are false, thecondition of assert after one step.From assert follows, if one exit condition is true, thepost-condition .

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-97

Exampleprocedure test(X,Y: in out Float)--# derives X from X &--# Y from X,Y;--# pre X>0.0;--# post X+Y=X∼+Y∼ and X<0.0;isbeginloop--# assert X +Y= X∼+Y∼;X := X - 1.0;Y:= Y + 1.0;exit when X < 0.0 ;

end loop ;end test ;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-98

Generated Verification Conditions.procedure test(X,Y: in out Float)--# pre X>0.0;--# post X+Y=X∼+Y∼ and X<0.0;is begin loop--# assert X +Y= X∼+Y∼;X := X - 1.0; Y:= Y + 1.0;exit when X < 0.0 ;

end loop; end test;

When entering the loop we have X= X∼, Y = Y∼.

So that from the pre condition X∼ >0.0 follows that atthe beginning of the loop we have X+Y = X∼ + Y∼,reads:

X∼ > 0.0 → X∼+Y∼ = X∼+Y∼.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-99

Generated Verification ConditionsThe examiner generates the following verification conditionfor this:

H1: x> 0.H2: true.H3: true.

->

C1: x + y = x + y.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-100

Generated Verification Conditions.procedure test(X,Y: in out Float)--# pre X>0.0;--# post X+Y=X∼+Y∼ and X<0.0;is begin loop--# assert X +Y= X∼+Y∼;X := X - 1.0; Y:= Y + 1.0;exit when X < 0.0 ;

end loop; end test;

After one iteration through the loop, X is decreased by1.0 and Y increased by 1.0.

The loop is left if X afterwards, (= X original -1), is < 0.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-101

Generated Verification Conditions.procedure test(X,Y: in out Float)--# pre X>0.0;--# post X+Y=X∼+Y∼ and X<0.0;is begin loop--# assert X +Y= X∼+Y∼;X := X - 1.0; Y:= Y + 1.0;exit when X < 0.0 ;

end loop; end test;So that the loop invariant is preserved means that

from the loop-invariant, before the iteration tookplace, i.e. from X+ Y = X∼ + Y∼and the fact that the exit condition was false, i.e.not(X - 1.0 < 0.0)it follows that the loop invariant in the next iteration istrue, i.e. (X-1.0)+ (Y+1.0) = X∼ + Y∼.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-102

Generated Verification Conditions.procedure test(X,Y: in out Float)--# pre X>0.0;--# post X+Y=X∼+Y∼ and X<0.0;is begin loop--# assert X +Y= X∼+Y∼;X := X - 1.0; Y:= Y + 1.0;exit when X < 0.0 ;

end loop; end test;

So the condition is:X+ Y = X∼ + Y∼ ∧ ¬(X - 1.0 < 0.0) implies(X-1.0)+ (Y+1.0) = X∼ + Y∼.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-103

Generated Verification Conditions.The examiner generates (note that here ∼ are used,since it is unavoidable):

H1: x+y = x∼ + y∼H2: not (x-1 < 0)

->

C1: x-1+(y+1) = x∼ + y∼.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-104

Generated Verification Conditions.procedure test(X,Y: in out Float)--# pre X>0.0;--# post X+Y=X∼+Y∼ and X<0.0;is begin loop--# assert X +Y= X∼+Y∼;X := X - 1.0; Y:= Y + 1.0;exit when X < 0.0 ;

end loop; end test;When getting from the last iteration through the assertformula to the end we have that again X afterwards is Xbefore -1 and Y afterwards is Y before + 1.

So that the post condition is implied by the last assertformula means that X + Y = X∼ + Y∼ and the conditionfor exiting (X - 1 < 0) both imply X -1 < 0.0 and (X - 1) +(Y+1) = X∼ + Y∼.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-105

Generated Verification Conditions.The examiner generates:

H1: x+y = x∼ + y∼H2: x-1 < 0

->

C1: x-1+(y+1) = x∼ + y∼.C2: x-1 < 0

In this example all three verification conditions areautomatically shown by the simplifier.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-106

Verification Conditions and ProceduresIn a program with several procedures, SPARK-Ada uses

The input output behaviour of the variables ofprocedures called when determining the input outputbehaviour of procedures using it.The dependencies of variables in the variables inprocedures called when determining thedependencies of variables in procedures using them.The pre- and post conditions in procedures called inorder to generate the verification conditions for theprocedures using them.

In the following example, we don’t separate thepackage into a specification and body (as it stands,SPARK Ada won’t accept it).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-107

Examplepackage body Test_Package--# own A : Integer;

is A : Integer;procedure Init--# global out A;--# derives A from ; post A = 0;is begin A:= 0;end Init;

procedure Procedure1;--# global in out A;--# derives A from A;--# pre A = 0; post A=2;

is begin A:= A+2;end Procedure1;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-108

Exampleprocedure Main;--# global out A;--# derives A from ;--# post A = 2;is begin

Init;Procedure1;

end Main;end Test_Package;

That in Main A is an out variable follows since in Init A isoutput variable, and in Procedure1 it is an input/outputvariable.

That Main derives A from nothing follows, since Initderives A from nothing, and Procedure1 derives A fromA.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-109

Verification Conditions for MainSince Init has no pre-condition, we don’t have to showany pre condition for Init in Main.

We have to show however that from the pre condition ofMain (true), and the post condition of Init (A=0) followsthe pre-condition for Procedure1 (A=0):

(true ∧ A = 0) → A = 0;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-110

Verification Conditions for MainWe have to show that from the pre condition of Main(true), the pre condition (A=0) and Post condition (A = 2)of Procedure1 follows the post condition of Main (A=2).

Since there are two versions of A involved, onewhich is as it is when Init is entered, and one, whichis as it is when Procedure1 is entered, we have towork with these two versions of A called A1 and A2.The verification condition is:(true ∧ A1 = 0 ∧ A1 =0 ∧ A2 = 2) → A2 = 2.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-111

Generated Verification ConditionsH1: true .H2: a__1 = 0 .

− >

C1: a__1 = 0 .

H1: true .H2: a__1 = 0 .H3: a__1 = 0 .H4: a__2 = 2 .

− >

C1: a__2 = 2 .

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-112

Using Post Conditions of FunctionsSlides for this part have to be rewritten (functions didn’twork well in the old edition but seem to work well in the2003 edition of the book).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-113

Other AnnotationsThe main program, which is not part of a package hasto be declared by:--#main_program;

One can hide the body of a procedure.Allows especially direct interaction with non-criticaland therefore non-verified Ada programs.Allows as well to integrate not yet implemented code.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-114

Hide DirectiveExample Syntax:

procedure MyGUI--# global out A; in B;--# derives A from B;is--# hide MyGUI-- Details of MyGUI will not be checked.

end MyGUI;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-115

ArraysMany practical examples involve arrays.

E.g. a lift controller might have as one data structurean array

Door_Status: array (Floor_Index) of (Open,Closed);

whereFloor_Index is an index set of floor numbers (e.g.1 .. 10)and Door_Status(i) determines whether the doorin the building on floor i is open or closed,· In Ada one writes A(i) for the ith element of array

A.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-116

ArraysDoor_Status: array (Floor_Index) of Door_Status_Type;type Door_Status_Type is (Open,Closed);

Problem: correctness conditions involve quantification:E.g. the condition that only the door at the currentposition (say Lift_Position) of the lift is open, isexpressed by the formula:

∀I : Floor_Index.(I 6= Lift_Position

→ Door_Status(I) = Closed) .

This makes it almost impossible to reason automaticallyabout such conditions.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-117

ArraysIn simple cases, we can solve such problems by usingarray formulae.

Notation: If A is an array, thenC:= A[I => B] stands for the array, in which the valueI is updated to B. Therefore

C(I) = B,and for J 6= I, C(J) = A(J).

Similarly D:= A[I => B, J => C] is the array, in whichI is updated to B, J is updated to C:

D(I)= B,D(J) = C,D(K) = A(K) otherwise.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-118

ExampleThe correctness for a procedure which swaps elementsA(I) and A(J) is expressed as follows:

type Index is range 1 .. 10;type Atype is array (Index) of Integer;

procedure Swap_Elements(I,J: in Index;A: in out Atype)

--# derives A from A,I,J;--# post A = A∼[I => A∼(J); J => A∼(I)];is

Temp: Integer;begin

Temp: = A(i); A(I) := A(J); A(J) := Temp;end Swap_Elements;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-119

ExampleA = A∼[I => A∼(J); J => A∼(I)];Expresses that

A(I) is the previous value of A(J),A(J) is the previous value of A(I),A(K) is unchanged otherwise.

In the above example, as for many simple examples,the correctness can be shown automatically by thesimplifier.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-120

More Complicated ExampleIn the lift controller example, one can express the factthat, w.r.t. to array Floor, exactly the door atLift_Position is open, as follows:

--# post Closed_Lift = Door_Type’(Index=> Closed)--# and--# Floor = Closed_Lift[Lift_Position => Open];

HereFloor_Type’(Index=> Closed)is the Ada notation for the array A of type Floor_Type, inwhich for all I:Index we have A(I) = Closed.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-121

More Complicated ExampleUnfortunately, with this version, the current version ofSPARK Ada doesn’t succeed in automatically provingthe correctness even of a simple function which movesthe lift from one floor to the other (and opens and closesthe doors appropriately).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-122

QuantificationIt is usually too complicated to express properties byusing array formulae, and one has to use quantifiersinstead.

As soon as one uses quantifiers, the simplifier usuallyfails, and one has to prove the statements by hand orusing the interactive theorem prover.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-123

Reduction of QuantificationIf the quantifiers range over finite sets (as they do whenwe quantify over index sets of arrays), one could avoidquantifiers and replace formulae by propositional (i.e.quantifier free) formulae. Examples:

One can replace the formula∀ I: Floor_Index.ϕ(I)(where ϕ(I) is some property), assuming thatFloor_Index is equal to 0 · · · 10, by the following one:ϕ(0) ∧ ϕ(1) ∧ · · · ∧ ϕ(10).One can replace the formula∃ I: Floor_Index.ϕ(I)(where ϕ(I) is some property), assuming thatFloor_Index is equal to 0 · · · 10, by the following one:ϕ(0) ∨ ϕ(1) ∨ · · · ∨ ϕ(10).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-124

Explosion of Formula SizeThis way one can get rid of all quantifiers.

If the resulting propositional formulae are true and nottoo big, one can search automatically for a solution.

General automatic theorem proving techniques(often using Prolog) can be applied here.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-125

Explosion of Formula SizeIn principal it is undecidable, whether such a formulaholds, since the formulae usually involve reference toarbitrary big integers

The undecidability holds only if one assumes thatintegers can be arbitrarily big.If one takes into account that there are only finitelymany integers, one obtains that the the validity ofpropositional formulae referring only to integers isdecidable.But this is only a theoretical result, since it isinfeasible to try out all possible integer values.

But still in many cases it is feasible to search forsolutions, if the formulae involved are not too big.

The problem is that the size of the formulae explodes.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-126

Explosion of Formula SizeAssume My_Index = 1 .. N for some fixed number N .

Then ∃ I: My_Index.ϕ(I) is the disjunction of Nformulae.∀ I: My_Index.∃ J: My_Index. ϕ(I,J)is the conjunction of N formulae, each of which isthe disjunction of M formulae, so we get a lengthof N ∗ N.

This approach brings easily the simplifier to its limits.Probably with some more sophisticated tools onecould solve much more problems automatically.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-127

Explosion of Formula SizeThe size of the formulae explodes much more if onetransforms the formulae into some normal form.

One can transform propositional formulae intoconjunctive normal form.

But then for instance (A ∧ B ∧ C) ∨ (D ∧ E ∧ F ) istranslated into

(A ∨ D) ∧ (A ∨ E) ∧ (A ∨ E) ∧ (A ∨ F )

∧(B ∨ D) ∧ (B ∨ E) ∧ (B ∨ E) ∧ (B ∨ F )

∧(C ∨ D) ∧ (C ∨ E) ∧ (C ∨ E) ∧ (C ∨ F )

In general one gets an exponential blow up.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-128

Explosion of Formula SizeSimilarly one can transform formulae into aconjunction of Horn formulae, i.e. formulae of theform A1 → · · ·An → B, where Ai, B are possiblynegated atomic formulae.

These are the formulae, the simplifier can dealwith.One obtains however the same exponential blowup.

Inherent reason: the number of possible statesexplodes exponentially.

For instance, if one has N state variables with 2states, the overall system has 2N possible states.

A correctness proof needs to show that the formulaehold for each of these 2N states.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-129

Proof CheckerTherefore in many cases one needs to carry out someproofs using interactive theorem proving.

In SPARK Ada done using the “proof checker” (notpart of the CD distributed with the book by Barnes[Ba03]).

Problem: Code often changes, but since the theoremsto be proved are automatically generated, proofs cannotdirectly be transported from one version to anotherversion of the program.

Need for theories, in which proving andprogramming are more closely connected.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (e) 2-130

(f) Example: Railway Interlocking System

We will look at the following at an example of verify asmall railway interlocking system using Ada.

We won’t achieve full verification.The verification of formulae, which cannot be derivedby the simplifier, will be done by hand.

We will look first at a relative general description ofrailway systems, and then look more concretely at asimplified example.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-131

Description of Rail YardsThe basic unit into which one divides a rail yard is thatof a

::::::

track::::::::::::

segment .

A track segment is stretch of a track without any furthersmaller parts, which are significant for an analysis of ainterlocking system.

there are no branches in between,there are no crossings in between,they are not divided by signals into parts.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-132

ExampleIn the following example we have track segments s1 -s10.

s9 s10s5 s7

s6s4

s8s1 s2p2 p3

p5

p6 p7

p1

p8

p9 p10

p4s3

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-133

PointsIn the example we see that each track segment isdelimited by two sets of points, one on each side.

We have here sets of points p1 - p10, and s3 isdelimited by p3 and p4.

s9 s10s5 s7

s6s4

s8s1 s2p2 p3

p5

p6 p7

p1

p8

p9 p10

p4s3

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-134

ConnectionsAt each point, 1, 2 or 3 track segments are connected.

Connection of 1 track segment means that we havethe end of a track or the end of what is guarded bythe interlocking system in question.

In the example, these are p1 and p8.Connection of 2 track segments means that we havea line, split into two usually by a signal.

In the example, these are p2, p4, p5, p7, p9, p10.Connection of 3 track segments means that we havepoints in between.

In the example, these are p3 and p6.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-135

ConnectionsAt a connection with 3 track segments connecting atone point, it is only for some of these segmentspossible to move between those.

In the example one can move at p3 from s2 to s3,from s2 to s4, but not from s3 to s4.

s9 s10s5 s7

s6s4

s8s1 s2p2 p3

p5

p6 p7

p1

p8

p9 p10

p4s3

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-136

Train RoutesThe control system for such a rail yard has several::::::

train:::::::::

routes .A

::::::

train:::::::

route is a sequence of track segments, thetrain can follow without ever having to stop inbetween (except in emergency cases).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-137

Train RoutesIn the example, (s2, s3) and (s2,s4) form train routes,but one might have a train route (s1,s2,s4,s6,s8,s9,s10)for a fast train, which passes through this stationwithout stopping.

s9 s10s5 s7

s6s4

s8s1 s2p2 p3

p5

p6 p7

p1

p8

p9 p10

p4s3

Route 1

Route 2

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-138

SignalsAt some points there are signals, which give access atone point from one segment into another.

One usually has advance and main signals.Distant signals are needed, since the brakingdistance of trains is too long for trains to be able tostop when they see the main signal.

We will look in the following only at main signals, andignore the speed of the trains.

Then we have that at the end of each route there mustbe a main signal.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-139

Locking of SegmentsIf a train route is chosen for a train, then all segments,the train route consists of, are locked.

For another train, a train route can only be chosen if itdoesn’t overlap with the train route of the first train.

So a train route can be only chosen, if all segments ofthe train route are currently unlocked.

A signal can only be green, if it is leading into or is partof a train route, which has been selected.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-140

Case StudyWe will now carry out a very simple case study.

Available fromhttp://www.cs.swan.ac.uk/∼csetzer/lectures/critsys/03/SPARK_Ada/railwayExample/

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-141

Case Study

Middle_Left Right_Middle

RightMiddleLeft

Left_Middle Middle_Right

We will investigate a very simple example of a rail yard.We have 3 segments, “Left”, “Middle”, “Right”.We have 4 signals, “Left_Middle”, “Middle_Left”,“Middle_Right”,“Right_Middle”.

E.g. “Right_Middle” guards access from Segment“Right” to segment “Middle”.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-142

Case Study

Middle_Left Right_Middle

RightMiddleLeft

Left_Middle Middle_Right

There are 8 routes:4 routes leading from one segment to an adjoiningone:“Route_Middle_Left”, “Route_Middle_Right”,“Route_Right_Middle”, “Route_Left_Middle”.· E.g. “Route_Middle_Left” is the route for a train

moving from segment “Middle” to segment“Left”.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-143

Case Study

Middle_Left Right_Middle

RightMiddleLeft

Left_Middle Middle_Right

2 routes which allow to give access from theneighbouring rail yards to segments “Left” and“Right”:“Route_Enter_Left”, “Route_Enter_Right”.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-144

Case Study

Middle_Left Right_Middle

RightMiddleLeft

Left_Middle Middle_Right

2 routes, which allow a train to leave fromsegments Left and Right to the neighbouring railyards.· “Route_Leave_Left”, “Route_Leave_Right”.

Note that in this situation, leaving and entering theyard from the outside is not guarded by signals – itwould be easy to take this into account as well.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-145

Case StudyEach segment will have 6 possible states:

“Occupied_Standing”, for a train is in this segment,but not about to leave it.“Occupied_Moving_Left”, “Occupied_Moving_Right”for a train is in this segment and moving to the nextsegment left or right.“Reserved_Moving_From_Left”,“Reserved_Moving_From_Right” for the segment isreserved for a train coming from the next segment tothe left or to the right.“Free”, for there is no train currently in this segmentor moving into this segment.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-146

State of Signals

Middle_Left Right_Middle

RightMiddleLeft

Left_Middle Middle_Right

Each Signal has two states: “Red” and “Green”.

The state of all signals together is given by a tuple with4 components, which give the signal state for each ofsignal:“Left_Middle”, “Middle_Left”, “Middle_Right”,“Right_Middle”.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-147

State of the Segments

Middle_Left Right_Middle

RightMiddleLeft

Left_Middle Middle_Right

The states of all segments together is given by a tuplewith 3 components, which give the state of eachsegment:“Left”, “Middle”, “Right”.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-148

Modes of OperationThere are two modes of operation:

“Mode_Open_Route”.In this mode we open a route for one train, whichis currently standing in one segment, to the nextsegment.

“Mode_Move_Train”.In this mode we assume that one train has movedfrom one segment to the next one, and adapt thestates of the segments correspondingly.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-149

Data Structure in Adawith Spark_IO;--# inherit Spark_IO;package Simple_Railway--# own Segment_State : Segment_State_Type;--# Signal_State : Signal_State_Type;is

type One_Signal_State is (Red,Green);

type Mode is (Mode_Open_Route, Mode_Move_Train);

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-150

Data Structure in Adatype Route_Type is (Route_Left_Middle,

Route_Middle_Left,Route_Middle_Right,Route_Right_Middle,Route_Leave_Left,Route_Enter_Left,Route_Leave_Right,Route_Enter_Right);

type One_Segment_State is (Occupied_Standing,Occupied_Moving_Left,Occupied_Moving_Right,Reserved_Moving_From_Left,Reserved_Moving_From_Right,Free);

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-151

Data Structure in Adatype Segment_State_Type is

recordLeft,Middle,Right: One_Segment_State;

end record;

type Signal_State_Type isrecord

Left_Middle,Middle_Left,Middle_Right,Right_Middle: One_Signal_State;

end record;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-152

Data Structure in AdaWe have the following two variables, describing the overallstate of the system:

Segment_State : Segment_State_Type;Signal_State : Signal_State_Type;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-153

ProceduresWe have one procedure„ which opens a route.It has one additional output parameter “Success”, whichreturns true, if the route could be opened, and false,otherwise:

procedure Open_Route(Route : in Route_Type;Success: out Boolean);

--# global in out Segment_State, Signal_State;--# derives Segment_State,Success--# from Segment_State, Route &--# Signal_State--# from Segment_State, Route, Signal_State;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-154

ProceduresWe have one procedure which moves a train along oneroute.Again we have an output parameter “Success”:

procedure Move_Train(Route : in Route_Type;Success : out Boolean);

--# global in out Segment_State, Signal_State;--# derives Segment_State,Success--# from Segment_State, Route &--# Signal_State--# from Segment_State, Route, Signal_State;

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-155

ProceduresFurther we have a procedure which prints the state

procedure Print_State;--# global in out Spark_IO.Outputs;--# in Segment_State, Signal_State;--# derives Spark_IO.Outputs--# from Spark_IO.Outputs, Segment_State, Signal_State;

We are using here a package Spark_IO, which dealswith file I/O and standard I/O (via console).

Spark_IO has internal state variables Spark_IO.Outputsand Spark_IO.Inputs, which are essentially streamsconsisting of all outputs and inputs, respectively, whichhave not been processed yet.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-156

Proceduresprocedure Print_State;--# global in out Spark_IO.Outputs;--# in Segment_State, Signal_State;--# derives Spark_IO.Outputs--# from Spark_IO.Outputs, Segment_State, Signal_State;

If we output something, we take the stream of outputsSpark_IO.Outputs, and append to it what we output.

Above, the output depends on Segment_State andSignal_State, and therefore Spark_IO.Outputs dependson itself (we are appending something to it), andSegment_State, Signal_State.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-157

ProceduresThe procedure Get_Action will determine the mode ofthe next action (from console input) and the route towhich it is applied:procedure Get_Action(Route : out Route_Type;

The_Mode: out Mode);--# global in out Spark_IO.Inputs, Spark_IO.Outputs;--# derives Spark_IO.Outputs--# from Spark_IO.Outputs, Spark_IO.Inputs &--# Spark_IO.Inputs, Route, The_Mode--# from Spark_IO.Inputs ;

Note that the fact that the last two functions don’tchange Segment_State and Signal_State (they are onlyoutput variables), means that they don’t perform anysafety critical action.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-158

Dependencies in Get_Action--# derives Spark_IO.Outputs--# from Spark_IO.Outputs, Spark_IO.Inputs &--# Spark_IO.Inputs, Route, The_Mode--# from Spark_IO.Inputs ;

Spark_IO.Outputs depends on Spark_IO.inputs, since,depending on the input, different informations areoutput.

Spark_IO.Inputs depends on Spark_IO.Inputs, since, ifwe ask for input, the next data from the input stream iscut off and taken as input. Therefore the input stream ischanged.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-159

Implementation of Open_Route“Open_Route” checks for instance in case the route is“Route_Left_Middle”

whether segment “Left” is in state“Occupied_Standing”and segment “Middle” is in state “Free”.

If yes it willset the state of segment “Left” to“Occupied_Moving_Right”,set the state of segment “Middle” to“Reserved_Moving_From_Left”,set signal “Left_Middle” to “Green”.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-160

Implementation of Open_Routeprocedure Open(Route : in Route_Type;

Success: out Boolean) isbegin

Success := False;if Route = Route_Left_Middle then

if (Segment_State.Left = Occupied_Standingand Segment_State.Middle = Free)then

Segment_State.Left:= Occupied_Moving_Right;Segment_State.Middle:= Reserved_Moving_From_Left;Signal_State.Left_Middle:= Green;Success := True;

elseSuccess := False;

end if ;elsif · · ·

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-161

Implementation of Move_Train“Move_Train” checks for instance in case the route is“Route_Left_Middle”

whether segment “Left” is in state“Occupied_Moving_Right”and segment “Middle” is in state“Reserved_Moving_From_Left”.

If yes it willset state of segment “Left” to “Free”,set state of segment “Middle” to“Occupied_Standing”,set signal “Left_Middle” to “Red”.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-162

Implementation of Open_Routeprocedure Move(Route : in Route_Type;

Success: out Boolean) isbeginSuccess := False;if Route = Route_Left_Middle then

if (Segment_State.Left = Occupied_Moving_RightandSegment_State.Middle = Reserved_Moving_From_Left) thenSignal_State.Left_Middle:= Red;Segment_State.Left:= Free;Segment_State.Middle:= Occupied_Standing;Success := True;

elseSuccess := False;

end if ;elsif · · ·

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-163

Limitations of SPARK AdaWhen introducing correctness conditions the followingproblems were encountered:

Although an industrial product used in the verification ofsafety critical systems, in many cases SPARK-Adagenerated, when using arrays, formulae which wereunprovable, although they were correct.

The logic behind array formulae isn’t as well thoughtthrough as it could be (at least in the version 1997,we are using).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-164

Limitations of SPARK AdaInstead we decided to use, as in the above datastructure, single variables for each state.

Therefore the resulting formulae become relativelylong, since they are conjunctions over all segmentsor over all signals.

In the current toy example not a problem, since itis very small, but this would soon becomeinfeasible for bigger examples.One problem is that this solution doesn’t scale (forinstance our example doesn’t extend easily from 3segments to 6 segments).

Because we are using a demo version (a license for thefull version would probably cost several thousandpounds), SPARK-Ada is not even able to parse longerformulae.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-165

Limitations of SPARK AdaThis is a problem which most tools involvingmachine-assisted theorem show:

Even small problems use a lot of memory, andverification can take very long (even months).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-166

Correctness ConditionsWe have the following correctness conditions for the traincontroller:

1. If a signal is green, thenthe segment it is leaving should be in stateOccupied_Moving_{Left,Right}.the segment it is leading to should be in stateReserved_Moving_From_{Right,Left}.

Expressed for Signal Middle_Left as follows:--# (Signal_State.Middle_Left = Green--# -> (Segment_State.Left =--# Reserved_Moving_From_Right--# and Segment_State.Middle =--# Occupied_Moving_Left))

Corresponding formulae are needed for each signal.CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-167

Correctness ConditionsThe previous formulae form pre- and post-conditionsfor both procedures Move and Open.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-168

Correctness Conditions2. In procedure “Open_Route”, which opens a route, we

need that no train gets lost:If a train is in one segment

i.e. the segment has state Occupied_Moving_Left,Occupied_Moving_Right, Occupied_Standing,

it should have such a state afterwards as well.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-169

Correctness ConditionsIn case of the left segment, this is expressed asfollows:--# ((Segment_State∼.Left = Occupied_Moving_Left--# or--# Segment_State∼.Left = Occupied_Moving_Right--# or--# Segment_State∼.Left = Occupied_Standing)--# ->--# (Segment_State.Left = Occupied_Moving_Left--# or--# Segment_State.Left = Occupied_Moving_Right--# or

Segment_State.Left = Occupied_Standing))

We need corresponding formulae for Middle and Leftas well.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-170

Correctness Conditions3. In procedure “Move_Train”, which moves a train from

one segment to another, if a segment was occupied, wehave

either afterwards the segment is again occupied,or we have chosen a corresponding route, thesegment is now free, and the new segment containsthe train.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-171

Correctness ConditionsExpressed in case of Segment Left as follows:--# (Segment_State∼.Left = Occupied_Moving_Right--# ->--# (Segment_State.Left = Occupied_Moving_Right--# or--# (Route = Route_Left_Middle--# and Segment_State∼.Middle =--# Reserved_Moving_From_Right--# and Segment_State.Left = Free--# and Segment_Sate.Middle = Occupied_Standing)))--# and--# (Segment_State∼.Left = Occupied_Standing--# ->--# Segment_State.Left = Occupied_Standing)

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-172

Correctness Conditions--#and--#(Segment_State∼.Left = Occupied_Moving_Left--# ->--# (Segment_State.Left = Occupied_Moving_Left--# or--# (Route = Route_Leave_Left--# and Segment_State.Left = Free)))

Corresponding formulae for the other two segments.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-173

Alternative ApproachAlternatively, one could have introduced a datastructure determining the current position of trains.Then one could instead of the last two conditionsformulate the condition:

the segment at the position of each train must havean “occupied”-state

Problem, since the number of trains varies over time.But that problem seems solvable.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-174

Result of VerificationBecause of the limitations of the demo-version, only theprogram with condition 1., and of it only of the followingcut down version could even by parsed by the system:

--# pre (Signal_State.Middle_Left = Green--#->--# Segment_State.Middle =--# Occupied_Moving_Left;

The simplifier can only prove half of the verificationconditions, although there are only propositionalformulae (no quantifiers) involved.

This seems not to be due to the fact that a demoversion is used, but due to the general limitations of thesimplifier.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-175

Result of VerificationIn case of the first verification condition forOpen_Route, the formula to be proved is of the form(H1 ∧ · · · ∧ H29) → C1,whereC1 = not (fld_right_middle(signal_status) = green ) .H4 = fld_right_middle(signal_status) = green

-> fld_middle(segment_status)= reserved_moving_from_right .

H29= fld_middle(segment_status) = free .

Assuming free 6= reserved_moving_from_right wecan easily conclude C1 from H4 and H29.But the simplifier doesn’t seem to be able to findsuch inferences.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-176

Result of VerificationIt seems that the simplifier

Can use term rewriting in order to· make standard transformation of functions (e.g.

a ∗ 2 = a + a)· some operations on array formulae,· transformation of functions defined by the user.The simplifier can delete unnecessary hypotheses,and determine, whether the conclusion iscontained in one of the hypotheses.

But the simplifier cannot carry out more complexlogical reasoning, even if affects only propositionalformulae.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-177

EvaluationThe restrictions imposed by SPARK-Ada on the Adalanguage are very sensible, and help avoid errors.

The flow control seems to help find many errors.

The possibility of stating pre- and post-conditions isimportant for the process of verifying the code later(even if this is, as usual, done by hand).

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-178

EvaluationHowever, it seems that in most cases, the simplifierdoesn’t automatically prove the verification conditions,and therefore one has to use the interactive theoremprover provided.

Problem is that if one changes the code later, mostof the work done using the interactive theoremprover is lost.Need to integrate programming and proving in abetter way, so that while changing the program theproofs are adapted.

In real world applications, proving of the verificationconditions is rarely carried out, or, if it is done, it isusually done by hand.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-179

Testing of Proof ConditionsBecause of the problems of proving the correctness ofverification conditions, often verification conditions arechecked by automatic testing.

One chooses large amounts of test casesautomatically, and checks whether the verificationconditions always hold.In our example one could test the verificationconditions by choosing arbitrary values for thesignals and the segment states, and checking,whether the generated formulae are always true.Testing can be very successful – often errors havebeen found this way.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-180

Role of Formal MethodsThe use of formal methods with full verification in realworld applications is yet limited since it is too difficult toverify even simple examples using the tools available.

This isdue to unsolved theoretical problems,and the fact that the market for such tools is verylimited, and therefore the systems available are notyet very far developed.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-181

Validation vs. VerificationWe saw as well that it is easy to make mistakes indefining the correctness formulae.

In a first implementation, we forgot to check thattrains don’t get lost, and they got actually lost, so theprogram was not correct, despite being verified.

:::::::::::::::

Verification is the process of verifying that a softwareproject meets its specification.

:::::::::::::

Validation is the process of confirming that thespecification is appropriate and consistent with thecustomer requirements.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-182

Validation vs. VerificationWhereas verification can be guaranteed by using formalderivation, validation is more complex and outside thecontrol of formal methods.

However, by formalising specifications using formalspecification languages, one can make thespecifications so precise that hopefully errors arefound.

CS 313 High Integrity Systems; CS M13 Critical Systems; Michaelmas Term 2008, Sec. 2 (f) 2-183