HAL Id: hal-02392938
https://hal.inria.fr/hal-02392938
Submitted on 4 Dec 2019
HAL is a multi-disciplinary open access
archive for the deposit and dissemination of
sci-entific research documents, whether they are
pub-lished or not. The documents may come from
teaching and research institutions in France or
abroad, or from public or private research centers.
L’archive ouverte pluridisciplinaire HAL, est
destinée au dépôt et à la diffusion de documents
scientifiques de niveau recherche, publiés ou non,
émanant des établissements d’enseignement et de
recherche français ou étrangers, des laboratoires
publics ou privés.
A lightweight deadlock analysis for programs with
threads and reentrant locks
Cosimo Laneve
To cite this version:
Cosimo Laneve. A lightweight deadlock analysis for programs with threads and reentrant locks.
Science of Computer Programming, Elsevier, 2019, 181, pp.64 - 81. �10.1016/j.scico.2019.06.002�.
�hal-02392938�
Contents lists available atScienceDirect
Science
of
Computer
Programming
www.elsevier.com/locate/scico
A
lightweight
deadlock
analysis
for
programs
with
threads
and
reentrant
locks
Cosimo Laneve
1DepartmentofComputerScienceandEngineering,UniversityofBologna–INRIAFocus,Italy
a
r
t
i
c
l
e
i
n
f
o
a
b
s
t
r
a
c
t
Articlehistory: Received5October2018
Receivedinrevisedform11June2019 Accepted14June2019
Availableonline21June2019 Keywords:
Deadlockanalysis Threadsandreentrantlocks Lams
Circularities Staticsemantics
Deadlockanalysis of multi-threaded programs with reentrant locks is complex because theseprograms may haveinfinitely manystates. We define asimple calculus featuring recursion, threads and synchronizations that guarantee exclusive access to objects. We detectdeadlocksbyassociatinganabstractmodeltoprograms–theextendedlam model –andwedefineanalgorithmforverifyingthataproblematicobjectdependency (e.g. a circularity)betweenthreadswillnotbemanifested.
Theanalysisislightweightbecausethedeadlockdetectionproblemisfullyreducedtothe correspondingoneinlams(withoutusingothermodels).Infact,thetechniqueisintended tobe aneffective tool forthe deadlock analysis ofprogramming languages bydefining ad-hocextractionprocesses.Wedemonstratethiseffectivitybyapplyingouranalysistoa corecalculusfeaturingsharedobjects,threadsandJava-likesynchronizationprimitives. Wealsodiscussaprototypeverifier,calledJaDA,thatcoversseveralfeaturesofJavaand deliverinitialassessmentsofthetool.
©2019ElsevierB.V.Allrightsreserved.
1. Introduction
Threadsandlocksare acommonmodelofconcurrent programmingthat isnowadayswidelyused bythemainstream programming languages(
Java
,C#
.C++
,Objective
C
, etc.). In theselanguages,deadlocksare flaws that occur when two or morethreads are blockedbecause eachone is attemptingto acquire an object’slock heldby another one.As an example,considerthefollowingmethodsetTable(C x,C y,int n) = (new C z)( if (n=0) then sync(y){ sync(x){ 0 } } else fork{ sync(x){ sync(z){ 0 } } } z.setTable(z,y,n-1)
)
where
new
C
z
createsanewobjectofclassC
,fork
{
P}
Q createsanewthreadwhosebodyis P andrunsitinparallel withthecontinuation Q ,andsync(x){
P}
istheoperationlockingtheobjectx
,performing P ,andreleasingx
when P terminates.ThemethodsetTable
createsatable ofn+
1 threads –thephilosophers –each one sharingan object– thefork –withthenearbyphilosopher.Everyphilosopher,exceptone,grabstheforkonhisleft–thefirstargument–and onhisright–thesecondargument–inthisorderandthenreleasesthem.Theexceptionalcaseisthethen
-branch(n=0
) wherethegrabbingstrategyisopposite.Itiswell-knownthat,whenthemethodisinvokedwithx.setTable(x,x,n)
,E-mailaddress:cosimo.laneve@unibo.it.
1 ResearchpartlysupportedbytheH2020-MSCA-RISEprojectID778233“BehaviouralApplicationProgramInterfaces(BEHAPI)”.
https://doi.org/10.1016/j.scico.2019.06.002 0167-6423/©2019ElsevierB.V.Allrightsreserved.
nodeadlock willeveroccurbecause atleastone philosopherhasa strategythat isdifferentfromtheotherones. Onthe contrary,ifwechangethe
then
-branchintosync(this){
sync(y){
0
}
}
adeadlock mayoccur because philoso-phers’strategiesare allsymmetric.Itisworthtonoticethatx.setTable(x,x,0)
isdeadlock-freebecauseitjustlocks twicetheobjectx
,whichisadmittedinthemodelwiththreadsandlocks–athreadmayacquireasamelockseveraltimes (lock-reentrancy).Inordertoensuretermination,currentanalyzers [4,7,1,16,27,28] usefiniteapproximatemodelsrepresentingthe
depen-dencies between object names. The corresponding algorithms usually return false positives with input
x.setTable(x,x,n)
becausetheyarenotpowerfulenoughtomanagestructuresthatarenotstaticallybounded. In [11,17] we solved this problem for value-passing CCS [21] and pi-calculus [22]. In that case, the technique used two formal models: PetriNets [25] anddeadLockAnalysisModels – lams [12]. The former onesare a well-known model ofconcurrent anddistributedsystems; the latteronesare basic recursive modelsthat collect dependencies andfeatures recursion anddynamic name creation. Inthe pi-calculus analyzer,Petri Netswere used toverify the consistency ofthe communication protocol of every channel, while lams were used for guaranteeing the correctness of the dependencies betweendifferentchannels.Theanalysisalgorithmof [11,17] requiredatoolforverifyingthereachabilityofPetriNetsthat modelchannels’behaviors (whichhasexponentialcomputational complexitywithrespecttothesizeofthenet [15])and a tool foranalyzing lams(which hasexponential computational complexity withrespectto thenumber ofargumentsof functions).Inthispaperwedemonstratethatitispossibletodefineadeadlockanalyzerforprogramswiththreadsand(reentrant) locksbyonlyusinganextensionoflams.Forexample,thelamfunctioncorrespondingto
setTable
is2setTable
(
t,
x,
y)
= (
ν
s,
z)
(
y,
x)
t+ ((
x,
z)
s&setTable
(
t,
z,
y))
.
Theterm
(
y,
x)
t,calleddependency,indicatesthatthethreadt,whichownsthelockof y,isgoingtograbthelockofx.The operation “+
” and“&”are disjunctionandconjunctionsof dependencies, respectively.The indext of(
y,
x)
t was missing in [12,11,17];ithas beennecessary formodeling reentrant locks.Inparticular,(
x,
x)
isa circularity inthe standardlam model,whilst(
x,
x)
t isnotacircularityintheextendedlammodel becauset canacquirex twice.Therefore,setTable
(
t,
x,
x)
manifestsacircularityinthemodelof [12,11,17] anditdoesnotintheextendedmodel.Acircularityintheextendedmodel is(
y,
x)
t&(
x,
y)
s,whichdenotesthattwodifferent threadsareattemptingtoacquiretwoobjectsindifferentorder.Thislam gives(
x,
x)
,whichrepresentsacircularity.Becauseoftheforegoing extension,thealgorithm fordetecting circularitiesinextendedlams isdifferentthantheone in [11,17]. Inparticular, while there is a decisionalgorithm for the presence/absence of circularities instandard lams,in Section 2wedefine an algorithmthat verifiestheabsence andis impreciseinsomecases(it mayreturnthat alamwill manifestacircularitywhileitwillnotbethecase–afalsepositive).
Wealsodefineasimplelanguageofconcurrentprogramsfeaturingrecursion,threads,sharedobjectsandsynchronization primitivesinspiredtothoseof
Java
.(TheforegoingmethodsetTable
isatermofourcalculus.)Thesyntax,semantics, andexamplesofthecalculusareinSection3.Section4reportsatypesystemthatassociateslamstoprocesses.Forexample, thetype systemreturnsthelamfunctionsetTable
forthemethodsetTable
.Asa byproductofthetype systemand thealgorithmfordetectingcircularitiesinlams,ourtechniquecandetectdeadlocksofprogramslikesetTable
.In order to deliver initial assessments of our technique, we have extended the basic language in Section 3 to cover severalfeatures of
Java
. InSection 5 we focus on inheritancethat allows classes to be definedassub-classes of other onesby deriving the corresponding method(and field) definitionsand eventually redefinethem (method overriding). In a languagewithinheritance, locating amethod definitionisperformedatrun-timethrougha mechanismcalleddynamic dispatch thatusestheactualvalue ofthecalledobject.Sinceourtechnique extractslamsfromprograms atstatictime,the precisemodeling ofdynamicdispatchisnotfeasible.Wethereforeover-approximatethetypebyreturningthelamfunctions ofeverypossibleoverriddenmethodinthesubclasses.InSection6wealsoanalyzeassignmentsandrecursivedata-types. TheanalysisofotherfeaturesofJava
canbefoundinGarcia’sPhDthesis [9].Thisanalysisdoesnotaddresscoordination primitives(methodswait
,notify
andnotifyAll
)andJava
concurrentlibraries,suchasjava.util.concurrent
, –seeSection9foradiscussion.Ourtheoreticaldevelopmentsarecomplementedbyan analyzerprototypecalled
JaDA
[10,19].Whilethetype system inthispapersimplychecksstaticinformation,JaDA
infers thebehavioral typesfromthe code.Inferenceisimportantin practicebecauseitlightensthe analysisbutcheckingiscrucialfortypesafety.Section 7reportsoninitialassessments of thetool.Wediscussafew weaknessesofthetechniquesinSection8 andwe pointtorelatedworksandgive some concluding remarksinSection 9.Thepaperalsoincludesanappendixthatcontainsthedemonstrationoftypesafetyforthelanguage ofSection3andthetypesystemofSection4.
Thispapercollectstwoconferencecontributionsaboutdeadlockanalysisof
Java
-likelanguages: [18] and [19].Herewe extend [18] withtheproofoftypesoundnessandwiththediscussionontheextensionsofthebasiccalculusinSection 3.2 Actually,thisisasimplifiedformofsetTable.ThelamfunctionassociatedtosetTablebythetypesysteminSection4hastwoadditionalnames
Withrespectto [19],weadopta differentpresentationstyle.Wediscusstypingrulesforthe
Java
language,whileinthe conferencepaperthefocuswasonJava
bytecode.2. Lamsandthealgorithmfordetectingcircularities
This sectionextends thetheory developedin [11,17] tocover threadreentrancy.Inparticular, thenewdefinitions are thoseoftransitiveclosureandDefinition2.3.Theorem2.8isnew.
Preliminaries. We usean infiniteset
A
ofnames,rangedoverbyx, y,t,s,· · ·
.ArelationonA
,denotedR
,
R
,
· · ·
,isan element ofP(A × A × (A ∪ {,
•}))
,whereP(·)
isthestandardpowersetoperator,· × ·
isthecartesianproduct,and,
•
∈
/
A
aretwospecial names.TheelementsofR
,calleddependencies,aredenotedby(
x,
y)
t,wheret iscalledthread.The nameindicatesthatthedependencyisduetothecontributionsoftwoormorethreads;
•
indicatesthatthedependency isduetoathreadwhosenameisunknown.Let
–
R
+betheleastrelationcontainingR
andclosedundertheoperations: 1. if(
x,
y)
t,
(
y,
z)
t∈ R
+ andt=
tthen(
x,
z)
∈ R
+;2. if
(
x,
y)
t,
(
y,
z)
t∈ R
+,t∈
A ∪ {}
,then(
x,
z)
t∈ R
+; 3. if(
x,
y)
•,
(
y,
z)
•∈ R
+,(
x,
y)
•= (
y,
z)
•,then(
x,
z)
∈ R
+.–
{R
1,
· · · ,
R
m}
{R
1,
· · · ,
R
n}
ifandonlyif,forallR
i,thereisR
jsuchthat 1. if(
x,
y)
t∈ R
i,t∈
A
,then(
x,
y)
t∈ R
j+2. if
(
x,
y)
∈ R
itheneither(
x,
y)
∈ R
j+orthereist∈
A
suchthat(
x,
y)
t∈ R
j+; 3. if(
x,
y)
•∈ R
i theneither(
x,
y)
•∈ R
j+orthereist
∈
A
suchthat(
x,
y)
t∈ R
j+. –{R
1,
· · · ,
R
m}
&{R
1,
· · · ,
R
n}
def
= {R
i∪ R
j|
1≤
i≤
mand 1≤
j≤
n}
.Weuse
R,
R
,
· · ·
torangeover{R
1,
· · · ,
R
m}
,whichareelementsofP(P(A × A × (A ∪ {,
•})))
.The names
and
•
aremanaged inanad-hocwayinthetransitiveclosureR
+ andintherelation.Inparticular,if
(
x,
y)
t and(
y,
z)
t belongtoarelationandt=
t,thedependencyobtainedby transitivity,e.g.(
x,
z)
,recordsthatithas beenproduced byacontributionoftwodifferentthreads–thisisimportantforseparatingcircularities,e.g.(
x,
x)
,from lockreentrancy,e.g.(
x,
x)
t.Thename•
copeswithanotherissue:itallowsustoabstractawaythreadnamesthatarecreated inside methods.For thisreasonthetransitivedependency of(
x,
y)
• and(
y,
z)
• is(
x,
z)
because thethreads producing(
x,
y)
•and(
y,
z)
•mightbedifferent.ThemeaningofR R
isthatR
is“moreprecise”withrespecttopairs(
x,
y)
:ifthis pairisindexedwitheitheror
•
insomeR
∈
R
then itmaybeindexedbyat (t=
)inthecorresponding(transitive closure)relationofR
.Forexample{ {(
x,
y)
•,
(
y,
z)
•,
(
x,
z)
} } { {(
x,
y)
t,
(
y,
z)
t} }
and{
{(
x,
x)
•} } { {(
x,
x)
t,
(
x,
x)
t}
}
.Definition2.1.Arelation
R
hasacircularity if(
x,
x)
∈ R
+forsomex.AsetofrelationsR
hasacircularity ifthereisR
∈
R
thathasacircularity.
Lams. Inourtechnique,dependenciesareexpressedbymeansoflams [12],noted
,whosesyntaxis
::=
0| (
x,
y)
t| (
ν
x)
|
&| + | f(
x)
The term0istheempty type;
(
x,
y)
t specifiesadependencybetweenthenamex andthename y thathasbeencreated by (thethread)t.Theoperation(
ν
x)
createsanewname x whosescope isthetype; theoperations
&
and
+
definetheconjunctionanddisjunctionofthedependenciesinand
,respectively.Theoperators
+
and& areassociative and commutative; theoperator & has precedence over+
. The termf
(
x)
defines the invocationoff
witharguments x. Theargumentsequencex hasalwaysatleasttwoelementsinourcase:thefirstelementisthethreadthatperformedthe invocation,thesecondelementisthelastobjectwhoselockhasbeenacquiredbyit.Alamprogram isapair
L ,
,where
L
isafiniteset offunctiondefinitionsf
(
x)
=
fwith
f beingthebody of
f
,andisthemainlam.Wealwaysassumethat(i)x isasequenceofpairwisedifferentnames
and(ii)
f
= (
ν
z)
f wherefhasno
ν
-binder.Theconstraint(ii)alsoappliestoand,wheneverwewrite
L ,
(
ν
x)
wealwaysmeanthathasno
ν
-binder.ThefunctionsetTable
intheIntroductionisanexampleofalamfunction.Letalamcontext,noted
L
[ ]
,beatermderivedbythefollowingsyntax:L
[ ] ::= [ ]
|
&
L
[ ]
|
+ L[ ]
Asusual
L
[]
isthelamwheretheholeofL
[ ]
isreplacedby.Weremarkthat,accordingtothesyntax,lamcontextshave no
ν
-binder.Sincerelations
R
are collectionsofdependencies, withanabuseofnotation, we oftenuseR
and&(x,y)t∈R(
x,
y)
tinter-changeably,allowing thecontexttodisambiguate whetherwe meana relationora lam.Forexample,wewilloftenwrite
L
[R]
meaningthe lamL
[
&(x,y)t∈R(
x,
y)
t]
.Similarly, whenwewriteR
{
y/
x}
,we maymeaneithertherelationR
wherethe occurrencesofx inthedependencieshavebeenreplacedby y orthelam(
&(x,y)t∈R(
x,
y)
t)
{
y/
x}
.The operational semanticsof a lamprogram
L ,
(
ν
x)
is a transitionsystemwhere states are lams,the transition relation isthesmallesttransitionrelationinducedbythefollowingrule(Red)
f
(
x)
= (
ν
z)
f∈
L
zare freshL
[f(
u)
] −→ L[
f{
z
/
z}{
u/
x}]
withinitialstate
.Wewrite
−→
∗ forthereflexiveandtransitiveclosureof−→
.Forexample,if
f
(
t,
x)
= (
ν
s,
z) ((
x,
z)
t&f
(
s,
z))
thenf
(
t,
x)
−→ (
x,
z)
t&f
(
t,
z)
,where t andz are freshnames. By continuingtheevaluationoff
(
t,
x)
,thereadermayobservethat(i)everyinvocationcreatesnewfreshnamesand(ii)the evaluationdoesnot terminatebecausef
is recursive.Thesetwo points implythata lammodelmayhave infinitestates, whichmakestheanalysisnontrivial.Flatteningandcircularities. Lamsrepresentelements oftheset
P(P(A × A × (A ∪ {,
•})))
.Thispropertyisdisplayed by thefollowingflatteningfunction.LetL
bea setoffunctiondefinitionsandlet I(
·)
,calledflattening, bea functionon lams that(1)maps functionnamef
definedinL
to elements ofP(P(A × A × (A ∪ {,
•})))
and(2)isdefinedon lamsasfollowsI
(
0)
= {∅},
I((
x,
y)
t)
= {{(
x,
y)
t}},
I(
&)
=
I()
&I(
),
I
(
+
)
=
I()
∪
I(
),
I((
ν
x) )
=
I()
{
x/
x
}
with xfresh,
I
(f(
u))
=
I(f)
{
u/
x
}
(where x are the formal parameters off
).
Let I⊥ be themap suchthat, forevery
f
definedinL
, I⊥(f)
= {∅}
.Forexample,letsetTable
be thefunctioninthe IntroductionandletI
(setTable)
= {{(
y,
x)
t}} = setTable(
t,
x,
y)
&(
x,
y)
s+ (
x,
y)
s.
Then I()
=
{(
y,
x)
t,
(
x,
y)
s}, {(
x,
y)
s}
,
I⊥()
=
{(
x,
y)
s}
.
Definition2.2.Alam
hasacircularity if I⊥
()
hasa circularity. Alam programL ,
(
ν
x)
hasacircularity if thereis−→
∗and
hasacircularity.
Forexampletheabovelam
hasacircularitybecause
setTable
(
t,
x,
y)
&(
x,
y)
s+ (
x,
y)
s−→ ((
y,
x)
t+ (
x,
z)
s&setTable
(
t,
z,
y))
&(
x,
y)
s+ (
x,
y)
s=
andI⊥
(
)
hasacircularity.Fixpointdefinitionoftheinterpretationfunction. Our algorithm relieson the computation oflam functions’ interpretation, whichisdonebyastandardfixpointtechnique.
Let
L
be the setf
i(
xi)
= (
ν
zi)
i, withi∈
1..
n.Let A=
i∈1..nxi and
be a specialname that doesnot occur in
L ,
.Weusethedomain
P(P((
A∪ {})
× (
A∪ {}) × (
A∪ {,
•}))), ⊆
whichisafinite lattice [5].
Definition2.3.Let
f
i(
xi)
= (
ν
zi)
i, with i∈
1..
n, be the function definitions inL
. The family of flattening functions I(k)L: {f
1,
· · · ,
f
n} →
P(P((
A∪ {})
× (
A∪ {}) × (
A∪ {,
•})))
isdefinedasfollows IL(0)(f
i)
= {∅}
IL(k+1)(f
i)
= {proj
xzi i(R
+)
| R ∈
I(k) L(
i)
}
whereproj
z x(R)
def=
{(
u,
v)
t| (
u,
v)
t∈ R
and u,
v∈
x and t∈
x∪ {}}
∪ {(, )
| (
u,
u)
∈ R
and u∈
/
x}
∪ {(
u,
v)
•| (
u,
v)
t∈ R
and u,
v∈
x and t∈
z}
Wenoticethat I(L0)isthefunctionI⊥.LetusanalyzethedefinitionofI(kL+1)
(f
i)
and,inparticular,thefunctionproj
:•
firstofall,noticethatproj
appliestothetransitiveclosuresofrelations,whichmayhavenamesin A,zi,,
•
and;
•
thetransitiveclosureoperationiscrucialbecauseacircularitymayfollowwiththekeycontributionoffreshnames.For instancethemodeloff
(
x)
= (
ν
t,
t,
z) (
x,
z)
t&(
z,
x)
t is{{(
x,
x)
}}
;themodelofg
()
= (
ν
t,
t,
x,
y) (
x,
y)
t&(
y,
x)
t is{
{(,
)
}
}
(thisisthereasonwhyweusethename);
•
everydependency(
u,
v)
t∈ proj
zx(R)
issuchthatu,
v∈
x,exceptfor(,
)
.Forexample,iff
(
x,
y)
= (
ν
s,
z) ((
x,
y)
s&(
x,
z)
s)
then,ifwe invokef
(
u,
v)
we obtain(
u,
v)
t&(
u,
z)
t,wheret andz arefreshobjectnames. Thislammay be simplified because, being z fresh and unknown elsewhere, the dependency(
u,
z)
t will never be involved in a circularity. For example,ifwe have= (
v,
u)
t&f
(
u,
v)
then we maysafely reasonon-simplified
(
u,
v)
t&(
u,
v)
t. Forthisreasonwedropthedependenciescontainingfreshnamesaftertheircontributiontothetransitiveclosurehasbeen computed;•
the sameargumentdoesnot applyto namesusedasthreads.Forexample,intheabove-simplifiedlamwecannot drop
(
u,
v)
t becausetisfresh. Infact,thecontext(
v,
u)
t&(
u,
v)
t givesacircularity. Therefore,dependencieswhose threadnamesarefreshmustbehandledinadifferentway.Wetakeasimplesolution:thesedependenciesallhave•
asthreadname.Thatis,weassume thatthey areallgeneratedby thecontributionofdifferentthreads.Forexample,g
(
x,
y)
= (
ν
t) (
x,
y)
t.Then, I(L1)(g
)
= {
{(
x,
y)
•}
}
.Example2.4.Theflatteningfunctionsof
setTable
areI(L0)
(setTable)
= {∅}
I(L1)
(setTable)
= { {(
y,
x)
t} }
Asanotherexample,considerthefunction
g
(
x,
y,
z)
= (
ν
t,
u) (
x,
y)
t&g
(
y,
z,
u)
.Then:I(L0)
(g)
= {∅}
I(L1)(g)
= { {(
x,
y)
•} }
I(L2)(g)
= { {(
x,
y)
•, (
y,
z)
•, (
x,
z)
} }
Proposition2.5.Letf
(
x)
= (
ν
z)
f∈
L
. 1. Forevery k,I(k)L(f)
∈
P(P((
x∪ {}) × (
x∪ {})
× (
x∪ {,
•})))
. 2. Foreveryk,I(k)L(f)
I(kL+1)
(f)
.Proof. (1)followsbydefinition.Asregards(2),weobservethat I
()
ismonotoniconI.Thatis,ifI andIaretwoflattening functions such that, for everyf
, I(f)
I
(f)
then it ispossible to demonstrate by a standard structuralinduction that I()
I
()
.Aninductiononk givesI(k)L(f)
I(kL+1)
(f)
.2
Since,foreveryk,I(k)L
(f
i)
rangesoverafinitelattice,bythefixpointtheory [5],thereexistsm suchthatIL(m)isafixpoint, namelyI(m)L≈
I(mL+1)where≈
istheequivalencerelationinducedby.Inthefollowing,welet IL,calledtheinterpretation function (ofalam),betheleastfixpointIL(m).InExample2.4,IL(1)isthefixpointof
setTable
andIL(2)isthefixpointofg
.Proposition2.6.Let
L
bealamcontext,bealamwithno
ν
binder,andI(
·)
beaflattening.Thenwehave: 1. I(L
[])
hasacircularityifandonlyifI(L
[R])
hasacircularityforsomeR
∈
I()
.2. Let
f
(
x)
= (
ν
z)
f∈
L
andR ∈
I(
f{
z
/
z})
withzfresh.IfI(L
[R{
u/
x
}])
hasacircularitythenI(L
[(proj
xz(R
+))
{
u/
x}])
hasa circularity.Proof. Property1followsfromthedefinitions.Tosee2,weuseastraightforwardinductionon
L
.WeanalyzethebasiccaseL = [
]
:thegeneralcasefollowsbyinduction.LetR ∈
I(
f{
z
/
z})
suchthatR
{
u/
x
}
hasacircularity.Therearetwocases:• (
v,
v)
∈ R
+.Bydefinitionofproj
z x(R
+)
either(
v,
v)
∈ proj
z x(R
+)
,whenv∈
/
z,or(,
)
∈ proj
z x(R
+)
,otherwise. Inthiscasethestatement2followsimmediately.• (
v,
v)
∈ R{
u/
x
}
+. BydefinitionoftransitiveclosureR
{
u/
x}
+= (R
+)
{
u/
x}
.Then thereisadependency(
x1,
x2)
∈ R
+suchthat
(
x1,
x2)
{
u/
x} = (
v,
v)
.Bydefinitionofproj
,(
x1,
x2)
∈ proj
zx(R
+)
.Thereforeproj
zx
(R
+)
{
u/
x}
hasalsoa circularity.2
Lemma2.7.Let
L = {f
1(
x1)
= (
ν
z1)
1,
· · · ,
f
n(
xn)
= (
ν
zn)
n}
andletL
[f
i1(
u1)
] · · · [f
im(
um)
] −→
mL
[
i1{
z 1/
z i1}{
u1/
xi1}] · · · [
im{
zm/
z im}{
um/
xim}]
where
L
[·]
· · · [·]
isamultiplecontextwithoutfunctioninvocations. IfIL(k)(L
[
i1{
z 1/
z i1}{
u1/
xi1}]
· · · [
im{
zm/
z im}{
um/
xim
}])
hasacircularitythenI(k+1)
L
(L
[f
i1(
u1)
]
· · · [f
im(
um)
])
hasalsoacircularity.Proof. Toshowtheimplicationsupposethat
IL(k)
(L
[
i1{
z 1/
zi1}{
u1/
xi1}] · · · [
im{
zm/
zim}{
um/
xim}])
hasacircularity.ByrepeatedapplicationsofProposition2.6(1),thereexists
R
j∈
IL(k)(
i1{
z
j
/
z ij}{
uj
/
xij
})
with1≤
j≤
m suchthat IL(k)
(L
[R
1]
· · · [R
m])
hasa circularity. It is easy to verifythat everyR
j maybe written asR
j{
uj/
xij
}
, forsomeR
j. By repeatedapplicationofProposition2.6(2),wehavethat
IL(k)
(L
[proj
zxi1 i1(R
1+)
{
u1/
x1}] · · · [proj
zim xim(R
m+)
{
um/
xm}])
hasacircularity.Since,forevery1
≤
j≤
m,proj
zxi j i j(R
j+)
{
u1/
x1} ∈
I (k+1) L(f
ij(
uj))
andsince
L
hasnofunctioninvocation,wederivethat IL(k+1)(L
[f
i1(
u1)
]
· · · [f
im(
um)
])
hasalsoacircularity.2
Unlike [11,17],Lemma2.7isstrictinourcase,foreveryk.Forexample,consider
h
(
x,
y,
z)
= (
ν
t) (
x,
y)
t&(
y,
z)
t.
Then,whenk
≥
1,I(k)L(h)
= {
{(
x,
y)
•,
(
y,
z)
•}
}
.Noticethat IL(k)(h(
x,
y,
x))
= {
{(
x,
y)
•,
(
y,
x)
•}
}
,whichhasacircularity–see Definition2.1.HoweverIL(k)
((
x,
y)
t&(
y,
x)
t)
= { {(
x,
y)
t, (
y,
x)
t, (
x,
x)
t} }
hasnocircularity(thisisacaseofreentrantlock).Theorem2.8.Let
L ,
(
ν
x)
bealamprogramand−→
∗.IfIL
(
)
hasacircularitythenIL()
hasalsoacircularity.ThereforeL ,
hasnocircularityifIL
()
hasnocircularity.Proof. Let
haveacircularity.Hence,bydefinition,I⊥
(
)
hasacircularityand,sinceI⊥(
)
=
IL(0)(
)
,byProposition2.5(2) I(L0)(
)
IL(
)
.Therefore IL(
)
hasalsoacircularity.Then,byLemma2.7,since IL isthefixpoint interpretation func-tion,IL()
hasalsoacircularity.2
Ouralgorithmforverifyingthat alamwillnever manifestacircularity consistsofcomputingIL
(f)
,foreveryf
,and IL()
, whereis the main lam.As discussed in thissection, IL
(f)
uses a saturation technique onnames based on a powersetconstruction. Henceit hasacomputational complexity thatis exponential onthenumberofnames. Weremind thatthenamesweconsiderarethearguments oflamfunctions(thatcorrespondstomethods’arguments),whichareusually notsomany.Infact,thisalgorithmisquiteefficientinpractice [10].3. Thelanguageanditssemantics
Inthis sectionwe define a simpleprogrammingmodel ofconcurrent object-oriented languagesfeaturing threadsand objectsynchronizations(thereadermayeasilyrecognizethebasicoperationsofthreadcreationandsynchronizationused in
Java
andC#
).Wegiveadescriptionofhowdeadlockmaybeidentified,anddiscussfewexamples.Thefollowingsection containsthetypesystemthatassociateslamstotheprograms.Ourmodelhastwodisjointcountable setsofnames: thereare integerandobjectnames,rangedover by x
,
y,
z,
t,
s,
· · ·
, andmethodnames,rangedoverbym
,n
,· · ·
.Aprogram isatupleC
1D
1,
· · · , C
nD
n,
Pwhere
D
iarefinitesets ofmethodnamedefinitionsm
(T
x)
=
Pm,withT
x beingtheformalparameters x andtheirtypesT
andPmbeingthebody of
m
;weassumethatmethodnamedefinitionshaveanimplicitformalparameterC
ithis whichrefersto thecarrier.Theprocess P isthemainprocess.TypesT
areeitherintegersint
orC
i.Thesyntaxofprocesses P andexpressionse isdefinedbelow
P
::=
0| (new C
x)
P| fork{
P}
P| if
ethen
Pelse
P|
x.m(
e)
| sync(
x)
{
P}
e::=
x|
v|
eop
eAprocesscanbetheinertprocess0,orarestriction
(new C
x)
P thatbehaveslike P exceptthattheexternalenvironment cannot accesstothe object x of classC
,orthe spawnfork
{
Q}
P of anew thread Q bya process P , ora conditionalif
ethen
Pelse
Q thatevaluatese andbehaveseitherlikeP orlike Q dependingonwhetherthevalueis=
0 (true)or=
0 (false),oraninvocationx.m(
e)
ofthemethodm
withcarrierx andactualparameterse.Thelastprocessissync
(
x)
{
P}
thatexecutes P withexclusiveaccesstox.Anexpressione canbeanamex,anintegervalue v,oragenericbinaryoperationonintegers
op
,whereop
ranges over a set includingthe usual operators like+
,≤
,etc. Integer expressions without names(constantexpressions) may be evaluatedtoanintegervalue(thedefinitionoftheevaluationofconstantexpressionsisomitted).LetJ
eK
betheevaluation of an expression e:J
eK
is undefined whene is an integer expression that contains integer names;J
xK =
x when x is a non-integername.To define the semantics ofthe above language, we usestates, ranged overby
P
,that are multisets of threads P•
σ
, whereσ
isa(possiblyempty)sequenceofobjectnamesrepresentingthelocksthattheprocess P hasalreadygrabbed(in order, fromtheleft toright).When P terminates,thelocksofσ
mustbeall released.Thethread P•
σ
isreentrant onx whenσ
contains atleasttwo occurrencesofx. Weusually write statesas P1•
σ
1| · · · |
Pn•
σ
n andsometimeshorten themintoi∈1..nPi
•
σ
i.Wewritex∈ P
ifP
containsσ
andx occursinσ
.Sincestatesaremultiset,weidentifythosethat are equalup-toassociativityandcommutativity of|
.Emptysequencesσ
are writtenε
.Inorderto easethedefinitions, wewillusefewnotationalconventions•
Object names are partitioned into infinitely countable disjoint sets that are addressed by class names. The notation z=
fresh(C)
statesthatz isafreshnameinthesetC
(e.g. z doesnotoccurinthestate).•
Wemakeexplicitthatz isanameinthesetC
bywritingz∈ C
.•
Ifaprogramhasapair
C
D
suchthatD
containsamethodm
(T
x)
=
P thenwewriteC
.m(T
x)
=
P∈
.Definition3.1.Theoperationalsemantics of a program
=
C
1D
1,
· · · ,
C
nD
n,
Pisa transitionsystemwherethe initial stateis P
•
ε
,andthetransitionrelation−→
istheleastoneclosedundertherules:(Zero) 0
•
σ
−→
(NewO) z=
fresh(C)
(new C
x)
P•
σ
| P −→
P{
z/
x} •
σ
| P
(NewT)fork
{
P}
Q•
σ
−→
P•
ε
|
Q•
σ
(IfT)[[
e]] =
0if
ethen
Pelse
Q•
σ
−→
P•
σ
(IfF)[[
e]] =
0if
ethen
Pelse
Q•
σ
−→
Q•
σ
(Call)J
eK =
v x∈ C C.m(T
z)
=
P∈
x.m(
e)
•
σ
−→
P{
x,v/
this,z} •
σ
(Sync) x∈ P
/
sync
(
x)
{
P} •
σ
| P −→
P•
σ
·
x| P
We oftenomit the subscript of
−→
when it isclear fromthe context. We write−→
∗ for the reflexive andtransitive closureof−→
.Wediscusstherelevantrules.Rule (Zero) modelstermination:everylocktakenbythethreadisreleasedandthethread disappears fromthe state(which isa multiset). Thisisbecause,accordingto thesyntax, thereis nocontinuation inthis case. Rule (NewO) creates a newobjectofclass
C
: we simply take aname that doesnot occurin thestate, replace the bound namewiththefreshone,andremovethebinder.Weobservethattherenamingonlyapplies to P :beingx new,it cannot havebeenalreadylocked(σ
isnot inthescope oftherenaming).Rule (NewT) spawnsa newthread thathasan empty sequenceoflocks(because ithasnotperformedanysynchronizationsofar).Rule (Call) dispatchestheinvocation totherightmethoddefinitionandexecutesthemethodbodyoncetheformalparametershavebeenreplacedbytheactual ones. Rule (Sync) modelssynchronizations.Athreadmaylockx provideditisnotalreadylockedby anotherthreadinthe state–premisex∈ P
/
.Weobservethatx mayoccurinσ
,thatisathreadmaylockx severaltimes(threadreentrancy).Ourbasicprogrammingmodeldoesnotretaintheexplicitinstructionforsequentialcomposition,e.g. P
;
Q .However, thisoperationmaybeeasilyencodedusingsynchronizations:(new C
x) sync(
x)
{ fork{sync(
x)
{
Q}}
P}
Thatis,wesequentialize P and Q byletting P to acquire thelockofanewobject x before spawning Q . Inturn Q will beginafter theterminationof P becausethelockofx isgrabbedbyit.Accordingtoourrules,wehave
(new C
x) sync(
x)
{ fork{sync(
x)
{
Q}}
P} •
σ
−→ sync(
x)
{ fork{sync(
x)
{
Q}}
P} •
σ
−→ fork{sync(
x)
{
Q}}
P•
σ
·
x−→
P•
σ
·
x| sync(
x)
{
Q} •
ε
and,byrule (Sync),Q cannotstartaslongasxislockedby P .Definition3.2(Deadlock-freedom).Aprogram
C
1D
1,
· · · ,
C
nD
n,
Pisdeadlock-free ifthefollowingconditionholds:
whenever P
•
ε
−→
∗P
andP
= sync(
x)
{
Q} •
σ
| P
then there existsP
such that
P
−→ P
.
Example3.3.Weselectthreeprocessesanddiscusstheirbehaviors,highlightingwhethertheydeadlockornot:
• fork{
sync(
x)
{
sync(
y)
{
0} }}
sync(
x)
{
sync(
y)
{
0} }
.Thisprocessspawnsathreadthatacquirethelocksofx and y in thesameorder ofthemainthread:nodeadlockwilleveroccur.•
Onthecontrary,theprocessfork
{
sync(
y)
{
sync(
x)
{
0} }}
sync(
x)
{
sync(
y)
{
0} }
spawnsathreadacquiringthelocks inreverseorder.Thisisacomputationgivingadeadlock:fork
{
sync(
y)
{
sync(
x)
{
0} }}
sync(
x)
{
sync(
y)
{
0} } •
ε
−→
sync(
y)
{
sync(
x)
{
0} } •
ε
|
sync(
x)
{
sync(
y)
{
0} } •
ε
−→
sync(
x)
{
0} •
y|
sync(
x)
{
sync(
y)
{
0} } •
ε
−→
sync(
x)
{
0} •
y|
sync(
y)
{
0} •
x•
Thefollowingmethodm
(C
x, C
y, int
n)
=
if
(
n=
0) then fork
{
sync(
y)
{
sync(
x)
{
0} }}
sync(
y)
{
0}
else
sync(
x)
{
this.m(
x,
y,
n−
1)
}
performsn-nestedsynchronizationsonthis (reentrancy)andthenspawnsathreadacquiringthelocks y andx inthis order,while themain threadacquire thelock y.Thismethoddeadlocksforevery n
≥
1,howeveritnever deadlocks whenn≤
0.4. Staticsemantics
Environments,rangedoverby
,containthetypesofobjects,e.g. x
: C
,thetypeofintegervariablese.g. x: int
,andthe typesofmethodnames,e.g.C
.m
: [T]
.Withoutlossofgenerality,inmethoddefinitionsofFig.1weorderformalparameters ofmethods:thoseoftypeclassareinfrontofthoseoftypeinteger.Therefore(C.m)
willhaveshape[C
,
int
]
.Letdom
()
bethedomainofandlet
• ,
x:T
,whenx∈
/
dom()
(,
x:T)(
y)
def=
T
if y=
x(
x)
otherwise•
+
,whenx∈
dom()
∩
dom(
)
implies(
x)
=
(
x)
:(
+
)(
x)
def=
⎧
⎨
⎩
(
x)
if x∈
dom()
(
x)
if x∈
dom(
)
undefined otherwiseProcesses: (T-Zero) ;σt0: (σ)t (T-New) ,x:C;σtP: x∈/σ ;σt(new Cx)P: (νx) (T-Sync) ;σ·xtP: ;σtsync(x){P} : (T-If) te: int ;σtP: ;σtP: ;σtifethenPelseP: + (T-Par) ;σtP: ,t: Thread,u: Obj;utP: ;σtfork{P}P: &(νt,u) (T-Call) (x)= C (C.m) = [C, int] u: C e: int
;σ·ztx.m(u,e): fC.m(t,z,x,u)&(σ·z)t Expressions: (T-Int) v: int (T-Var) ,x: T x: T (T-Op) e: int e: int eope: int (T-Seq) (ei: Ti)i∈1..n e1,. . .,en: T1,. . ., Tn Programs: (T-Prog) = {C.m : [C, int] | C.m(Cx, inty)=PC.m∈ }
,this: C,x: C,y: int,t: Thread,u: Obj;utPC.m: C.m
C.m(Cx,inty)=PC.m∈ L =C.m(Cx,inty)=P
C.m∈{fC.m
(t,z,this,x)= C.m}
,t: Thread,u: Obj;ut.main:
:L ,
Fig. 1. The type system (we assume a function namefC.mfor every method namemof classC).
Letalso
(
x1· · ·
xn·
xn+1)
t def=
⎧
⎨
⎩
0 if n=
0(
x1· · ·
xn)
t if xn+1∈ {
x1,
· · · ,
xn}
(
x1· · ·
xn)
t&(
xn,
xn+1)
t otherwise Thestaticsemanticshasthreejudgments:•
e: T
–theexpressione hastypeT
in;
• ; σ
tP:
–thethreadP withnamet haslamin
; σ
.Weassumethattheclassoft isapredefinedclassThread
andcontainsthebindingst
: Thread
;• :
L ,
theprogram
haslamprogram
L ,
in
.
In addition to
Thread
, thestatic semanticsalso usesanother predefinedclass, calledObj
. The objectsof thisclass are used fortyping newthreads (cf. rule (T-Par) inFig.1;thisexpedientallowsusto havea simplerrulefortyping function invocations.Fewnotationalconventionsareinorder.When
=
C
1D
1,
· · · ,
C
nD
n,
P,welet.
main=
P andwewriteC
i.m(T
x)
=
PC
i.m∈
wheneverD
i containsm
(
T x)
=
PC
i.m.ThetypesystemisdefinedinFig.1.Afewkeyrulesarediscussed.Rule (T-Zero) typestheprocess0inathreadt that haslockedtheobjectsin
σ
in(inverse)order.Thelamistheconjunctionofdependenciesinσ
withthreadt –cf. notation(
σ
)
t.Rule (T-Sync) types the critical section P with a sequence oflocks extended with x. Rule (T-Par) typesa parallel composition ofprocessesbycollectingthelamsofthecomponents.Weuseanewnamet forthespawnedthreadanda newnameufortheobjectthatisalreadygrabbedbyt.ThisobjecthasclassObj
.(Accordingtoourconvention,whenwe write,
t: Thread,
u: Obj
weassumethatt,
u∈
/
dom()
.)Rule (T-Call) typesamethodnameinvocationintermsofa (lam)functioninvocationandconstrainsthetypesofactualargumentstomatchwiththetypesofformalparametersinthe methoddeclaration.Theargumentsofthelamfunctioninvocationareextendedwiththethreadnameofthecallerandthe nameofthelastobjectlockedbyit(andnotyetreleased).Inadditionwealsoconjunctthedependencies(
σ
·
x)
t created by thecallerbecausethemethodinvocationruninathreadthat holdsthoselocks.Thisrulemustbereadinconjunctionwith (T-Prog). (T-Prog) associatesalamfunctiontoeverymethod–c.f. itssecondandthirdpremises.Thebodyofthelam function isdefinedby typing the bodyof themethodin thehypotheticalcontext wherethe threadonly owns one lock, which isgivenasargument ofthelam function.Ofcourse, thisis not thegeneralcase: amethod maybe invokedby a threadthatgrabsmanylocks.Toaddressthegeneralcasewe recordthelastobjectsynchronizedbythethreadandbuild thedependenciesoftheinvocationstartingfromit.Itturnsoutthat takingthesedependenciesinconjunctionwiththose ofthecaller–seerule (T-Call) –doessufficeforkeepingtrackoftheoveralldependencies(seePropositionA.1).Because ofthistechnicality,werequirethateverythread,eventhosethatarejustcreated,locksatleastoneobject.
Example4.1.Letusshowthetypingofthemethod
setTable
intheIntroduction.Let= C.setTable : [C, C, int],
this: C,
x: C,
y: C,
n: int,
t: Thread,
u: Obj
P= sync(
y)
{ sync(
x)
{
0} }
Q
= fork{sync(
x)
{ sync(
z)
{
0} }}
z.setTable(
z,
y,
n−
1)
Then
,
z: C;
u·
y·
xt0:
11
= (
u,
y)
t&(
y,
x)
t,
z: C;
u·
ytsync
(
x)
{
0} :
1,
z: C;
ut P:
1(
∗)
,
z: C;
ut Q:
2,
z: C;
utif
n=
0then
Pelse
Q:
1+
2;
ut(new C
z) (if
n=
0then
Pelse
Q)
: (
ν
z) (
1+
2)
where(
∗)
arethetwoprooftrees· · ·
,
z: C;
utz.setTable(
z,
y,
n−
1)
:
2 and· · ·
,
z: C,
t: Thread,
u: Obj;
wtsync
(
x)
{ sync(
z)
{
0} } :
2(asanexercise,thereadermaytrytocompletethem).Byrule (T-Par),wederive
2
=
2&(
ν
t,
u)
2.Aftercompletingthe prooftree,oneobtainsthelamfunctionsetTable
(
t,
u,
this,
x,
y)
=
(
ν
z,
t,
u)
(
u,
y)
t&(
y,
x)
t+ (
u,
x)
t&(
x,
z)
t&setTable
(
t,
u,
x,
z,
y)
whichhastwo additionalargumentswithrespectto theone intheIntroduction: u andthis.Infact, thesearguments,as wellasu,donotplayanyroleintheanalysisofcircularitiesof
setTable
(
t,
u,
this,
x,
y)
.Thefollowing theoremstatesthesoundnessofour typesystem. The technicaldetailsofthe proof arereportedinthe Appendix.
Theorem4.2.Let
C
1D
1,
· · · ,
C
nD
n,
P:
L ,
.If
L ,
hasnocircularitythen
C
1D
1,
· · · ,
C
nD
n,
Pisdeadlock-free.Example4.3.Letusverify whethertheprocess x
.setTable(
x,
x,
n)
isdeadlock-free.The lamfunction associatedby the typesystemisdetailedinExample4.1.Theinterpretationfunction IL(setTable)
iscomputedasfollows:IL(0)
(setTable)
= {∅}
IL(1)
(setTable)
= { {(
u,
y)
t, (
y,
x)
t, (
u,
x)
t} }
IL(2)
(setTable)
= { {(
u,
y)
t, (
y,
x)
t, (
u,
x)
t}, {(
u,
y)
t} } .
Since I(L2)