• Keine Ergebnisse gefunden

On the verification of SCOOP programs

N/A
N/A
Protected

Academic year: 2022

Aktie "On the verification of SCOOP programs"

Copied!
22
0
0

Wird geladen.... (Jetzt Volltext ansehen)

Volltext

(1)

On the verification of SCOOP programs

Georgiana Caltais

a,b,∗

, Bertrand Meyer

a,c,∗

aDepartmentofComputerScience,ETHZürich,Switzerland

bDepartmentforComputerandInformationScience,UniversityofKonstanz,Germany

cSoftwareEngineeringLab,InnopolisUniversity,Russia

a b s t r a c t

In this paper we focus on the development of a unifying framework for the formal modeling ofanobject oriented-programminglanguage,its underlyingconcurrencymodel and their associated analysis tools. More precisely, we target SCOOP an elegant concurrencymodel,recentlyformalizedbasedonRewritingLogic(RL)andMaude.SCOOP is implemented in Eiffel and its applicability is demonstrated also from a practical perspective,intheareaofroboticsprogramming.Ourcontributionconsistsofdevisingand integratinganaliasanalyzerandaCoffmandeadlockdetectorundertheroofofthesame RL-based semantic framework ofSCOOP. This enables using theMaude rewriting engine and its LTL model-checker “for free,” in order to perform the analyses of interest. We discussthelimitationsofourapproachformodel-checkingdeadlocksandprovidepossible workarounds for the state space explosion problem. On the aliasing side, we propose an extension of a previously introduced alias calculus based on program expressions, to the setting ofunbounded program executions. Moreover, we devise a corresponding executable specification easily implementable on top of the SCOOP formalization. An importantpropertyofourextensionisthat,innon-concurrentsettings,thecorresponding alias expressions canbe over-approximated in terms ofa notion ofregular expressions.

Thisfurtherenablesustoderiveanalgorithmforcomputingasoundover-approximation ofthe“mayaliasing”information,wheresoundnessstandsforthelackoffalsenegatives.

1. Introduction

Inlightofthewidespreaddeployment andcomplexityofconcurrentsystems,thedevelopmentofcorrespondingframe- worksforrigorousdesignandanalysishasbeenagreatchallenge.Inthispaperwefocusonthedevelopmentofaunifying framework for the formal modeling of an object oriented-programming language, its underlying concurrency model and theirassociatedanalysistools.

We are targeting SCOOP [1], a simple object-oriented programming model for concurrency. Two main characteristics makeSCOOPsimple:1)justonekeywordprogrammershavetolearnanduseinordertoenableconcurrentexecutions,and 2)theburdenoforchestratingconcurrentexecutionsishandledwithinthemodel,thereforereducingtheriskofcorrectness issues.ThereferenceimplementationisEiffel[2],butimplementationshavealsobeenbuiltontopofJava-likelanguages[3].

The success of SCOOP is demonstrated not only from a research perspective, but also from a practical perspective, with applications appearing,forinstance,intheareaofroboticsprogramming[4].

*

Correspondingauthors.

E-mailaddresses:gcaltais@gmail.com(G. Caltais),bertrand.meyer@inf.ethz.ch(B. Meyer).

Konstanzer Online-Publikations-System (KOPS) URL: http://nbn-resolving.de/urn:nbn:de:bsz:352-2-rw8j0pvgtud22

https://dx.doi.org/10.1016/j.scico.2016.08.005

(2)

Thebasisofaframeworkforthedesignand analysisoftheSCOOPmodelhas alreadybeen set.Inthisrespect,werefer to therecent formalization ofSCOOP in [1] based on Rewriting Logic (RL) [5], which is executable and straightforwardly implementable intheprogramminglanguageMaude [6].In[1]these capabilities havebeen successfullyexploited inorder toreasonabout theoriginalSCOOPmodelandtoidentifyanumberofdesignflaws.

Moreover,anexecutablesemanticscanbeexploitedinordertoformalizeand“run”analysistoolsforSCOOPprogramsas well.ThisfacilitatestheextensionoftheaforementionedSCOOPformalizationtothelevelofaunifyingexecutablesemantic framework for thedesign and analysis of both themodel and its concurrent applications. In this paper we focuson the developmentofaRL-basedtoolboxfortheanalysisofSCOOPprograms on topof theformalization in [1]. Weare interestedin constructing analiasanalyzerand adeadlockdetector.

Aliasanalysis has been an interesting research direction for the verification and optimization of programs. One of the challenges along thisline of research has been the undecidability of determining whether two expressions in a program mayreferencethesameobject.Arichsuiteofapproachesaimingatprovidingasatisfactorybalancebetweenscalabilityand precision has already been developed in thisregard. Examples include: (i) intra-procedural frameworks [7,8] that handle isolatedfunctionsonly,andtheirinter-proceduralcounterparts[8–10]thatconsidertheinteractionsbetweenfunction calls;

(ii) type-based techniques [11]; (iii) flow-based techniques [12,13] that establish aliases depending on the control-flow information of aprocedure; (iv) context-(in)sensitive approaches[14,15] that depend on whether thecalling contextof a function istakenintoaccountornot;(v)field-(in)sensitiveapproaches[16,17]thatdependonwhethertheindividualfields ofobjectsinaprogramaretracedornot.

