RetainCountChecker.cpp 127 KB

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