CFRefCount.cpp 123 KB

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