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