There isahugeliteratureon heap analysisforaliasing [18], but hardlyanypaperthat presents acalculusallowingthe derivationofaliasrelationsastheresultofapplyingvariousinstructionsofaprogramminglanguage.Hence,ofparticularin- terestfortheworkinthispaperistheuntyped,flow-sensitive,fieldsensitive,inter-proceduralandcontext-sensitivecalculus formayaliasing,introducedin[19].Thecalculuscoversmostoftheaspectsofamodern object-orientedlanguage,namely:

object creation and deletion, conditionals, assignments,loops and (possiblyrecursive) function calls.The approach in[19]

abstractsthealiasinginformationintermsofexplicitaccesspaths[20]referredtoasaliasexpressionsstraightforwardlycom- putedinanequationalfashion,basedonthelanguageconstructs.Asweshallseelateroninthispaper,thelanguage-based expressions canbeexploitedinordertoreasonabout“mayaliasing”inafinitenumberofstepsinnon-concurrentsettings and, moreover,canbeeasilyincorporatedinthesemanticrulesdefiningSCOOPin[1].

The work most similar to our contribution is the one in [21], where aliasing information is identified by exploiting regularbehavior of(non-concurrent)programs, inaRLsetting.Themaindifferencewiththeresultsin[21]consistsofhow the abstractmemory addressescorrespondingto pointer variablesarerepresented. In [21]these rangeover afiniteset of natural numbers. In this paper we consider alias expressions build according to the calculus in [19], based on program constructs.

In [22] theauthors focus on alias analysisand type inference for PHP and sketch a hypothetical solution of their ap- proach inMaude.Thealiasanalysisin[22]isinter-proceduralaswell,andcanhandlefunctionpointers,recursivecallsand references.Oneofthemajordifferenceswithourworkisthatin[22],inordertoderivecorrectanalysisresults,theauthors run aliasingandtypeinference analysisin“tandem” until afixpoint isreached.Weguaranteetheterminationouranalysis byexploitingasoundover-approximationofaliasingviatheso-calledregularaliasexpressions.

Deadlock is one of the most serious problems in concurrent systems. It occurs when two or more executing threads are each waiting for the other to finish. Along time, the complexity of the problem determined various approaches to combat deadlocks [23]. Examples include: (i) deadlock prevention [24] which ensures that at least one of the deadlock conditions cannot hold,(ii)deadlock avoidance [25]that providesaprioriinformation so that thesystem canpredictand avoid deadlocksituations, (iii)deadlockdetection[26,27]thatdetectsandrecovers fromadeadlockstate.

OurfocusisondeadlockdetectionforSCOOPprograms.Webaseourworkonthefactthatthistypeofanalysisisinstrict connectionwiththeunderlyingmodelofinterest.Consequently,asdescribedinthecorrespondingsubsequentsections,our approachconsistsofformalizingdeadlocksinthecontextoftheSCOOPconcurrencymodelandenrichingitssemanticsin[1]

withtheequivalentoperational-baseddefinitionofdeadlocks.ThisenablesusingtheMauderewritingcapabilities“forfree”

inordertotestSCOOPprogramsfordeadlock.Nevertheless,themoreambitiousgoalofusingtheMaudeLTLmodel-checker for deadlock detectionis not straightforward. As discussed in more detaillater on in thispaper, verification of deadlocks was possibleafter reducing theSCOOPsemantics in [1]and abstracting itbased onaliasing information, and modifyinga seriesofimplementationaspects(suchasindexed-basedparameterizations)thatdeterminedstatespaceexplosionissues.

The literature on usingstatic analysis[8] and abstracting techniques for (related) concurrency models isconsiderable.

Werefer,forinstance,totherecentworkin[28]thatintroducesaframeworkfordetectingdeadlocksbyidentifyingcircular dependencies inthe(finite state)model ofso-called contractsthat abstract methodsinanOO-language. Nevertheless,the integrationofadeadlockanalyzerinSCOOPontopofMaudeisanorthogonalapproachthataimsatconstructingaRL-based toolbox forSCOOPprogramslayingoverthesamesemanticframework.

In[29]SCOOPprogramsareverifiedfordeadlocksand otherbehavioralpropertiesusingGROOVE[30].Theworkin[29]

proposesaredefinitionofthemostcommonfeaturesoftheSCOOPsemanticsbasedongraphtransformationsystems(GPSs).

Thisisabottom-upapproach,asitaimsatredefiningtheSCOOPsemanticsfromscratchviaGPSs,orthogonaltoourrather top-down strategyofnarrowingtheoriginalsemanticsproposedin[1].

There are several RL-basedapproaches to deadlockdetection inthe literature. In [31,32], for instance, the authorsuse theMaudeLTLmodelchecker toshowdeadlock-freedominadiningphilosophersimplementationinC.In[33],theMaude

(3)

LTL model checker is used to verify safety and liveness properties of Orc [34] programs such as a dining philosophers implementation andanonlineauctionsystem. Nevertheless,none oftheaforementioned resultsareused inthecontextof aunifyingframeworkforspecifyingandclarifyingaconcurrencymodel[1],andanalyzingitscorrespondingapplications.

TheresultsinthispapercentrearoundSCOOP,astacklingaliasinganddeadlockrelatedaspectsisparticularlychallenging in thecontextof aconcurrencymodel ascomplexasSCOOP. However, exploitingaunifying RL-basedframework forboth designing the concurrencymodel and analyzingits correspondingapplications raises certain issuesthat werenot obvious at the stage of just formalizing SCOOP in [1]. Some of the identified design and implementation decision affecting the verification of SCOOP applications in a negative way can serve as guidelines in the context of other RL-based models as well.

