RetainCountChecker.cpp 139 KB

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