CFRefCount.cpp 122 KB

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