Thispaperisanextendedversion of[35]whereweproposed:

1. atranslationofthe(finite) aliascalculusin[19]to thesettingofunboundedprogramexecutions determinedbyfinite executionsofanylength,togetherwithasoundover-approximationtechniquebasedon(finitelyrepresentable)“regular aliasexpressions”capturingunboundedexecutionsinnon-concurrentsettings;

2. aRL-basedspecificationoftheextendedcalculussuitableforintegrationwithintheSCOOPformalizationin[1](forthis purposeweuseanotationinspiredbytheK-framework enablingcompact andmodulardefinitions);

3. analgorithm for“mayaliasing”(exploitingthefinitenesspropertyin1.)calculating over-approximatingaliasesinnon- concurrentsettings.

Thecurrent workaddsto1.–3.above:

4. the full, revised RL-based specification in 2. and the complete formal proofs showing the soundness of the over- approximatingtechniquebasedon“regularaliasexpressions”;

5. examples ofexploitingthealgorithmin3.anditsimplementationon topoftheSCOOPformalizationinMaude[1];

6. the formalization and integration ofa deadlock detectionmechanismon top of theSCOOP operationalsemantics [1], togetherwithdiscussionson thelimitationsofourapproachand associatedworkarounds.

Paperstructure The paper is organized as follows. In Section 2 we provide a brief overview of SCOOP. In Section 3 we introduce theextension ofthe alias calculus in [19]to unbounded executions. In Section 4 we providethe full RL-based executable specificationofthecalculusandaterminationresult.TheimplementationinSCOOPandfurtherapplicationsare discussedinSection5.Section6isdedicatedtodeadlockinginSCOOP.InSection7wedrawsomeconclusions andprovide pointerstofuturedevelopments.

2. BriefintroductiontoSCOOP

As alreadystated,thepurposeofthecurrent workisthedevelopmentofatoolbox fortheanalysisofSCOOPprograms byexploitingthesemanticsproposed in[1].SCOOPisparticularlyattractivedue toitssimplicityandelegance, asitallows theswitch fromsequentialto concurrentprogramminginaratherstraightforward fashion,bymeans ofjust onekeyword, namely,separate.Transparenttotheuser,thekeynotioninSCOOPistheprocessor,orhandler(that canbeaCPU,oritcan also be implemented in software, as a process or thread). Handlers are in charge of executing the routines of “separate”

objects,inaconcurrentfashion.

For anexample, assumeaprocessor p that performsacallo.f(a1,a2,. . .) onanobjecto.If oisdeclaredas“separate”, then p sendsa requestforexecuting f(a1,a2,. . .) to q thehandlerof o (notethat p and qcan coincide).Meanwhile, p can continue. Moreover, assumethat a1,a2,. . . areof “separate”types.According to theSCOOPsemantics, the application of the call f(. . .) willwait until ithas been able to lock allthe separateobjects associated to a1,a2,. . .. Thismechanism guarantees exclusive access to these objects. Given a processor p, by W(p) we denote the set of processors p waits to release the resources p needs for its asynchronous execution. Orthogonally, by H(p) we represent the set of resources (more precisely,resourcehandlers)that p alreadyacquired.

ThesemanticsofSCOOPin[1]isdefinedovertuplesofshape

p1::St1|. . .|pn::Stn,

σ

(1)

where, pi denotes a processor(for i∈ {1,. . . ,n}), Sti is the callstack of pi and σ is thestate of thesystem. States hold information abouttheheap(which isamappingof referencestoobjects)and thestore(whichincludes thebindingofthe formalparameterstoactual arguments,localvariables,etc.).Processors communicateviachannels.

Roughlyspeaking,onecouldclassifytheoperationalrulesformalizingSCOOPin[1]in:a)languagerulesthat providethe semanticsoflanguageconstructssuchas“if. . . then. . . else. . . end”or“until. . . loop. . . end”,andb)controlrulesimplement- ingmechanisms suchaslockingorscheduling.

Foranexampleincategorya)above,considertherulesspecifying“if”instructions:

ais fresh

p::ifethenSt1elseSt2end;St,

σ

p:: eval(a,e); wait(a);provided a.data then St1else St2;St,

σ

(2)

(4)

.

p::provided true then St1else St2;St,

σ

p::St1;St,

σ

(3)

.

p::provided f alse then St1else St2;St,

σ

p::St2;St,

σ

(4) Intuitively,“eval(a,e)evaluatese andputstheresultonafreshchannela and“wait(a)enablesprocessor p tousethe evaluation resultstoredina.data.It isstraightforwardto seethat,accordingto (3), incasethecondition e isevaluated to truethenthe“if branch” St1 isplacedon topofthecallstackof p. Otherwise,basedon (4),ife isevaluatedto f alse,the

“elsebranch”isexecuted.

As weshallseeinSection 5, anoperationalviewon thealiascalculusin[19]exploitingtheinstructionsofaprogram- minglanguagewillenableastraightforwardimplementationontopofthe“languagerules” ofSCOOP.

Forthecaseb) abovewerefertothelockingrule:

·

p::lock({q1, . . .qm});St,

σ

p::St,

σ

.lock_rqs(p,{q1, . . .qm})

qi∈ {q1, . . . ,qm}:

σ

.rq_locked(qi)= f alse (5)

stating that aprocessor p canlockaset ofhandlers {q1,. . . ,qm} bycallinglock_rqson thestateσ whenever noneofthe handlers qi has previouslybeenacquiredbyotherprocessors,i.e.,σ.rq_locked(qi)= f alse.

