CFRefCount.cpp 124 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714
  1. // CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the methods for CFRefCount, which implements
  11. // a reference count checker for Core Foundation (Mac OS X).
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/StaticAnalyzer/Core/Checker.h"
  15. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  16. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  17. #include "clang/AST/DeclObjC.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/StmtVisitor.h"
  20. #include "clang/Basic/LangOptions.h"
  21. #include "clang/Basic/SourceManager.h"
  22. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  23. #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
  24. #include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
  25. #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
  26. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngineBuilders.h"
  27. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  28. #include "clang/StaticAnalyzer/Core/PathSensitive/TransferFuncs.h"
  29. #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
  30. #include "llvm/ADT/DenseMap.h"
  31. #include "llvm/ADT/FoldingSet.h"
  32. #include "llvm/ADT/ImmutableList.h"
  33. #include "llvm/ADT/ImmutableMap.h"
  34. #include "llvm/ADT/STLExtras.h"
  35. #include "llvm/ADT/StringExtras.h"
  36. #include <cstdarg>
  37. using namespace clang;
  38. using namespace ento;
  39. using llvm::StrInStrNoCase;
  40. namespace {
  41. class InstanceReceiver {
  42. ObjCMessage Msg;
  43. const LocationContext *LC;
  44. public:
  45. InstanceReceiver() : LC(0) { }
  46. InstanceReceiver(const ObjCMessage &msg,
  47. const LocationContext *lc = 0) : Msg(msg), LC(lc) {}
  48. bool isValid() const {
  49. return Msg.isValid() && Msg.isInstanceMessage();
  50. }
  51. operator bool() const {
  52. return isValid();
  53. }
  54. SVal getSValAsScalarOrLoc(const ProgramState *state) {
  55. assert(isValid());
  56. // We have an expression for the receiver? Fetch the value
  57. // of that expression.
  58. if (const Expr *Ex = Msg.getInstanceReceiver())
  59. return state->getSValAsScalarOrLoc(Ex);
  60. // Otherwise we are sending a message to super. In this case the
  61. // object reference is the same as 'self'.
  62. if (const ImplicitParamDecl *SelfDecl = LC->getSelfDecl())
  63. return state->getSVal(state->getRegion(SelfDecl, LC));
  64. return UnknownVal();
  65. }
  66. SourceRange getSourceRange() const {
  67. assert(isValid());
  68. if (const Expr *Ex = Msg.getInstanceReceiver())
  69. return Ex->getSourceRange();
  70. // Otherwise we are sending a message to super.
  71. SourceLocation L = Msg.getSuperLoc();
  72. assert(L.isValid());
  73. return SourceRange(L, L);
  74. }
  75. };
  76. }
  77. namespace {
  78. class GenericNodeBuilderRefCount {
  79. StmtNodeBuilder *SNB;
  80. const Stmt *S;
  81. const ProgramPointTag *tag;
  82. EndOfFunctionNodeBuilder *ENB;
  83. public:
  84. GenericNodeBuilderRefCount(StmtNodeBuilder &snb, const Stmt *s,
  85. const ProgramPointTag *t)
  86. : SNB(&snb), S(s), tag(t), ENB(0) {}
  87. GenericNodeBuilderRefCount(EndOfFunctionNodeBuilder &enb)
  88. : SNB(0), S(0), tag(0), ENB(&enb) {}
  89. ExplodedNode *MakeNode(const ProgramState *state, ExplodedNode *Pred) {
  90. if (SNB)
  91. return SNB->generateNode(PostStmt(S, Pred->getLocationContext(), tag),
  92. state, Pred);
  93. assert(ENB);
  94. return ENB->generateNode(state, Pred);
  95. }
  96. };
  97. } // end anonymous namespace
  98. //===----------------------------------------------------------------------===//
  99. // Primitives used for constructing summaries for function/method calls.
  100. //===----------------------------------------------------------------------===//
  101. /// ArgEffect is used to summarize a function/method call's effect on a
  102. /// particular argument.
  103. enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
  104. DecRefBridgedTransfered,
  105. DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
  106. NewAutoreleasePool, SelfOwn, StopTracking };
  107. namespace llvm {
  108. template <> struct FoldingSetTrait<ArgEffect> {
  109. static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
  110. ID.AddInteger((unsigned) X);
  111. }
  112. };
  113. } // end llvm namespace
  114. /// ArgEffects summarizes the effects of a function/method call on all of
  115. /// its arguments.
  116. typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
  117. namespace {
  118. /// RetEffect is used to summarize a function/method call's behavior with
  119. /// respect to its return value.
  120. class RetEffect {
  121. public:
  122. enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
  123. NotOwnedSymbol, GCNotOwnedSymbol, ARCNotOwnedSymbol,
  124. ReceiverAlias,
  125. OwnedWhenTrackedReceiver };
  126. enum ObjKind { CF, ObjC, AnyObj };
  127. private:
  128. Kind K;
  129. ObjKind O;
  130. unsigned index;
  131. RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
  132. RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
  133. public:
  134. Kind getKind() const { return K; }
  135. ObjKind getObjKind() const { return O; }
  136. unsigned getIndex() const {
  137. assert(getKind() == Alias);
  138. return index;
  139. }
  140. bool isOwned() const {
  141. return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
  142. K == OwnedWhenTrackedReceiver;
  143. }
  144. static RetEffect MakeOwnedWhenTrackedReceiver() {
  145. return RetEffect(OwnedWhenTrackedReceiver, ObjC);
  146. }
  147. static RetEffect MakeAlias(unsigned Idx) {
  148. return RetEffect(Alias, Idx);
  149. }
  150. static RetEffect MakeReceiverAlias() {
  151. return RetEffect(ReceiverAlias);
  152. }
  153. static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
  154. return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
  155. }
  156. static RetEffect MakeNotOwned(ObjKind o) {
  157. return RetEffect(NotOwnedSymbol, o);
  158. }
  159. static RetEffect MakeGCNotOwned() {
  160. return RetEffect(GCNotOwnedSymbol, ObjC);
  161. }
  162. static RetEffect MakeARCNotOwned() {
  163. return RetEffect(ARCNotOwnedSymbol, ObjC);
  164. }
  165. static RetEffect MakeNoRet() {
  166. return RetEffect(NoRet);
  167. }
  168. };
  169. //===----------------------------------------------------------------------===//
  170. // Reference-counting logic (typestate + counts).
  171. //===----------------------------------------------------------------------===//
  172. class RefVal {
  173. public:
  174. enum Kind {
  175. Owned = 0, // Owning reference.
  176. NotOwned, // Reference is not owned by still valid (not freed).
  177. Released, // Object has been released.
  178. ReturnedOwned, // Returned object passes ownership to caller.
  179. ReturnedNotOwned, // Return object does not pass ownership to caller.
  180. ERROR_START,
  181. ErrorDeallocNotOwned, // -dealloc called on non-owned object.
  182. ErrorDeallocGC, // Calling -dealloc with GC enabled.
  183. ErrorUseAfterRelease, // Object used after released.
  184. ErrorReleaseNotOwned, // Release of an object that was not owned.
  185. ERROR_LEAK_START,
  186. ErrorLeak, // A memory leak due to excessive reference counts.
  187. ErrorLeakReturned, // A memory leak due to the returning method not having
  188. // the correct naming conventions.
  189. ErrorGCLeakReturned,
  190. ErrorOverAutorelease,
  191. ErrorReturnedNotOwned
  192. };
  193. private:
  194. Kind kind;
  195. RetEffect::ObjKind okind;
  196. unsigned Cnt;
  197. unsigned ACnt;
  198. QualType T;
  199. RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
  200. : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
  201. public:
  202. Kind getKind() const { return kind; }
  203. RetEffect::ObjKind getObjKind() const { return okind; }
  204. unsigned getCount() const { return Cnt; }
  205. unsigned getAutoreleaseCount() const { return ACnt; }
  206. unsigned getCombinedCounts() const { return Cnt + ACnt; }
  207. void clearCounts() { Cnt = 0; ACnt = 0; }
  208. void setCount(unsigned i) { Cnt = i; }
  209. void setAutoreleaseCount(unsigned i) { ACnt = i; }
  210. QualType getType() const { return T; }
  211. bool isOwned() const {
  212. return getKind() == Owned;
  213. }
  214. bool isNotOwned() const {
  215. return getKind() == NotOwned;
  216. }
  217. bool isReturnedOwned() const {
  218. return getKind() == ReturnedOwned;
  219. }
  220. bool isReturnedNotOwned() const {
  221. return getKind() == ReturnedNotOwned;
  222. }
  223. static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
  224. unsigned Count = 1) {
  225. return RefVal(Owned, o, Count, 0, t);
  226. }
  227. static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
  228. unsigned Count = 0) {
  229. return RefVal(NotOwned, o, Count, 0, t);
  230. }
  231. // Comparison, profiling, and pretty-printing.
  232. bool operator==(const RefVal& X) const {
  233. return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
  234. }
  235. RefVal operator-(size_t i) const {
  236. return RefVal(getKind(), getObjKind(), getCount() - i,
  237. getAutoreleaseCount(), getType());
  238. }
  239. RefVal operator+(size_t i) const {
  240. return RefVal(getKind(), getObjKind(), getCount() + i,
  241. getAutoreleaseCount(), getType());
  242. }
  243. RefVal operator^(Kind k) const {
  244. return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
  245. getType());
  246. }
  247. RefVal autorelease() const {
  248. return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
  249. getType());
  250. }
  251. void Profile(llvm::FoldingSetNodeID& ID) const {
  252. ID.AddInteger((unsigned) kind);
  253. ID.AddInteger(Cnt);
  254. ID.AddInteger(ACnt);
  255. ID.Add(T);
  256. }
  257. void print(raw_ostream &Out) const;
  258. };
  259. void RefVal::print(raw_ostream &Out) const {
  260. if (!T.isNull())
  261. Out << "Tracked Type:" << T.getAsString() << '\n';
  262. switch (getKind()) {
  263. default: assert(false);
  264. case Owned: {
  265. Out << "Owned";
  266. unsigned cnt = getCount();
  267. if (cnt) Out << " (+ " << cnt << ")";
  268. break;
  269. }
  270. case NotOwned: {
  271. Out << "NotOwned";
  272. unsigned cnt = getCount();
  273. if (cnt) Out << " (+ " << cnt << ")";
  274. break;
  275. }
  276. case ReturnedOwned: {
  277. Out << "ReturnedOwned";
  278. unsigned cnt = getCount();
  279. if (cnt) Out << " (+ " << cnt << ")";
  280. break;
  281. }
  282. case ReturnedNotOwned: {
  283. Out << "ReturnedNotOwned";
  284. unsigned cnt = getCount();
  285. if (cnt) Out << " (+ " << cnt << ")";
  286. break;
  287. }
  288. case Released:
  289. Out << "Released";
  290. break;
  291. case ErrorDeallocGC:
  292. Out << "-dealloc (GC)";
  293. break;
  294. case ErrorDeallocNotOwned:
  295. Out << "-dealloc (not-owned)";
  296. break;
  297. case ErrorLeak:
  298. Out << "Leaked";
  299. break;
  300. case ErrorLeakReturned:
  301. Out << "Leaked (Bad naming)";
  302. break;
  303. case ErrorGCLeakReturned:
  304. Out << "Leaked (GC-ed at return)";
  305. break;
  306. case ErrorUseAfterRelease:
  307. Out << "Use-After-Release [ERROR]";
  308. break;
  309. case ErrorReleaseNotOwned:
  310. Out << "Release of Not-Owned [ERROR]";
  311. break;
  312. case RefVal::ErrorOverAutorelease:
  313. Out << "Over autoreleased";
  314. break;
  315. case RefVal::ErrorReturnedNotOwned:
  316. Out << "Non-owned object returned instead of owned";
  317. break;
  318. }
  319. if (ACnt) {
  320. Out << " [ARC +" << ACnt << ']';
  321. }
  322. }
  323. } //end anonymous namespace
  324. //===----------------------------------------------------------------------===//
  325. // RefBindings - State used to track object reference counts.
  326. //===----------------------------------------------------------------------===//
  327. typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
  328. namespace clang {
  329. namespace ento {
  330. template<>
  331. struct ProgramStateTrait<RefBindings>
  332. : public ProgramStatePartialTrait<RefBindings> {
  333. static void *GDMIndex() {
  334. static int RefBIndex = 0;
  335. return &RefBIndex;
  336. }
  337. };
  338. }
  339. }
  340. //===----------------------------------------------------------------------===//
  341. // Summaries
  342. //===----------------------------------------------------------------------===//
  343. namespace {
  344. class RetainSummary {
  345. /// Args - an ordered vector of (index, ArgEffect) pairs, where index
  346. /// specifies the argument (starting from 0). This can be sparsely
  347. /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
  348. ArgEffects Args;
  349. /// DefaultArgEffect - The default ArgEffect to apply to arguments that
  350. /// do not have an entry in Args.
  351. ArgEffect DefaultArgEffect;
  352. /// Receiver - If this summary applies to an Objective-C message expression,
  353. /// this is the effect applied to the state of the receiver.
  354. ArgEffect Receiver;
  355. /// Ret - The effect on the return value. Used to indicate if the
  356. /// function/method call returns a new tracked symbol, returns an
  357. /// alias of one of the arguments in the call, and so on.
  358. RetEffect Ret;
  359. /// EndPath - Indicates that execution of this method/function should
  360. /// terminate the simulation of a path.
  361. bool EndPath;
  362. public:
  363. RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
  364. ArgEffect ReceiverEff, bool endpath = false)
  365. : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
  366. EndPath(endpath) {}
  367. /// getArg - Return the argument effect on the argument specified by
  368. /// idx (starting from 0).
  369. ArgEffect getArg(unsigned idx) const {
  370. if (const ArgEffect *AE = Args.lookup(idx))
  371. return *AE;
  372. return DefaultArgEffect;
  373. }
  374. void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
  375. Args = af.add(Args, idx, e);
  376. }
  377. /// setDefaultArgEffect - Set the default argument effect.
  378. void setDefaultArgEffect(ArgEffect E) {
  379. DefaultArgEffect = E;
  380. }
  381. /// getRetEffect - Returns the effect on the return value of the call.
  382. RetEffect getRetEffect() const { return Ret; }
  383. /// setRetEffect - Set the effect of the return value of the call.
  384. void setRetEffect(RetEffect E) { Ret = E; }
  385. /// isEndPath - Returns true if executing the given method/function should
  386. /// terminate the path.
  387. bool isEndPath() const { return EndPath; }
  388. /// Sets the effect on the receiver of the message.
  389. void setReceiverEffect(ArgEffect e) { Receiver = e; }
  390. /// getReceiverEffect - Returns the effect on the receiver of the call.
  391. /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
  392. ArgEffect getReceiverEffect() const { return Receiver; }
  393. };
  394. } // end anonymous namespace
  395. //===----------------------------------------------------------------------===//
  396. // Data structures for constructing summaries.
  397. //===----------------------------------------------------------------------===//
  398. namespace {
  399. class ObjCSummaryKey {
  400. IdentifierInfo* II;
  401. Selector S;
  402. public:
  403. ObjCSummaryKey(IdentifierInfo* ii, Selector s)
  404. : II(ii), S(s) {}
  405. ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
  406. : II(d ? d->getIdentifier() : 0), S(s) {}
  407. ObjCSummaryKey(const ObjCInterfaceDecl *d, IdentifierInfo *ii, Selector s)
  408. : II(d ? d->getIdentifier() : ii), S(s) {}
  409. ObjCSummaryKey(Selector s)
  410. : II(0), S(s) {}
  411. IdentifierInfo* getIdentifier() const { return II; }
  412. Selector getSelector() const { return S; }
  413. };
  414. }
  415. namespace llvm {
  416. template <> struct DenseMapInfo<ObjCSummaryKey> {
  417. static inline ObjCSummaryKey getEmptyKey() {
  418. return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
  419. DenseMapInfo<Selector>::getEmptyKey());
  420. }
  421. static inline ObjCSummaryKey getTombstoneKey() {
  422. return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
  423. DenseMapInfo<Selector>::getTombstoneKey());
  424. }
  425. static unsigned getHashValue(const ObjCSummaryKey &V) {
  426. return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
  427. & 0x88888888)
  428. | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
  429. & 0x55555555);
  430. }
  431. static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
  432. return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
  433. RHS.getIdentifier()) &&
  434. DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
  435. RHS.getSelector());
  436. }
  437. };
  438. template <>
  439. struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
  440. } // end llvm namespace
  441. namespace {
  442. class ObjCSummaryCache {
  443. typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
  444. MapTy M;
  445. public:
  446. ObjCSummaryCache() {}
  447. RetainSummary* find(const ObjCInterfaceDecl *D, IdentifierInfo *ClsName,
  448. Selector S) {
  449. // Lookup the method using the decl for the class @interface. If we
  450. // have no decl, lookup using the class name.
  451. return D ? find(D, S) : find(ClsName, S);
  452. }
  453. RetainSummary* find(const ObjCInterfaceDecl *D, Selector S) {
  454. // Do a lookup with the (D,S) pair. If we find a match return
  455. // the iterator.
  456. ObjCSummaryKey K(D, S);
  457. MapTy::iterator I = M.find(K);
  458. if (I != M.end() || !D)
  459. return I->second;
  460. // Walk the super chain. If we find a hit with a parent, we'll end
  461. // up returning that summary. We actually allow that key (null,S), as
  462. // we cache summaries for the null ObjCInterfaceDecl* to allow us to
  463. // generate initial summaries without having to worry about NSObject
  464. // being declared.
  465. // FIXME: We may change this at some point.
  466. for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
  467. if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
  468. break;
  469. if (!C)
  470. return NULL;
  471. }
  472. // Cache the summary with original key to make the next lookup faster
  473. // and return the iterator.
  474. RetainSummary *Summ = I->second;
  475. M[K] = Summ;
  476. return Summ;
  477. }
  478. RetainSummary* find(IdentifierInfo* II, Selector S) {
  479. // FIXME: Class method lookup. Right now we dont' have a good way
  480. // of going between IdentifierInfo* and the class hierarchy.
  481. MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
  482. if (I == M.end())
  483. I = M.find(ObjCSummaryKey(S));
  484. return I == M.end() ? NULL : I->second;
  485. }
  486. RetainSummary*& operator[](ObjCSummaryKey K) {
  487. return M[K];
  488. }
  489. RetainSummary*& operator[](Selector S) {
  490. return M[ ObjCSummaryKey(S) ];
  491. }
  492. };
  493. } // end anonymous namespace
  494. //===----------------------------------------------------------------------===//
  495. // Data structures for managing collections of summaries.
  496. //===----------------------------------------------------------------------===//
  497. namespace {
  498. class RetainSummaryManager {
  499. //==-----------------------------------------------------------------==//
  500. // Typedefs.
  501. //==-----------------------------------------------------------------==//
  502. typedef llvm::DenseMap<const FunctionDecl*, RetainSummary*>
  503. FuncSummariesTy;
  504. typedef ObjCSummaryCache ObjCMethodSummariesTy;
  505. //==-----------------------------------------------------------------==//
  506. // Data.
  507. //==-----------------------------------------------------------------==//
  508. /// Ctx - The ASTContext object for the analyzed ASTs.
  509. ASTContext &Ctx;
  510. /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
  511. /// "CFDictionaryCreate".
  512. IdentifierInfo* CFDictionaryCreateII;
  513. /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
  514. const bool GCEnabled;
  515. /// Records whether or not the analyzed code runs in ARC mode.
  516. const bool ARCEnabled;
  517. /// FuncSummaries - A map from FunctionDecls to summaries.
  518. FuncSummariesTy FuncSummaries;
  519. /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
  520. /// to summaries.
  521. ObjCMethodSummariesTy ObjCClassMethodSummaries;
  522. /// ObjCMethodSummaries - A map from selectors to summaries.
  523. ObjCMethodSummariesTy ObjCMethodSummaries;
  524. /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
  525. /// and all other data used by the checker.
  526. llvm::BumpPtrAllocator BPAlloc;
  527. /// AF - A factory for ArgEffects objects.
  528. ArgEffects::Factory AF;
  529. /// ScratchArgs - A holding buffer for construct ArgEffects.
  530. ArgEffects ScratchArgs;
  531. /// ObjCAllocRetE - Default return effect for methods returning Objective-C
  532. /// objects.
  533. RetEffect ObjCAllocRetE;
  534. /// ObjCInitRetE - Default return effect for init methods returning
  535. /// Objective-C objects.
  536. RetEffect ObjCInitRetE;
  537. RetainSummary DefaultSummary;
  538. RetainSummary* StopSummary;
  539. //==-----------------------------------------------------------------==//
  540. // Methods.
  541. //==-----------------------------------------------------------------==//
  542. /// getArgEffects - Returns a persistent ArgEffects object based on the
  543. /// data in ScratchArgs.
  544. ArgEffects getArgEffects();
  545. enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
  546. public:
  547. RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
  548. RetainSummary *getDefaultSummary() {
  549. RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
  550. return new (Summ) RetainSummary(DefaultSummary);
  551. }
  552. RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
  553. RetainSummary* getCFSummaryCreateRule(const FunctionDecl *FD);
  554. RetainSummary* getCFSummaryGetRule(const FunctionDecl *FD);
  555. RetainSummary* getCFCreateGetRuleSummary(const FunctionDecl *FD,
  556. StringRef FName);
  557. RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
  558. ArgEffect ReceiverEff = DoNothing,
  559. ArgEffect DefaultEff = MayEscape,
  560. bool isEndPath = false);
  561. RetainSummary* getPersistentSummary(RetEffect RE,
  562. ArgEffect ReceiverEff = DoNothing,
  563. ArgEffect DefaultEff = MayEscape) {
  564. return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
  565. }
  566. RetainSummary *getPersistentStopSummary() {
  567. if (StopSummary)
  568. return StopSummary;
  569. StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
  570. StopTracking, StopTracking);
  571. return StopSummary;
  572. }
  573. RetainSummary *getInitMethodSummary(QualType RetTy);
  574. void InitializeClassMethodSummaries();
  575. void InitializeMethodSummaries();
  576. private:
  577. void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
  578. ObjCClassMethodSummaries[S] = Summ;
  579. }
  580. void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
  581. ObjCMethodSummaries[S] = Summ;
  582. }
  583. void addClassMethSummary(const char* Cls, const char* nullaryName,
  584. RetainSummary *Summ) {
  585. IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
  586. Selector S = GetNullarySelector(nullaryName, Ctx);
  587. ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
  588. }
  589. void addInstMethSummary(const char* Cls, const char* nullaryName,
  590. RetainSummary *Summ) {
  591. IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
  592. Selector S = GetNullarySelector(nullaryName, Ctx);
  593. ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
  594. }
  595. Selector generateSelector(va_list argp) {
  596. SmallVector<IdentifierInfo*, 10> II;
  597. while (const char* s = va_arg(argp, const char*))
  598. II.push_back(&Ctx.Idents.get(s));
  599. return Ctx.Selectors.getSelector(II.size(), &II[0]);
  600. }
  601. void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
  602. RetainSummary* Summ, va_list argp) {
  603. Selector S = generateSelector(argp);
  604. Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
  605. }
  606. void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
  607. va_list argp;
  608. va_start(argp, Summ);
  609. addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
  610. va_end(argp);
  611. }
  612. void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
  613. va_list argp;
  614. va_start(argp, Summ);
  615. addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
  616. va_end(argp);
  617. }
  618. void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
  619. va_list argp;
  620. va_start(argp, Summ);
  621. addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
  622. va_end(argp);
  623. }
  624. void addPanicSummary(const char* Cls, ...) {
  625. RetainSummary* Summ = getPersistentSummary(AF.getEmptyMap(),
  626. RetEffect::MakeNoRet(),
  627. DoNothing, DoNothing, true);
  628. va_list argp;
  629. va_start (argp, Cls);
  630. addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
  631. va_end(argp);
  632. }
  633. public:
  634. RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
  635. : Ctx(ctx),
  636. CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
  637. GCEnabled(gcenabled),
  638. ARCEnabled(usesARC),
  639. AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
  640. ObjCAllocRetE(gcenabled
  641. ? RetEffect::MakeGCNotOwned()
  642. : (usesARC ? RetEffect::MakeARCNotOwned()
  643. : RetEffect::MakeOwned(RetEffect::ObjC, true))),
  644. ObjCInitRetE(gcenabled
  645. ? RetEffect::MakeGCNotOwned()
  646. : (usesARC ? RetEffect::MakeARCNotOwned()
  647. : RetEffect::MakeOwnedWhenTrackedReceiver())),
  648. DefaultSummary(AF.getEmptyMap() /* per-argument effects (none) */,
  649. RetEffect::MakeNoRet() /* return effect */,
  650. MayEscape, /* default argument effect */
  651. DoNothing /* receiver effect */),
  652. StopSummary(0) {
  653. InitializeClassMethodSummaries();
  654. InitializeMethodSummaries();
  655. }
  656. ~RetainSummaryManager();
  657. RetainSummary* getSummary(const FunctionDecl *FD);
  658. RetainSummary *getInstanceMethodSummary(const ObjCMessage &msg,
  659. const ProgramState *state,
  660. const LocationContext *LC);
  661. RetainSummary* getInstanceMethodSummary(const ObjCMessage &msg,
  662. const ObjCInterfaceDecl *ID) {
  663. return getInstanceMethodSummary(msg.getSelector(), 0,
  664. ID, msg.getMethodDecl(), msg.getType(Ctx));
  665. }
  666. RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
  667. const ObjCInterfaceDecl *ID,
  668. const ObjCMethodDecl *MD,
  669. QualType RetTy);
  670. RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
  671. const ObjCInterfaceDecl *ID,
  672. const ObjCMethodDecl *MD,
  673. QualType RetTy);
  674. RetainSummary *getClassMethodSummary(const ObjCMessage &msg) {
  675. const ObjCInterfaceDecl *Class = 0;
  676. if (!msg.isInstanceMessage())
  677. Class = msg.getReceiverInterface();
  678. return getClassMethodSummary(msg.getSelector(),
  679. Class? Class->getIdentifier() : 0,
  680. Class,
  681. msg.getMethodDecl(), msg.getType(Ctx));
  682. }
  683. /// getMethodSummary - This version of getMethodSummary is used to query
  684. /// the summary for the current method being analyzed.
  685. RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
  686. // FIXME: Eventually this should be unneeded.
  687. const ObjCInterfaceDecl *ID = MD->getClassInterface();
  688. Selector S = MD->getSelector();
  689. IdentifierInfo *ClsName = ID->getIdentifier();
  690. QualType ResultTy = MD->getResultType();
  691. if (MD->isInstanceMethod())
  692. return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
  693. else
  694. return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
  695. }
  696. RetainSummary* getCommonMethodSummary(const ObjCMethodDecl *MD,
  697. Selector S, QualType RetTy);
  698. void updateSummaryFromAnnotations(RetainSummary &Summ,
  699. const ObjCMethodDecl *MD);
  700. void updateSummaryFromAnnotations(RetainSummary &Summ,
  701. const FunctionDecl *FD);
  702. bool isGCEnabled() const { return GCEnabled; }
  703. bool isARCEnabled() const { return ARCEnabled; }
  704. bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
  705. RetainSummary *copySummary(RetainSummary *OldSumm) {
  706. RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
  707. new (Summ) RetainSummary(*OldSumm);
  708. return Summ;
  709. }
  710. };
  711. } // end anonymous namespace
  712. //===----------------------------------------------------------------------===//
  713. // Implementation of checker data structures.
  714. //===----------------------------------------------------------------------===//
  715. RetainSummaryManager::~RetainSummaryManager() {}
  716. ArgEffects RetainSummaryManager::getArgEffects() {
  717. ArgEffects AE = ScratchArgs;
  718. ScratchArgs = AF.getEmptyMap();
  719. return AE;
  720. }
  721. RetainSummary*
  722. RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
  723. ArgEffect ReceiverEff,
  724. ArgEffect DefaultEff,
  725. bool isEndPath) {
  726. // Create the summary and return it.
  727. RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
  728. new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
  729. return Summ;
  730. }
  731. //===----------------------------------------------------------------------===//
  732. // Summary creation for functions (largely uses of Core Foundation).
  733. //===----------------------------------------------------------------------===//
  734. static bool isRetain(const FunctionDecl *FD, StringRef FName) {
  735. return FName.endswith("Retain");
  736. }
  737. static bool isRelease(const FunctionDecl *FD, StringRef FName) {
  738. return FName.endswith("Release");
  739. }
  740. RetainSummary* RetainSummaryManager::getSummary(const FunctionDecl *FD) {
  741. // Look up a summary in our cache of FunctionDecls -> Summaries.
  742. FuncSummariesTy::iterator I = FuncSummaries.find(FD);
  743. if (I != FuncSummaries.end())
  744. return I->second;
  745. // No summary? Generate one.
  746. RetainSummary *S = 0;
  747. do {
  748. // We generate "stop" summaries for implicitly defined functions.
  749. if (FD->isImplicit()) {
  750. S = getPersistentStopSummary();
  751. break;
  752. }
  753. // For C++ methods, generate an implicit "stop" summary as well. We
  754. // can relax this once we have a clear policy for C++ methods and
  755. // ownership attributes.
  756. if (isa<CXXMethodDecl>(FD)) {
  757. S = getPersistentStopSummary();
  758. break;
  759. }
  760. // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
  761. // function's type.
  762. const FunctionType* FT = FD->getType()->getAs<FunctionType>();
  763. const IdentifierInfo *II = FD->getIdentifier();
  764. if (!II)
  765. break;
  766. StringRef FName = II->getName();
  767. // Strip away preceding '_'. Doing this here will effect all the checks
  768. // down below.
  769. FName = FName.substr(FName.find_first_not_of('_'));
  770. // Inspect the result type.
  771. QualType RetTy = FT->getResultType();
  772. // FIXME: This should all be refactored into a chain of "summary lookup"
  773. // filters.
  774. assert(ScratchArgs.isEmpty());
  775. if (FName == "pthread_create") {
  776. // Part of: <rdar://problem/7299394>. This will be addressed
  777. // better with IPA.
  778. S = getPersistentStopSummary();
  779. } else if (FName == "NSMakeCollectable") {
  780. // Handle: id NSMakeCollectable(CFTypeRef)
  781. S = (RetTy->isObjCIdType())
  782. ? getUnarySummary(FT, cfmakecollectable)
  783. : getPersistentStopSummary();
  784. } else if (FName == "IOBSDNameMatching" ||
  785. FName == "IOServiceMatching" ||
  786. FName == "IOServiceNameMatching" ||
  787. FName == "IORegistryEntryIDMatching" ||
  788. FName == "IOOpenFirmwarePathMatching") {
  789. // Part of <rdar://problem/6961230>. (IOKit)
  790. // This should be addressed using a API table.
  791. S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
  792. DoNothing, DoNothing);
  793. } else if (FName == "IOServiceGetMatchingService" ||
  794. FName == "IOServiceGetMatchingServices") {
  795. // FIXES: <rdar://problem/6326900>
  796. // This should be addressed using a API table. This strcmp is also
  797. // a little gross, but there is no need to super optimize here.
  798. ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
  799. S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
  800. } else if (FName == "IOServiceAddNotification" ||
  801. FName == "IOServiceAddMatchingNotification") {
  802. // Part of <rdar://problem/6961230>. (IOKit)
  803. // This should be addressed using a API table.
  804. ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
  805. S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
  806. } else if (FName == "CVPixelBufferCreateWithBytes") {
  807. // FIXES: <rdar://problem/7283567>
  808. // Eventually this can be improved by recognizing that the pixel
  809. // buffer passed to CVPixelBufferCreateWithBytes is released via
  810. // a callback and doing full IPA to make sure this is done correctly.
  811. // FIXME: This function has an out parameter that returns an
  812. // allocated object.
  813. ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
  814. S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
  815. } else if (FName == "CGBitmapContextCreateWithData") {
  816. // FIXES: <rdar://problem/7358899>
  817. // Eventually this can be improved by recognizing that 'releaseInfo'
  818. // passed to CGBitmapContextCreateWithData is released via
  819. // a callback and doing full IPA to make sure this is done correctly.
  820. ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
  821. S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
  822. DoNothing, DoNothing);
  823. } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
  824. // FIXES: <rdar://problem/7283567>
  825. // Eventually this can be improved by recognizing that the pixel
  826. // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
  827. // via a callback and doing full IPA to make sure this is done
  828. // correctly.
  829. ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
  830. S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
  831. }
  832. // Did we get a summary?
  833. if (S)
  834. break;
  835. // Enable this code once the semantics of NSDeallocateObject are resolved
  836. // for GC. <rdar://problem/6619988>
  837. #if 0
  838. // Handle: NSDeallocateObject(id anObject);
  839. // This method does allow 'nil' (although we don't check it now).
  840. if (strcmp(FName, "NSDeallocateObject") == 0) {
  841. return RetTy == Ctx.VoidTy
  842. ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
  843. : getPersistentStopSummary();
  844. }
  845. #endif
  846. if (RetTy->isPointerType()) {
  847. // For CoreFoundation ('CF') types.
  848. if (cocoa::isRefType(RetTy, "CF", FName)) {
  849. if (isRetain(FD, FName))
  850. S = getUnarySummary(FT, cfretain);
  851. else if (FName.find("MakeCollectable") != StringRef::npos)
  852. S = getUnarySummary(FT, cfmakecollectable);
  853. else
  854. S = getCFCreateGetRuleSummary(FD, FName);
  855. break;
  856. }
  857. // For CoreGraphics ('CG') types.
  858. if (cocoa::isRefType(RetTy, "CG", FName)) {
  859. if (isRetain(FD, FName))
  860. S = getUnarySummary(FT, cfretain);
  861. else
  862. S = getCFCreateGetRuleSummary(FD, FName);
  863. break;
  864. }
  865. // For the Disk Arbitration API (DiskArbitration/DADisk.h)
  866. if (cocoa::isRefType(RetTy, "DADisk") ||
  867. cocoa::isRefType(RetTy, "DADissenter") ||
  868. cocoa::isRefType(RetTy, "DASessionRef")) {
  869. S = getCFCreateGetRuleSummary(FD, FName);
  870. break;
  871. }
  872. break;
  873. }
  874. // Check for release functions, the only kind of functions that we care
  875. // about that don't return a pointer type.
  876. if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
  877. // Test for 'CGCF'.
  878. FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
  879. if (isRelease(FD, FName))
  880. S = getUnarySummary(FT, cfrelease);
  881. else {
  882. assert (ScratchArgs.isEmpty());
  883. // Remaining CoreFoundation and CoreGraphics functions.
  884. // We use to assume that they all strictly followed the ownership idiom
  885. // and that ownership cannot be transferred. While this is technically
  886. // correct, many methods allow a tracked object to escape. For example:
  887. //
  888. // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
  889. // CFDictionaryAddValue(y, key, x);
  890. // CFRelease(x);
  891. // ... it is okay to use 'x' since 'y' has a reference to it
  892. //
  893. // We handle this and similar cases with the follow heuristic. If the
  894. // function name contains "InsertValue", "SetValue", "AddValue",
  895. // "AppendValue", or "SetAttribute", then we assume that arguments may
  896. // "escape." This means that something else holds on to the object,
  897. // allowing it be used even after its local retain count drops to 0.
  898. ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
  899. StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
  900. StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
  901. StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
  902. StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
  903. ? MayEscape : DoNothing;
  904. S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
  905. }
  906. }
  907. }
  908. while (0);
  909. if (!S)
  910. S = getDefaultSummary();
  911. // Annotations override defaults.
  912. assert(S);
  913. updateSummaryFromAnnotations(*S, FD);
  914. FuncSummaries[FD] = S;
  915. return S;
  916. }
  917. RetainSummary*
  918. RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD,
  919. StringRef FName) {
  920. if (coreFoundation::followsCreateRule(FName))
  921. return getCFSummaryCreateRule(FD);
  922. return getCFSummaryGetRule(FD);
  923. }
  924. RetainSummary*
  925. RetainSummaryManager::getUnarySummary(const FunctionType* FT,
  926. UnaryFuncKind func) {
  927. // Sanity check that this is *really* a unary function. This can
  928. // happen if people do weird things.
  929. const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
  930. if (!FTP || FTP->getNumArgs() != 1)
  931. return getPersistentStopSummary();
  932. assert (ScratchArgs.isEmpty());
  933. switch (func) {
  934. case cfretain: {
  935. ScratchArgs = AF.add(ScratchArgs, 0, IncRef);
  936. return getPersistentSummary(RetEffect::MakeAlias(0),
  937. DoNothing, DoNothing);
  938. }
  939. case cfrelease: {
  940. ScratchArgs = AF.add(ScratchArgs, 0, DecRef);
  941. return getPersistentSummary(RetEffect::MakeNoRet(),
  942. DoNothing, DoNothing);
  943. }
  944. case cfmakecollectable: {
  945. ScratchArgs = AF.add(ScratchArgs, 0, MakeCollectable);
  946. return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
  947. }
  948. default:
  949. assert (false && "Not a supported unary function.");
  950. return getDefaultSummary();
  951. }
  952. }
  953. RetainSummary*
  954. RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
  955. assert (ScratchArgs.isEmpty());
  956. if (FD->getIdentifier() == CFDictionaryCreateII) {
  957. ScratchArgs = AF.add(ScratchArgs, 1, DoNothingByRef);
  958. ScratchArgs = AF.add(ScratchArgs, 2, DoNothingByRef);
  959. }
  960. return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
  961. }
  962. RetainSummary*
  963. RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
  964. assert (ScratchArgs.isEmpty());
  965. return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
  966. DoNothing, DoNothing);
  967. }
  968. //===----------------------------------------------------------------------===//
  969. // Summary creation for Selectors.
  970. //===----------------------------------------------------------------------===//
  971. RetainSummary*
  972. RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
  973. assert(ScratchArgs.isEmpty());
  974. // 'init' methods conceptually return a newly allocated object and claim
  975. // the receiver.
  976. if (cocoa::isCocoaObjectRef(RetTy) ||
  977. coreFoundation::isCFObjectRef(RetTy))
  978. return getPersistentSummary(ObjCInitRetE, DecRefMsg);
  979. return getDefaultSummary();
  980. }
  981. void
  982. RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
  983. const FunctionDecl *FD) {
  984. if (!FD)
  985. return;
  986. // Effects on the parameters.
  987. unsigned parm_idx = 0;
  988. for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
  989. pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
  990. const ParmVarDecl *pd = *pi;
  991. if (pd->getAttr<NSConsumedAttr>()) {
  992. if (!GCEnabled)
  993. Summ.addArg(AF, parm_idx, DecRef);
  994. }
  995. else if(pd->getAttr<CFConsumedAttr>()) {
  996. Summ.addArg(AF, parm_idx, DecRef);
  997. }
  998. }
  999. QualType RetTy = FD->getResultType();
  1000. // Determine if there is a special return effect for this method.
  1001. if (cocoa::isCocoaObjectRef(RetTy)) {
  1002. if (FD->getAttr<NSReturnsRetainedAttr>()) {
  1003. Summ.setRetEffect(ObjCAllocRetE);
  1004. }
  1005. else if (FD->getAttr<CFReturnsRetainedAttr>()) {
  1006. Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
  1007. }
  1008. else if (FD->getAttr<NSReturnsNotRetainedAttr>()) {
  1009. Summ.setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
  1010. }
  1011. else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
  1012. Summ.setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
  1013. }
  1014. }
  1015. else if (RetTy->getAs<PointerType>()) {
  1016. if (FD->getAttr<CFReturnsRetainedAttr>()) {
  1017. Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
  1018. }
  1019. else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
  1020. Summ.setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
  1021. }
  1022. }
  1023. }
  1024. void
  1025. RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
  1026. const ObjCMethodDecl *MD) {
  1027. if (!MD)
  1028. return;
  1029. bool isTrackedLoc = false;
  1030. // Effects on the receiver.
  1031. if (MD->getAttr<NSConsumesSelfAttr>()) {
  1032. if (!GCEnabled)
  1033. Summ.setReceiverEffect(DecRefMsg);
  1034. }
  1035. // Effects on the parameters.
  1036. unsigned parm_idx = 0;
  1037. for (ObjCMethodDecl::param_iterator pi=MD->param_begin(), pe=MD->param_end();
  1038. pi != pe; ++pi, ++parm_idx) {
  1039. const ParmVarDecl *pd = *pi;
  1040. if (pd->getAttr<NSConsumedAttr>()) {
  1041. if (!GCEnabled)
  1042. Summ.addArg(AF, parm_idx, DecRef);
  1043. }
  1044. else if(pd->getAttr<CFConsumedAttr>()) {
  1045. Summ.addArg(AF, parm_idx, DecRef);
  1046. }
  1047. }
  1048. // Determine if there is a special return effect for this method.
  1049. if (cocoa::isCocoaObjectRef(MD->getResultType())) {
  1050. if (MD->getAttr<NSReturnsRetainedAttr>()) {
  1051. Summ.setRetEffect(ObjCAllocRetE);
  1052. return;
  1053. }
  1054. if (MD->getAttr<NSReturnsNotRetainedAttr>()) {
  1055. Summ.setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
  1056. return;
  1057. }
  1058. isTrackedLoc = true;
  1059. }
  1060. if (!isTrackedLoc)
  1061. isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
  1062. if (isTrackedLoc) {
  1063. if (MD->getAttr<CFReturnsRetainedAttr>())
  1064. Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
  1065. else if (MD->getAttr<CFReturnsNotRetainedAttr>())
  1066. Summ.setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
  1067. }
  1068. }
  1069. RetainSummary*
  1070. RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl *MD,
  1071. Selector S, QualType RetTy) {
  1072. if (MD) {
  1073. // Scan the method decl for 'void*' arguments. These should be treated
  1074. // as 'StopTracking' because they are often used with delegates.
  1075. // Delegates are a frequent form of false positives with the retain
  1076. // count checker.
  1077. unsigned i = 0;
  1078. for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
  1079. E = MD->param_end(); I != E; ++I, ++i)
  1080. if (ParmVarDecl *PD = *I) {
  1081. QualType Ty = Ctx.getCanonicalType(PD->getType());
  1082. if (Ty.getLocalUnqualifiedType() == Ctx.VoidPtrTy)
  1083. ScratchArgs = AF.add(ScratchArgs, i, StopTracking);
  1084. }
  1085. }
  1086. // Any special effect for the receiver?
  1087. ArgEffect ReceiverEff = DoNothing;
  1088. // If one of the arguments in the selector has the keyword 'delegate' we
  1089. // should stop tracking the reference count for the receiver. This is
  1090. // because the reference count is quite possibly handled by a delegate
  1091. // method.
  1092. if (S.isKeywordSelector()) {
  1093. const std::string &str = S.getAsString();
  1094. assert(!str.empty());
  1095. if (StrInStrNoCase(str, "delegate:") != StringRef::npos)
  1096. ReceiverEff = StopTracking;
  1097. }
  1098. // Look for methods that return an owned object.
  1099. if (cocoa::isCocoaObjectRef(RetTy)) {
  1100. // EXPERIMENTAL: assume the Cocoa conventions for all objects returned
  1101. // by instance methods.
  1102. RetEffect E = cocoa::followsFundamentalRule(S, MD)
  1103. ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
  1104. return getPersistentSummary(E, ReceiverEff, MayEscape);
  1105. }
  1106. // Look for methods that return an owned core foundation object.
  1107. if (coreFoundation::isCFObjectRef(RetTy)) {
  1108. RetEffect E = cocoa::followsFundamentalRule(S, MD)
  1109. ? RetEffect::MakeOwned(RetEffect::CF, true)
  1110. : RetEffect::MakeNotOwned(RetEffect::CF);
  1111. return getPersistentSummary(E, ReceiverEff, MayEscape);
  1112. }
  1113. if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
  1114. return getDefaultSummary();
  1115. return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
  1116. }
  1117. RetainSummary*
  1118. RetainSummaryManager::getInstanceMethodSummary(const ObjCMessage &msg,
  1119. const ProgramState *state,
  1120. const LocationContext *LC) {
  1121. // We need the type-information of the tracked receiver object
  1122. // Retrieve it from the state.
  1123. const Expr *Receiver = msg.getInstanceReceiver();
  1124. const ObjCInterfaceDecl *ID = 0;
  1125. // FIXME: Is this really working as expected? There are cases where
  1126. // we just use the 'ID' from the message expression.
  1127. SVal receiverV;
  1128. if (Receiver) {
  1129. receiverV = state->getSValAsScalarOrLoc(Receiver);
  1130. // FIXME: Eventually replace the use of state->get<RefBindings> with
  1131. // a generic API for reasoning about the Objective-C types of symbolic
  1132. // objects.
  1133. if (SymbolRef Sym = receiverV.getAsLocSymbol())
  1134. if (const RefVal *T = state->get<RefBindings>(Sym))
  1135. if (const ObjCObjectPointerType* PT =
  1136. T->getType()->getAs<ObjCObjectPointerType>())
  1137. ID = PT->getInterfaceDecl();
  1138. // FIXME: this is a hack. This may or may not be the actual method
  1139. // that is called.
  1140. if (!ID) {
  1141. if (const ObjCObjectPointerType *PT =
  1142. Receiver->getType()->getAs<ObjCObjectPointerType>())
  1143. ID = PT->getInterfaceDecl();
  1144. }
  1145. } else {
  1146. // FIXME: Hack for 'super'.
  1147. ID = msg.getReceiverInterface();
  1148. }
  1149. // FIXME: The receiver could be a reference to a class, meaning that
  1150. // we should use the class method.
  1151. RetainSummary *Summ = getInstanceMethodSummary(msg, ID);
  1152. return Summ ? Summ : getDefaultSummary();
  1153. }
  1154. RetainSummary*
  1155. RetainSummaryManager::getInstanceMethodSummary(Selector S,
  1156. IdentifierInfo *ClsName,
  1157. const ObjCInterfaceDecl *ID,
  1158. const ObjCMethodDecl *MD,
  1159. QualType RetTy) {
  1160. // Look up a summary in our summary cache.
  1161. RetainSummary *Summ = ObjCMethodSummaries.find(ID, ClsName, S);
  1162. if (!Summ) {
  1163. assert(ScratchArgs.isEmpty());
  1164. // "initXXX": pass-through for receiver.
  1165. if (cocoa::deriveNamingConvention(S, MD) == cocoa::InitRule)
  1166. Summ = getInitMethodSummary(RetTy);
  1167. else
  1168. Summ = getCommonMethodSummary(MD, S, RetTy);
  1169. // Annotations override defaults.
  1170. updateSummaryFromAnnotations(*Summ, MD);
  1171. // Memoize the summary.
  1172. ObjCMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
  1173. }
  1174. return Summ;
  1175. }
  1176. RetainSummary*
  1177. RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
  1178. const ObjCInterfaceDecl *ID,
  1179. const ObjCMethodDecl *MD,
  1180. QualType RetTy) {
  1181. assert(ClsName && "Class name must be specified.");
  1182. RetainSummary *Summ = ObjCClassMethodSummaries.find(ID, ClsName, S);
  1183. if (!Summ) {
  1184. Summ = getCommonMethodSummary(MD, S, RetTy);
  1185. // Annotations override defaults.
  1186. updateSummaryFromAnnotations(*Summ, MD);
  1187. // Memoize the summary.
  1188. ObjCClassMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
  1189. }
  1190. return Summ;
  1191. }
  1192. void RetainSummaryManager::InitializeClassMethodSummaries() {
  1193. assert(ScratchArgs.isEmpty());
  1194. // Create the [NSAssertionHandler currentHander] summary.
  1195. addClassMethSummary("NSAssertionHandler", "currentHandler",
  1196. getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
  1197. // Create the [NSAutoreleasePool addObject:] summary.
  1198. ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
  1199. addClassMethSummary("NSAutoreleasePool", "addObject",
  1200. getPersistentSummary(RetEffect::MakeNoRet(),
  1201. DoNothing, Autorelease));
  1202. // Create the summaries for [NSObject performSelector...]. We treat
  1203. // these as 'stop tracking' for the arguments because they are often
  1204. // used for delegates that can release the object. When we have better
  1205. // inter-procedural analysis we can potentially do something better. This
  1206. // workaround is to remove false positives.
  1207. RetainSummary *Summ =
  1208. getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
  1209. IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
  1210. addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
  1211. "afterDelay", NULL);
  1212. addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
  1213. "afterDelay", "inModes", NULL);
  1214. addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
  1215. "withObject", "waitUntilDone", NULL);
  1216. addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
  1217. "withObject", "waitUntilDone", "modes", NULL);
  1218. addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
  1219. "withObject", "waitUntilDone", NULL);
  1220. addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
  1221. "withObject", "waitUntilDone", "modes", NULL);
  1222. addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
  1223. "withObject", NULL);
  1224. }
  1225. void RetainSummaryManager::InitializeMethodSummaries() {
  1226. assert (ScratchArgs.isEmpty());
  1227. // Create the "init" selector. It just acts as a pass-through for the
  1228. // receiver.
  1229. RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
  1230. addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
  1231. // awakeAfterUsingCoder: behaves basically like an 'init' method. It
  1232. // claims the receiver and returns a retained object.
  1233. addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
  1234. InitSumm);
  1235. // The next methods are allocators.
  1236. RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
  1237. RetainSummary *CFAllocSumm =
  1238. getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
  1239. // Create the "retain" selector.
  1240. RetEffect E = RetEffect::MakeReceiverAlias();
  1241. RetainSummary *Summ = getPersistentSummary(E, IncRefMsg);
  1242. addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
  1243. // Create the "release" selector.
  1244. Summ = getPersistentSummary(E, DecRefMsg);
  1245. addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
  1246. // Create the "drain" selector.
  1247. Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
  1248. addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
  1249. // Create the -dealloc summary.
  1250. Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
  1251. addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
  1252. // Create the "autorelease" selector.
  1253. Summ = getPersistentSummary(E, Autorelease);
  1254. addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
  1255. // Specially handle NSAutoreleasePool.
  1256. addInstMethSummary("NSAutoreleasePool", "init",
  1257. getPersistentSummary(RetEffect::MakeReceiverAlias(),
  1258. NewAutoreleasePool));
  1259. // For NSWindow, allocated objects are (initially) self-owned.
  1260. // FIXME: For now we opt for false negatives with NSWindow, as these objects
  1261. // self-own themselves. However, they only do this once they are displayed.
  1262. // Thus, we need to track an NSWindow's display status.
  1263. // This is tracked in <rdar://problem/6062711>.
  1264. // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
  1265. RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
  1266. StopTracking,
  1267. StopTracking);
  1268. addClassMethSummary("NSWindow", "alloc", NoTrackYet);
  1269. #if 0
  1270. addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
  1271. "styleMask", "backing", "defer", NULL);
  1272. addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
  1273. "styleMask", "backing", "defer", "screen", NULL);
  1274. #endif
  1275. // For NSPanel (which subclasses NSWindow), allocated objects are not
  1276. // self-owned.
  1277. // FIXME: For now we don't track NSPanels. object for the same reason
  1278. // as for NSWindow objects.
  1279. addClassMethSummary("NSPanel", "alloc", NoTrackYet);
  1280. #if 0
  1281. addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
  1282. "styleMask", "backing", "defer", NULL);
  1283. addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
  1284. "styleMask", "backing", "defer", "screen", NULL);
  1285. #endif
  1286. // Don't track allocated autorelease pools yet, as it is okay to prematurely
  1287. // exit a method.
  1288. addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
  1289. // Create NSAssertionHandler summaries.
  1290. addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
  1291. "lineNumber", "description", NULL);
  1292. addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
  1293. "file", "lineNumber", "description", NULL);
  1294. // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
  1295. addInstMethSummary("QCRenderer", AllocSumm,
  1296. "createSnapshotImageOfType", NULL);
  1297. addInstMethSummary("QCView", AllocSumm,
  1298. "createSnapshotImageOfType", NULL);
  1299. // Create summaries for CIContext, 'createCGImage' and
  1300. // 'createCGLayerWithSize'. These objects are CF objects, and are not
  1301. // automatically garbage collected.
  1302. addInstMethSummary("CIContext", CFAllocSumm,
  1303. "createCGImage", "fromRect", NULL);
  1304. addInstMethSummary("CIContext", CFAllocSumm,
  1305. "createCGImage", "fromRect", "format", "colorSpace", NULL);
  1306. addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
  1307. "info", NULL);
  1308. }
  1309. //===----------------------------------------------------------------------===//
  1310. // AutoreleaseBindings - State used to track objects in autorelease pools.
  1311. //===----------------------------------------------------------------------===//
  1312. typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
  1313. typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
  1314. typedef llvm::ImmutableList<SymbolRef> ARStack;
  1315. static int AutoRCIndex = 0;
  1316. static int AutoRBIndex = 0;
  1317. namespace { class AutoreleasePoolContents {}; }
  1318. namespace { class AutoreleaseStack {}; }
  1319. namespace clang {
  1320. namespace ento {
  1321. template<> struct ProgramStateTrait<AutoreleaseStack>
  1322. : public ProgramStatePartialTrait<ARStack> {
  1323. static inline void *GDMIndex() { return &AutoRBIndex; }
  1324. };
  1325. template<> struct ProgramStateTrait<AutoreleasePoolContents>
  1326. : public ProgramStatePartialTrait<ARPoolContents> {
  1327. static inline void *GDMIndex() { return &AutoRCIndex; }
  1328. };
  1329. } // end GR namespace
  1330. } // end clang namespace
  1331. static SymbolRef GetCurrentAutoreleasePool(const ProgramState *state) {
  1332. ARStack stack = state->get<AutoreleaseStack>();
  1333. return stack.isEmpty() ? SymbolRef() : stack.getHead();
  1334. }
  1335. static const ProgramState *
  1336. SendAutorelease(const ProgramState *state,
  1337. ARCounts::Factory &F,
  1338. SymbolRef sym) {
  1339. SymbolRef pool = GetCurrentAutoreleasePool(state);
  1340. const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
  1341. ARCounts newCnts(0);
  1342. if (cnts) {
  1343. const unsigned *cnt = (*cnts).lookup(sym);
  1344. newCnts = F.add(*cnts, sym, cnt ? *cnt + 1 : 1);
  1345. }
  1346. else
  1347. newCnts = F.add(F.getEmptyMap(), sym, 1);
  1348. return state->set<AutoreleasePoolContents>(pool, newCnts);
  1349. }
  1350. //===----------------------------------------------------------------------===//
  1351. // Transfer functions.
  1352. //===----------------------------------------------------------------------===//
  1353. namespace {
  1354. class CFRefCount : public TransferFuncs {
  1355. public:
  1356. class BindingsPrinter : public ProgramState::Printer {
  1357. public:
  1358. virtual void Print(raw_ostream &Out,
  1359. const ProgramState *state,
  1360. const char* nl,
  1361. const char* sep);
  1362. };
  1363. typedef llvm::DenseMap<const ExplodedNode*, const RetainSummary*>
  1364. SummaryLogTy;
  1365. RetainSummaryManager Summaries;
  1366. SummaryLogTy SummaryLog;
  1367. const LangOptions& LOpts;
  1368. ARCounts::Factory ARCountFactory;
  1369. BugType *useAfterRelease, *releaseNotOwned;
  1370. BugType *deallocGC, *deallocNotOwned;
  1371. BugType *leakWithinFunction, *leakAtReturn;
  1372. BugType *overAutorelease;
  1373. BugType *returnNotOwnedForOwned;
  1374. BugReporter *BR;
  1375. llvm::DenseMap<SymbolRef, const SimpleProgramPointTag*> DeadSymbolTags;
  1376. const ProgramState *Update(const ProgramState * state,
  1377. SymbolRef sym,
  1378. RefVal V,
  1379. ArgEffect E,
  1380. RefVal::Kind& hasErr);
  1381. void ProcessNonLeakError(ExplodedNodeSet &Dst,
  1382. StmtNodeBuilder& Builder,
  1383. const Expr *NodeExpr,
  1384. SourceRange ErrorRange,
  1385. ExplodedNode *Pred,
  1386. const ProgramState *St,
  1387. RefVal::Kind hasErr,
  1388. SymbolRef Sym);
  1389. const ProgramState *HandleSymbolDeath(const ProgramState * state,
  1390. SymbolRef sid,
  1391. RefVal V,
  1392. SmallVectorImpl<SymbolRef> &Leaked);
  1393. ExplodedNode *ProcessLeaks(const ProgramState * state,
  1394. SmallVectorImpl<SymbolRef> &Leaked,
  1395. GenericNodeBuilderRefCount &Builder,
  1396. ExprEngine &Eng,
  1397. ExplodedNode *Pred = 0);
  1398. public:
  1399. CFRefCount(ASTContext &Ctx, bool gcenabled, const LangOptions& lopts)
  1400. : Summaries(Ctx, gcenabled, (bool)lopts.ObjCAutoRefCount),
  1401. LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
  1402. deallocGC(0), deallocNotOwned(0),
  1403. leakWithinFunction(0), leakAtReturn(0), overAutorelease(0),
  1404. returnNotOwnedForOwned(0), BR(0) {}
  1405. virtual ~CFRefCount() {
  1406. for (llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *>::iterator
  1407. it = DeadSymbolTags.begin(), ei = DeadSymbolTags.end(); it != ei; ++it)
  1408. delete it->second;
  1409. }
  1410. void RegisterChecks(ExprEngine &Eng);
  1411. virtual void RegisterPrinters(std::vector<ProgramState::Printer*>& Printers) {
  1412. Printers.push_back(new BindingsPrinter());
  1413. }
  1414. bool isGCEnabled() const { return Summaries.isGCEnabled(); }
  1415. bool isARCorGCEnabled() const { return Summaries.isARCorGCEnabled(); }
  1416. const LangOptions& getLangOptions() const { return LOpts; }
  1417. const RetainSummary *getSummaryOfNode(const ExplodedNode *N) const {
  1418. SummaryLogTy::const_iterator I = SummaryLog.find(N);
  1419. return I == SummaryLog.end() ? 0 : I->second;
  1420. }
  1421. // Calls.
  1422. void evalSummary(ExplodedNodeSet &Dst,
  1423. ExprEngine& Eng,
  1424. StmtNodeBuilder& Builder,
  1425. const Expr *Ex,
  1426. const CallOrObjCMessage &callOrMsg,
  1427. InstanceReceiver Receiver,
  1428. const RetainSummary& Summ,
  1429. const MemRegion *Callee,
  1430. ExplodedNode *Pred, const ProgramState *state);
  1431. virtual void evalCall(ExplodedNodeSet &Dst,
  1432. ExprEngine& Eng,
  1433. StmtNodeBuilder& Builder,
  1434. const CallExpr *CE, SVal L,
  1435. ExplodedNode *Pred);
  1436. virtual void evalObjCMessage(ExplodedNodeSet &Dst,
  1437. ExprEngine& Engine,
  1438. StmtNodeBuilder& Builder,
  1439. ObjCMessage msg,
  1440. ExplodedNode *Pred,
  1441. const ProgramState *state);
  1442. // End-of-path.
  1443. virtual void evalEndPath(ExprEngine& Engine,
  1444. EndOfFunctionNodeBuilder& Builder);
  1445. virtual void evalDeadSymbols(ExplodedNodeSet &Dst,
  1446. ExprEngine& Engine,
  1447. StmtNodeBuilder& Builder,
  1448. ExplodedNode *Pred,
  1449. const ProgramState *state,
  1450. SymbolReaper& SymReaper);
  1451. const ProgramPointTag *getDeadSymbolTag(SymbolRef sym);
  1452. std::pair<ExplodedNode*, const ProgramState *>
  1453. HandleAutoreleaseCounts(const ProgramState * state,
  1454. GenericNodeBuilderRefCount Bd,
  1455. ExplodedNode *Pred,
  1456. ExprEngine &Eng,
  1457. SymbolRef Sym,
  1458. RefVal V,
  1459. bool &stop);
  1460. // Return statements.
  1461. virtual void evalReturn(ExplodedNodeSet &Dst,
  1462. ExprEngine& Engine,
  1463. StmtNodeBuilder& Builder,
  1464. const ReturnStmt *S,
  1465. ExplodedNode *Pred);
  1466. void evalReturnWithRetEffect(ExplodedNodeSet &Dst,
  1467. ExprEngine& Engine,
  1468. StmtNodeBuilder& Builder,
  1469. const ReturnStmt *S,
  1470. ExplodedNode *Pred,
  1471. RetEffect RE, RefVal X,
  1472. SymbolRef Sym, const ProgramState *state);
  1473. };
  1474. } // end anonymous namespace
  1475. static void PrintPool(raw_ostream &Out,
  1476. SymbolRef Sym,
  1477. const ProgramState *state) {
  1478. Out << ' ';
  1479. if (Sym)
  1480. Out << Sym->getSymbolID();
  1481. else
  1482. Out << "<pool>";
  1483. Out << ":{";
  1484. // Get the contents of the pool.
  1485. if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
  1486. for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
  1487. Out << '(' << J.getKey() << ',' << J.getData() << ')';
  1488. Out << '}';
  1489. }
  1490. void CFRefCount::BindingsPrinter::Print(raw_ostream &Out,
  1491. const ProgramState *state,
  1492. const char* nl, const char* sep) {
  1493. RefBindings B = state->get<RefBindings>();
  1494. if (!B.isEmpty())
  1495. Out << sep << nl;
  1496. for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
  1497. Out << (*I).first << " : ";
  1498. (*I).second.print(Out);
  1499. Out << nl;
  1500. }
  1501. // Print the autorelease stack.
  1502. Out << sep << nl << "AR pool stack:";
  1503. ARStack stack = state->get<AutoreleaseStack>();
  1504. PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
  1505. for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
  1506. PrintPool(Out, *I, state);
  1507. Out << nl;
  1508. }
  1509. //===----------------------------------------------------------------------===//
  1510. // Error reporting.
  1511. //===----------------------------------------------------------------------===//
  1512. namespace {
  1513. //===-------------===//
  1514. // Bug Descriptions. //
  1515. //===-------------===//
  1516. class CFRefBug : public BugType {
  1517. protected:
  1518. CFRefCount& TF;
  1519. CFRefBug(CFRefCount* tf, StringRef name)
  1520. : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
  1521. public:
  1522. CFRefCount& getTF() { return TF; }
  1523. // FIXME: Eventually remove.
  1524. virtual const char* getDescription() const = 0;
  1525. virtual bool isLeak() const { return false; }
  1526. };
  1527. class UseAfterRelease : public CFRefBug {
  1528. public:
  1529. UseAfterRelease(CFRefCount* tf)
  1530. : CFRefBug(tf, "Use-after-release") {}
  1531. const char* getDescription() const {
  1532. return "Reference-counted object is used after it is released";
  1533. }
  1534. };
  1535. class BadRelease : public CFRefBug {
  1536. public:
  1537. BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
  1538. const char* getDescription() const {
  1539. return "Incorrect decrement of the reference count of an object that is "
  1540. "not owned at this point by the caller";
  1541. }
  1542. };
  1543. class DeallocGC : public CFRefBug {
  1544. public:
  1545. DeallocGC(CFRefCount *tf)
  1546. : CFRefBug(tf, "-dealloc called while using garbage collection") {}
  1547. const char *getDescription() const {
  1548. return "-dealloc called while using garbage collection";
  1549. }
  1550. };
  1551. class DeallocNotOwned : public CFRefBug {
  1552. public:
  1553. DeallocNotOwned(CFRefCount *tf)
  1554. : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
  1555. const char *getDescription() const {
  1556. return "-dealloc sent to object that may be referenced elsewhere";
  1557. }
  1558. };
  1559. class OverAutorelease : public CFRefBug {
  1560. public:
  1561. OverAutorelease(CFRefCount *tf) :
  1562. CFRefBug(tf, "Object sent -autorelease too many times") {}
  1563. const char *getDescription() const {
  1564. return "Object sent -autorelease too many times";
  1565. }
  1566. };
  1567. class ReturnedNotOwnedForOwned : public CFRefBug {
  1568. public:
  1569. ReturnedNotOwnedForOwned(CFRefCount *tf) :
  1570. CFRefBug(tf, "Method should return an owned object") {}
  1571. const char *getDescription() const {
  1572. return "Object with a +0 retain count returned to caller where a +1 "
  1573. "(owning) retain count is expected";
  1574. }
  1575. };
  1576. class Leak : public CFRefBug {
  1577. const bool isReturn;
  1578. protected:
  1579. Leak(CFRefCount* tf, StringRef name, bool isRet)
  1580. : CFRefBug(tf, name), isReturn(isRet) {}
  1581. public:
  1582. const char* getDescription() const { return ""; }
  1583. bool isLeak() const { return true; }
  1584. };
  1585. class LeakAtReturn : public Leak {
  1586. public:
  1587. LeakAtReturn(CFRefCount* tf, StringRef name)
  1588. : Leak(tf, name, true) {}
  1589. };
  1590. class LeakWithinFunction : public Leak {
  1591. public:
  1592. LeakWithinFunction(CFRefCount* tf, StringRef name)
  1593. : Leak(tf, name, false) {}
  1594. };
  1595. //===---------===//
  1596. // Bug Reports. //
  1597. //===---------===//
  1598. class CFRefReport : public BugReport {
  1599. protected:
  1600. SymbolRef Sym;
  1601. const CFRefCount &TF;
  1602. public:
  1603. CFRefReport(CFRefBug& D, const CFRefCount &tf,
  1604. ExplodedNode *n, SymbolRef sym)
  1605. : BugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
  1606. CFRefReport(CFRefBug& D, const CFRefCount &tf,
  1607. ExplodedNode *n, SymbolRef sym, StringRef endText)
  1608. : BugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
  1609. virtual ~CFRefReport() {}
  1610. CFRefBug& getBugType() const {
  1611. return (CFRefBug&) BugReport::getBugType();
  1612. }
  1613. virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
  1614. if (!getBugType().isLeak())
  1615. return BugReport::getRanges();
  1616. else
  1617. return std::make_pair(ranges_iterator(), ranges_iterator());
  1618. }
  1619. SymbolRef getSymbol() const { return Sym; }
  1620. PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
  1621. const ExplodedNode *N);
  1622. std::pair<const char**,const char**> getExtraDescriptiveText();
  1623. PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
  1624. const ExplodedNode *PrevN,
  1625. BugReporterContext &BRC);
  1626. };
  1627. class CFRefLeakReport : public CFRefReport {
  1628. SourceLocation AllocSite;
  1629. const MemRegion* AllocBinding;
  1630. public:
  1631. CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
  1632. ExplodedNode *n, SymbolRef sym,
  1633. ExprEngine& Eng);
  1634. PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
  1635. const ExplodedNode *N);
  1636. SourceLocation getLocation() const { return AllocSite; }
  1637. };
  1638. } // end anonymous namespace
  1639. static const char* Msgs[] = {
  1640. // GC only
  1641. "Code is compiled to only use garbage collection",
  1642. // No GC.
  1643. "Code is compiled to use reference counts",
  1644. // Hybrid, with GC.
  1645. "Code is compiled to use either garbage collection (GC) or reference counts"
  1646. " (non-GC). The bug occurs with GC enabled",
  1647. // Hybrid, without GC
  1648. "Code is compiled to use either garbage collection (GC) or reference counts"
  1649. " (non-GC). The bug occurs in non-GC mode"
  1650. };
  1651. std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
  1652. CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
  1653. switch (TF.getLangOptions().getGCMode()) {
  1654. default:
  1655. assert(false);
  1656. case LangOptions::GCOnly:
  1657. assert (TF.isGCEnabled());
  1658. return std::make_pair(&Msgs[0], &Msgs[0]+1);
  1659. case LangOptions::NonGC:
  1660. assert (!TF.isGCEnabled());
  1661. return std::make_pair(&Msgs[1], &Msgs[1]+1);
  1662. case LangOptions::HybridGC:
  1663. if (TF.isGCEnabled())
  1664. return std::make_pair(&Msgs[2], &Msgs[2]+1);
  1665. else
  1666. return std::make_pair(&Msgs[3], &Msgs[3]+1);
  1667. }
  1668. }
  1669. static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
  1670. ArgEffect X) {
  1671. for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
  1672. I!=E; ++I)
  1673. if (*I == X) return true;
  1674. return false;
  1675. }
  1676. PathDiagnosticPiece *CFRefReport::VisitNode(const ExplodedNode *N,
  1677. const ExplodedNode *PrevN,
  1678. BugReporterContext &BRC) {
  1679. if (!isa<PostStmt>(N->getLocation()))
  1680. return NULL;
  1681. // Check if the type state has changed.
  1682. const ProgramState *PrevSt = PrevN->getState();
  1683. const ProgramState *CurrSt = N->getState();
  1684. const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
  1685. if (!CurrT) return NULL;
  1686. const RefVal &CurrV = *CurrT;
  1687. const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
  1688. // Create a string buffer to constain all the useful things we want
  1689. // to tell the user.
  1690. std::string sbuf;
  1691. llvm::raw_string_ostream os(sbuf);
  1692. // This is the allocation site since the previous node had no bindings
  1693. // for this symbol.
  1694. if (!PrevT) {
  1695. const Stmt *S = cast<PostStmt>(N->getLocation()).getStmt();
  1696. if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
  1697. // Get the name of the callee (if it is available).
  1698. SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee());
  1699. if (const FunctionDecl *FD = X.getAsFunctionDecl())
  1700. os << "Call to function '" << FD << '\'';
  1701. else
  1702. os << "function call";
  1703. }
  1704. else if (isa<ObjCMessageExpr>(S)) {
  1705. os << "Method";
  1706. } else {
  1707. os << "Property";
  1708. }
  1709. if (CurrV.getObjKind() == RetEffect::CF) {
  1710. os << " returns a Core Foundation object with a ";
  1711. }
  1712. else {
  1713. assert (CurrV.getObjKind() == RetEffect::ObjC);
  1714. os << " returns an Objective-C object with a ";
  1715. }
  1716. if (CurrV.isOwned()) {
  1717. os << "+1 retain count";
  1718. if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
  1719. assert(CurrV.getObjKind() == RetEffect::CF);
  1720. os << ". "
  1721. "Core Foundation objects are not automatically garbage collected.";
  1722. }
  1723. }
  1724. else {
  1725. assert (CurrV.isNotOwned());
  1726. os << "+0 retain count";
  1727. }
  1728. PathDiagnosticLocation Pos(S, BRC.getSourceManager());
  1729. return new PathDiagnosticEventPiece(Pos, os.str());
  1730. }
  1731. // Gather up the effects that were performed on the object at this
  1732. // program point
  1733. SmallVector<ArgEffect, 2> AEffects;
  1734. if (const RetainSummary *Summ =
  1735. TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
  1736. // We only have summaries attached to nodes after evaluating CallExpr and
  1737. // ObjCMessageExprs.
  1738. const Stmt *S = cast<PostStmt>(N->getLocation()).getStmt();
  1739. if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
  1740. // Iterate through the parameter expressions and see if the symbol
  1741. // was ever passed as an argument.
  1742. unsigned i = 0;
  1743. for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
  1744. AI!=AE; ++AI, ++i) {
  1745. // Retrieve the value of the argument. Is it the symbol
  1746. // we are interested in?
  1747. if (CurrSt->getSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
  1748. continue;
  1749. // We have an argument. Get the effect!
  1750. AEffects.push_back(Summ->getArg(i));
  1751. }
  1752. }
  1753. else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
  1754. if (const Expr *receiver = ME->getInstanceReceiver())
  1755. if (CurrSt->getSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
  1756. // The symbol we are tracking is the receiver.
  1757. AEffects.push_back(Summ->getReceiverEffect());
  1758. }
  1759. }
  1760. }
  1761. do {
  1762. // Get the previous type state.
  1763. RefVal PrevV = *PrevT;
  1764. // Specially handle -dealloc.
  1765. if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
  1766. // Determine if the object's reference count was pushed to zero.
  1767. assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
  1768. // We may not have transitioned to 'release' if we hit an error.
  1769. // This case is handled elsewhere.
  1770. if (CurrV.getKind() == RefVal::Released) {
  1771. assert(CurrV.getCombinedCounts() == 0);
  1772. os << "Object released by directly sending the '-dealloc' message";
  1773. break;
  1774. }
  1775. }
  1776. // Specially handle CFMakeCollectable and friends.
  1777. if (contains(AEffects, MakeCollectable)) {
  1778. // Get the name of the function.
  1779. const Stmt *S = cast<PostStmt>(N->getLocation()).getStmt();
  1780. SVal X = CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
  1781. const FunctionDecl *FD = X.getAsFunctionDecl();
  1782. const std::string& FName = FD->getNameAsString();
  1783. if (TF.isGCEnabled()) {
  1784. // Determine if the object's reference count was pushed to zero.
  1785. assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
  1786. os << "In GC mode a call to '" << FName
  1787. << "' decrements an object's retain count and registers the "
  1788. "object with the garbage collector. ";
  1789. if (CurrV.getKind() == RefVal::Released) {
  1790. assert(CurrV.getCount() == 0);
  1791. os << "Since it now has a 0 retain count the object can be "
  1792. "automatically collected by the garbage collector.";
  1793. }
  1794. else
  1795. os << "An object must have a 0 retain count to be garbage collected. "
  1796. "After this call its retain count is +" << CurrV.getCount()
  1797. << '.';
  1798. }
  1799. else
  1800. os << "When GC is not enabled a call to '" << FName
  1801. << "' has no effect on its argument.";
  1802. // Nothing more to say.
  1803. break;
  1804. }
  1805. // Determine if the typestate has changed.
  1806. if (!(PrevV == CurrV))
  1807. switch (CurrV.getKind()) {
  1808. case RefVal::Owned:
  1809. case RefVal::NotOwned:
  1810. if (PrevV.getCount() == CurrV.getCount()) {
  1811. // Did an autorelease message get sent?
  1812. if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
  1813. return 0;
  1814. assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
  1815. os << "Object sent -autorelease message";
  1816. break;
  1817. }
  1818. if (PrevV.getCount() > CurrV.getCount())
  1819. os << "Reference count decremented.";
  1820. else
  1821. os << "Reference count incremented.";
  1822. if (unsigned Count = CurrV.getCount())
  1823. os << " The object now has a +" << Count << " retain count.";
  1824. if (PrevV.getKind() == RefVal::Released) {
  1825. assert(TF.isGCEnabled() && CurrV.getCount() > 0);
  1826. os << " The object is not eligible for garbage collection until the "
  1827. "retain count reaches 0 again.";
  1828. }
  1829. break;
  1830. case RefVal::Released:
  1831. os << "Object released.";
  1832. break;
  1833. case RefVal::ReturnedOwned:
  1834. os << "Object returned to caller as an owning reference (single retain "
  1835. "count transferred to caller)";
  1836. break;
  1837. case RefVal::ReturnedNotOwned:
  1838. os << "Object returned to caller with a +0 retain count";
  1839. break;
  1840. default:
  1841. return NULL;
  1842. }
  1843. // Emit any remaining diagnostics for the argument effects (if any).
  1844. for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
  1845. E=AEffects.end(); I != E; ++I) {
  1846. // A bunch of things have alternate behavior under GC.
  1847. if (TF.isGCEnabled())
  1848. switch (*I) {
  1849. default: break;
  1850. case Autorelease:
  1851. os << "In GC mode an 'autorelease' has no effect.";
  1852. continue;
  1853. case IncRefMsg:
  1854. os << "In GC mode the 'retain' message has no effect.";
  1855. continue;
  1856. case DecRefMsg:
  1857. os << "In GC mode the 'release' message has no effect.";
  1858. continue;
  1859. }
  1860. }
  1861. } while (0);
  1862. if (os.str().empty())
  1863. return 0; // We have nothing to say!
  1864. const Stmt *S = cast<PostStmt>(N->getLocation()).getStmt();
  1865. PathDiagnosticLocation Pos(S, BRC.getSourceManager());
  1866. PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
  1867. // Add the range by scanning the children of the statement for any bindings
  1868. // to Sym.
  1869. for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
  1870. I!=E; ++I)
  1871. if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
  1872. if (CurrSt->getSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
  1873. P->addRange(Exp->getSourceRange());
  1874. break;
  1875. }
  1876. return P;
  1877. }
  1878. namespace {
  1879. class FindUniqueBinding :
  1880. public StoreManager::BindingsHandler {
  1881. SymbolRef Sym;
  1882. const MemRegion* Binding;
  1883. bool First;
  1884. public:
  1885. FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
  1886. bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
  1887. SVal val) {
  1888. SymbolRef SymV = val.getAsSymbol();
  1889. if (!SymV || SymV != Sym)
  1890. return true;
  1891. if (Binding) {
  1892. First = false;
  1893. return false;
  1894. }
  1895. else
  1896. Binding = R;
  1897. return true;
  1898. }
  1899. operator bool() { return First && Binding; }
  1900. const MemRegion* getRegion() { return Binding; }
  1901. };
  1902. }
  1903. static std::pair<const ExplodedNode*,const MemRegion*>
  1904. GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
  1905. SymbolRef Sym) {
  1906. // Find both first node that referred to the tracked symbol and the
  1907. // memory location that value was store to.
  1908. const ExplodedNode *Last = N;
  1909. const MemRegion* FirstBinding = 0;
  1910. while (N) {
  1911. const ProgramState *St = N->getState();
  1912. RefBindings B = St->get<RefBindings>();
  1913. if (!B.lookup(Sym))
  1914. break;
  1915. FindUniqueBinding FB(Sym);
  1916. StateMgr.iterBindings(St, FB);
  1917. if (FB) FirstBinding = FB.getRegion();
  1918. Last = N;
  1919. N = N->pred_empty() ? NULL : *(N->pred_begin());
  1920. }
  1921. return std::make_pair(Last, FirstBinding);
  1922. }
  1923. PathDiagnosticPiece*
  1924. CFRefReport::getEndPath(BugReporterContext &BRC,
  1925. const ExplodedNode *EndN) {
  1926. // Tell the BugReporterContext to report cases when the tracked symbol is
  1927. // assigned to different variables, etc.
  1928. BRC.addNotableSymbol(Sym);
  1929. return BugReport::getEndPath(BRC, EndN);
  1930. }
  1931. PathDiagnosticPiece*
  1932. CFRefLeakReport::getEndPath(BugReporterContext &BRC,
  1933. const ExplodedNode *EndN){
  1934. // Tell the BugReporterContext to report cases when the tracked symbol is
  1935. // assigned to different variables, etc.
  1936. BRC.addNotableSymbol(Sym);
  1937. // We are reporting a leak. Walk up the graph to get to the first node where
  1938. // the symbol appeared, and also get the first VarDecl that tracked object
  1939. // is stored to.
  1940. const ExplodedNode *AllocNode = 0;
  1941. const MemRegion* FirstBinding = 0;
  1942. llvm::tie(AllocNode, FirstBinding) =
  1943. GetAllocationSite(BRC.getStateManager(), EndN, Sym);
  1944. SourceManager& SMgr = BRC.getSourceManager();
  1945. // Compute an actual location for the leak. Sometimes a leak doesn't
  1946. // occur at an actual statement (e.g., transition between blocks; end
  1947. // of function) so we need to walk the graph and compute a real location.
  1948. const ExplodedNode *LeakN = EndN;
  1949. PathDiagnosticLocation L;
  1950. while (LeakN) {
  1951. ProgramPoint P = LeakN->getLocation();
  1952. if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
  1953. L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
  1954. break;
  1955. }
  1956. else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
  1957. if (const Stmt *Term = BE->getSrc()->getTerminator()) {
  1958. L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
  1959. break;
  1960. }
  1961. }
  1962. LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
  1963. }
  1964. if (!L.isValid()) {
  1965. const Decl &D = EndN->getCodeDecl();
  1966. L = PathDiagnosticLocation(D.getBodyRBrace(), SMgr);
  1967. }
  1968. std::string sbuf;
  1969. llvm::raw_string_ostream os(sbuf);
  1970. os << "Object leaked: ";
  1971. if (FirstBinding) {
  1972. os << "object allocated and stored into '"
  1973. << FirstBinding->getString() << '\'';
  1974. }
  1975. else
  1976. os << "allocated object";
  1977. // Get the retain count.
  1978. const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
  1979. if (RV->getKind() == RefVal::ErrorLeakReturned) {
  1980. // FIXME: Per comments in rdar://6320065, "create" only applies to CF
  1981. // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
  1982. // to the caller for NS objects.
  1983. const Decl *D = &EndN->getCodeDecl();
  1984. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  1985. os << " is returned from a method whose name ('"
  1986. << MD->getSelector().getAsString()
  1987. << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
  1988. " This violates the naming convention rules"
  1989. " given in the Memory Management Guide for Cocoa";
  1990. }
  1991. else {
  1992. const FunctionDecl *FD = cast<FunctionDecl>(D);
  1993. os << " is return from a function whose name ('"
  1994. << FD->getNameAsString()
  1995. << "') does not contain 'Copy' or 'Create'. This violates the naming"
  1996. " convention rules given the Memory Management Guide for Core"
  1997. " Foundation";
  1998. }
  1999. }
  2000. else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
  2001. ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
  2002. os << " and returned from method '" << MD.getSelector().getAsString()
  2003. << "' is potentially leaked when using garbage collection. Callers "
  2004. "of this method do not expect a returned object with a +1 retain "
  2005. "count since they expect the object to be managed by the garbage "
  2006. "collector";
  2007. }
  2008. else
  2009. os << " is not referenced later in this execution path and has a retain "
  2010. "count of +" << RV->getCount();
  2011. return new PathDiagnosticEventPiece(L, os.str());
  2012. }
  2013. CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
  2014. ExplodedNode *n,
  2015. SymbolRef sym, ExprEngine& Eng)
  2016. : CFRefReport(D, tf, n, sym) {
  2017. // Most bug reports are cached at the location where they occurred.
  2018. // With leaks, we want to unique them by the location where they were
  2019. // allocated, and only report a single path. To do this, we need to find
  2020. // the allocation site of a piece of tracked memory, which we do via a
  2021. // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
  2022. // Note that this is *not* the trimmed graph; we are guaranteed, however,
  2023. // that all ancestor nodes that represent the allocation site have the
  2024. // same SourceLocation.
  2025. const ExplodedNode *AllocNode = 0;
  2026. llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
  2027. GetAllocationSite(Eng.getStateManager(), getErrorNode(), getSymbol());
  2028. // Get the SourceLocation for the allocation site.
  2029. ProgramPoint P = AllocNode->getLocation();
  2030. AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
  2031. // Fill in the description of the bug.
  2032. Description.clear();
  2033. llvm::raw_string_ostream os(Description);
  2034. SourceManager& SMgr = Eng.getContext().getSourceManager();
  2035. unsigned AllocLine = SMgr.getExpansionLineNumber(AllocSite);
  2036. os << "Potential leak ";
  2037. if (tf.isGCEnabled()) {
  2038. os << "(when using garbage collection) ";
  2039. }
  2040. os << "of an object allocated on line " << AllocLine;
  2041. // FIXME: AllocBinding doesn't get populated for RegionStore yet.
  2042. if (AllocBinding)
  2043. os << " and stored into '" << AllocBinding->getString() << '\'';
  2044. }
  2045. //===----------------------------------------------------------------------===//
  2046. // Main checker logic.
  2047. //===----------------------------------------------------------------------===//
  2048. /// GetReturnType - Used to get the return type of a message expression or
  2049. /// function call with the intention of affixing that type to a tracked symbol.
  2050. /// While the the return type can be queried directly from RetEx, when
  2051. /// invoking class methods we augment to the return type to be that of
  2052. /// a pointer to the class (as opposed it just being id).
  2053. static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
  2054. QualType RetTy = RetE->getType();
  2055. // If RetE is not a message expression just return its type.
  2056. // If RetE is a message expression, return its types if it is something
  2057. /// more specific than id.
  2058. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
  2059. if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
  2060. if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
  2061. PT->isObjCClassType()) {
  2062. // At this point we know the return type of the message expression is
  2063. // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
  2064. // is a call to a class method whose type we can resolve. In such
  2065. // cases, promote the return type to XXX* (where XXX is the class).
  2066. const ObjCInterfaceDecl *D = ME->getReceiverInterface();
  2067. return !D ? RetTy :
  2068. Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
  2069. }
  2070. return RetTy;
  2071. }
  2072. // HACK: Symbols that have ref-count state that are referenced directly
  2073. // (not as structure or array elements, or via bindings) by an argument
  2074. // should not have their ref-count state stripped after we have
  2075. // done an invalidation pass.
  2076. //
  2077. // FIXME: This is a global to currently share between CFRefCount and
  2078. // RetainReleaseChecker. Eventually all functionality in CFRefCount should
  2079. // be migrated to RetainReleaseChecker, and we can make this a non-global.
  2080. llvm::DenseSet<SymbolRef> WhitelistedSymbols;
  2081. namespace {
  2082. struct ResetWhiteList {
  2083. ResetWhiteList() {}
  2084. ~ResetWhiteList() { WhitelistedSymbols.clear(); }
  2085. };
  2086. }
  2087. void CFRefCount::evalSummary(ExplodedNodeSet &Dst,
  2088. ExprEngine& Eng,
  2089. StmtNodeBuilder& Builder,
  2090. const Expr *Ex,
  2091. const CallOrObjCMessage &callOrMsg,
  2092. InstanceReceiver Receiver,
  2093. const RetainSummary& Summ,
  2094. const MemRegion *Callee,
  2095. ExplodedNode *Pred,
  2096. const ProgramState *state) {
  2097. // Evaluate the effect of the arguments.
  2098. RefVal::Kind hasErr = (RefVal::Kind) 0;
  2099. SourceRange ErrorRange;
  2100. SymbolRef ErrorSym = 0;
  2101. SmallVector<const MemRegion*, 10> RegionsToInvalidate;
  2102. // Use RAII to make sure the whitelist is properly cleared.
  2103. ResetWhiteList resetWhiteList;
  2104. // Invalidate all instance variables of the receiver of a message.
  2105. // FIXME: We should be able to do better with inter-procedural analysis.
  2106. if (Receiver) {
  2107. SVal V = Receiver.getSValAsScalarOrLoc(state);
  2108. if (SymbolRef Sym = V.getAsLocSymbol()) {
  2109. if (state->get<RefBindings>(Sym))
  2110. WhitelistedSymbols.insert(Sym);
  2111. }
  2112. if (const MemRegion *region = V.getAsRegion())
  2113. RegionsToInvalidate.push_back(region);
  2114. }
  2115. // Invalidate all instance variables for the callee of a C++ method call.
  2116. // FIXME: We should be able to do better with inter-procedural analysis.
  2117. // FIXME: we can probably do better for const versus non-const methods.
  2118. if (callOrMsg.isCXXCall()) {
  2119. if (const MemRegion *callee = callOrMsg.getCXXCallee().getAsRegion())
  2120. RegionsToInvalidate.push_back(callee);
  2121. }
  2122. for (unsigned idx = 0, e = callOrMsg.getNumArgs(); idx != e; ++idx) {
  2123. SVal V = callOrMsg.getArgSValAsScalarOrLoc(idx);
  2124. SymbolRef Sym = V.getAsLocSymbol();
  2125. if (Sym)
  2126. if (RefBindings::data_type* T = state->get<RefBindings>(Sym)) {
  2127. WhitelistedSymbols.insert(Sym);
  2128. state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
  2129. if (hasErr) {
  2130. ErrorRange = callOrMsg.getArgSourceRange(idx);
  2131. ErrorSym = Sym;
  2132. break;
  2133. }
  2134. }
  2135. tryAgain:
  2136. if (isa<Loc>(V)) {
  2137. if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
  2138. if (Summ.getArg(idx) == DoNothingByRef)
  2139. continue;
  2140. // Invalidate the value of the variable passed by reference.
  2141. const MemRegion *R = MR->getRegion();
  2142. // Are we dealing with an ElementRegion? If the element type is
  2143. // a basic integer type (e.g., char, int) and the underying region
  2144. // is a variable region then strip off the ElementRegion.
  2145. // FIXME: We really need to think about this for the general case
  2146. // as sometimes we are reasoning about arrays and other times
  2147. // about (char*), etc., is just a form of passing raw bytes.
  2148. // e.g., void *p = alloca(); foo((char*)p);
  2149. if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
  2150. // Checking for 'integral type' is probably too promiscuous, but
  2151. // we'll leave it in for now until we have a systematic way of
  2152. // handling all of these cases. Eventually we need to come up
  2153. // with an interface to StoreManager so that this logic can be
  2154. // approriately delegated to the respective StoreManagers while
  2155. // still allowing us to do checker-specific logic (e.g.,
  2156. // invalidating reference counts), probably via callbacks.
  2157. if (ER->getElementType()->isIntegralOrEnumerationType()) {
  2158. const MemRegion *superReg = ER->getSuperRegion();
  2159. if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
  2160. isa<ObjCIvarRegion>(superReg))
  2161. R = cast<TypedRegion>(superReg);
  2162. }
  2163. // FIXME: What about layers of ElementRegions?
  2164. }
  2165. // Mark this region for invalidation. We batch invalidate regions
  2166. // below for efficiency.
  2167. RegionsToInvalidate.push_back(R);
  2168. continue;
  2169. }
  2170. else {
  2171. // Nuke all other arguments passed by reference.
  2172. // FIXME: is this necessary or correct? This handles the non-Region
  2173. // cases. Is it ever valid to store to these?
  2174. state = state->unbindLoc(cast<Loc>(V));
  2175. }
  2176. }
  2177. else if (isa<nonloc::LocAsInteger>(V)) {
  2178. // If we are passing a location wrapped as an integer, unwrap it and
  2179. // invalidate the values referred by the location.
  2180. V = cast<nonloc::LocAsInteger>(V).getLoc();
  2181. goto tryAgain;
  2182. }
  2183. }
  2184. // Block calls result in all captured values passed-via-reference to be
  2185. // invalidated.
  2186. if (const BlockDataRegion *BR = dyn_cast_or_null<BlockDataRegion>(Callee)) {
  2187. RegionsToInvalidate.push_back(BR);
  2188. }
  2189. // Invalidate regions we designed for invalidation use the batch invalidation
  2190. // API.
  2191. // FIXME: We can have collisions on the conjured symbol if the
  2192. // expression *I also creates conjured symbols. We probably want
  2193. // to identify conjured symbols by an expression pair: the enclosing
  2194. // expression (the context) and the expression itself. This should
  2195. // disambiguate conjured symbols.
  2196. unsigned Count = Builder.getCurrentBlockCount();
  2197. StoreManager::InvalidatedSymbols IS;
  2198. // NOTE: Even if RegionsToInvalidate is empty, we must still invalidate
  2199. // global variables.
  2200. // NOTE: RetainReleaseChecker handles the actual invalidation of symbols.
  2201. state =
  2202. state->invalidateRegions(RegionsToInvalidate.data(),
  2203. RegionsToInvalidate.data() +
  2204. RegionsToInvalidate.size(),
  2205. Ex, Count, &IS,
  2206. /* invalidateGlobals = */
  2207. Eng.doesInvalidateGlobals(callOrMsg));
  2208. // Evaluate the effect on the message receiver.
  2209. if (!ErrorRange.isValid() && Receiver) {
  2210. SymbolRef Sym = Receiver.getSValAsScalarOrLoc(state).getAsLocSymbol();
  2211. if (Sym) {
  2212. if (const RefVal* T = state->get<RefBindings>(Sym)) {
  2213. state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
  2214. if (hasErr) {
  2215. ErrorRange = Receiver.getSourceRange();
  2216. ErrorSym = Sym;
  2217. }
  2218. }
  2219. }
  2220. }
  2221. // Process any errors.
  2222. if (hasErr) {
  2223. ProcessNonLeakError(Dst, Builder, Ex, ErrorRange, Pred, state,
  2224. hasErr, ErrorSym);
  2225. return;
  2226. }
  2227. // Consult the summary for the return value.
  2228. RetEffect RE = Summ.getRetEffect();
  2229. if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
  2230. bool found = false;
  2231. if (Receiver) {
  2232. SVal V = Receiver.getSValAsScalarOrLoc(state);
  2233. if (SymbolRef Sym = V.getAsLocSymbol())
  2234. if (state->get<RefBindings>(Sym)) {
  2235. found = true;
  2236. RE = Summaries.getObjAllocRetEffect();
  2237. }
  2238. } // FIXME: Otherwise, this is a send-to-super instance message.
  2239. if (!found)
  2240. RE = RetEffect::MakeNoRet();
  2241. }
  2242. switch (RE.getKind()) {
  2243. default:
  2244. assert (false && "Unhandled RetEffect."); break;
  2245. case RetEffect::NoRet: {
  2246. // Make up a symbol for the return value (not reference counted).
  2247. // FIXME: Most of this logic is not specific to the retain/release
  2248. // checker.
  2249. // FIXME: We eventually should handle structs and other compound types
  2250. // that are returned by value.
  2251. // Use the result type from callOrMsg as it automatically adjusts
  2252. // for methods/functions that return references.
  2253. QualType resultTy = callOrMsg.getResultType(Eng.getContext());
  2254. if (Loc::isLocType(resultTy) ||
  2255. (resultTy->isIntegerType() && resultTy->isScalarType())) {
  2256. unsigned Count = Builder.getCurrentBlockCount();
  2257. SValBuilder &svalBuilder = Eng.getSValBuilder();
  2258. SVal X = svalBuilder.getConjuredSymbolVal(NULL, Ex, resultTy, Count);
  2259. state = state->BindExpr(Ex, X, false);
  2260. }
  2261. break;
  2262. }
  2263. case RetEffect::Alias: {
  2264. unsigned idx = RE.getIndex();
  2265. assert (idx < callOrMsg.getNumArgs());
  2266. SVal V = callOrMsg.getArgSValAsScalarOrLoc(idx);
  2267. state = state->BindExpr(Ex, V, false);
  2268. break;
  2269. }
  2270. case RetEffect::ReceiverAlias: {
  2271. assert(Receiver);
  2272. SVal V = Receiver.getSValAsScalarOrLoc(state);
  2273. state = state->BindExpr(Ex, V, false);
  2274. break;
  2275. }
  2276. case RetEffect::OwnedAllocatedSymbol:
  2277. case RetEffect::OwnedSymbol: {
  2278. unsigned Count = Builder.getCurrentBlockCount();
  2279. SValBuilder &svalBuilder = Eng.getSValBuilder();
  2280. SymbolRef Sym = svalBuilder.getConjuredSymbol(Ex, Count);
  2281. // Use the result type from callOrMsg as it automatically adjusts
  2282. // for methods/functions that return references.
  2283. QualType resultTy = callOrMsg.getResultType(Eng.getContext());
  2284. state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
  2285. resultTy));
  2286. state = state->BindExpr(Ex, svalBuilder.makeLoc(Sym), false);
  2287. // FIXME: Add a flag to the checker where allocations are assumed to
  2288. // *not fail.
  2289. #if 0
  2290. if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
  2291. bool isFeasible;
  2292. state = state.assume(loc::SymbolVal(Sym), true, isFeasible);
  2293. assert(isFeasible && "Cannot assume fresh symbol is non-null.");
  2294. }
  2295. #endif
  2296. break;
  2297. }
  2298. case RetEffect::GCNotOwnedSymbol:
  2299. case RetEffect::ARCNotOwnedSymbol:
  2300. case RetEffect::NotOwnedSymbol: {
  2301. unsigned Count = Builder.getCurrentBlockCount();
  2302. SValBuilder &svalBuilder = Eng.getSValBuilder();
  2303. SymbolRef Sym = svalBuilder.getConjuredSymbol(Ex, Count);
  2304. QualType RetT = GetReturnType(Ex, svalBuilder.getContext());
  2305. state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
  2306. RetT));
  2307. state = state->BindExpr(Ex, svalBuilder.makeLoc(Sym), false);
  2308. break;
  2309. }
  2310. }
  2311. // Generate a sink node if we are at the end of a path.
  2312. ExplodedNode *NewNode =
  2313. Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
  2314. : Builder.MakeNode(Dst, Ex, Pred, state);
  2315. // Annotate the edge with summary we used.
  2316. if (NewNode) SummaryLog[NewNode] = &Summ;
  2317. }
  2318. void CFRefCount::evalCall(ExplodedNodeSet &Dst,
  2319. ExprEngine& Eng,
  2320. StmtNodeBuilder& Builder,
  2321. const CallExpr *CE, SVal L,
  2322. ExplodedNode *Pred) {
  2323. RetainSummary *Summ = 0;
  2324. // FIXME: Better support for blocks. For now we stop tracking anything
  2325. // that is passed to blocks.
  2326. // FIXME: Need to handle variables that are "captured" by the block.
  2327. if (dyn_cast_or_null<BlockDataRegion>(L.getAsRegion())) {
  2328. Summ = Summaries.getPersistentStopSummary();
  2329. }
  2330. else if (const FunctionDecl *FD = L.getAsFunctionDecl()) {
  2331. Summ = Summaries.getSummary(FD);
  2332. }
  2333. else if (const CXXMemberCallExpr *me = dyn_cast<CXXMemberCallExpr>(CE)) {
  2334. if (const CXXMethodDecl *MD = me->getMethodDecl())
  2335. Summ = Summaries.getSummary(MD);
  2336. else
  2337. Summ = Summaries.getDefaultSummary();
  2338. }
  2339. else
  2340. Summ = Summaries.getDefaultSummary();
  2341. assert(Summ);
  2342. evalSummary(Dst, Eng, Builder, CE,
  2343. CallOrObjCMessage(CE, Pred->getState()),
  2344. InstanceReceiver(), *Summ,L.getAsRegion(),
  2345. Pred, Pred->getState());
  2346. }
  2347. void CFRefCount::evalObjCMessage(ExplodedNodeSet &Dst,
  2348. ExprEngine& Eng,
  2349. StmtNodeBuilder& Builder,
  2350. ObjCMessage msg,
  2351. ExplodedNode *Pred,
  2352. const ProgramState *state) {
  2353. RetainSummary *Summ =
  2354. msg.isInstanceMessage()
  2355. ? Summaries.getInstanceMethodSummary(msg, state,Pred->getLocationContext())
  2356. : Summaries.getClassMethodSummary(msg);
  2357. assert(Summ && "RetainSummary is null");
  2358. evalSummary(Dst, Eng, Builder, msg.getOriginExpr(),
  2359. CallOrObjCMessage(msg, Pred->getState()),
  2360. InstanceReceiver(msg, Pred->getLocationContext()), *Summ, NULL,
  2361. Pred, state);
  2362. }
  2363. // Return statements.
  2364. void CFRefCount::evalReturn(ExplodedNodeSet &Dst,
  2365. ExprEngine& Eng,
  2366. StmtNodeBuilder& Builder,
  2367. const ReturnStmt *S,
  2368. ExplodedNode *Pred) {
  2369. const Expr *RetE = S->getRetValue();
  2370. if (!RetE)
  2371. return;
  2372. const ProgramState *state = Pred->getState();
  2373. SymbolRef Sym = state->getSValAsScalarOrLoc(RetE).getAsLocSymbol();
  2374. if (!Sym)
  2375. return;
  2376. // Get the reference count binding (if any).
  2377. const RefVal* T = state->get<RefBindings>(Sym);
  2378. if (!T)
  2379. return;
  2380. // Change the reference count.
  2381. RefVal X = *T;
  2382. switch (X.getKind()) {
  2383. case RefVal::Owned: {
  2384. unsigned cnt = X.getCount();
  2385. assert (cnt > 0);
  2386. X.setCount(cnt - 1);
  2387. X = X ^ RefVal::ReturnedOwned;
  2388. break;
  2389. }
  2390. case RefVal::NotOwned: {
  2391. unsigned cnt = X.getCount();
  2392. if (cnt) {
  2393. X.setCount(cnt - 1);
  2394. X = X ^ RefVal::ReturnedOwned;
  2395. }
  2396. else {
  2397. X = X ^ RefVal::ReturnedNotOwned;
  2398. }
  2399. break;
  2400. }
  2401. default:
  2402. return;
  2403. }
  2404. // Update the binding.
  2405. state = state->set<RefBindings>(Sym, X);
  2406. Pred = Builder.MakeNode(Dst, S, Pred, state);
  2407. // Did we cache out?
  2408. if (!Pred)
  2409. return;
  2410. // Update the autorelease counts.
  2411. static SimpleProgramPointTag autoreleasetag("CFRefCount : Autorelease");
  2412. GenericNodeBuilderRefCount Bd(Builder, S, &autoreleasetag);
  2413. bool stop = false;
  2414. llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
  2415. X, stop);
  2416. // Did we cache out?
  2417. if (!Pred || stop)
  2418. return;
  2419. // Get the updated binding.
  2420. T = state->get<RefBindings>(Sym);
  2421. assert(T);
  2422. X = *T;
  2423. // Consult the summary of the enclosing method.
  2424. Decl const *CD = &Pred->getCodeDecl();
  2425. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
  2426. const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
  2427. return evalReturnWithRetEffect(Dst, Eng, Builder, S,
  2428. Pred, Summ.getRetEffect(), X,
  2429. Sym, state);
  2430. }
  2431. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
  2432. if (!isa<CXXMethodDecl>(FD))
  2433. if (const RetainSummary *Summ = Summaries.getSummary(FD))
  2434. return evalReturnWithRetEffect(Dst, Eng, Builder, S,
  2435. Pred, Summ->getRetEffect(), X,
  2436. Sym, state);
  2437. }
  2438. }
  2439. void CFRefCount::evalReturnWithRetEffect(ExplodedNodeSet &Dst,
  2440. ExprEngine &Eng,
  2441. StmtNodeBuilder &Builder,
  2442. const ReturnStmt *S,
  2443. ExplodedNode *Pred,
  2444. RetEffect RE, RefVal X,
  2445. SymbolRef Sym,
  2446. const ProgramState *state) {
  2447. // Any leaks or other errors?
  2448. if (X.isReturnedOwned() && X.getCount() == 0) {
  2449. if (RE.getKind() != RetEffect::NoRet) {
  2450. bool hasError = false;
  2451. if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
  2452. // Things are more complicated with garbage collection. If the
  2453. // returned object is suppose to be an Objective-C object, we have
  2454. // a leak (as the caller expects a GC'ed object) because no
  2455. // method should return ownership unless it returns a CF object.
  2456. hasError = true;
  2457. X = X ^ RefVal::ErrorGCLeakReturned;
  2458. }
  2459. else if (!RE.isOwned()) {
  2460. // Either we are using GC and the returned object is a CF type
  2461. // or we aren't using GC. In either case, we expect that the
  2462. // enclosing method is expected to return ownership.
  2463. hasError = true;
  2464. X = X ^ RefVal::ErrorLeakReturned;
  2465. }
  2466. if (hasError) {
  2467. // Generate an error node.
  2468. static SimpleProgramPointTag
  2469. ReturnOwnLeakTag("CFRefCount : ReturnsOwnLeak");
  2470. state = state->set<RefBindings>(Sym, X);
  2471. ExplodedNode *N =
  2472. Builder.generateNode(PostStmt(S, Pred->getLocationContext(),
  2473. &ReturnOwnLeakTag), state, Pred);
  2474. if (N) {
  2475. CFRefReport *report =
  2476. new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
  2477. N, Sym, Eng);
  2478. BR->EmitReport(report);
  2479. }
  2480. }
  2481. }
  2482. return;
  2483. }
  2484. if (X.isReturnedNotOwned()) {
  2485. if (RE.isOwned()) {
  2486. // Trying to return a not owned object to a caller expecting an
  2487. // owned object.
  2488. static SimpleProgramPointTag
  2489. ReturnNotOwnedForOwnedTag("CFRefCount : ReturnNotOwnedForOwned");
  2490. state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
  2491. if (ExplodedNode *N =
  2492. Builder.generateNode(PostStmt(S, Pred->getLocationContext(),
  2493. &ReturnNotOwnedForOwnedTag),
  2494. state, Pred)) {
  2495. CFRefReport *report =
  2496. new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
  2497. *this, N, Sym);
  2498. BR->EmitReport(report);
  2499. }
  2500. }
  2501. }
  2502. }
  2503. const ProgramState * CFRefCount::Update(const ProgramState * state,
  2504. SymbolRef sym,
  2505. RefVal V,
  2506. ArgEffect E,
  2507. RefVal::Kind& hasErr) {
  2508. // In GC mode [... release] and [... retain] do nothing.
  2509. switch (E) {
  2510. default: break;
  2511. case IncRefMsg: E = isARCorGCEnabled() ? DoNothing : IncRef; break;
  2512. case DecRefMsg: E = isARCorGCEnabled() ? DoNothing : DecRef; break;
  2513. case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
  2514. case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
  2515. NewAutoreleasePool; break;
  2516. }
  2517. // Handle all use-after-releases.
  2518. if (!isGCEnabled() && V.getKind() == RefVal::Released) {
  2519. V = V ^ RefVal::ErrorUseAfterRelease;
  2520. hasErr = V.getKind();
  2521. return state->set<RefBindings>(sym, V);
  2522. }
  2523. switch (E) {
  2524. case DecRefMsg:
  2525. case IncRefMsg:
  2526. case MakeCollectable:
  2527. assert(false &&
  2528. "DecRefMsg/IncRefMsg/MakeCollectable already transformed");
  2529. return state;
  2530. case Dealloc:
  2531. // Any use of -dealloc in GC is *bad*.
  2532. if (isGCEnabled()) {
  2533. V = V ^ RefVal::ErrorDeallocGC;
  2534. hasErr = V.getKind();
  2535. break;
  2536. }
  2537. switch (V.getKind()) {
  2538. default:
  2539. assert(false && "Invalid case.");
  2540. case RefVal::Owned:
  2541. // The object immediately transitions to the released state.
  2542. V = V ^ RefVal::Released;
  2543. V.clearCounts();
  2544. return state->set<RefBindings>(sym, V);
  2545. case RefVal::NotOwned:
  2546. V = V ^ RefVal::ErrorDeallocNotOwned;
  2547. hasErr = V.getKind();
  2548. break;
  2549. }
  2550. break;
  2551. case NewAutoreleasePool:
  2552. assert(!isGCEnabled());
  2553. return state->add<AutoreleaseStack>(sym);
  2554. case MayEscape:
  2555. if (V.getKind() == RefVal::Owned) {
  2556. V = V ^ RefVal::NotOwned;
  2557. break;
  2558. }
  2559. // Fall-through.
  2560. case DoNothingByRef:
  2561. case DoNothing:
  2562. return state;
  2563. case Autorelease:
  2564. if (isGCEnabled())
  2565. return state;
  2566. // Update the autorelease counts.
  2567. state = SendAutorelease(state, ARCountFactory, sym);
  2568. V = V.autorelease();
  2569. break;
  2570. case StopTracking:
  2571. return state->remove<RefBindings>(sym);
  2572. case IncRef:
  2573. switch (V.getKind()) {
  2574. default:
  2575. assert(false);
  2576. case RefVal::Owned:
  2577. case RefVal::NotOwned:
  2578. V = V + 1;
  2579. break;
  2580. case RefVal::Released:
  2581. // Non-GC cases are handled above.
  2582. assert(isGCEnabled());
  2583. V = (V ^ RefVal::Owned) + 1;
  2584. break;
  2585. }
  2586. break;
  2587. case SelfOwn:
  2588. V = V ^ RefVal::NotOwned;
  2589. // Fall-through.
  2590. case DecRef:
  2591. case DecRefBridgedTransfered:
  2592. switch (V.getKind()) {
  2593. default:
  2594. // case 'RefVal::Released' handled above.
  2595. assert (false);
  2596. case RefVal::Owned:
  2597. assert(V.getCount() > 0);
  2598. if (V.getCount() == 1)
  2599. V = V ^ (E == DecRefBridgedTransfered ?
  2600. RefVal::NotOwned : RefVal::Released);
  2601. V = V - 1;
  2602. break;
  2603. case RefVal::NotOwned:
  2604. if (V.getCount() > 0)
  2605. V = V - 1;
  2606. else {
  2607. V = V ^ RefVal::ErrorReleaseNotOwned;
  2608. hasErr = V.getKind();
  2609. }
  2610. break;
  2611. case RefVal::Released:
  2612. // Non-GC cases are handled above.
  2613. assert(isGCEnabled());
  2614. V = V ^ RefVal::ErrorUseAfterRelease;
  2615. hasErr = V.getKind();
  2616. break;
  2617. }
  2618. break;
  2619. }
  2620. return state->set<RefBindings>(sym, V);
  2621. }
  2622. //===----------------------------------------------------------------------===//
  2623. // Handle dead symbols and end-of-path.
  2624. //===----------------------------------------------------------------------===//
  2625. std::pair<ExplodedNode*, const ProgramState *>
  2626. CFRefCount::HandleAutoreleaseCounts(const ProgramState *state,
  2627. GenericNodeBuilderRefCount Bd,
  2628. ExplodedNode *Pred,
  2629. ExprEngine &Eng,
  2630. SymbolRef Sym,
  2631. RefVal V,
  2632. bool &stop) {
  2633. unsigned ACnt = V.getAutoreleaseCount();
  2634. stop = false;
  2635. // No autorelease counts? Nothing to be done.
  2636. if (!ACnt)
  2637. return std::make_pair(Pred, state);
  2638. assert(!isGCEnabled() && "Autorelease counts in GC mode?");
  2639. unsigned Cnt = V.getCount();
  2640. // FIXME: Handle sending 'autorelease' to already released object.
  2641. if (V.getKind() == RefVal::ReturnedOwned)
  2642. ++Cnt;
  2643. if (ACnt <= Cnt) {
  2644. if (ACnt == Cnt) {
  2645. V.clearCounts();
  2646. if (V.getKind() == RefVal::ReturnedOwned)
  2647. V = V ^ RefVal::ReturnedNotOwned;
  2648. else
  2649. V = V ^ RefVal::NotOwned;
  2650. }
  2651. else {
  2652. V.setCount(Cnt - ACnt);
  2653. V.setAutoreleaseCount(0);
  2654. }
  2655. state = state->set<RefBindings>(Sym, V);
  2656. ExplodedNode *N = Bd.MakeNode(state, Pred);
  2657. stop = (N == 0);
  2658. return std::make_pair(N, state);
  2659. }
  2660. // Woah! More autorelease counts then retain counts left.
  2661. // Emit hard error.
  2662. stop = true;
  2663. V = V ^ RefVal::ErrorOverAutorelease;
  2664. state = state->set<RefBindings>(Sym, V);
  2665. if (ExplodedNode *N = Bd.MakeNode(state, Pred)) {
  2666. N->markAsSink();
  2667. std::string sbuf;
  2668. llvm::raw_string_ostream os(sbuf);
  2669. os << "Object over-autoreleased: object was sent -autorelease ";
  2670. if (V.getAutoreleaseCount() > 1)
  2671. os << V.getAutoreleaseCount() << " times ";
  2672. os << "but the object has a +" << V.getCount() << " retain count";
  2673. CFRefReport *report =
  2674. new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
  2675. *this, N, Sym, os.str());
  2676. BR->EmitReport(report);
  2677. }
  2678. return std::make_pair((ExplodedNode*)0, state);
  2679. }
  2680. const ProgramState *
  2681. CFRefCount::HandleSymbolDeath(const ProgramState *state,
  2682. SymbolRef sid,
  2683. RefVal V,
  2684. SmallVectorImpl<SymbolRef> &Leaked) {
  2685. bool hasLeak = V.isOwned() ||
  2686. ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
  2687. if (!hasLeak)
  2688. return state->remove<RefBindings>(sid);
  2689. Leaked.push_back(sid);
  2690. return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
  2691. }
  2692. ExplodedNode*
  2693. CFRefCount::ProcessLeaks(const ProgramState * state,
  2694. SmallVectorImpl<SymbolRef> &Leaked,
  2695. GenericNodeBuilderRefCount &Builder,
  2696. ExprEngine& Eng,
  2697. ExplodedNode *Pred) {
  2698. if (Leaked.empty())
  2699. return Pred;
  2700. // Generate an intermediate node representing the leak point.
  2701. ExplodedNode *N = Builder.MakeNode(state, Pred);
  2702. if (N) {
  2703. for (SmallVectorImpl<SymbolRef>::iterator
  2704. I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
  2705. CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
  2706. : leakAtReturn);
  2707. assert(BT && "BugType not initialized.");
  2708. CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
  2709. BR->EmitReport(report);
  2710. }
  2711. }
  2712. return N;
  2713. }
  2714. void CFRefCount::evalEndPath(ExprEngine& Eng,
  2715. EndOfFunctionNodeBuilder& Builder) {
  2716. const ProgramState *state = Builder.getState();
  2717. GenericNodeBuilderRefCount Bd(Builder);
  2718. RefBindings B = state->get<RefBindings>();
  2719. ExplodedNode *Pred = 0;
  2720. for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
  2721. bool stop = false;
  2722. llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
  2723. (*I).first,
  2724. (*I).second, stop);
  2725. if (stop)
  2726. return;
  2727. }
  2728. B = state->get<RefBindings>();
  2729. SmallVector<SymbolRef, 10> Leaked;
  2730. for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
  2731. state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
  2732. ProcessLeaks(state, Leaked, Bd, Eng, Pred);
  2733. }
  2734. const ProgramPointTag *CFRefCount::getDeadSymbolTag(SymbolRef sym) {
  2735. const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
  2736. if (!tag) {
  2737. llvm::SmallString<128> buf;
  2738. llvm::raw_svector_ostream out(buf);
  2739. out << "CFRefCount : Dead Symbol : " << sym->getSymbolID();
  2740. tag = new SimpleProgramPointTag(out.str());
  2741. }
  2742. return tag;
  2743. }
  2744. void CFRefCount::evalDeadSymbols(ExplodedNodeSet &Dst,
  2745. ExprEngine& Eng,
  2746. StmtNodeBuilder& Builder,
  2747. ExplodedNode *Pred,
  2748. const ProgramState *state,
  2749. SymbolReaper& SymReaper) {
  2750. const Stmt *S = Builder.getStmt();
  2751. RefBindings B = state->get<RefBindings>();
  2752. // Update counts from autorelease pools
  2753. for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
  2754. E = SymReaper.dead_end(); I != E; ++I) {
  2755. SymbolRef Sym = *I;
  2756. if (const RefVal* T = B.lookup(Sym)){
  2757. // Use the symbol as the tag.
  2758. // FIXME: This might not be as unique as we would like.
  2759. GenericNodeBuilderRefCount Bd(Builder, S, getDeadSymbolTag(Sym));
  2760. bool stop = false;
  2761. llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
  2762. Sym, *T, stop);
  2763. if (stop)
  2764. return;
  2765. }
  2766. }
  2767. B = state->get<RefBindings>();
  2768. SmallVector<SymbolRef, 10> Leaked;
  2769. for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
  2770. E = SymReaper.dead_end(); I != E; ++I) {
  2771. if (const RefVal* T = B.lookup(*I))
  2772. state = HandleSymbolDeath(state, *I, *T, Leaked);
  2773. }
  2774. static SimpleProgramPointTag LeakPPTag("CFRefCount : Leak");
  2775. {
  2776. GenericNodeBuilderRefCount Bd(Builder, S, &LeakPPTag);
  2777. Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
  2778. }
  2779. // Did we cache out?
  2780. if (!Pred)
  2781. return;
  2782. // Now generate a new node that nukes the old bindings.
  2783. RefBindings::Factory& F = state->get_context<RefBindings>();
  2784. for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
  2785. E = SymReaper.dead_end(); I!=E; ++I) B = F.remove(B, *I);
  2786. state = state->set<RefBindings>(B);
  2787. Builder.MakeNode(Dst, S, Pred, state);
  2788. }
  2789. void CFRefCount::ProcessNonLeakError(ExplodedNodeSet &Dst,
  2790. StmtNodeBuilder& Builder,
  2791. const Expr *NodeExpr,
  2792. SourceRange ErrorRange,
  2793. ExplodedNode *Pred,
  2794. const ProgramState *St,
  2795. RefVal::Kind hasErr, SymbolRef Sym) {
  2796. Builder.BuildSinks = true;
  2797. ExplodedNode *N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
  2798. if (!N)
  2799. return;
  2800. CFRefBug *BT = 0;
  2801. switch (hasErr) {
  2802. default:
  2803. assert(false && "Unhandled error.");
  2804. return;
  2805. case RefVal::ErrorUseAfterRelease:
  2806. BT = static_cast<CFRefBug*>(useAfterRelease);
  2807. break;
  2808. case RefVal::ErrorReleaseNotOwned:
  2809. BT = static_cast<CFRefBug*>(releaseNotOwned);
  2810. break;
  2811. case RefVal::ErrorDeallocGC:
  2812. BT = static_cast<CFRefBug*>(deallocGC);
  2813. break;
  2814. case RefVal::ErrorDeallocNotOwned:
  2815. BT = static_cast<CFRefBug*>(deallocNotOwned);
  2816. break;
  2817. }
  2818. CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
  2819. report->addRange(ErrorRange);
  2820. BR->EmitReport(report);
  2821. }
  2822. //===----------------------------------------------------------------------===//
  2823. // Pieces of the retain/release checker implemented using a CheckerVisitor.
  2824. // More pieces of the retain/release checker will be migrated to this interface
  2825. // (ideally, all of it some day).
  2826. //===----------------------------------------------------------------------===//
  2827. namespace {
  2828. class RetainReleaseChecker
  2829. : public Checker< check::Bind,
  2830. check::PostStmt<BlockExpr>,
  2831. check::PostStmt<CastExpr>,
  2832. check::RegionChanges,
  2833. eval::Assume > {
  2834. public:
  2835. bool wantsRegionUpdate;
  2836. RetainReleaseChecker() : wantsRegionUpdate(true) {}
  2837. void checkBind(SVal loc, SVal val, CheckerContext &C) const;
  2838. void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
  2839. void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
  2840. const ProgramState *evalAssume(const ProgramState *state, SVal Cond,
  2841. bool Assumption) const;
  2842. const ProgramState *checkRegionChanges(const ProgramState *state,
  2843. const StoreManager::InvalidatedSymbols *invalidated,
  2844. const MemRegion * const *begin,
  2845. const MemRegion * const *end) const;
  2846. bool wantsRegionChangeUpdate(const ProgramState *state) const {
  2847. return wantsRegionUpdate;
  2848. }
  2849. };
  2850. } // end anonymous namespace
  2851. namespace {
  2852. class StopTrackingCallback : public SymbolVisitor {
  2853. const ProgramState *state;
  2854. public:
  2855. StopTrackingCallback(const ProgramState *st) : state(st) {}
  2856. const ProgramState *getState() const { return state; }
  2857. bool VisitSymbol(SymbolRef sym) {
  2858. state = state->remove<RefBindings>(sym);
  2859. return true;
  2860. }
  2861. };
  2862. } // end anonymous namespace
  2863. void RetainReleaseChecker::checkBind(SVal loc, SVal val,
  2864. CheckerContext &C) const {
  2865. // Are we storing to something that causes the value to "escape"?
  2866. bool escapes = true;
  2867. // A value escapes in three possible cases (this may change):
  2868. //
  2869. // (1) we are binding to something that is not a memory region.
  2870. // (2) we are binding to a memregion that does not have stack storage
  2871. // (3) we are binding to a memregion with stack storage that the store
  2872. // does not understand.
  2873. const ProgramState *state = C.getState();
  2874. if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
  2875. escapes = !regionLoc->getRegion()->hasStackStorage();
  2876. if (!escapes) {
  2877. // To test (3), generate a new state with the binding added. If it is
  2878. // the same state, then it escapes (since the store cannot represent
  2879. // the binding).
  2880. escapes = (state == (state->bindLoc(*regionLoc, val)));
  2881. }
  2882. }
  2883. // If our store can represent the binding and we aren't storing to something
  2884. // that doesn't have local storage then just return and have the simulation
  2885. // state continue as is.
  2886. if (!escapes)
  2887. return;
  2888. // Otherwise, find all symbols referenced by 'val' that we are tracking
  2889. // and stop tracking them.
  2890. state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
  2891. C.addTransition(state);
  2892. }
  2893. // Assumptions.
  2894. const ProgramState *RetainReleaseChecker::evalAssume(const ProgramState *state,
  2895. SVal Cond,
  2896. bool Assumption) const {
  2897. // FIXME: We may add to the interface of evalAssume the list of symbols
  2898. // whose assumptions have changed. For now we just iterate through the
  2899. // bindings and check if any of the tracked symbols are NULL. This isn't
  2900. // too bad since the number of symbols we will track in practice are
  2901. // probably small and evalAssume is only called at branches and a few
  2902. // other places.
  2903. RefBindings B = state->get<RefBindings>();
  2904. if (B.isEmpty())
  2905. return state;
  2906. bool changed = false;
  2907. RefBindings::Factory &RefBFactory = state->get_context<RefBindings>();
  2908. for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
  2909. // Check if the symbol is null (or equal to any constant).
  2910. // If this is the case, stop tracking the symbol.
  2911. if (state->getSymVal(I.getKey())) {
  2912. changed = true;
  2913. B = RefBFactory.remove(B, I.getKey());
  2914. }
  2915. }
  2916. if (changed)
  2917. state = state->set<RefBindings>(B);
  2918. return state;
  2919. }
  2920. const ProgramState *
  2921. RetainReleaseChecker::checkRegionChanges(const ProgramState *state,
  2922. const StoreManager::InvalidatedSymbols *invalidated,
  2923. const MemRegion * const *begin,
  2924. const MemRegion * const *end) const {
  2925. if (!invalidated)
  2926. return state;
  2927. for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
  2928. E = invalidated->end(); I!=E; ++I) {
  2929. SymbolRef sym = *I;
  2930. if (WhitelistedSymbols.count(sym))
  2931. continue;
  2932. // Remove any existing reference-count binding.
  2933. state = state->remove<RefBindings>(sym);
  2934. }
  2935. return state;
  2936. }
  2937. void RetainReleaseChecker::checkPostStmt(const BlockExpr *BE,
  2938. CheckerContext &C) const {
  2939. // Scan the BlockDecRefExprs for any object the retain/release checker
  2940. // may be tracking.
  2941. if (!BE->getBlockDecl()->hasCaptures())
  2942. return;
  2943. const ProgramState *state = C.getState();
  2944. const BlockDataRegion *R =
  2945. cast<BlockDataRegion>(state->getSVal(BE).getAsRegion());
  2946. BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
  2947. E = R->referenced_vars_end();
  2948. if (I == E)
  2949. return;
  2950. // FIXME: For now we invalidate the tracking of all symbols passed to blocks
  2951. // via captured variables, even though captured variables result in a copy
  2952. // and in implicit increment/decrement of a retain count.
  2953. SmallVector<const MemRegion*, 10> Regions;
  2954. const LocationContext *LC = C.getPredecessor()->getLocationContext();
  2955. MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
  2956. for ( ; I != E; ++I) {
  2957. const VarRegion *VR = *I;
  2958. if (VR->getSuperRegion() == R) {
  2959. VR = MemMgr.getVarRegion(VR->getDecl(), LC);
  2960. }
  2961. Regions.push_back(VR);
  2962. }
  2963. state =
  2964. state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
  2965. Regions.data() + Regions.size()).getState();
  2966. C.addTransition(state);
  2967. }
  2968. void RetainReleaseChecker::checkPostStmt(const CastExpr *CE,
  2969. CheckerContext &C) const {
  2970. const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
  2971. if (!BE)
  2972. return;
  2973. ArgEffect AE = IncRef;
  2974. switch (BE->getBridgeKind()) {
  2975. case clang::OBC_Bridge:
  2976. // Do nothing.
  2977. return;
  2978. case clang::OBC_BridgeRetained:
  2979. AE = IncRef;
  2980. break;
  2981. case clang::OBC_BridgeTransfer:
  2982. AE = DecRefBridgedTransfered;
  2983. break;
  2984. }
  2985. const ProgramState *state = C.getState();
  2986. SymbolRef Sym = state->getSVal(CE).getAsLocSymbol();
  2987. if (!Sym)
  2988. return;
  2989. const RefVal* T = state->get<RefBindings>(Sym);
  2990. if (!T)
  2991. return;
  2992. // This is gross. Once the checker and CFRefCount are unified,
  2993. // this will go away.
  2994. CFRefCount &cf = static_cast<CFRefCount&>(C.getEngine().getTF());
  2995. RefVal::Kind hasErr = (RefVal::Kind) 0;
  2996. state = cf.Update(state, Sym, *T, AE, hasErr);
  2997. if (hasErr) {
  2998. return;
  2999. }
  3000. C.generateNode(state);
  3001. }
  3002. //===----------------------------------------------------------------------===//
  3003. // Transfer function creation for external clients.
  3004. //===----------------------------------------------------------------------===//
  3005. void CFRefCount::RegisterChecks(ExprEngine& Eng) {
  3006. BugReporter &BR = Eng.getBugReporter();
  3007. useAfterRelease = new UseAfterRelease(this);
  3008. BR.Register(useAfterRelease);
  3009. releaseNotOwned = new BadRelease(this);
  3010. BR.Register(releaseNotOwned);
  3011. deallocGC = new DeallocGC(this);
  3012. BR.Register(deallocGC);
  3013. deallocNotOwned = new DeallocNotOwned(this);
  3014. BR.Register(deallocNotOwned);
  3015. overAutorelease = new OverAutorelease(this);
  3016. BR.Register(overAutorelease);
  3017. returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
  3018. BR.Register(returnNotOwnedForOwned);
  3019. // First register "return" leaks.
  3020. const char* name = 0;
  3021. if (isGCEnabled())
  3022. name = "Leak of returned object when using garbage collection";
  3023. else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
  3024. name = "Leak of returned object when not using garbage collection (GC) in "
  3025. "dual GC/non-GC code";
  3026. else {
  3027. assert(getLangOptions().getGCMode() == LangOptions::NonGC);
  3028. name = "Leak of returned object";
  3029. }
  3030. // Leaks should not be reported if they are post-dominated by a sink.
  3031. leakAtReturn = new LeakAtReturn(this, name);
  3032. leakAtReturn->setSuppressOnSink(true);
  3033. BR.Register(leakAtReturn);
  3034. // Second, register leaks within a function/method.
  3035. if (isGCEnabled())
  3036. name = "Leak of object when using garbage collection";
  3037. else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
  3038. name = "Leak of object when not using garbage collection (GC) in "
  3039. "dual GC/non-GC code";
  3040. else {
  3041. assert(getLangOptions().getGCMode() == LangOptions::NonGC);
  3042. name = "Leak";
  3043. }
  3044. // Leaks should not be reported if they are post-dominated by sinks.
  3045. leakWithinFunction = new LeakWithinFunction(this, name);
  3046. leakWithinFunction->setSuppressOnSink(true);
  3047. BR.Register(leakWithinFunction);
  3048. // Save the reference to the BugReporter.
  3049. this->BR = &BR;
  3050. // Register the RetainReleaseChecker with the ExprEngine object.
  3051. // Functionality in CFRefCount will be migrated to RetainReleaseChecker
  3052. // over time.
  3053. // FIXME: HACK! Remove TransferFuncs and turn all of CFRefCount into fully
  3054. // using the checker mechanism.
  3055. Eng.getCheckerManager().registerChecker<RetainReleaseChecker>();
  3056. }
  3057. TransferFuncs* ento::MakeCFRefCountTF(ASTContext &Ctx, bool GCEnabled,
  3058. const LangOptions& lopts) {
  3059. return new CFRefCount(Ctx, GCEnabled, lopts);
  3060. }