Promela/SPIN

Promela/SPIN

Promela/SPIN Acknowledgements: Thesenotesusedsomeof thematerialpresentedby Flavio Lerda aspartofEd Clarke’smodel-checking course SPIN Forcheckingcorrectnessofprocessinteractions Specifiedusingbufferedchannels,sharedvariablesorcombination Focus:asynchronouscontrolinsoftwaresystems Promela – program-likenotationforspecifyingdesignchoices Modelsareboundedandhavecountably manydistinctbehaviors GenerateaCprogramthatperformsanefficient onlineverificationofthesystem’scorrectness properties Typesofproperties: Deadlock,violatedassertions,unreachablecode Systeminvariants,generalLTLproperties Randomsimulationsofthesystem’sexecution “Proofapproximation” •2 1 ExplicitStateModelChecker Representsthesystemasafinitestatemachine Visitseachreachablestate(statespace)explicitly (usingNestedDFS) Performson-the-flycomputation Usespartialorderreduction Efficientmemoryusage Statecompression Bit-statehashing Version4: Uninterpreted CcodecanbeusedaspartofPromela model •3 HighLevelOrganization LTLformula Promela Model LTLTranslator Buchi Automaton Buchi Translator Promela Parser TheBuchi automatonis turnedintoaPromela AbstractSyntaxTree processandcomposed Automata Automata withtherestofthesystem. Generator Thegeneratedverifieris CGeneratospr ecifictothemodeland propertywestartedwith. CCode CCompiler PanVerifier VerificationResult •4 2 Promela (ProcessMetaLanguage) Asynchronouscompositionofindependent processes Communicationusingchannelsandglobal variables Non-deterministicchoicesandinterleavings BasedonDijkstra’s guardedcommandlanguage Everystatementguardedbyaconditionandblocksuntilcondition becomestrue Example: while(a==b) skip/*waitfora==b*/ vs (a==b) •5 ProcessTypes Stateofvariableormessagechannelcanonlybe changedorinspectedbyprocesses(defined usingproctype) ;and->arestatementseparatorswithsame semantics. ->usedinformallytoindicatecausalrelationbetweenstatements Example: bytestate=2; proctype A() { (state==1)->state=3 } proctype B() { state=state-1 } state hereisaglobalvariable •6 3 ProcessInstantiation Needtoexecuteprocesses proctype onlydefinesthem Howtodoit? Bydefault,processoftypeinit alwaysexecutes runstartsprocesses Alternatively,definethemasactive(seelater) Processescanreceiveparameters allbasicdatatypesandmessagechannels. Dataarraysandprocesstypesarenotallowed. Example: proctype A(bytestate;shortfoo) { (state==1)->state=foo } init { runA(1,3) } •7 Example Asmentionedearlier,nodistinctionbetweena statementandcondition. bool a,b; proctype p1() { a=true; a&b; Thesestatementsareenabled onlyifbotha andb aretrue. a=false; } Inthiscaseb isalwaysfalse proctype p2() andthereforethereisa { deadlock. b=false; a&b; b=true; } init{a=false;b=false;runp1();runp2();} •8 4 AnExample mtype ={NONCRITICAL,TRYING,CRITICAL}; Atmostonemtype canbe mtype state[2]; declared proctype process(int id){ beginning: noncritical: state[id]=NONCRITICAL; if ::goto noncritical; NC ::true; fi; trying: state[id]=TRYING; if T ::goto trying; ::true; fi; critical: C state[id]=CRITICAL; if ::goto critical; ::true; fi; goto beginning;} init{runprocess(0);runprocess(1)} •9 Otherconstructs Doloops do ::count=count +1; ::count=count - 1; ::(count==0)->break od •10 5 Otherconstructs Doloops Communicationoverchannels proctype sender(chan out) { int x; if ::x=0; ::x=1; fi out!x; } •11 Otherconstructs Doloops Communicationoverchannels Assertions proctype receiver(chan in) { int value; out?value; assert(value ==0||value==1) } •12 6 Otherconstructs Doloops Communicationoverchannels Assertions AtomicSteps int value; proctype increment() { atomic { x=value; x=x+1; value=x; } } •13 MessagePassing chan qname =[16]of{short} qname!expr – writing(appending)tochannel qname?expr – reading(fromhead)ofthechannel qname??expr – “peaking”(withoutremovingcontent) qname!!expr – checkingifthereisroomtowrite candeclarechannelforexclusivereadorwrite: chan in,out;xr in;xs out; qname!exp1,exp2,exp3 – writingseveralvars qname!expr1(expr2,expr3) – typeandparams qname?vari(var2,var3) qname?cons1,var2,cons2 – cansendconstants Lessparameterssentthanreceived– othersareundefined Moreparameterssent– remainingvaluesarelost Constantssentmustmatchwithconstantsreceived •14 7 MessagePassingExample proctype A(chan q1) { chan q2; q1?q2; q2!123 } proctype B(chan qforb) { int x; qforb?x; print(“x=%d\n”,x) } init { chan qname =[1]of{chan }; chan qforb =[1]of{int }; runA(gname); runB(qforb); qname!qforb } Prints: 123 •15 Randez-vous Communications Bufferofsize0– canpassbutnotstore messages Messageinteractionsbydefinitionsynchronous Example: #definemsgtype 33 chan name=[0]of{byte,byte}; proctype A() { name!msgtype(123); name!msgtype(121);/*non-executable*/ } proctype B() { bytestate; name?msgtype(state) } init { atomic{ runA();runB()} } •16 8 Randez-Vous Communications(Cont’d) Ifchannelname haszerobuffercapacity: Handshakeonmessagemsgtype andtransferofvalue123to variablestate. Thesecondstatementwillnotbeexecutablesincenomatching receiveoperationinB Ifchannelnamehassize1: ProcessAcancompleteitsfirstsendbutblocksonthesecond sincechannelisfilled. Bcanretrievethismessageandcomplete. ThenAcompletes,leavingthelastmessageinthechannel Ifchannelnamehassize2ormore: AcanfinishitsexecutionbeforeBevenstarts •17 Example– protocol ChannelsAin andBin tobefilledwithtokenmessagesoftypenextandarbitraryvalues (ASCIIchars)… byunspecifiedbackgroundprocesses:theusersofthetransfer service Theseuserscanalsoreadreceiveddatafromthe channelsAout andBout Thechannelsareinitializedinasingleatomic statement… Andstartedwiththedummyerr message. •18 9 ExampleCont’d mtype ={ack,nak,err,next,accept}; proctype transfer(chan in,out,chin,chout) { byteo,I; in?next(o); do ::chin?nak(I)-> out!accept(I); chout!ack(o) ::chin?ack(I)-> out!accept(I); in?next(o); chout!ack(o) ::chin?err(I)-> chout!nak(o) od } •19 Example(Cont’d) init { chan AtoB =[1]if{mtype,byte}; chan BtoA =[1]of{mtype,byte}; chan Ain =[2]of{mtype,byte}; chan Bin=[2]of{mtype,byte}; chan Aout =[2]of{mtype,byte}; chan Bout=[2]of{mtype,byte}; atomic{ runtransfer(Ain,Aout,AtoB,BtoA); runtransfer(Bin,Bout,BtoA,AtoB); } AtoB!err(0) } •20 10 MutualExclusion Peterson’ssolutiontothemutualexclusion problem flag0=1 turn=0 flag0=0 flag1 ==0||turn==1 flag1 !=0&&turn!=1 Critical Section •21 MutualExclusioninSPIN bool turn; bool flag[2]; proctype mutex0(){ again: flag[0]=1; flag0=1 turn=0; (flag[1]==0||turn==0); turn=0 flag =0 /*criticalsection*/ 0 flag ==0||turn==1 flag[0]=0; 1 goto again; flag1 !=0&&turn!=1 } Critical Section •22 11 MutualExclusioninSPIN _pid: bool turn,flag[2]; Identifieroftheprocess active[2]proctype user() assert: { Checksthatthereareonly atmosttwoinstanceswith assert(_pid ==0||__pid ==1); identifiers0and1 again: flag[_pid]=1; turn=_pid; (flag[1- _pid]==0||turn==1- _pid); /*criticalsection*/ flag[_pid]=0; goto again; } •23 MutualExclusioninSPIN bool turn,flag[2]; bytencrit; ncrit: Countsthenumberof active[2]proctype user() processesinthecriticalsection { assert(_pid ==0||__pid ==1); again: flag[_pid]=1; turn=_pid; (flag[1- _pid]==0||turn==1- _pid); ncrit++; assert(ncrit ==1);/*criticalsection*/ assert: ncrit--; Checksthatthereisalways atmostoneprocessinthe flag[_pid]=0; criticalsection goto again; •24 } 12 Verification Generate,compileandruntheverifier tocheckfordeadlocksandothermajorproblems: $spin–amutex $cc–Opanpan.c $pan fullstatespacesearchfor: assertionviolationsandinvalidendstates vector20bytes,depthreached19,errors:0 79states,stored 0states,linked 38states,matched total:117 hashconflicts:4(resolved) (sizes^18states,stackframes:3/0) unreached code_init(proc0); reachedall3states unreached codeP(proc1): reachedall12states •25 MutualExclusion Verifier:Assertioncanbeviolated Canuse-t-ptofindoutthetrace OruseXSpin Anotherwayofcatchingtheerror Haveanothermonitorprocessraninparallel Allowsallpossiblerelativetimingsoftheprocesses Elegantwaytocheckvalidityofsysteminvariant •26 13 MutualExclusioninSPIN bool turn,flag[2]; bytencrit; active[2]proctype user() { assert(_pid ==0||__pid ==1); again: flag[_pid]=1; turn=_pid; (flag[1- _pid]==0||turn==1- _pid); ncrit++; /*criticalsection*/ ncrit--; flag[_pid]=0; goto again; } activeproctype monitor() { assert(ncrit ==0||ncrit ==1)} •27 Finally, CanspecifyanLTLformulaandrunthemodel- checker Example: #definepcount<=1 LTLclaim:[]p Note:allvariablesinLTLclaimshavetobeglobal! LTLclaimgetstranslatedintoNEVERclaimand storedeitherin.ltl fileorattheendofmodelfile OnlyoneLTLpropertycanbeverifiedatatime ParameterscanbesetusingXSpin Depthofsearch,availablememory,etc. •28 14 MutualExclusioninSPIN bool turn,flag[2]; bool critical[2]; LTLProperties: active[2]proctype user() [](critial[0]||critical[1]) { assert(_pid ==0||__pid ==1); []<>(critical[0]) again: []<>(critical[1]) flag[_pid]=1; turn=_pid; [](critical[0]-> (flag[1- _pid]==0|| (critial[0]U (!critical[0]&& turn==1- _pid); ((!critical[0]&& !critical[1])Ucritical[1])))) critical[_pid]=1; /*criticalsection*/ [](critical[1]-> critical[_pid]=0; (critial[1]U (!critical[1]&& flag[_pid]=0; ((!critical[1]&& goto again; !critical[0])Ucritical[0])))) } Note:critical[]isaglobalvar! •29 Alternatively, #definepncrit <=1 #defineqncrit =0 LTLProperties: bool turn,flag[2]; bytencrit; [](p) []<>(!q) active[2]proctype user() { assert(_pid ==0||__pid ==1); again: flag[_pid]=1; turn=_pid; (flag[1- _pid]==0|| turn==1- _pid); ncrit++; /*criticalsection*/ ncrit--; flag[_pid]=0; goto again; •30 } 15 CommandLineTools Spin GeneratesthePromela codefortheLTLformula $spin–f“[]<>p” Thepropositionintheformulamustcorrespondto#defines GeneratestheCsourcecode $spin–asource.pro

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    29 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us