As will become clear in Section 6, “control rules” pave the way to an immediate implementation of a corresponding

“deadlock rule”ontopoftheMaude formalizationofSCOOPin[1].

3. Thealiascalculus

The calculus for mayaliasing introduced in [19] abstracts the aliasing information in terms of explicit access paths referredtoas“aliasexpressions”.Consider, foranexample,thecaseofalinkedlist.Wewritexi (i≥0)torepresentnode i inthelist,anduseasettertoassignthenextnodeofthelist:

createx0

loop i:=i+1 createxi

xi.set_next(xi1) end

(6)

Theresultoftheexecutionofthecodeabovecanbeintuitivelydepictedastheinfinitesequence:

x0

←−−next x1

←−−next . . .xk1←−−next xk

←−−next xk+1. . .

Hence, x0 becomes aliasedto x1.next, x2.next.next, x3.next.next.next,so on and so on. In short, theset of associated alias expressions canbeequivalentlywrittenas:

{[xi,xi+k.nextk] |i0k1}. (7)

The sources ofimprecision introducedbythecalculusin [19]arelimited to ignoringtestsin conditionals,and to “cutting at length L” for the case of possibly infinite alias relation corresponding to unbounded executions as in (6). The cutting techniqueconsiderssequenceslonger thanagivenlengthL asaliasedtoallexpressions.

Inthissectionwedefineanextensionofthecalculusin[19],tounboundedprogramexecutions.Moreover,wedevisea correspondingsoundover-approximationof“mayaliasing”intermsofregularexpressions,applicableinsequentialcontexts.

Thispavesthewaytodevelopinganalgorithmforthealiasingproblem,aspresentedinSection4.Themachineryforcollect- ingaliasesisdefinedusinganotationinspiredbytheKframework[36],asitsoperationalflavor enablesastraightforward integrationwithintheSCOOPformalizationin[1].

We proceed byrecallingthe notion ofaliasrelationand a seriesof associatednotations and basic operations, asintro- ducedin[19].

Definition1(Aliasexpressions[19]).Wecallanaliasexpressiona(possiblyinfinite)pathofshapex.y.z.. . .,wherexisalocal variable,classattributeorCurrent,and y,z,. . .areattributes.Here,Current,alsoknownasthisorself,standsforthecurrent object. For an arbitrary alias expression e, it is thecase that e.C urrent=C urrent.e=e. Intuitively,anexpressione.C urrent makessenseif,forinstance,thetypeofCurrentistheclassoftheobjectsreachedbye.

Definition2(Aliasrelations[19]).Let E representthesetofallexpressionsofaprogram.Analiasrelationisasymmetricand irreflexivebinaryrelationrE×E.Let[e1,e2]∈r;wecall[e1,e2]analiaspairinr.

Givenanaliasrelationr andanexpressione,wedefine r/e= {e} ∪ {x:E| [x,e] ∈r}

denotingtheset consistingofallelementsinr whicharealiasedtoe,pluse itself.

(5)

Let xbeanexpression;wewriterxtorepresent r withoutthepairswithoneelementofshapex.e:

rx= {[e1,e2] | ∀e:E.[e1,e2] ∈re1=x.ee2=x.e}.

Byadom(t)werefertoanattributeintheclasscorrespondingtotheobjectreferredbythealiasexpressionassociated to t. For instance, given a class NODE with a field next of type NODE, and a NODE object x, we say that next is in the domainoft= x.next.next.

Intuitively, wesaythat analias relationisdot-complete, wheneveritselements aresoundlyextendedvia fieldsintheir correspondingdomains.Theoperationmakingarelationdot-completeisdefinedasfollows:

dot-complete(r)=r∪ {[t.a,s.a] | [t,s] ∈radom(t)} ∪ {[s.a,v] | [t,s] ∈r∧ [t.a,v] ∈r}.

Letx beanaliasexpressionandubeaset ofexpressionsin E.Wedefinetherelationr augmentedwithpairs[x,y],for yu,andmadedotcompleteas

r[x=u] =dot-complete(r)wherer=r∪ {[x,y] |yu}.

3.1. Extensiontounboundedexecutions

We further introduce an extension of the alias calculus in [19] to infinite alias relations corresponding to unbounded executions. The maindifference inour approach isreflected bythe definitionof loops, which now complies to the usual fixed-point denotationalsemantics.

The aliascalculusis defined byaset ofaxioms “describing”how theexecutionaprogramaffects thealiasing between expressions.Asin[19],thecalculusignorestestsinconditionalsandloops.

Definition3(Programinstructions[19]).Letx,x bevariablenamesand s avalidsequence x.y1.y2. . .yn with y1dom(x), y2dom(x.y1),. . . ,yndom(x.y1. . .yn1). Let f be a routine name and l the actual parameters of a call of f. The programinstructionsaredefinedasfollows:

p ::= p;p|thenpelsepend| createx|forgetx|x:= s|

looppend|callf(l)|x.callf(l). (8)

Wewriter»p torepresentthealiasinformationobtainedbyexecuting p whenstarting withtheinitialaliasrelationr.

Wefurthergivetheaxiomsoftheextendedaliascalculus.Theaxiomforsequentialcompositionisdefinedintheobvious way:

r»(p;q)=(r»p)»q. (9)

Conditionals are handled by considering the union of the alias pairs resulted from the execution of the instructions correspondingtoeachofthetwobranches,whenstartingwiththesameinitialrelation:

