2Thisevenreducesthesizeoftheoriginalcode q q q q q q q q q q q q q q a111001012af02567gb011010002bf356g q q q q q q q q q q c000010012cf03gabc100001002anbncf27gFig3Interpret ID: 212242
Download Pdf The PPT/PDF document "interactivetheoremproverswithinthesamefr..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
interactivetheoremproverswithinthesameframework.Additionally,thispaperprovidesanicebenchmarkforpeopledevelopingtoolsforthevericationofCprograms;theymayconsiderreningourproofintoaproofoftheCcodeabove.Thispaperisorganizedasfollows.Section2\unobfuscates"theprogram,explainingthealgorithmanditsdata.Section3brie yintroducesWhy3,atoolwhichtakesannotatedcodeasinputandproducesvericationconditionsinthenativesyntaxofseveralexistingprovers.Section4detailsthevericationprocess,namelythelogicalannotationsinsertedintheprogramandthemethodsusedtodischargetheresultingvericationconditions.WeconcludewithadiscussioninSection5.Annotatedsourcecodeandproofsareavailableonlineathttp://why3.lri.fr/queens/.Proofscanbereplayedinabatchmode.2UnobfuscationBeforeweentertheformalvericationprocess,werstexplainthisobfuscatedCprogram.Thecodeisdividedintoarecursivefunctiont,whichtakesthreeintegersasargumentsandreturnsaninteger,andamainfunctionwhichreadsanintegerfromstandardinput,callsfunctiontandprintstheresultonstandardoutput.Withaddedtypedeclarationsandabitofindentation,functiontreadsasfollows:intt(inta,intb,intc){intd=0,e=a&~b&~c,f=1;if(a)for(f=0;d=(e-=d)&-e;f+=t(a-d,(b+d)*2,(c+d)/2));returnf;}Theassignmentd=(e-=d)&-edoesnotstrictlyconformwithANSICstandard,becauseitassumesthattheinnerassignmente-=disperformedbeforeevaluating-e.Thisisnotguaranteedandthecompilermayfreelychoosebetweenbothpossibleevaluationstrategies.ItiseasytoturnthecodeinlegalC:sincedisinitializedto0,wecansafelymoveassignmente-=dtotheendoftheloopbody.Thenwedonotneedtheinitializationd=0anymore2.Thesecondmodicationwemakeistoreplacethemainfunctionwithaqueensfunctionfrominttoint,sinceweareonlyinterestedintheintegerfunctionandnotininput-outputs.WeendupwiththecodegiveninFig.1.Ourgoalistoshowthatqueens(n)isindeedthenumberofsolutionstothen-queensproblem.Letusnowexplainthealgorithmanditsdata.Thisisabacktrackingalgo-rithmwhichllstherowsofthechessboardoneatatime.Moreprecisely,eachcalltotenumeratesallpossiblepositionsforaqueenonthecurrentrowinsidetheforloopand,foreachofthem,recursivelycallsttolltheremainingrows.Thenumberofsolutionsisaccumulatedinfandreturned.Thekeyideaistouseintegersassetsor,equivalently,asbitvectors:ibelongstothe\set"xifandonlyifthei-thbitofxisset.Accordingtothistrick,programvariablesa,b,c, 2Thisevenreducesthesizeoftheoriginalcode. q q q q q q q q q q q q q q a=111001012,a=f0;2;5;6;7gb=011010002,b=f3;5;6g q q q q q q q q q q c=000010012,c=f0;3ga&~b&~c=100001002,anbnc=f2;7gFig.3.Interpretationofvariablesa,b,andcassets.row.Initially,acontainsallpossiblepositions,thatisa=f0;1;:::;n1g.Ifwehavefoundonesolution,abecomesempty,thenwereturn1.Otherwise,wehavetoconsiderallpossiblepositionsonthecurrentrow.Setsbandcrespectivelycontainthepositionstobeavoidedbecausetheyareonanascending(resp.descending)diagonalofaqueenonpreviousrows.Thuse=anbncpreciselycontainsthepositionstobeconsideredforthecurrentrow.Theyareallexaminedoneatatimebyrepeatedlyremovingthesmallestelementfrome,whichissettod.Thennextrowsareconsideredbyarecursivecalltotwitha,bandcbeingupdatedaccordingtothechoiceofcolumndforthecurrentrow:disremovedfromthesetofpossiblecolumns(anfdg),addedtothesetofascendingdiagonalswhichisshifted(succ(b[fdg),andsimilarlyaddedtothesetofdescendingdiagonalswhichisshiftedtheotherway(pred(c[fdg)).Thevaluesofa,bandcareillustratedinFig.3forn=8onacongurationwhere3rowsarealreadyset(columnsarenumberedfromrighttoleft,startingfrom0).3OverviewofWhy3 le.why le.mlw WhyML VCgen Why transform/translate print/run Coq Alt-Ergo CVC3 Z3etc. Why3isasetoftoolsforprogramverica-tion.Basically,itiscomposedoftwoparts,whicharedepictedtotheright:alogicallan-guagecalledWhywithaninfrastructuretotranslateittoexistingtheoremprovers;andaprogramminglanguagecalledWhyMLwithavericationconditiongenerator.ThelogicofWhy3isapolymorphicrst-orderlogicwithalgebraicdatatypesandin-ductivepredicates[5].Logicaldeclarationsareorganizedinsmallunitscalledtheories.Inthefollowing,weusetwosuchtheoriesfrom Programsareannotatedusingpre-andpostconditions,loopinvariants,andvariantstoensuretermination.Vericationconditionsarecomputedusingaweakestpreconditioncalculusandthenpassedtotheback-endofWhy3tobesenttotheoremprovers.4VericationWefocushereonthevericationofthecodeinFig.4.(ThevericationoftheoriginalCcodeinFig.1isdiscussedattheendofthispaper.)Weneedtoprovethreepropertiesregardingthiscode:itdoesnotfail,itterminates,anditindeedcomputesthenumberofsolutionstothen-queensproblem.Therstpropertyisimmediatesincethereisnodivision,noarrayaccess,oranysimilaroperationthatcouldfail.Wewillconsiderterminationlater,aspartofthevericationprocess(Sec.4.2).Letusrstfocusonthespecication.4.1SpecicationWeneedtoexpressthatthevaluereturnedbyacalltoqueensnisindeedthenumberofsolutionstothen-queensproblem.Aswehaveseen,theprogramisbuildingsolutionsonebyone.Thuswehavetoprovethatitndsallsolutions,onlysolutionsandthatitdoesnotndthesamesolutiontwice.Thereisamajordicultyhere:theprogramisnotstoringanything,noteventhecurrentsolutionbeingbuilt.Howcanwestatepropertiesaboutthesolutionsbeingfound? q q q q q q q q Onesolutionistouseghostcode,thatisadditionalcodenotparticipatinginthecomputationofthenalresultbutpotentiallyaccessingtheprogramdata.Thisghostcodewillllanarraywithallsolutions.Onesolutionisrepresentedbyanarrayofnintegers.Eachcellgivesthecolumnassignedtothequeenonthecorrespondingrow.Forinstance,thearray 5 2 4 6 0 3 1 7 correspondstothesolutionofthe8-queensproblemdisplayedtotheright.Rowsarenumberedfromtoptobottomandcolumnsfromrighttoleft|thelatterfollowstheusualconventionofdisplayingleastsignicantbitstotheright,asinFig.3.Arraysusedinghostcodedonotreallyhavetobe\true"arrays:thereisneedneitherforeciency,norforarrayboundchecking.ThuswecanmodelsucharraysusingpurelyapplicativemapsfromWhy3'sstandardlibrary.Thuswesimplydenetypesolution=mapintintWeintroduceaglobalvariablecoltorecordthecurrentsolutionundercon-struction,aswellasaglobalvariablektorecordthenextrowtobelled:valcol:refsolution(*solutionunderconstruction*)valk:refint(*nextrowinthecurrentsolution*)Thesetofallsolutionsfoundsofarisrecordedintoanotherarray.Ithastypetypesolutions=mapintsolution 0 4 7 5 2 6 1 3 0 5 7 2 6 3 1 4 0 6 3 5 7 1 4 2 0 6 4 7 1 3 5 2 1 3 5 7 2 0 6 4 ... Forinstance,therstvesolutionsforn=8aredisplayedtotheright.Todenethelexicographicorder,werstdenethepropertyfortwoarraystohaveacommonprexoflengthi:predicateeq prefix(tu:mapint)(i:int)=8k:int.0ki!t[k]=u[k]Wemakethisapolymorphicpredicate,toreuseitonbothsolutionsandarraysofsolutions.Thenitiseasytodenethelexicographicorderoversolutions:predicatelt sol(s1s2:solution)=9i:int.0in^eq prefixs1s2i^s1[i]s2[i]Finally,weintroducetwoconvenientshortcutsfortheforthcomingspecications.Equalityoftwosolutionsisdenedusingeq prefix:predicateeq sol(tu:solution)=eq prefixtunThepropertyforanarrayofsolutionsstobesortedinincreasingorderbetweenindexaincludedandindexbexcludedisdenedinanobviousway:predicatesorted(s:solutions)(ab:int)=8ij:int.aijb!lt sols[i]s[j]Thiscompletesthesetofdenitionsneededtospecifythecode'sbehavior.Thefullspecicationforfunctionqueens(lines14{15)isthefollowing4:letqueens(q:int)=f0q=n^!s=0^!k=0gt(belowq)emptyemptyfresult=!s^sorted!sol0!s^8u:solution.solutionu$(9i:int.0iresult^eq solu!sol[i])g(S)Thepreconditionrequiresbothsandktobeinitiallyequaltozero.Thepostcon-ditionstatesthatthereturnedvalueisequaltothenumberofsolutionsstoredinarraysol,thatis!s.Additionally,itstatesthatarraysolissortedandthatanarrayuisasolutionifandonlyifitappearsinsol.Atthispoint,thereadershouldbeconvincedthatspecication(S)isindeedexpressingthatthisprogramiscomputingthenumberofsolutionstothen-queensproblem.Thisisslightlysubtle,sincetheabsenceofduplicatedsolutionsisnotimmediate:itisonlyaprovableconsequenceofsolbeingsorted.Ourproofincludesthispropertyasalemma.4.2CorrectnessProofWenowhavetoprovethatfunctionqueensterminatesandobeysspecication(S)above.Asawarm-up,letusproveterminationrst. 4Thecodewithallannotationsisgivenintheappendix. Thenitsaysthatallsolutionsfoundinthisrunoft,thatisbetweentheinitialandnalvaluesofs,mustbesortedinincreasingorder:f...sorted!sol(old!s)!s^...g(Q2)Additionally,thesenewsolutionsmustbeexactlythesolutionsextendingtherstkrowsofarraycol:f...(8u:solution.solutionu^eq prefix!colu!k$9i:int.old!si!s^eq solu!sol[i])^...g(Q3)Finally,therstkrowsofcolmustnotbemodied,andsoarethesolutionsthatwerecontainedinsolpriortothecalltot:f...eq prefix(old!col)!col!k^eq prefix(old!sol)!sol(old!s)g(Q4)Withsuchpre-andpostconditionforfunctiont,functionqueenscanbeprovedcorrecteasily(vericationconditionsaredischargedautomatically).Thelaststepinthespecicationprocessistocomeupwithaloopinvariantforfunctiont(lines5{9).Itshouldbestrongenoughtoestablishpostconditions(Q1){(Q4).Wealreadycameupwithinvariant(I1)toensuretermination.Toensurepostcondition(Q1),thereisanobviousinvariantregardingsandk:f...!f=!s-at!s'L0^!k=at!k'L^...g(I2)Notationat!s'Lisusedtorefertothevalueofsattheprogrampointdesignatedbylabel'L.Thislabelisintroducedbeforethewhilekeywordatline5(thislabelappearsinthecodegivenintheappendix).Onekeypropertytoensurethatsolutionsarefoundinincreasingorderforlt solisthatwetraverseelementsofeinincreasingorder,byrepeatedextrac-tionofitsminimumelement.Thismustbeturnedintoaloopinvariant.Itstatesthatelementsofealreadyconsideredareallsmallerthanelementsofeyettobeconsidered:f...(8ij:int.memi(diff(at!e'L)!e)!memj!e!ij)^...g(I3)Additionally,wemustmaintainthatsolutionsfoundinthisrunoft,thatisbetweentheinitialvalueofsanditscurrentvalue,aresortedinincreasingorder:f...sorted!sol(at!s'L)!s^...g(I4)Wealsohavetomaintainproperty(P3),sincearraycolismodiedbyrecursivecallstot:f...partial solution!k!col^...g(I5)Themostcomplexpartoftheloopinvariantissurelythefollowing,whichisneededtoensurepostcondition(Q3).Itstatesthatthesolutionsfoundsofarinthisrunoffunctiontareexactlythoseextendingtherstkrowsofcolwithanelementofealreadyprocessed: toillustrateseveralkeyfeaturessuchasuseraxiomatizationsorcombineduseofinteractiveandautomatedtheoremprovers.Weconcludethispaperwithseveraldiscussions.Originality.ThevericationcompetitionorganizedduringVSTTE2010[9]alreadyincludedaproblemrelatedtothen-queensproblem.Itwassimpler,though,sincethecodetobeveriedonlyhadtochecktheexistenceofatleastonesolution(andtoreturnone,ifany).Ghostcode.Thiscasestudyisyetanotherexampleofwhereghostcodeisusefulinverication[12].Inthisparticularcase,theprogramisenumeratingthesolutionstoaproblem,butdoesnotstoreanyofthem,noteventhecurrentone.Thusweenrichedthecodewithnewstatementssothatarichspecicationispossible.ThereiscurrentlynosupportforghostcodeinWhy3;weplantoaddthisfeatureinthefuture.Inparticular,thiswillincludeacheckthat(1)ghostcodeisnotmodifyingtheprogramdata,and(2)theprogramisnotaccessingtheghostdata.Inthisproof,wehaveonlyperformedthisvericationmanually.VericationoftheoriginalCcode.WehavenotveriedtheoriginalCcode,onlyitsabstractionintoWhyML.Regardingthecodestructure,thisisnotreallyanissue,sinceallCfeaturesinvolved(recursivefunction,whileloop,mutablevariables)areavailableinWhyMLaswell.Regardingthecodedata,onthecontrary,ourproofdidnotconsidertheuseofintegersasbitvectors;weusedsetsinstead.Ourpurposewastofocusonthespecicationofthealgorithm.Nowthatwehavecomeupwithasuitablespecication,wecouldreneourproofintoaproofoftheoriginalCcode.Apossiblerouteistointroduceafunctionsymbol,saybits,thatturnsanintegerintothesetof1-bitsinitstwo'scomplementrepresentation.Thenwecanmechanicallytranslatealltheannotations,replacingawithbitsa,bwithbitsb,andsoon.Theonlychangeintheannotationsislikelytobeanextrapreconditionstatingthattheupperbitsofcarezeros(otherwise,onescouldbeerroneouslyintroducedbythedivisionsbytwo).Theproofthenrequiresextralemmastojustifythetricksusedinthecode.Forinstance,alemmawillshowthat,undersuitableconditionsonx,wehavebits(x&-x)=singleton(min elt(bitsx)).Abitvectorlibrarywithtwo'scomplementinterpretationsiscurrentlyunderdevelopmentinWhy3;weconsiderreningourproofalongthelineswejustsketchedinafuturework.Last,translatingtheresultingproofintoavericationtoolforCprograms,suchasVCC[6]orFrama-C[8],shouldbestraightforward.Itwouldbeinterestingtoseewhichlevelofproofautomationcanbeachieved.Over ows.Therearetwokindsofintegerover owsinthisprogram,dependingontheuseofintegersasbitvectorsorascounters.Regardingintegersusedasbitvectors,wecaneasilycopewiththeboundednessofintegersbyimposing 5.FrancoisBobot,Jean-ChristopheFilli^atre,ClaudeMarche,andAndreiPaskevich.Why3:Shepherdyourherdofprovers.InBoogie2011:FirstInternationalWork-shoponIntermediateVericationLanguages,Wroc law,Poland,August2011.6.ErnieCohen,MarkusDahlweid,MarkHillebrand,DirkLeinenbach,Micha lMoskal,ThomasSanten,WolframSchulte,andStephanTobies.VCC:ApracticalsystemforverifyingconcurrentC.InTheoremProvinginHigherOrderLogics(TPHOLs),volume5674ofLectureNotesinComputerScience.Springer,2009.7.TechnischeUniversitatDresden.Theworldrecordtothen-queenspuzzle(n=26).http://queens.inf.tu-dresden.de/,2009.8.TheFrama-CplatformforstaticanalysisofCprograms,2008.http://www.frama-c.cea.fr/.9.VladimirKlebanov,PeterMuller,NatarajanShankar,GaryT.Leavens,ValentinWustholz,EyadAlkassar,RobArthan,DerekBronish,RodChapman,ErnieCohen,MarkHillebrand,BartJacobs,K.RustanM.Leino,RosemaryMona-han,FrankPiessens,NadiaPolikarpova,TomRidge,JanSmans,StephanTobies,ThomasTuerk,MattiasUlbrich,andBenjaminWei.The1stVeriedSoftwareCompetition:Experiencereport.InMichaelButlerandWolframSchulte,editors,Proceedings,17thInternationalSymposiumonFormalMethods(FM2011),volume6664ofLNCS.Springer,2011.Materialsavailableatwww.vscomp.org.10.DonaldE.Knuth.TheArtofComputerProgramming,volume4A:CombinatorialAlgorithms,Part1.Addison-WesleyProfessional,1stedition,2011.11.DonaldR.Morrison.PATRICIA|PracticalAlgorithmToRetrieveInformationCodedinAlphanumeric.J.ACM,15(4):514{534,1968.12.SusanOwickiandDavidGries.Verifyingpropertiesofparallelprograms:Anaxiomaticapproach.CommunicationsoftheACM,19(5):279{285,may1976.13.TheCoqDevelopmentTeam.TheCoqProofAssistantReferenceManual{VersionV8.3,2010.http://coq.inria.fr.14.HenryS.Warren.Hackers'sDelight.Addison-Wesley,2003.AAnnotatedSourceCodeThisistheannotatedsourcecodefortheprograminFig.4.letrect(abc:setint)variantfcardinalag=f0!k^!k+cardinala=n^!s0^(8i:int.memia$(0in^8j:int.0j!k!!col[j]6=i))^(8i:int.i0!not(memib)$(8j:int.0j!k!!col[j]6=i+j-!k))^(8i:int.i0!not(memic)$(8j:int.0j!k!!col[j]6=i+!k-j))^partial solution!k!colgifnot(is emptya)thenbeginlete=ref(diff(diffab)c)inletf=ref0in'L:whilenot(is empty!e)doinvariantf