RetainCountChecker.cpp 123 KB

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