r»(thenpelseqend)=r»pr»q. (10)

Aspreviouslymentioned,wedefiner»loop pendaccordingtoitsinformalsemantics:“executep repeatedlyanynumber oftimes,includingzero”.Thecorrespondingruleis:

r»(looppend)=

n∈N

(r»pn) (11)

where pn isthesequential compositionof p withitselfforntimesand

standsfortheunionofaliasrelations,asabove.

This way,ourcalculusisextendedto finiteexecutionsofany length.Thisisthemaindifference withtheapproachin[19]

that proposes a “cutting” technique restricting the model to a maximum length L. In [19], sequences longer than L are considered as aliased to allexpressions.Orthogonally, forsequential settings, weprovide finiterepresentations of infinite alias relationsbasedonover-approximatingregularexpressions,asweshallseeinSection 3.2.

Both the creation and the deletion of an object x eliminate from the current alias relation all the pairs having one element prefixedbyx:

r»(createx) = rx

r»(forgetx) = rx. (12)

The(qualified)function callscomplytotheirinitialdefinitionsin[19]:

r»(callf(l)) = (r[f:l])» | f |

r»(x.callf(l)) = x.((x.r)»callf(x.l)). (13)

(6)

Here f and | f | stand for the formal argumentlist and the body of f, respectively, whereas r[u:v] is therelation r in whichevery elementofthelist v isreplacedbyitscounterpartinu.

Consider acall x.callf(l) executedon behalf ofa certainclientobject, which applies f to asupplier object referenced by x. In order to compute the aliasing induced by x.callf(l) when starting with an aliasing environment r, we need to computethealiasinginduced bytheexecutionof f fromr asseen bythesupplierobject x.Thissupplier viewisx.r with both elementsof every pairin r prefixed bythenegative reference x.Intuitively, x canbeseen asabackpointer giving accessto theclient.Inaccordance,thealiascalculusevaluates x.x toC urrent. Intuitively,thenegativevariablex ismeant totranspose thecontextofthequalifiedcalltothecontextofthecaller.

For an example, consider a class C in an OO-language, and an associated procedure f that assigns a local variable y, defined as: f(x){ y:=x}.Then,forinstance,thealiasingfora.callf(a)computesasfollows:

» a.callf(a) = a.(a.∅ » y:=a.a) = a.(∅ » y:=Current) = dot-complete({[a.y,a]}).

Recursive function calls can lead to infinite alias relations if they do not terminate. In sequential settings, as for the caseofloops,themechanismexploitingsoundregularover-approximationsinordertoderivefiniterepresentationsofsuch relationsispresentedinthesubsequentsections.

Theaxiomforassignmentisaswellinaccordancewithitsoriginalcounterpart in[19]:

r»(x:= s) = (r1x)[x=(r1/sx)] −ox

wherer1=r[ox=x] (14)

whereoxisafreshvariable(thatstandsfor“oldx”).Intuitively,thealiasinginformationw.r.t.theinitialvalueofx is“saved”

by associatingx and ox inr and closing the newrelation underdot-completeness, in r1. Then, theinitial x is“forgotten”

bycomputingr1xand thenewaliasinginformationisaddedinaconsistentway.Namely, weaddallpairs(x,s),where s ranges over r1/sx representing all expressions already aliased with s in r1, including s itself, but without x. Recall that alias relations are not reflexive, thus by eliminating x we make sure we do not include pairs of shape [x,x]. Then, we consider again the closure under dot-completeness and forgetthe aliasing information w.r.t. the initial value of x, by removing ox.

Remark4.Itisworthdiscussingthereasonbehindnotconsideringtransitivealiasrelations.Assumethefollowingprogram:

thenx:= yelsey:= zend

Based on theequations (10)and (14) handlingconditionals and assignments,respectively, the calculuscorrectlyidentifies the alias set:{[x,y],[y,z]}. Including[x,z] wouldbesemantically equivalent tothe executionofthe two branchesin the conditionalatthesametime,whichisnotwhatwewant.

3.2. Asoundover-approximation

In anon-concurrentor, sequential setting, thechallenge ofcomputing the aliasinformation inthe contextof (infinite) loops andrecursivecallsreducestoevaluatingtheircorresponding“unfoldings”,capturedbyexpressionsofshape

r»pn,

withnrangingovernaturalsN,ran(initial)aliasrelation(r= ∅),and p abasicblockdefined by:

p ::= p;p|thenpelsepend| createx|forgetx|

x:= s. (15)

The value r»pn refers to the alias relation obtained by recursively executing the control block p for n times, and it is calculatedintheexpectedway:

r»p0 = r

r»pk+1 = (r»pk)»p. Consideragainthecodein(6):

createx0

loop i:=i+1 createxi

xi.set_next(xi1) end

(7)

Itsexecutiongeneratesanaliasrelationincludinganinfinitenumberofpairsofshape:

[xi,xi+1.next],[xi,xi+2.next.next],[xi,xi+3.next.next.next]. . . . (16) Inwhatfollowsweprovideawaytocomputefiniterepresentationsofinfinitealiasrelationsinsequentialsettings.The key observation is that alias expressions corresponding to unbounded programexecutions grow in aregular fashion. See, forinstance, thealiasesin(16),whicharepairsoftype[xi,xi+k.nextk1].

