RetainCountChecker.cpp 123 KB

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