RetainCountChecker.cpp 141 KB

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