Regularaliasexpressionsaredefinedsimilarlytotheregularlanguagesoveranalphabet.Wesaythatanaliasexpression isregularif itisalocalvariable,classattributeorCurrent.Moreover,theconcatenatione1.e2andthechoicee1+e2oftwo regular alias expressions e1 and e2 are also regular. Given a regular alias expression e, theexpression e is also regular;

here(−)denotestheKleenestar.Wecallanalias relationregular ifitconsistsofpairsofregularaliasexpressions.

Proposition5.Letr bearegularaliasrelationand p::= createx|forgetx|x:= s.

Inasequentialsetting,itisthecasethatr»p isregular.

Proof. First, observe that the name of a variable x and the right-hand side of an assignment x:= s as introduced in Definition 3,inSection3,areregularaliasexpressions.Hence,byDefinition 2,itfollows thatr/s,rx,dot-complete(r) and r[x=s]preserveregularityofaliasrelations.Consequently,by(12)and(14)r»createx,r»forgetxandr»x:=s areregular alias relations. 2

Lemma6.Letr bearegularaliasrelationandp abasicblockasin(15).Inasequentialsetting,thefollowinghold:

(a) r»p isregular;

(b) r»pn,withn1,isregular.

Proof. Theproofof(a)followsbyinductiononthestructureof p.

Basecase: p::= createx|forgetx|x:= s.TheresultfollowsbyProposition 5.

Inductionstep.Assumer»p isregularforallregularrelationsr andallbasicblocks p withsimplerstructurethan p.

Let p=then p1 else p2 end. By definition, r=r»then p1 else p2 end=(r»p1)(r»p2). Hence, by the induction hypothesis,itfollows thatr isregular.

Letp=p1;p2.Bydefinition,r=r»p1;p2=(r»p1)»p2.Bytheinductionhypothesis,itholdsthat˜r=(r»p1)isregular.

Hence,bytheinductionhypothesis,itfollows thatr= ˜r»p2 isregularaswell.

The proof of (b) is by induction on n. The base case, when n=1, follows by Lemma 6(a). The induction step follows immediatelybytheinductionhypothesis,asr»pn+1=(r»pn)»p. 2

Lemma7.Letr bearegularaliasrelationand p ::= p;p|thenpelsepend|

createx|forgetx|x:= s| looppend

(17) Inasequentialsetting,thefollowinghold:

(a) r»p isregular;

(b) r»pn,withn1,isregular.

Proof. Theproofof(a)isbyinductiononn–thenumberofnestedloopsin p.

Basecase: n=0.Theresultfollows immediatelybyLemma 6(a), for p abasicblockasin(15).

Let p=p1;loopqend;p2,with p1,p2and qbasicblocksasin(15).Thefollowingholds:

r=r»p1;loopqend;p2=

n∈N

r»p1»qn»p2. Hence,byLemma 6(b),risregular.

Inductionstep. Assume r»p is regular for all regular relations r and p instruction blocks with maximum n nested loops,builtasin(17).Let p=p1;loopqend;p2,with p1,p2 andq instructionblockswithmaximumnnestedloops, builtasin(17).It isthecasethat r=r»p1;loopqend;p2=

n∈Nr»p1»qn»p2. Hence,r isregularbytheinduction hypothesis.

(8)

The proof of (b) is by induction on n. The base case, when n=1, follows by Lemma 7(a). The induction step follows immediatelybytheinductionhypothesis,asr»pn+1=(r»pn)»p. 2

Lemma8.Letr bearegularaliasrelationand f afunctionwith|f |asin(17).Inasequentialsetting,thefollowinghold:

(a) r»callf(l0)and r»x.callf(l0);

(b) r»callf(l0)». . .»callf(ln)and r»x.callf(l0)». . .»x.callf(ln)

areregular,wheren∈Nandli(0in)representvalidlistsofactualargumentsof f .

Proof sketch. The result is a direct consequence of Lemma 7 and exploits the definition of (qualified) function calls in(13). 2

Wecallnon-recursivecontrolblocksthecontrolblocksbuiltasin(8),that lack(mutual)recursion.

Lemma9.Letr bearegularaliasrelationandp anon-recursivecontrolblock.Inasequentialsetting,thefollowinghold:

(a) r»p isregular;

(b) r»pn,withn1,isregular.

Proofsketch. TheresultisadirectconsequenceofLemma 7andLemma 8. 2

We callnon-qualifiedrecursivefunctions the (mutually)recursive functions built asin (8), that lackqualified (mutually) recursivecalls.

Next,weshowthattheexecutionofnon-qualifiedrecursivecallsleadtoregularrelationsaswell.Inshort,ourapproach consists ofprovidingaflattening of therecursivefunctions byextractingthecontrolblocks that do notinclude (mutually) recursive calls. Eventually, we combine these blocks via sequencing ; and exponentiation (−)n in order to derive over- approximating aliases.Thistechniquecannotbeappliedinthecontextofqualifiedfunction calls,asitloosesthenecessary informationfortransposing thecontextofthequalifiedcalltothecontextofthecaller.

Wefirstprovideanover-approximatingresultforthe(instructive)caseofasimplerecursivefunction,where,intuitively, the“flattening”procedure returnstwonon-recursive blocks(p1and p2).

Lemma10.Letr bearegularaliasrelationand f(l)= {p1;callf(l);p2}

beanon-qualifiedrecursivefunction,withp1,p2non-recursivecontrolblocksandl,lvalidargumentlists.Inasequentialsetting,it isthecasethat

r»callf(l0)

isregular,wherel0isavalidlistofactualparametersof f .

Proof. First,forsimplicityofnotation,wewriteli,i1,inordertorefertotheactualparametersof f correspondingtoits i’threcursivecall.Then:

r»callf(l0) = r[f:l0]» | f | = r[f:l0]»p1»callf(l1)»p2 = (r[f:l0]»p1)[f:l1]»p1»callf(l2)»p2»p2 = . . . =

((r[f:l0]»p1)[f:l1]»p1. . .)[f:ln]»p1»callf(ln)»pn2,

for n∈N. Letr bethealias relationobtained from r byrepeatedly replacingtheactual argumentsof f with theirformal counterparts, inthereasoning above.Thus, alsobasedon theresults inLemma 7,it follows thatr isregular. Additionally, thealiasinginformationcorrespondingtor»callf(l0) canbeover-approximatedby

i,j∈Nr»pi1»p2j.Hence,asr isregular and p1,p2 arenon-recursive controlblocks, thestatementinLemma 10isaconsequenceofLemma 9. 2

Definition11 (Flattening). Consider f, g two non-qualified recursive functions, S a non-recursive control block, and C a possiblyrecursive,butnon-qualifiedrecursive,controlblock. SandC canalsobeempty,i.e.,theyaresemanticallyequivalent withanemptysequencing(;).Moreover, f and gmightrefertothesamefunction.

Byabuseofnotation,wewrite S[f:u] inordertorefertotheblock S “enriched” withtheinformation[f:u]necessary accordingto(13)inordertoreplacethelistofactualargumentsuofthefunction f withitsformalcounterpart f.

Theflatteningof f(u)isrecursivelydefinedasfollows:

(9)

flat(f(u)) = flat(| f |,[f:u]) flat(;,[f:u]) = ∅

flat(S,[f:u]) = {S[f:u]}ifS=;

flat(S;g(v);C,[f:u]) = flat(S,[f:u])∪flat(C,[f:u])∪flat(g(v)) Asexpected, theexecutionr»S[f:u]isdefinedasr[f:u]»S.

Lemma12.Letr bearegularaliasrelationand f anon-qualified(possiblymutually)recursivefunction.Inasequentialsetting,itis thecasethat

r»callf(l)

isregular,wherel isavalidlistofactualparametersof f .

Proofsketch. First, notethat thealiasrelationr»callf(a)canbesoundlyover-approximatedby

k∈ {1, . . . ,n} hk,wN qkflat(f(l))

r»(qh11;. . .;qhnn)w (18)

where n stands for the size of flat(f(l)), and r is obtained from r by repeatedly replacing the actual arguments of the (possibly mutually) recursive calls with their formal counterparts, according to the semantics of the “enriched” control blocksqi.As risregular,thestatementinLemma 12isaconsequenceofLemma 9. 2

Theorem13. Assumep aprogrambuiltaccordingtotherulesin(8)thatdoesnotcontainqualifiedrecursivecalls.Letr bearegular relation.Then,inasequentialsetting,therelationsr»p andr»pn,withn∈N,areregular.

Proofsketch. Theprooffollows byinductiononthestructureof p and Lemmas 6–12. 2

Inspired by theidea behind the pumpinglemmaforregularlanguages[37], inwhat follows,we show that in sequential settings, executions of shape r»pn, for n∈N, can beover-approximated by aregular alias relation “closed underthe ap- plication of p”. More precisely, there exists a regular alias relation R that includes all aliases produced by r»pn, for all n∈N.

Definition14 (Closureunderprogramexecutions).We writewords(e) inorderto referto theset of wordscorresponding to theregular aliasexpressione.Let r bearegularalias relation.Wewritereg(r) inordertorepresent afiniteregularalias relation R suchthat:

if[e1,e2]∈r then∃[E1,E2]∈R s.t.words(e1)words(E1) andwords(e2)words(E2)

By abuseofnotation,wewriterR wheneverif[e1,e2]∈r then∃[E1,E2]∈R s.t.words(e1)words(E1) and words(e2)words(E2).Let p beacontrolblockasin(8).Wesaythatreg(r)=R isclosedundertheexecutionofp whenever R»pnR, foralln∈N.

Lemma15.Considerr aregularaliasrelation,andp ablockasin(8)thatdoesnotcontainqualifiedrecursivecalls.Inasequential setting,itisthecasethatthereexistsm∈NandR aregularaliasrelationsuchthatreg(r»pm)=R isclosedundertheexecution of p.

Proofsketch. The resultfollows asa consequence ofthe “pumping lemmafor regular languages”.Recall that, due to the executionofloopsand(unqualified)recursivefunctioncalls,aliasexpressions[e1,e2]inr»pi,withi∈N,growinaregular fashion.Hence,theremustbea“sufficientlylarge”m∈Nand Raregularaliasrelationsuchthatexpressionse1ande2may be“pumped”.Thatis,e1 ande2haveamiddlesectionsrepeatedanarbitrarynumberoftimes,toproducenewexpressions that alsobelongto R. 2

4. ARL-basedprocedureforcollectingaliases

In thissectionwe providethespecification ofaRL-based mechanismcollecting thealiasinformation. TheRL rulesare specifiedusingtheKnotationforconfigurationsand areimplementedinMaudeon topoftheformalizationofSCOOP[1]

(werefertoSection5formoredetailsonourapproach).

In short, our strategy is to start with aprogram built on top of the control structuresin (8), thento apply their cor- responding K-rules in orderto getthe “may aliasing”information in a designated K-cell (al). Independently of the

(10)

setting (sequential orconcurrent)one can exploitthisapproachin orderto evaluate thealiasesofa given finitelength L.

We alsoshow that for sequentialcontexts, forcontrol blocks notincludingqualified recursivecalls,theapplication of the K-like rulesisfiniteand thealiasesinthefinalconfigurationsoundlyover-approximate the(infinite) “mayalias”relations ofthecalculus.

K-likenotationsforconfigurationsand(RL)rules K[38,36]isanexecutable semanticframework originatingfromRewriting Logic[5],suitablefordefining(concurrent)languagesandcorrespondingformalanalysistools.K-definitionsmakeuseofthe so-called cells,which arelabeled andcan benested,and (rewriting) rulesdescribing theintended(operational) semantics.

Inthissectionweadopt aK-likenotationinordertoprovideaRL-basedspecificationofthealiascalculus.

Acell isdenoted by−[name],where [name]standsfor thenameofthecell.Intuitively, aconstruction.n standsfor an emptycell namedn.We use“patternmatching” and writec . . .n fora cellwithcontent c atthetop,followed byan arbitrarycontent(. . .).Wecanutilizecellsofshape. . . cn and . . .c. . .n,definedintheobviousway.

Of particular interest is −k – the continuationcell holding the stack of program instructions, in the context of a programminglanguageformalization.Wewrite

i1i2 . . .k

for a set of instructions to be“executed”, starting with instruction i1, followed by i2. The associative operation isthe instructionsequencing.

Arule c . . .n1

c cn2. . . . n3

c

reads as: ifcelln1 has c atthetopandcelln2 containsvalue c, thencisreplacedbyc inn1 andc isaddedattheend ofthecelln3.Thecontentofn2remainsunchanged.

We furtherprovide thedetailsbehind the K-like specificationof thealias calculus.As expected, thek-cell retains the instruction stack of the object-oriented program. We utilize cells −al to enclose the current alias information, and the so-called back-trackingcellsbkt-. . . enablingthe soundcomputation ofaliases forthe caseof thenelseend and, in non-concurrentcontexts, forloopendstructuresand (possiblyrecursive)function calls.As aconvention, wemark with (♣)therulesthataresoundonlyfornon-concurrentapplications,basedonLemma 15.

ThefollowingK-likerulesarestraightforward,basedontheaxioms(9)–(14)inSection3.1.Namely,theruleimplement- inganinstruction p;qsimplyforcesthesequentialexecutionofp andqbypositioning pqatthetopofthecontinuation cell:

p;q . . .k

pq (19)

Handling create x and forget x compliesto the associated definitions.Namely, it updatesthecurrent aliasrelation by removing allthepairshaving(at least)oneelement withxasprefix.Inaddition,italsopopsthecorrespondinginstruction fromthecontinuationstack:

r al

rx

createx. . .k

.

r al

rx

forgetx. . .k

. (20)

The assignment rule restores the current alias relation according to its axiom in (14), and removes the assignment instructionfromthetopofthek-cell:

r al

(r1t)[t=(r1/st)] −ot

t:=s. . .k

. withr1=r[ot=t] (21)

Handling then p else q end statements is more sophisticated, as it requires instrumenting a stack-based mechanism enablingthecomputationoftheunionofalias relationsr»pr»qinthreesteps.First, wedefinetheK-likerule:

r althenpelseqend. . .k

p et q ee

. . . .bkt-te

r,ptr,qe (22) savingatthetopoftheback-trackingstack−bkt-te theinitialaliasrelationr tobemodifiedbyboth pandq,viatwocells r,pt andr,qe,respectively.Notethattheoriginal instructioninthek-cellisreplacedbyaconstructionmarkingtheend oftheexecutionscorrespondingtothethen andelsebrancheswith et and ee ,respectively.

Second,wheneverthesuccessfulexecutionofp (signaledby et )atthetopofthek-cell)buildsanaliasrelationr,the executionofqstartingwiththeoriginalrelationr isforcedbyreplacingr withr in−al,and bypositioningq ee atthe topofthek-cell. Thenewalias informationafter p,denoted byr,pt,isupdatedintheback-tracking cell:

ral

r

et q ee . . .k

q ee

r,ptr,qe. . .bkt-te

r,pt

(23)

Referenzen

ÄHNLICHE DOKUMENTE

Different from the digital signatures, which are based on computational complexity, the proposed protocol has perfect security in the noiseless quantum channels.. Compared to

The 2D nutation exchange NMR and NQR powder patterns are calculated for spins I = 1 and I = 3/2 for different symmetry of reorienting molecular groups.. Key words: 2D Spectroscopy;

oriented  instructional  practice  be  made  based  on  the  classroom  artifacts  and  teacher  reflections  assembled  in  the  Scoop  Notebook?”    This 

Weiteres informierte Frau Bergknapp, welche selbst Betriebswirtschaftslehre stu- dierte und die Personalleiterin von Infineon darstellt, über die vielfältigen

In general the set of states will be a subset of , as a consequence there can be more event vectors than contained in , such that (1.15) still holds, thus. Let us sum up

Falls nach einer Manipulation auf dem Mobil- telefon Guthaben an einem anderen POS ausgege- ben wird, so wird dies nicht unmittelbar erkannt, sondern erst, wenn diese Transaktion

the normal operation, since after wrong timeout expiration, the system moves definitely into the state 7 (p2.p3,p4,p6), which characterizes duplex transmission; however,

To make a transition from one configuration to another, we pick an applicable guarded action from the head of the program expression, and then transform the model and the