clang API Documentation
00001 //==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- C++ -*--// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file defines the methods for RetainCountChecker, which implements 00011 // a reference count checker for Core Foundation and Cocoa on (Mac OS X). 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #include "ClangSACheckers.h" 00016 #include "AllocationDiagnostics.h" 00017 #include "SelectorExtras.h" 00018 #include "clang/AST/Attr.h" 00019 #include "clang/AST/DeclCXX.h" 00020 #include "clang/AST/DeclObjC.h" 00021 #include "clang/AST/ParentMap.h" 00022 #include "clang/Analysis/DomainSpecific/CocoaConventions.h" 00023 #include "clang/Basic/LangOptions.h" 00024 #include "clang/Basic/SourceManager.h" 00025 #include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h" 00026 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 00027 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" 00028 #include "clang/StaticAnalyzer/Core/Checker.h" 00029 #include "clang/StaticAnalyzer/Core/CheckerManager.h" 00030 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 00031 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 00032 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" 00033 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h" 00034 #include "llvm/ADT/DenseMap.h" 00035 #include "llvm/ADT/FoldingSet.h" 00036 #include "llvm/ADT/ImmutableList.h" 00037 #include "llvm/ADT/ImmutableMap.h" 00038 #include "llvm/ADT/STLExtras.h" 00039 #include "llvm/ADT/SmallString.h" 00040 #include "llvm/ADT/StringExtras.h" 00041 #include <cstdarg> 00042 00043 using namespace clang; 00044 using namespace ento; 00045 using namespace objc_retain; 00046 using llvm::StrInStrNoCase; 00047 00048 //===----------------------------------------------------------------------===// 00049 // Adapters for FoldingSet. 00050 //===----------------------------------------------------------------------===// 00051 00052 namespace llvm { 00053 template <> struct FoldingSetTrait<ArgEffect> { 00054 static inline void Profile(const ArgEffect X, FoldingSetNodeID &ID) { 00055 ID.AddInteger((unsigned) X); 00056 } 00057 }; 00058 template <> struct FoldingSetTrait<RetEffect> { 00059 static inline void Profile(const RetEffect &X, FoldingSetNodeID &ID) { 00060 ID.AddInteger((unsigned) X.getKind()); 00061 ID.AddInteger((unsigned) X.getObjKind()); 00062 } 00063 }; 00064 } // end llvm namespace 00065 00066 //===----------------------------------------------------------------------===// 00067 // Reference-counting logic (typestate + counts). 00068 //===----------------------------------------------------------------------===// 00069 00070 /// ArgEffects summarizes the effects of a function/method call on all of 00071 /// its arguments. 00072 typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects; 00073 00074 namespace { 00075 class RefVal { 00076 public: 00077 enum Kind { 00078 Owned = 0, // Owning reference. 00079 NotOwned, // Reference is not owned by still valid (not freed). 00080 Released, // Object has been released. 00081 ReturnedOwned, // Returned object passes ownership to caller. 00082 ReturnedNotOwned, // Return object does not pass ownership to caller. 00083 ERROR_START, 00084 ErrorDeallocNotOwned, // -dealloc called on non-owned object. 00085 ErrorDeallocGC, // Calling -dealloc with GC enabled. 00086 ErrorUseAfterRelease, // Object used after released. 00087 ErrorReleaseNotOwned, // Release of an object that was not owned. 00088 ERROR_LEAK_START, 00089 ErrorLeak, // A memory leak due to excessive reference counts. 00090 ErrorLeakReturned, // A memory leak due to the returning method not having 00091 // the correct naming conventions. 00092 ErrorGCLeakReturned, 00093 ErrorOverAutorelease, 00094 ErrorReturnedNotOwned 00095 }; 00096 00097 private: 00098 /// The number of outstanding retains. 00099 unsigned Cnt; 00100 /// The number of outstanding autoreleases. 00101 unsigned ACnt; 00102 /// The (static) type of the object at the time we started tracking it. 00103 QualType T; 00104 00105 /// The current state of the object. 00106 /// 00107 /// See the RefVal::Kind enum for possible values. 00108 unsigned RawKind : 5; 00109 00110 /// The kind of object being tracked (CF or ObjC), if known. 00111 /// 00112 /// See the RetEffect::ObjKind enum for possible values. 00113 unsigned RawObjectKind : 2; 00114 00115 /// True if the current state and/or retain count may turn out to not be the 00116 /// best possible approximation of the reference counting state. 00117 /// 00118 /// If true, the checker may decide to throw away ("override") this state 00119 /// in favor of something else when it sees the object being used in new ways. 00120 /// 00121 /// This setting should not be propagated to state derived from this state. 00122 /// Once we start deriving new states, it would be inconsistent to override 00123 /// them. 00124 unsigned IsOverridable : 1; 00125 00126 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t, 00127 bool Overridable = false) 00128 : Cnt(cnt), ACnt(acnt), T(t), RawKind(static_cast<unsigned>(k)), 00129 RawObjectKind(static_cast<unsigned>(o)), IsOverridable(Overridable) { 00130 assert(getKind() == k && "not enough bits for the kind"); 00131 assert(getObjKind() == o && "not enough bits for the object kind"); 00132 } 00133 00134 public: 00135 Kind getKind() const { return static_cast<Kind>(RawKind); } 00136 00137 RetEffect::ObjKind getObjKind() const { 00138 return static_cast<RetEffect::ObjKind>(RawObjectKind); 00139 } 00140 00141 unsigned getCount() const { return Cnt; } 00142 unsigned getAutoreleaseCount() const { return ACnt; } 00143 unsigned getCombinedCounts() const { return Cnt + ACnt; } 00144 void clearCounts() { 00145 Cnt = 0; 00146 ACnt = 0; 00147 IsOverridable = false; 00148 } 00149 void setCount(unsigned i) { 00150 Cnt = i; 00151 IsOverridable = false; 00152 } 00153 void setAutoreleaseCount(unsigned i) { 00154 ACnt = i; 00155 IsOverridable = false; 00156 } 00157 00158 QualType getType() const { return T; } 00159 00160 bool isOverridable() const { return IsOverridable; } 00161 00162 bool isOwned() const { 00163 return getKind() == Owned; 00164 } 00165 00166 bool isNotOwned() const { 00167 return getKind() == NotOwned; 00168 } 00169 00170 bool isReturnedOwned() const { 00171 return getKind() == ReturnedOwned; 00172 } 00173 00174 bool isReturnedNotOwned() const { 00175 return getKind() == ReturnedNotOwned; 00176 } 00177 00178 /// Create a state for an object whose lifetime is the responsibility of the 00179 /// current function, at least partially. 00180 /// 00181 /// Most commonly, this is an owned object with a retain count of +1. 00182 static RefVal makeOwned(RetEffect::ObjKind o, QualType t, 00183 unsigned Count = 1) { 00184 return RefVal(Owned, o, Count, 0, t); 00185 } 00186 00187 /// Create a state for an object whose lifetime is not the responsibility of 00188 /// the current function. 00189 /// 00190 /// Most commonly, this is an unowned object with a retain count of +0. 00191 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t, 00192 unsigned Count = 0) { 00193 return RefVal(NotOwned, o, Count, 0, t); 00194 } 00195 00196 /// Create an "overridable" state for an unowned object at +0. 00197 /// 00198 /// An overridable state is one that provides a good approximation of the 00199 /// reference counting state now, but which may be discarded later if the 00200 /// checker sees the object being used in new ways. 00201 static RefVal makeOverridableNotOwned(RetEffect::ObjKind o, QualType t) { 00202 return RefVal(NotOwned, o, 0, 0, t, /*Overridable=*/true); 00203 } 00204 00205 RefVal operator-(size_t i) const { 00206 return RefVal(getKind(), getObjKind(), getCount() - i, 00207 getAutoreleaseCount(), getType()); 00208 } 00209 00210 RefVal operator+(size_t i) const { 00211 return RefVal(getKind(), getObjKind(), getCount() + i, 00212 getAutoreleaseCount(), getType()); 00213 } 00214 00215 RefVal operator^(Kind k) const { 00216 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(), 00217 getType()); 00218 } 00219 00220 RefVal autorelease() const { 00221 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1, 00222 getType()); 00223 } 00224 00225 // Comparison, profiling, and pretty-printing. 00226 00227 bool hasSameState(const RefVal &X) const { 00228 return getKind() == X.getKind() && Cnt == X.Cnt && ACnt == X.ACnt; 00229 } 00230 00231 bool operator==(const RefVal& X) const { 00232 return T == X.T && hasSameState(X) && getObjKind() == X.getObjKind() && 00233 IsOverridable == X.IsOverridable; 00234 } 00235 00236 void Profile(llvm::FoldingSetNodeID& ID) const { 00237 ID.Add(T); 00238 ID.AddInteger(RawKind); 00239 ID.AddInteger(Cnt); 00240 ID.AddInteger(ACnt); 00241 ID.AddInteger(RawObjectKind); 00242 ID.AddBoolean(IsOverridable); 00243 } 00244 00245 void print(raw_ostream &Out) const; 00246 }; 00247 00248 void RefVal::print(raw_ostream &Out) const { 00249 if (!T.isNull()) 00250 Out << "Tracked " << T.getAsString() << '/'; 00251 00252 if (isOverridable()) 00253 Out << "(overridable) "; 00254 00255 switch (getKind()) { 00256 default: llvm_unreachable("Invalid RefVal kind"); 00257 case Owned: { 00258 Out << "Owned"; 00259 unsigned cnt = getCount(); 00260 if (cnt) Out << " (+ " << cnt << ")"; 00261 break; 00262 } 00263 00264 case NotOwned: { 00265 Out << "NotOwned"; 00266 unsigned cnt = getCount(); 00267 if (cnt) Out << " (+ " << cnt << ")"; 00268 break; 00269 } 00270 00271 case ReturnedOwned: { 00272 Out << "ReturnedOwned"; 00273 unsigned cnt = getCount(); 00274 if (cnt) Out << " (+ " << cnt << ")"; 00275 break; 00276 } 00277 00278 case ReturnedNotOwned: { 00279 Out << "ReturnedNotOwned"; 00280 unsigned cnt = getCount(); 00281 if (cnt) Out << " (+ " << cnt << ")"; 00282 break; 00283 } 00284 00285 case Released: 00286 Out << "Released"; 00287 break; 00288 00289 case ErrorDeallocGC: 00290 Out << "-dealloc (GC)"; 00291 break; 00292 00293 case ErrorDeallocNotOwned: 00294 Out << "-dealloc (not-owned)"; 00295 break; 00296 00297 case ErrorLeak: 00298 Out << "Leaked"; 00299 break; 00300 00301 case ErrorLeakReturned: 00302 Out << "Leaked (Bad naming)"; 00303 break; 00304 00305 case ErrorGCLeakReturned: 00306 Out << "Leaked (GC-ed at return)"; 00307 break; 00308 00309 case ErrorUseAfterRelease: 00310 Out << "Use-After-Release [ERROR]"; 00311 break; 00312 00313 case ErrorReleaseNotOwned: 00314 Out << "Release of Not-Owned [ERROR]"; 00315 break; 00316 00317 case RefVal::ErrorOverAutorelease: 00318 Out << "Over-autoreleased"; 00319 break; 00320 00321 case RefVal::ErrorReturnedNotOwned: 00322 Out << "Non-owned object returned instead of owned"; 00323 break; 00324 } 00325 00326 if (ACnt) { 00327 Out << " [ARC +" << ACnt << ']'; 00328 } 00329 } 00330 } //end anonymous namespace 00331 00332 //===----------------------------------------------------------------------===// 00333 // RefBindings - State used to track object reference counts. 00334 //===----------------------------------------------------------------------===// 00335 00336 REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal) 00337 00338 static inline const RefVal *getRefBinding(ProgramStateRef State, 00339 SymbolRef Sym) { 00340 return State->get<RefBindings>(Sym); 00341 } 00342 00343 static inline ProgramStateRef setRefBinding(ProgramStateRef State, 00344 SymbolRef Sym, RefVal Val) { 00345 return State->set<RefBindings>(Sym, Val); 00346 } 00347 00348 static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) { 00349 return State->remove<RefBindings>(Sym); 00350 } 00351 00352 //===----------------------------------------------------------------------===// 00353 // Function/Method behavior summaries. 00354 //===----------------------------------------------------------------------===// 00355 00356 namespace { 00357 class RetainSummary { 00358 /// Args - a map of (index, ArgEffect) pairs, where index 00359 /// specifies the argument (starting from 0). This can be sparsely 00360 /// populated; arguments with no entry in Args use 'DefaultArgEffect'. 00361 ArgEffects Args; 00362 00363 /// DefaultArgEffect - The default ArgEffect to apply to arguments that 00364 /// do not have an entry in Args. 00365 ArgEffect DefaultArgEffect; 00366 00367 /// Receiver - If this summary applies to an Objective-C message expression, 00368 /// this is the effect applied to the state of the receiver. 00369 ArgEffect Receiver; 00370 00371 /// Ret - The effect on the return value. Used to indicate if the 00372 /// function/method call returns a new tracked symbol. 00373 RetEffect Ret; 00374 00375 public: 00376 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff, 00377 ArgEffect ReceiverEff) 00378 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {} 00379 00380 /// getArg - Return the argument effect on the argument specified by 00381 /// idx (starting from 0). 00382 ArgEffect getArg(unsigned idx) const { 00383 if (const ArgEffect *AE = Args.lookup(idx)) 00384 return *AE; 00385 00386 return DefaultArgEffect; 00387 } 00388 00389 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) { 00390 Args = af.add(Args, idx, e); 00391 } 00392 00393 /// setDefaultArgEffect - Set the default argument effect. 00394 void setDefaultArgEffect(ArgEffect E) { 00395 DefaultArgEffect = E; 00396 } 00397 00398 /// getRetEffect - Returns the effect on the return value of the call. 00399 RetEffect getRetEffect() const { return Ret; } 00400 00401 /// setRetEffect - Set the effect of the return value of the call. 00402 void setRetEffect(RetEffect E) { Ret = E; } 00403 00404 00405 /// Sets the effect on the receiver of the message. 00406 void setReceiverEffect(ArgEffect e) { Receiver = e; } 00407 00408 /// getReceiverEffect - Returns the effect on the receiver of the call. 00409 /// This is only meaningful if the summary applies to an ObjCMessageExpr*. 00410 ArgEffect getReceiverEffect() const { return Receiver; } 00411 00412 /// Test if two retain summaries are identical. Note that merely equivalent 00413 /// summaries are not necessarily identical (for example, if an explicit 00414 /// argument effect matches the default effect). 00415 bool operator==(const RetainSummary &Other) const { 00416 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect && 00417 Receiver == Other.Receiver && Ret == Other.Ret; 00418 } 00419 00420 /// Profile this summary for inclusion in a FoldingSet. 00421 void Profile(llvm::FoldingSetNodeID& ID) const { 00422 ID.Add(Args); 00423 ID.Add(DefaultArgEffect); 00424 ID.Add(Receiver); 00425 ID.Add(Ret); 00426 } 00427 00428 /// A retain summary is simple if it has no ArgEffects other than the default. 00429 bool isSimple() const { 00430 return Args.isEmpty(); 00431 } 00432 00433 private: 00434 ArgEffects getArgEffects() const { return Args; } 00435 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; } 00436 00437 friend class RetainSummaryManager; 00438 }; 00439 } // end anonymous namespace 00440 00441 //===----------------------------------------------------------------------===// 00442 // Data structures for constructing summaries. 00443 //===----------------------------------------------------------------------===// 00444 00445 namespace { 00446 class ObjCSummaryKey { 00447 IdentifierInfo* II; 00448 Selector S; 00449 public: 00450 ObjCSummaryKey(IdentifierInfo* ii, Selector s) 00451 : II(ii), S(s) {} 00452 00453 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s) 00454 : II(d ? d->getIdentifier() : nullptr), S(s) {} 00455 00456 ObjCSummaryKey(Selector s) 00457 : II(nullptr), S(s) {} 00458 00459 IdentifierInfo *getIdentifier() const { return II; } 00460 Selector getSelector() const { return S; } 00461 }; 00462 } 00463 00464 namespace llvm { 00465 template <> struct DenseMapInfo<ObjCSummaryKey> { 00466 static inline ObjCSummaryKey getEmptyKey() { 00467 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(), 00468 DenseMapInfo<Selector>::getEmptyKey()); 00469 } 00470 00471 static inline ObjCSummaryKey getTombstoneKey() { 00472 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(), 00473 DenseMapInfo<Selector>::getTombstoneKey()); 00474 } 00475 00476 static unsigned getHashValue(const ObjCSummaryKey &V) { 00477 typedef std::pair<IdentifierInfo*, Selector> PairTy; 00478 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(), 00479 V.getSelector())); 00480 } 00481 00482 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) { 00483 return LHS.getIdentifier() == RHS.getIdentifier() && 00484 LHS.getSelector() == RHS.getSelector(); 00485 } 00486 00487 }; 00488 } // end llvm namespace 00489 00490 namespace { 00491 class ObjCSummaryCache { 00492 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy; 00493 MapTy M; 00494 public: 00495 ObjCSummaryCache() {} 00496 00497 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) { 00498 // Do a lookup with the (D,S) pair. If we find a match return 00499 // the iterator. 00500 ObjCSummaryKey K(D, S); 00501 MapTy::iterator I = M.find(K); 00502 00503 if (I != M.end()) 00504 return I->second; 00505 if (!D) 00506 return nullptr; 00507 00508 // Walk the super chain. If we find a hit with a parent, we'll end 00509 // up returning that summary. We actually allow that key (null,S), as 00510 // we cache summaries for the null ObjCInterfaceDecl* to allow us to 00511 // generate initial summaries without having to worry about NSObject 00512 // being declared. 00513 // FIXME: We may change this at some point. 00514 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) { 00515 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end()) 00516 break; 00517 00518 if (!C) 00519 return nullptr; 00520 } 00521 00522 // Cache the summary with original key to make the next lookup faster 00523 // and return the iterator. 00524 const RetainSummary *Summ = I->second; 00525 M[K] = Summ; 00526 return Summ; 00527 } 00528 00529 const RetainSummary *find(IdentifierInfo* II, Selector S) { 00530 // FIXME: Class method lookup. Right now we dont' have a good way 00531 // of going between IdentifierInfo* and the class hierarchy. 00532 MapTy::iterator I = M.find(ObjCSummaryKey(II, S)); 00533 00534 if (I == M.end()) 00535 I = M.find(ObjCSummaryKey(S)); 00536 00537 return I == M.end() ? nullptr : I->second; 00538 } 00539 00540 const RetainSummary *& operator[](ObjCSummaryKey K) { 00541 return M[K]; 00542 } 00543 00544 const RetainSummary *& operator[](Selector S) { 00545 return M[ ObjCSummaryKey(S) ]; 00546 } 00547 }; 00548 } // end anonymous namespace 00549 00550 //===----------------------------------------------------------------------===// 00551 // Data structures for managing collections of summaries. 00552 //===----------------------------------------------------------------------===// 00553 00554 namespace { 00555 class RetainSummaryManager { 00556 00557 //==-----------------------------------------------------------------==// 00558 // Typedefs. 00559 //==-----------------------------------------------------------------==// 00560 00561 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *> 00562 FuncSummariesTy; 00563 00564 typedef ObjCSummaryCache ObjCMethodSummariesTy; 00565 00566 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode; 00567 00568 //==-----------------------------------------------------------------==// 00569 // Data. 00570 //==-----------------------------------------------------------------==// 00571 00572 /// Ctx - The ASTContext object for the analyzed ASTs. 00573 ASTContext &Ctx; 00574 00575 /// GCEnabled - Records whether or not the analyzed code runs in GC mode. 00576 const bool GCEnabled; 00577 00578 /// Records whether or not the analyzed code runs in ARC mode. 00579 const bool ARCEnabled; 00580 00581 /// FuncSummaries - A map from FunctionDecls to summaries. 00582 FuncSummariesTy FuncSummaries; 00583 00584 /// ObjCClassMethodSummaries - A map from selectors (for instance methods) 00585 /// to summaries. 00586 ObjCMethodSummariesTy ObjCClassMethodSummaries; 00587 00588 /// ObjCMethodSummaries - A map from selectors to summaries. 00589 ObjCMethodSummariesTy ObjCMethodSummaries; 00590 00591 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects, 00592 /// and all other data used by the checker. 00593 llvm::BumpPtrAllocator BPAlloc; 00594 00595 /// AF - A factory for ArgEffects objects. 00596 ArgEffects::Factory AF; 00597 00598 /// ScratchArgs - A holding buffer for construct ArgEffects. 00599 ArgEffects ScratchArgs; 00600 00601 /// ObjCAllocRetE - Default return effect for methods returning Objective-C 00602 /// objects. 00603 RetEffect ObjCAllocRetE; 00604 00605 /// ObjCInitRetE - Default return effect for init methods returning 00606 /// Objective-C objects. 00607 RetEffect ObjCInitRetE; 00608 00609 /// SimpleSummaries - Used for uniquing summaries that don't have special 00610 /// effects. 00611 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries; 00612 00613 //==-----------------------------------------------------------------==// 00614 // Methods. 00615 //==-----------------------------------------------------------------==// 00616 00617 /// getArgEffects - Returns a persistent ArgEffects object based on the 00618 /// data in ScratchArgs. 00619 ArgEffects getArgEffects(); 00620 00621 enum UnaryFuncKind { cfretain, cfrelease, cfautorelease, cfmakecollectable }; 00622 00623 const RetainSummary *getUnarySummary(const FunctionType* FT, 00624 UnaryFuncKind func); 00625 00626 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD); 00627 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD); 00628 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD); 00629 00630 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm); 00631 00632 const RetainSummary *getPersistentSummary(RetEffect RetEff, 00633 ArgEffect ReceiverEff = DoNothing, 00634 ArgEffect DefaultEff = MayEscape) { 00635 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff); 00636 return getPersistentSummary(Summ); 00637 } 00638 00639 const RetainSummary *getDoNothingSummary() { 00640 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); 00641 } 00642 00643 const RetainSummary *getDefaultSummary() { 00644 return getPersistentSummary(RetEffect::MakeNoRet(), 00645 DoNothing, MayEscape); 00646 } 00647 00648 const RetainSummary *getPersistentStopSummary() { 00649 return getPersistentSummary(RetEffect::MakeNoRet(), 00650 StopTracking, StopTracking); 00651 } 00652 00653 void InitializeClassMethodSummaries(); 00654 void InitializeMethodSummaries(); 00655 private: 00656 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) { 00657 ObjCClassMethodSummaries[S] = Summ; 00658 } 00659 00660 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) { 00661 ObjCMethodSummaries[S] = Summ; 00662 } 00663 00664 void addClassMethSummary(const char* Cls, const char* name, 00665 const RetainSummary *Summ, bool isNullary = true) { 00666 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls); 00667 Selector S = isNullary ? GetNullarySelector(name, Ctx) 00668 : GetUnarySelector(name, Ctx); 00669 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ; 00670 } 00671 00672 void addInstMethSummary(const char* Cls, const char* nullaryName, 00673 const RetainSummary *Summ) { 00674 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls); 00675 Selector S = GetNullarySelector(nullaryName, Ctx); 00676 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ; 00677 } 00678 00679 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy &Summaries, 00680 const RetainSummary *Summ, va_list argp) { 00681 Selector S = getKeywordSelector(Ctx, argp); 00682 Summaries[ObjCSummaryKey(ClsII, S)] = Summ; 00683 } 00684 00685 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) { 00686 va_list argp; 00687 va_start(argp, Summ); 00688 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp); 00689 va_end(argp); 00690 } 00691 00692 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) { 00693 va_list argp; 00694 va_start(argp, Summ); 00695 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp); 00696 va_end(argp); 00697 } 00698 00699 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) { 00700 va_list argp; 00701 va_start(argp, Summ); 00702 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp); 00703 va_end(argp); 00704 } 00705 00706 public: 00707 00708 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC) 00709 : Ctx(ctx), 00710 GCEnabled(gcenabled), 00711 ARCEnabled(usesARC), 00712 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()), 00713 ObjCAllocRetE(gcenabled 00714 ? RetEffect::MakeGCNotOwned() 00715 : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC) 00716 : RetEffect::MakeOwned(RetEffect::ObjC, true))), 00717 ObjCInitRetE(gcenabled 00718 ? RetEffect::MakeGCNotOwned() 00719 : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC) 00720 : RetEffect::MakeOwnedWhenTrackedReceiver())) { 00721 InitializeClassMethodSummaries(); 00722 InitializeMethodSummaries(); 00723 } 00724 00725 const RetainSummary *getSummary(const CallEvent &Call, 00726 ProgramStateRef State = nullptr); 00727 00728 const RetainSummary *getFunctionSummary(const FunctionDecl *FD); 00729 00730 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID, 00731 const ObjCMethodDecl *MD, 00732 QualType RetTy, 00733 ObjCMethodSummariesTy &CachedSummaries); 00734 00735 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M, 00736 ProgramStateRef State); 00737 00738 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) { 00739 assert(!M.isInstanceMessage()); 00740 const ObjCInterfaceDecl *Class = M.getReceiverInterface(); 00741 00742 return getMethodSummary(M.getSelector(), Class, M.getDecl(), 00743 M.getResultType(), ObjCClassMethodSummaries); 00744 } 00745 00746 /// getMethodSummary - This version of getMethodSummary is used to query 00747 /// the summary for the current method being analyzed. 00748 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) { 00749 const ObjCInterfaceDecl *ID = MD->getClassInterface(); 00750 Selector S = MD->getSelector(); 00751 QualType ResultTy = MD->getReturnType(); 00752 00753 ObjCMethodSummariesTy *CachedSummaries; 00754 if (MD->isInstanceMethod()) 00755 CachedSummaries = &ObjCMethodSummaries; 00756 else 00757 CachedSummaries = &ObjCClassMethodSummaries; 00758 00759 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries); 00760 } 00761 00762 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD, 00763 Selector S, QualType RetTy); 00764 00765 /// Determine if there is a special return effect for this function or method. 00766 Optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy, 00767 const Decl *D); 00768 00769 void updateSummaryFromAnnotations(const RetainSummary *&Summ, 00770 const ObjCMethodDecl *MD); 00771 00772 void updateSummaryFromAnnotations(const RetainSummary *&Summ, 00773 const FunctionDecl *FD); 00774 00775 void updateSummaryForCall(const RetainSummary *&Summ, 00776 const CallEvent &Call); 00777 00778 bool isGCEnabled() const { return GCEnabled; } 00779 00780 bool isARCEnabled() const { return ARCEnabled; } 00781 00782 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; } 00783 00784 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; } 00785 00786 friend class RetainSummaryTemplate; 00787 }; 00788 00789 // Used to avoid allocating long-term (BPAlloc'd) memory for default retain 00790 // summaries. If a function or method looks like it has a default summary, but 00791 // it has annotations, the annotations are added to the stack-based template 00792 // and then copied into managed memory. 00793 class RetainSummaryTemplate { 00794 RetainSummaryManager &Manager; 00795 const RetainSummary *&RealSummary; 00796 RetainSummary ScratchSummary; 00797 bool Accessed; 00798 public: 00799 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr) 00800 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {} 00801 00802 ~RetainSummaryTemplate() { 00803 if (Accessed) 00804 RealSummary = Manager.getPersistentSummary(ScratchSummary); 00805 } 00806 00807 RetainSummary &operator*() { 00808 Accessed = true; 00809 return ScratchSummary; 00810 } 00811 00812 RetainSummary *operator->() { 00813 Accessed = true; 00814 return &ScratchSummary; 00815 } 00816 }; 00817 00818 } // end anonymous namespace 00819 00820 //===----------------------------------------------------------------------===// 00821 // Implementation of checker data structures. 00822 //===----------------------------------------------------------------------===// 00823 00824 ArgEffects RetainSummaryManager::getArgEffects() { 00825 ArgEffects AE = ScratchArgs; 00826 ScratchArgs = AF.getEmptyMap(); 00827 return AE; 00828 } 00829 00830 const RetainSummary * 00831 RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) { 00832 // Unique "simple" summaries -- those without ArgEffects. 00833 if (OldSumm.isSimple()) { 00834 llvm::FoldingSetNodeID ID; 00835 OldSumm.Profile(ID); 00836 00837 void *Pos; 00838 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos); 00839 00840 if (!N) { 00841 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>(); 00842 new (N) CachedSummaryNode(OldSumm); 00843 SimpleSummaries.InsertNode(N, Pos); 00844 } 00845 00846 return &N->getValue(); 00847 } 00848 00849 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>(); 00850 new (Summ) RetainSummary(OldSumm); 00851 return Summ; 00852 } 00853 00854 //===----------------------------------------------------------------------===// 00855 // Summary creation for functions (largely uses of Core Foundation). 00856 //===----------------------------------------------------------------------===// 00857 00858 static bool isRetain(const FunctionDecl *FD, StringRef FName) { 00859 return FName.endswith("Retain"); 00860 } 00861 00862 static bool isRelease(const FunctionDecl *FD, StringRef FName) { 00863 return FName.endswith("Release"); 00864 } 00865 00866 static bool isAutorelease(const FunctionDecl *FD, StringRef FName) { 00867 return FName.endswith("Autorelease"); 00868 } 00869 00870 static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) { 00871 // FIXME: Remove FunctionDecl parameter. 00872 // FIXME: Is it really okay if MakeCollectable isn't a suffix? 00873 return FName.find("MakeCollectable") != StringRef::npos; 00874 } 00875 00876 static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) { 00877 switch (E) { 00878 case DoNothing: 00879 case Autorelease: 00880 case DecRefBridgedTransferred: 00881 case IncRef: 00882 case IncRefMsg: 00883 case MakeCollectable: 00884 case MayEscape: 00885 case StopTracking: 00886 case StopTrackingHard: 00887 return StopTrackingHard; 00888 case DecRef: 00889 case DecRefAndStopTrackingHard: 00890 return DecRefAndStopTrackingHard; 00891 case DecRefMsg: 00892 case DecRefMsgAndStopTrackingHard: 00893 return DecRefMsgAndStopTrackingHard; 00894 case Dealloc: 00895 return Dealloc; 00896 } 00897 00898 llvm_unreachable("Unknown ArgEffect kind"); 00899 } 00900 00901 void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S, 00902 const CallEvent &Call) { 00903 if (Call.hasNonZeroCallbackArg()) { 00904 ArgEffect RecEffect = 00905 getStopTrackingHardEquivalent(S->getReceiverEffect()); 00906 ArgEffect DefEffect = 00907 getStopTrackingHardEquivalent(S->getDefaultArgEffect()); 00908 00909 ArgEffects CustomArgEffects = S->getArgEffects(); 00910 for (ArgEffects::iterator I = CustomArgEffects.begin(), 00911 E = CustomArgEffects.end(); 00912 I != E; ++I) { 00913 ArgEffect Translated = getStopTrackingHardEquivalent(I->second); 00914 if (Translated != DefEffect) 00915 ScratchArgs = AF.add(ScratchArgs, I->first, Translated); 00916 } 00917 00918 RetEffect RE = RetEffect::MakeNoRetHard(); 00919 00920 // Special cases where the callback argument CANNOT free the return value. 00921 // This can generally only happen if we know that the callback will only be 00922 // called when the return value is already being deallocated. 00923 if (const SimpleFunctionCall *FC = dyn_cast<SimpleFunctionCall>(&Call)) { 00924 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) { 00925 // When the CGBitmapContext is deallocated, the callback here will free 00926 // the associated data buffer. 00927 if (Name->isStr("CGBitmapContextCreateWithData")) 00928 RE = S->getRetEffect(); 00929 } 00930 } 00931 00932 S = getPersistentSummary(RE, RecEffect, DefEffect); 00933 } 00934 00935 // Special case '[super init];' and '[self init];' 00936 // 00937 // Even though calling '[super init]' without assigning the result to self 00938 // and checking if the parent returns 'nil' is a bad pattern, it is common. 00939 // Additionally, our Self Init checker already warns about it. To avoid 00940 // overwhelming the user with messages from both checkers, we model the case 00941 // of '[super init]' in cases when it is not consumed by another expression 00942 // as if the call preserves the value of 'self'; essentially, assuming it can 00943 // never fail and return 'nil'. 00944 // Note, we don't want to just stop tracking the value since we want the 00945 // RetainCount checker to report leaks and use-after-free if SelfInit checker 00946 // is turned off. 00947 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) { 00948 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) { 00949 00950 // Check if the message is not consumed, we know it will not be used in 00951 // an assignment, ex: "self = [super init]". 00952 const Expr *ME = MC->getOriginExpr(); 00953 const LocationContext *LCtx = MC->getLocationContext(); 00954 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap(); 00955 if (!PM.isConsumedExpr(ME)) { 00956 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this); 00957 ModifiableSummaryTemplate->setReceiverEffect(DoNothing); 00958 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet()); 00959 } 00960 } 00961 00962 } 00963 } 00964 00965 const RetainSummary * 00966 RetainSummaryManager::getSummary(const CallEvent &Call, 00967 ProgramStateRef State) { 00968 const RetainSummary *Summ; 00969 switch (Call.getKind()) { 00970 case CE_Function: 00971 Summ = getFunctionSummary(cast<SimpleFunctionCall>(Call).getDecl()); 00972 break; 00973 case CE_CXXMember: 00974 case CE_CXXMemberOperator: 00975 case CE_Block: 00976 case CE_CXXConstructor: 00977 case CE_CXXDestructor: 00978 case CE_CXXAllocator: 00979 // FIXME: These calls are currently unsupported. 00980 return getPersistentStopSummary(); 00981 case CE_ObjCMessage: { 00982 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call); 00983 if (Msg.isInstanceMessage()) 00984 Summ = getInstanceMethodSummary(Msg, State); 00985 else 00986 Summ = getClassMethodSummary(Msg); 00987 break; 00988 } 00989 } 00990 00991 updateSummaryForCall(Summ, Call); 00992 00993 assert(Summ && "Unknown call type?"); 00994 return Summ; 00995 } 00996 00997 const RetainSummary * 00998 RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) { 00999 // If we don't know what function we're calling, use our default summary. 01000 if (!FD) 01001 return getDefaultSummary(); 01002 01003 // Look up a summary in our cache of FunctionDecls -> Summaries. 01004 FuncSummariesTy::iterator I = FuncSummaries.find(FD); 01005 if (I != FuncSummaries.end()) 01006 return I->second; 01007 01008 // No summary? Generate one. 01009 const RetainSummary *S = nullptr; 01010 bool AllowAnnotations = true; 01011 01012 do { 01013 // We generate "stop" summaries for implicitly defined functions. 01014 if (FD->isImplicit()) { 01015 S = getPersistentStopSummary(); 01016 break; 01017 } 01018 01019 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the 01020 // function's type. 01021 const FunctionType* FT = FD->getType()->getAs<FunctionType>(); 01022 const IdentifierInfo *II = FD->getIdentifier(); 01023 if (!II) 01024 break; 01025 01026 StringRef FName = II->getName(); 01027 01028 // Strip away preceding '_'. Doing this here will effect all the checks 01029 // down below. 01030 FName = FName.substr(FName.find_first_not_of('_')); 01031 01032 // Inspect the result type. 01033 QualType RetTy = FT->getReturnType(); 01034 01035 // FIXME: This should all be refactored into a chain of "summary lookup" 01036 // filters. 01037 assert(ScratchArgs.isEmpty()); 01038 01039 if (FName == "pthread_create" || FName == "pthread_setspecific") { 01040 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>. 01041 // This will be addressed better with IPA. 01042 S = getPersistentStopSummary(); 01043 } else if (FName == "NSMakeCollectable") { 01044 // Handle: id NSMakeCollectable(CFTypeRef) 01045 S = (RetTy->isObjCIdType()) 01046 ? getUnarySummary(FT, cfmakecollectable) 01047 : getPersistentStopSummary(); 01048 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained, 01049 // but we can fully model NSMakeCollectable ourselves. 01050 AllowAnnotations = false; 01051 } else if (FName == "CFPlugInInstanceCreate") { 01052 S = getPersistentSummary(RetEffect::MakeNoRet()); 01053 } else if (FName == "IOBSDNameMatching" || 01054 FName == "IOServiceMatching" || 01055 FName == "IOServiceNameMatching" || 01056 FName == "IORegistryEntrySearchCFProperty" || 01057 FName == "IORegistryEntryIDMatching" || 01058 FName == "IOOpenFirmwarePathMatching") { 01059 // Part of <rdar://problem/6961230>. (IOKit) 01060 // This should be addressed using a API table. 01061 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true), 01062 DoNothing, DoNothing); 01063 } else if (FName == "IOServiceGetMatchingService" || 01064 FName == "IOServiceGetMatchingServices") { 01065 // FIXES: <rdar://problem/6326900> 01066 // This should be addressed using a API table. This strcmp is also 01067 // a little gross, but there is no need to super optimize here. 01068 ScratchArgs = AF.add(ScratchArgs, 1, DecRef); 01069 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); 01070 } else if (FName == "IOServiceAddNotification" || 01071 FName == "IOServiceAddMatchingNotification") { 01072 // Part of <rdar://problem/6961230>. (IOKit) 01073 // This should be addressed using a API table. 01074 ScratchArgs = AF.add(ScratchArgs, 2, DecRef); 01075 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); 01076 } else if (FName == "CVPixelBufferCreateWithBytes") { 01077 // FIXES: <rdar://problem/7283567> 01078 // Eventually this can be improved by recognizing that the pixel 01079 // buffer passed to CVPixelBufferCreateWithBytes is released via 01080 // a callback and doing full IPA to make sure this is done correctly. 01081 // FIXME: This function has an out parameter that returns an 01082 // allocated object. 01083 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking); 01084 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); 01085 } else if (FName == "CGBitmapContextCreateWithData") { 01086 // FIXES: <rdar://problem/7358899> 01087 // Eventually this can be improved by recognizing that 'releaseInfo' 01088 // passed to CGBitmapContextCreateWithData is released via 01089 // a callback and doing full IPA to make sure this is done correctly. 01090 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking); 01091 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true), 01092 DoNothing, DoNothing); 01093 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") { 01094 // FIXES: <rdar://problem/7283567> 01095 // Eventually this can be improved by recognizing that the pixel 01096 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released 01097 // via a callback and doing full IPA to make sure this is done 01098 // correctly. 01099 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking); 01100 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); 01101 } else if (FName == "dispatch_set_context" || 01102 FName == "xpc_connection_set_context") { 01103 // <rdar://problem/11059275> - The analyzer currently doesn't have 01104 // a good way to reason about the finalizer function for libdispatch. 01105 // If we pass a context object that is memory managed, stop tracking it. 01106 // <rdar://problem/13783514> - Same problem, but for XPC. 01107 // FIXME: this hack should possibly go away once we can handle 01108 // libdispatch and XPC finalizers. 01109 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking); 01110 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); 01111 } else if (FName.startswith("NSLog")) { 01112 S = getDoNothingSummary(); 01113 } else if (FName.startswith("NS") && 01114 (FName.find("Insert") != StringRef::npos)) { 01115 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can 01116 // be deallocated by NSMapRemove. (radar://11152419) 01117 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking); 01118 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking); 01119 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); 01120 } 01121 01122 // Did we get a summary? 01123 if (S) 01124 break; 01125 01126 if (RetTy->isPointerType()) { 01127 // For CoreFoundation ('CF') types. 01128 if (cocoa::isRefType(RetTy, "CF", FName)) { 01129 if (isRetain(FD, FName)) { 01130 S = getUnarySummary(FT, cfretain); 01131 } else if (isAutorelease(FD, FName)) { 01132 S = getUnarySummary(FT, cfautorelease); 01133 // The headers use cf_consumed, but we can fully model CFAutorelease 01134 // ourselves. 01135 AllowAnnotations = false; 01136 } else if (isMakeCollectable(FD, FName)) { 01137 S = getUnarySummary(FT, cfmakecollectable); 01138 AllowAnnotations = false; 01139 } else { 01140 S = getCFCreateGetRuleSummary(FD); 01141 } 01142 01143 break; 01144 } 01145 01146 // For CoreGraphics ('CG') types. 01147 if (cocoa::isRefType(RetTy, "CG", FName)) { 01148 if (isRetain(FD, FName)) 01149 S = getUnarySummary(FT, cfretain); 01150 else 01151 S = getCFCreateGetRuleSummary(FD); 01152 01153 break; 01154 } 01155 01156 // For the Disk Arbitration API (DiskArbitration/DADisk.h) 01157 if (cocoa::isRefType(RetTy, "DADisk") || 01158 cocoa::isRefType(RetTy, "DADissenter") || 01159 cocoa::isRefType(RetTy, "DASessionRef")) { 01160 S = getCFCreateGetRuleSummary(FD); 01161 break; 01162 } 01163 01164 if (FD->hasAttr<CFAuditedTransferAttr>()) { 01165 S = getCFCreateGetRuleSummary(FD); 01166 break; 01167 } 01168 01169 break; 01170 } 01171 01172 // Check for release functions, the only kind of functions that we care 01173 // about that don't return a pointer type. 01174 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) { 01175 // Test for 'CGCF'. 01176 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2); 01177 01178 if (isRelease(FD, FName)) 01179 S = getUnarySummary(FT, cfrelease); 01180 else { 01181 assert (ScratchArgs.isEmpty()); 01182 // Remaining CoreFoundation and CoreGraphics functions. 01183 // We use to assume that they all strictly followed the ownership idiom 01184 // and that ownership cannot be transferred. While this is technically 01185 // correct, many methods allow a tracked object to escape. For example: 01186 // 01187 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...); 01188 // CFDictionaryAddValue(y, key, x); 01189 // CFRelease(x); 01190 // ... it is okay to use 'x' since 'y' has a reference to it 01191 // 01192 // We handle this and similar cases with the follow heuristic. If the 01193 // function name contains "InsertValue", "SetValue", "AddValue", 01194 // "AppendValue", or "SetAttribute", then we assume that arguments may 01195 // "escape." This means that something else holds on to the object, 01196 // allowing it be used even after its local retain count drops to 0. 01197 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos|| 01198 StrInStrNoCase(FName, "AddValue") != StringRef::npos || 01199 StrInStrNoCase(FName, "SetValue") != StringRef::npos || 01200 StrInStrNoCase(FName, "AppendValue") != StringRef::npos|| 01201 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos) 01202 ? MayEscape : DoNothing; 01203 01204 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E); 01205 } 01206 } 01207 } 01208 while (0); 01209 01210 // If we got all the way here without any luck, use a default summary. 01211 if (!S) 01212 S = getDefaultSummary(); 01213 01214 // Annotations override defaults. 01215 if (AllowAnnotations) 01216 updateSummaryFromAnnotations(S, FD); 01217 01218 FuncSummaries[FD] = S; 01219 return S; 01220 } 01221 01222 const RetainSummary * 01223 RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) { 01224 if (coreFoundation::followsCreateRule(FD)) 01225 return getCFSummaryCreateRule(FD); 01226 01227 return getCFSummaryGetRule(FD); 01228 } 01229 01230 const RetainSummary * 01231 RetainSummaryManager::getUnarySummary(const FunctionType* FT, 01232 UnaryFuncKind func) { 01233 01234 // Sanity check that this is *really* a unary function. This can 01235 // happen if people do weird things. 01236 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT); 01237 if (!FTP || FTP->getNumParams() != 1) 01238 return getPersistentStopSummary(); 01239 01240 assert (ScratchArgs.isEmpty()); 01241 01242 ArgEffect Effect; 01243 switch (func) { 01244 case cfretain: Effect = IncRef; break; 01245 case cfrelease: Effect = DecRef; break; 01246 case cfautorelease: Effect = Autorelease; break; 01247 case cfmakecollectable: Effect = MakeCollectable; break; 01248 } 01249 01250 ScratchArgs = AF.add(ScratchArgs, 0, Effect); 01251 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); 01252 } 01253 01254 const RetainSummary * 01255 RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) { 01256 assert (ScratchArgs.isEmpty()); 01257 01258 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true)); 01259 } 01260 01261 const RetainSummary * 01262 RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) { 01263 assert (ScratchArgs.isEmpty()); 01264 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF), 01265 DoNothing, DoNothing); 01266 } 01267 01268 //===----------------------------------------------------------------------===// 01269 // Summary creation for Selectors. 01270 //===----------------------------------------------------------------------===// 01271 01272 Optional<RetEffect> 01273 RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy, 01274 const Decl *D) { 01275 if (cocoa::isCocoaObjectRef(RetTy)) { 01276 if (D->hasAttr<NSReturnsRetainedAttr>()) 01277 return ObjCAllocRetE; 01278 01279 if (D->hasAttr<NSReturnsNotRetainedAttr>() || 01280 D->hasAttr<NSReturnsAutoreleasedAttr>()) 01281 return RetEffect::MakeNotOwned(RetEffect::ObjC); 01282 01283 } else if (!RetTy->isPointerType()) { 01284 return None; 01285 } 01286 01287 if (D->hasAttr<CFReturnsRetainedAttr>()) 01288 return RetEffect::MakeOwned(RetEffect::CF, true); 01289 01290 if (D->hasAttr<CFReturnsNotRetainedAttr>()) 01291 return RetEffect::MakeNotOwned(RetEffect::CF); 01292 01293 return None; 01294 } 01295 01296 void 01297 RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ, 01298 const FunctionDecl *FD) { 01299 if (!FD) 01300 return; 01301 01302 assert(Summ && "Must have a summary to add annotations to."); 01303 RetainSummaryTemplate Template(Summ, *this); 01304 01305 // Effects on the parameters. 01306 unsigned parm_idx = 0; 01307 for (FunctionDecl::param_const_iterator pi = FD->param_begin(), 01308 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) { 01309 const ParmVarDecl *pd = *pi; 01310 if (pd->hasAttr<NSConsumedAttr>()) 01311 Template->addArg(AF, parm_idx, DecRefMsg); 01312 else if (pd->hasAttr<CFConsumedAttr>()) 01313 Template->addArg(AF, parm_idx, DecRef); 01314 } 01315 01316 QualType RetTy = FD->getReturnType(); 01317 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD)) 01318 Template->setRetEffect(*RetE); 01319 } 01320 01321 void 01322 RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ, 01323 const ObjCMethodDecl *MD) { 01324 if (!MD) 01325 return; 01326 01327 assert(Summ && "Must have a valid summary to add annotations to"); 01328 RetainSummaryTemplate Template(Summ, *this); 01329 01330 // Effects on the receiver. 01331 if (MD->hasAttr<NSConsumesSelfAttr>()) 01332 Template->setReceiverEffect(DecRefMsg); 01333 01334 // Effects on the parameters. 01335 unsigned parm_idx = 0; 01336 for (ObjCMethodDecl::param_const_iterator 01337 pi=MD->param_begin(), pe=MD->param_end(); 01338 pi != pe; ++pi, ++parm_idx) { 01339 const ParmVarDecl *pd = *pi; 01340 if (pd->hasAttr<NSConsumedAttr>()) 01341 Template->addArg(AF, parm_idx, DecRefMsg); 01342 else if (pd->hasAttr<CFConsumedAttr>()) { 01343 Template->addArg(AF, parm_idx, DecRef); 01344 } 01345 } 01346 01347 QualType RetTy = MD->getReturnType(); 01348 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD)) 01349 Template->setRetEffect(*RetE); 01350 } 01351 01352 const RetainSummary * 01353 RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD, 01354 Selector S, QualType RetTy) { 01355 // Any special effects? 01356 ArgEffect ReceiverEff = DoNothing; 01357 RetEffect ResultEff = RetEffect::MakeNoRet(); 01358 01359 // Check the method family, and apply any default annotations. 01360 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) { 01361 case OMF_None: 01362 case OMF_initialize: 01363 case OMF_performSelector: 01364 // Assume all Objective-C methods follow Cocoa Memory Management rules. 01365 // FIXME: Does the non-threaded performSelector family really belong here? 01366 // The selector could be, say, @selector(copy). 01367 if (cocoa::isCocoaObjectRef(RetTy)) 01368 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC); 01369 else if (coreFoundation::isCFObjectRef(RetTy)) { 01370 // ObjCMethodDecl currently doesn't consider CF objects as valid return 01371 // values for alloc, new, copy, or mutableCopy, so we have to 01372 // double-check with the selector. This is ugly, but there aren't that 01373 // many Objective-C methods that return CF objects, right? 01374 if (MD) { 01375 switch (S.getMethodFamily()) { 01376 case OMF_alloc: 01377 case OMF_new: 01378 case OMF_copy: 01379 case OMF_mutableCopy: 01380 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true); 01381 break; 01382 default: 01383 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF); 01384 break; 01385 } 01386 } else { 01387 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF); 01388 } 01389 } 01390 break; 01391 case OMF_init: 01392 ResultEff = ObjCInitRetE; 01393 ReceiverEff = DecRefMsg; 01394 break; 01395 case OMF_alloc: 01396 case OMF_new: 01397 case OMF_copy: 01398 case OMF_mutableCopy: 01399 if (cocoa::isCocoaObjectRef(RetTy)) 01400 ResultEff = ObjCAllocRetE; 01401 else if (coreFoundation::isCFObjectRef(RetTy)) 01402 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true); 01403 break; 01404 case OMF_autorelease: 01405 ReceiverEff = Autorelease; 01406 break; 01407 case OMF_retain: 01408 ReceiverEff = IncRefMsg; 01409 break; 01410 case OMF_release: 01411 ReceiverEff = DecRefMsg; 01412 break; 01413 case OMF_dealloc: 01414 ReceiverEff = Dealloc; 01415 break; 01416 case OMF_self: 01417 // -self is handled specially by the ExprEngine to propagate the receiver. 01418 break; 01419 case OMF_retainCount: 01420 case OMF_finalize: 01421 // These methods don't return objects. 01422 break; 01423 } 01424 01425 // If one of the arguments in the selector has the keyword 'delegate' we 01426 // should stop tracking the reference count for the receiver. This is 01427 // because the reference count is quite possibly handled by a delegate 01428 // method. 01429 if (S.isKeywordSelector()) { 01430 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) { 01431 StringRef Slot = S.getNameForSlot(i); 01432 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) { 01433 if (ResultEff == ObjCInitRetE) 01434 ResultEff = RetEffect::MakeNoRetHard(); 01435 else 01436 ReceiverEff = StopTrackingHard; 01437 } 01438 } 01439 } 01440 01441 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing && 01442 ResultEff.getKind() == RetEffect::NoRet) 01443 return getDefaultSummary(); 01444 01445 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape); 01446 } 01447 01448 const RetainSummary * 01449 RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg, 01450 ProgramStateRef State) { 01451 const ObjCInterfaceDecl *ReceiverClass = nullptr; 01452 01453 // We do better tracking of the type of the object than the core ExprEngine. 01454 // See if we have its type in our private state. 01455 // FIXME: Eventually replace the use of state->get<RefBindings> with 01456 // a generic API for reasoning about the Objective-C types of symbolic 01457 // objects. 01458 SVal ReceiverV = Msg.getReceiverSVal(); 01459 if (SymbolRef Sym = ReceiverV.getAsLocSymbol()) 01460 if (const RefVal *T = getRefBinding(State, Sym)) 01461 if (const ObjCObjectPointerType *PT = 01462 T->getType()->getAs<ObjCObjectPointerType>()) 01463 ReceiverClass = PT->getInterfaceDecl(); 01464 01465 // If we don't know what kind of object this is, fall back to its static type. 01466 if (!ReceiverClass) 01467 ReceiverClass = Msg.getReceiverInterface(); 01468 01469 // FIXME: The receiver could be a reference to a class, meaning that 01470 // we should use the class method. 01471 // id x = [NSObject class]; 01472 // [x performSelector:... withObject:... afterDelay:...]; 01473 Selector S = Msg.getSelector(); 01474 const ObjCMethodDecl *Method = Msg.getDecl(); 01475 if (!Method && ReceiverClass) 01476 Method = ReceiverClass->getInstanceMethod(S); 01477 01478 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(), 01479 ObjCMethodSummaries); 01480 } 01481 01482 const RetainSummary * 01483 RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID, 01484 const ObjCMethodDecl *MD, QualType RetTy, 01485 ObjCMethodSummariesTy &CachedSummaries) { 01486 01487 // Look up a summary in our summary cache. 01488 const RetainSummary *Summ = CachedSummaries.find(ID, S); 01489 01490 if (!Summ) { 01491 Summ = getStandardMethodSummary(MD, S, RetTy); 01492 01493 // Annotations override defaults. 01494 updateSummaryFromAnnotations(Summ, MD); 01495 01496 // Memoize the summary. 01497 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ; 01498 } 01499 01500 return Summ; 01501 } 01502 01503 void RetainSummaryManager::InitializeClassMethodSummaries() { 01504 assert(ScratchArgs.isEmpty()); 01505 // Create the [NSAssertionHandler currentHander] summary. 01506 addClassMethSummary("NSAssertionHandler", "currentHandler", 01507 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC))); 01508 01509 // Create the [NSAutoreleasePool addObject:] summary. 01510 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease); 01511 addClassMethSummary("NSAutoreleasePool", "addObject", 01512 getPersistentSummary(RetEffect::MakeNoRet(), 01513 DoNothing, Autorelease)); 01514 } 01515 01516 void RetainSummaryManager::InitializeMethodSummaries() { 01517 01518 assert (ScratchArgs.isEmpty()); 01519 01520 // Create the "init" selector. It just acts as a pass-through for the 01521 // receiver. 01522 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg); 01523 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm); 01524 01525 // awakeAfterUsingCoder: behaves basically like an 'init' method. It 01526 // claims the receiver and returns a retained object. 01527 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx), 01528 InitSumm); 01529 01530 // The next methods are allocators. 01531 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE); 01532 const RetainSummary *CFAllocSumm = 01533 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true)); 01534 01535 // Create the "retain" selector. 01536 RetEffect NoRet = RetEffect::MakeNoRet(); 01537 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg); 01538 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ); 01539 01540 // Create the "release" selector. 01541 Summ = getPersistentSummary(NoRet, DecRefMsg); 01542 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ); 01543 01544 // Create the -dealloc summary. 01545 Summ = getPersistentSummary(NoRet, Dealloc); 01546 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ); 01547 01548 // Create the "autorelease" selector. 01549 Summ = getPersistentSummary(NoRet, Autorelease); 01550 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ); 01551 01552 // For NSWindow, allocated objects are (initially) self-owned. 01553 // FIXME: For now we opt for false negatives with NSWindow, as these objects 01554 // self-own themselves. However, they only do this once they are displayed. 01555 // Thus, we need to track an NSWindow's display status. 01556 // This is tracked in <rdar://problem/6062711>. 01557 // See also http://llvm.org/bugs/show_bug.cgi?id=3714. 01558 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(), 01559 StopTracking, 01560 StopTracking); 01561 01562 addClassMethSummary("NSWindow", "alloc", NoTrackYet); 01563 01564 // For NSPanel (which subclasses NSWindow), allocated objects are not 01565 // self-owned. 01566 // FIXME: For now we don't track NSPanels. object for the same reason 01567 // as for NSWindow objects. 01568 addClassMethSummary("NSPanel", "alloc", NoTrackYet); 01569 01570 // For NSNull, objects returned by +null are singletons that ignore 01571 // retain/release semantics. Just don't track them. 01572 // <rdar://problem/12858915> 01573 addClassMethSummary("NSNull", "null", NoTrackYet); 01574 01575 // Don't track allocated autorelease pools, as it is okay to prematurely 01576 // exit a method. 01577 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet); 01578 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false); 01579 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet); 01580 01581 // Create summaries QCRenderer/QCView -createSnapShotImageOfType: 01582 addInstMethSummary("QCRenderer", AllocSumm, 01583 "createSnapshotImageOfType", NULL); 01584 addInstMethSummary("QCView", AllocSumm, 01585 "createSnapshotImageOfType", NULL); 01586 01587 // Create summaries for CIContext, 'createCGImage' and 01588 // 'createCGLayerWithSize'. These objects are CF objects, and are not 01589 // automatically garbage collected. 01590 addInstMethSummary("CIContext", CFAllocSumm, 01591 "createCGImage", "fromRect", NULL); 01592 addInstMethSummary("CIContext", CFAllocSumm, 01593 "createCGImage", "fromRect", "format", "colorSpace", NULL); 01594 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", 01595 "info", NULL); 01596 } 01597 01598 //===----------------------------------------------------------------------===// 01599 // Error reporting. 01600 //===----------------------------------------------------------------------===// 01601 namespace { 01602 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *> 01603 SummaryLogTy; 01604 01605 //===-------------===// 01606 // Bug Descriptions. // 01607 //===-------------===// 01608 01609 class CFRefBug : public BugType { 01610 protected: 01611 CFRefBug(const CheckerBase *checker, StringRef name) 01612 : BugType(checker, name, categories::MemoryCoreFoundationObjectiveC) {} 01613 01614 public: 01615 01616 // FIXME: Eventually remove. 01617 virtual const char *getDescription() const = 0; 01618 01619 virtual bool isLeak() const { return false; } 01620 }; 01621 01622 class UseAfterRelease : public CFRefBug { 01623 public: 01624 UseAfterRelease(const CheckerBase *checker) 01625 : CFRefBug(checker, "Use-after-release") {} 01626 01627 const char *getDescription() const override { 01628 return "Reference-counted object is used after it is released"; 01629 } 01630 }; 01631 01632 class BadRelease : public CFRefBug { 01633 public: 01634 BadRelease(const CheckerBase *checker) : CFRefBug(checker, "Bad release") {} 01635 01636 const char *getDescription() const override { 01637 return "Incorrect decrement of the reference count of an object that is " 01638 "not owned at this point by the caller"; 01639 } 01640 }; 01641 01642 class DeallocGC : public CFRefBug { 01643 public: 01644 DeallocGC(const CheckerBase *checker) 01645 : CFRefBug(checker, "-dealloc called while using garbage collection") {} 01646 01647 const char *getDescription() const override { 01648 return "-dealloc called while using garbage collection"; 01649 } 01650 }; 01651 01652 class DeallocNotOwned : public CFRefBug { 01653 public: 01654 DeallocNotOwned(const CheckerBase *checker) 01655 : CFRefBug(checker, "-dealloc sent to non-exclusively owned object") {} 01656 01657 const char *getDescription() const override { 01658 return "-dealloc sent to object that may be referenced elsewhere"; 01659 } 01660 }; 01661 01662 class OverAutorelease : public CFRefBug { 01663 public: 01664 OverAutorelease(const CheckerBase *checker) 01665 : CFRefBug(checker, "Object autoreleased too many times") {} 01666 01667 const char *getDescription() const override { 01668 return "Object autoreleased too many times"; 01669 } 01670 }; 01671 01672 class ReturnedNotOwnedForOwned : public CFRefBug { 01673 public: 01674 ReturnedNotOwnedForOwned(const CheckerBase *checker) 01675 : CFRefBug(checker, "Method should return an owned object") {} 01676 01677 const char *getDescription() const override { 01678 return "Object with a +0 retain count returned to caller where a +1 " 01679 "(owning) retain count is expected"; 01680 } 01681 }; 01682 01683 class Leak : public CFRefBug { 01684 public: 01685 Leak(const CheckerBase *checker, StringRef name) : CFRefBug(checker, name) { 01686 // Leaks should not be reported if they are post-dominated by a sink. 01687 setSuppressOnSink(true); 01688 } 01689 01690 const char *getDescription() const override { return ""; } 01691 01692 bool isLeak() const override { return true; } 01693 }; 01694 01695 //===---------===// 01696 // Bug Reports. // 01697 //===---------===// 01698 01699 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> { 01700 protected: 01701 SymbolRef Sym; 01702 const SummaryLogTy &SummaryLog; 01703 bool GCEnabled; 01704 01705 public: 01706 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log) 01707 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {} 01708 01709 void Profile(llvm::FoldingSetNodeID &ID) const override { 01710 static int x = 0; 01711 ID.AddPointer(&x); 01712 ID.AddPointer(Sym); 01713 } 01714 01715 PathDiagnosticPiece *VisitNode(const ExplodedNode *N, 01716 const ExplodedNode *PrevN, 01717 BugReporterContext &BRC, 01718 BugReport &BR) override; 01719 01720 std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC, 01721 const ExplodedNode *N, 01722 BugReport &BR) override; 01723 }; 01724 01725 class CFRefLeakReportVisitor : public CFRefReportVisitor { 01726 public: 01727 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled, 01728 const SummaryLogTy &log) 01729 : CFRefReportVisitor(sym, GCEnabled, log) {} 01730 01731 std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC, 01732 const ExplodedNode *N, 01733 BugReport &BR) override; 01734 01735 std::unique_ptr<BugReporterVisitor> clone() const override { 01736 // The curiously-recurring template pattern only works for one level of 01737 // subclassing. Rather than make a new template base for 01738 // CFRefReportVisitor, we simply override clone() to do the right thing. 01739 // This could be trouble someday if BugReporterVisitorImpl is ever 01740 // used for something else besides a convenient implementation of clone(). 01741 return llvm::make_unique<CFRefLeakReportVisitor>(*this); 01742 } 01743 }; 01744 01745 class CFRefReport : public BugReport { 01746 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled); 01747 01748 public: 01749 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled, 01750 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym, 01751 bool registerVisitor = true) 01752 : BugReport(D, D.getDescription(), n) { 01753 if (registerVisitor) 01754 addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log)); 01755 addGCModeDescription(LOpts, GCEnabled); 01756 } 01757 01758 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled, 01759 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym, 01760 StringRef endText) 01761 : BugReport(D, D.getDescription(), endText, n) { 01762 addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log)); 01763 addGCModeDescription(LOpts, GCEnabled); 01764 } 01765 01766 std::pair<ranges_iterator, ranges_iterator> getRanges() override { 01767 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType()); 01768 if (!BugTy.isLeak()) 01769 return BugReport::getRanges(); 01770 else 01771 return std::make_pair(ranges_iterator(), ranges_iterator()); 01772 } 01773 }; 01774 01775 class CFRefLeakReport : public CFRefReport { 01776 const MemRegion* AllocBinding; 01777 public: 01778 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled, 01779 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym, 01780 CheckerContext &Ctx, 01781 bool IncludeAllocationLine); 01782 01783 PathDiagnosticLocation getLocation(const SourceManager &SM) const override { 01784 assert(Location.isValid()); 01785 return Location; 01786 } 01787 }; 01788 } // end anonymous namespace 01789 01790 void CFRefReport::addGCModeDescription(const LangOptions &LOpts, 01791 bool GCEnabled) { 01792 const char *GCModeDescription = nullptr; 01793 01794 switch (LOpts.getGC()) { 01795 case LangOptions::GCOnly: 01796 assert(GCEnabled); 01797 GCModeDescription = "Code is compiled to only use garbage collection"; 01798 break; 01799 01800 case LangOptions::NonGC: 01801 assert(!GCEnabled); 01802 GCModeDescription = "Code is compiled to use reference counts"; 01803 break; 01804 01805 case LangOptions::HybridGC: 01806 if (GCEnabled) { 01807 GCModeDescription = "Code is compiled to use either garbage collection " 01808 "(GC) or reference counts (non-GC). The bug occurs " 01809 "with GC enabled"; 01810 break; 01811 } else { 01812 GCModeDescription = "Code is compiled to use either garbage collection " 01813 "(GC) or reference counts (non-GC). The bug occurs " 01814 "in non-GC mode"; 01815 break; 01816 } 01817 } 01818 01819 assert(GCModeDescription && "invalid/unknown GC mode"); 01820 addExtraText(GCModeDescription); 01821 } 01822 01823 static bool isNumericLiteralExpression(const Expr *E) { 01824 // FIXME: This set of cases was copied from SemaExprObjC. 01825 return isa<IntegerLiteral>(E) || 01826 isa<CharacterLiteral>(E) || 01827 isa<FloatingLiteral>(E) || 01828 isa<ObjCBoolLiteralExpr>(E) || 01829 isa<CXXBoolLiteralExpr>(E); 01830 } 01831 01832 PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N, 01833 const ExplodedNode *PrevN, 01834 BugReporterContext &BRC, 01835 BugReport &BR) { 01836 // FIXME: We will eventually need to handle non-statement-based events 01837 // (__attribute__((cleanup))). 01838 if (!N->getLocation().getAs<StmtPoint>()) 01839 return nullptr; 01840 01841 // Check if the type state has changed. 01842 ProgramStateRef PrevSt = PrevN->getState(); 01843 ProgramStateRef CurrSt = N->getState(); 01844 const LocationContext *LCtx = N->getLocationContext(); 01845 01846 const RefVal* CurrT = getRefBinding(CurrSt, Sym); 01847 if (!CurrT) return nullptr; 01848 01849 const RefVal &CurrV = *CurrT; 01850 const RefVal *PrevT = getRefBinding(PrevSt, Sym); 01851 01852 // Create a string buffer to constain all the useful things we want 01853 // to tell the user. 01854 std::string sbuf; 01855 llvm::raw_string_ostream os(sbuf); 01856 01857 // This is the allocation site since the previous node had no bindings 01858 // for this symbol. 01859 if (!PrevT) { 01860 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt(); 01861 01862 if (isa<ObjCArrayLiteral>(S)) { 01863 os << "NSArray literal is an object with a +0 retain count"; 01864 } 01865 else if (isa<ObjCDictionaryLiteral>(S)) { 01866 os << "NSDictionary literal is an object with a +0 retain count"; 01867 } 01868 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) { 01869 if (isNumericLiteralExpression(BL->getSubExpr())) 01870 os << "NSNumber literal is an object with a +0 retain count"; 01871 else { 01872 const ObjCInterfaceDecl *BoxClass = nullptr; 01873 if (const ObjCMethodDecl *Method = BL->getBoxingMethod()) 01874 BoxClass = Method->getClassInterface(); 01875 01876 // We should always be able to find the boxing class interface, 01877 // but consider this future-proofing. 01878 if (BoxClass) 01879 os << *BoxClass << " b"; 01880 else 01881 os << "B"; 01882 01883 os << "oxed expression produces an object with a +0 retain count"; 01884 } 01885 } 01886 else { 01887 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) { 01888 // Get the name of the callee (if it is available). 01889 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx); 01890 if (const FunctionDecl *FD = X.getAsFunctionDecl()) 01891 os << "Call to function '" << *FD << '\''; 01892 else 01893 os << "function call"; 01894 } 01895 else { 01896 assert(isa<ObjCMessageExpr>(S)); 01897 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager(); 01898 CallEventRef<ObjCMethodCall> Call 01899 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx); 01900 01901 switch (Call->getMessageKind()) { 01902 case OCM_Message: 01903 os << "Method"; 01904 break; 01905 case OCM_PropertyAccess: 01906 os << "Property"; 01907 break; 01908 case OCM_Subscript: 01909 os << "Subscript"; 01910 break; 01911 } 01912 } 01913 01914 if (CurrV.getObjKind() == RetEffect::CF) { 01915 os << " returns a Core Foundation object with a "; 01916 } 01917 else { 01918 assert (CurrV.getObjKind() == RetEffect::ObjC); 01919 os << " returns an Objective-C object with a "; 01920 } 01921 01922 if (CurrV.isOwned()) { 01923 os << "+1 retain count"; 01924 01925 if (GCEnabled) { 01926 assert(CurrV.getObjKind() == RetEffect::CF); 01927 os << ". " 01928 "Core Foundation objects are not automatically garbage collected."; 01929 } 01930 } 01931 else { 01932 assert (CurrV.isNotOwned()); 01933 os << "+0 retain count"; 01934 } 01935 } 01936 01937 PathDiagnosticLocation Pos(S, BRC.getSourceManager(), 01938 N->getLocationContext()); 01939 return new PathDiagnosticEventPiece(Pos, os.str()); 01940 } 01941 01942 // Gather up the effects that were performed on the object at this 01943 // program point 01944 SmallVector<ArgEffect, 2> AEffects; 01945 01946 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N); 01947 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) { 01948 // We only have summaries attached to nodes after evaluating CallExpr and 01949 // ObjCMessageExprs. 01950 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt(); 01951 01952 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) { 01953 // Iterate through the parameter expressions and see if the symbol 01954 // was ever passed as an argument. 01955 unsigned i = 0; 01956 01957 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end(); 01958 AI!=AE; ++AI, ++i) { 01959 01960 // Retrieve the value of the argument. Is it the symbol 01961 // we are interested in? 01962 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym) 01963 continue; 01964 01965 // We have an argument. Get the effect! 01966 AEffects.push_back(Summ->getArg(i)); 01967 } 01968 } 01969 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) { 01970 if (const Expr *receiver = ME->getInstanceReceiver()) 01971 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx) 01972 .getAsLocSymbol() == Sym) { 01973 // The symbol we are tracking is the receiver. 01974 AEffects.push_back(Summ->getReceiverEffect()); 01975 } 01976 } 01977 } 01978 01979 do { 01980 // Get the previous type state. 01981 RefVal PrevV = *PrevT; 01982 01983 // Specially handle -dealloc. 01984 if (!GCEnabled && std::find(AEffects.begin(), AEffects.end(), Dealloc) != 01985 AEffects.end()) { 01986 // Determine if the object's reference count was pushed to zero. 01987 assert(!PrevV.hasSameState(CurrV) && "The state should have changed."); 01988 // We may not have transitioned to 'release' if we hit an error. 01989 // This case is handled elsewhere. 01990 if (CurrV.getKind() == RefVal::Released) { 01991 assert(CurrV.getCombinedCounts() == 0); 01992 os << "Object released by directly sending the '-dealloc' message"; 01993 break; 01994 } 01995 } 01996 01997 // Specially handle CFMakeCollectable and friends. 01998 if (std::find(AEffects.begin(), AEffects.end(), MakeCollectable) != 01999 AEffects.end()) { 02000 // Get the name of the function. 02001 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt(); 02002 SVal X = 02003 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx); 02004 const FunctionDecl *FD = X.getAsFunctionDecl(); 02005 02006 if (GCEnabled) { 02007 // Determine if the object's reference count was pushed to zero. 02008 assert(!PrevV.hasSameState(CurrV) && "The state should have changed."); 02009 02010 os << "In GC mode a call to '" << *FD 02011 << "' decrements an object's retain count and registers the " 02012 "object with the garbage collector. "; 02013 02014 if (CurrV.getKind() == RefVal::Released) { 02015 assert(CurrV.getCount() == 0); 02016 os << "Since it now has a 0 retain count the object can be " 02017 "automatically collected by the garbage collector."; 02018 } 02019 else 02020 os << "An object must have a 0 retain count to be garbage collected. " 02021 "After this call its retain count is +" << CurrV.getCount() 02022 << '.'; 02023 } 02024 else 02025 os << "When GC is not enabled a call to '" << *FD 02026 << "' has no effect on its argument."; 02027 02028 // Nothing more to say. 02029 break; 02030 } 02031 02032 // Determine if the typestate has changed. 02033 if (!PrevV.hasSameState(CurrV)) 02034 switch (CurrV.getKind()) { 02035 case RefVal::Owned: 02036 case RefVal::NotOwned: 02037 02038 if (PrevV.getCount() == CurrV.getCount()) { 02039 // Did an autorelease message get sent? 02040 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount()) 02041 return nullptr; 02042 02043 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount()); 02044 os << "Object autoreleased"; 02045 break; 02046 } 02047 02048 if (PrevV.getCount() > CurrV.getCount()) 02049 os << "Reference count decremented."; 02050 else 02051 os << "Reference count incremented."; 02052 02053 if (unsigned Count = CurrV.getCount()) 02054 os << " The object now has a +" << Count << " retain count."; 02055 02056 if (PrevV.getKind() == RefVal::Released) { 02057 assert(GCEnabled && CurrV.getCount() > 0); 02058 os << " The object is not eligible for garbage collection until " 02059 "the retain count reaches 0 again."; 02060 } 02061 02062 break; 02063 02064 case RefVal::Released: 02065 os << "Object released."; 02066 break; 02067 02068 case RefVal::ReturnedOwned: 02069 // Autoreleases can be applied after marking a node ReturnedOwned. 02070 if (CurrV.getAutoreleaseCount()) 02071 return nullptr; 02072 02073 os << "Object returned to caller as an owning reference (single " 02074 "retain count transferred to caller)"; 02075 break; 02076 02077 case RefVal::ReturnedNotOwned: 02078 os << "Object returned to caller with a +0 retain count"; 02079 break; 02080 02081 default: 02082 return nullptr; 02083 } 02084 02085 // Emit any remaining diagnostics for the argument effects (if any). 02086 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(), 02087 E=AEffects.end(); I != E; ++I) { 02088 02089 // A bunch of things have alternate behavior under GC. 02090 if (GCEnabled) 02091 switch (*I) { 02092 default: break; 02093 case Autorelease: 02094 os << "In GC mode an 'autorelease' has no effect."; 02095 continue; 02096 case IncRefMsg: 02097 os << "In GC mode the 'retain' message has no effect."; 02098 continue; 02099 case DecRefMsg: 02100 os << "In GC mode the 'release' message has no effect."; 02101 continue; 02102 } 02103 } 02104 } while (0); 02105 02106 if (os.str().empty()) 02107 return nullptr; // We have nothing to say! 02108 02109 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt(); 02110 PathDiagnosticLocation Pos(S, BRC.getSourceManager(), 02111 N->getLocationContext()); 02112 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str()); 02113 02114 // Add the range by scanning the children of the statement for any bindings 02115 // to Sym. 02116 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); 02117 I!=E; ++I) 02118 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I)) 02119 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) { 02120 P->addRange(Exp->getSourceRange()); 02121 break; 02122 } 02123 02124 return P; 02125 } 02126 02127 // Find the first node in the current function context that referred to the 02128 // tracked symbol and the memory location that value was stored to. Note, the 02129 // value is only reported if the allocation occurred in the same function as 02130 // the leak. The function can also return a location context, which should be 02131 // treated as interesting. 02132 struct AllocationInfo { 02133 const ExplodedNode* N; 02134 const MemRegion *R; 02135 const LocationContext *InterestingMethodContext; 02136 AllocationInfo(const ExplodedNode *InN, 02137 const MemRegion *InR, 02138 const LocationContext *InInterestingMethodContext) : 02139 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {} 02140 }; 02141 02142 static AllocationInfo 02143 GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N, 02144 SymbolRef Sym) { 02145 const ExplodedNode *AllocationNode = N; 02146 const ExplodedNode *AllocationNodeInCurrentContext = N; 02147 const MemRegion *FirstBinding = nullptr; 02148 const LocationContext *LeakContext = N->getLocationContext(); 02149 02150 // The location context of the init method called on the leaked object, if 02151 // available. 02152 const LocationContext *InitMethodContext = nullptr; 02153 02154 while (N) { 02155 ProgramStateRef St = N->getState(); 02156 const LocationContext *NContext = N->getLocationContext(); 02157 02158 if (!getRefBinding(St, Sym)) 02159 break; 02160 02161 StoreManager::FindUniqueBinding FB(Sym); 02162 StateMgr.iterBindings(St, FB); 02163 02164 if (FB) { 02165 const MemRegion *R = FB.getRegion(); 02166 const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>(); 02167 // Do not show local variables belonging to a function other than 02168 // where the error is reported. 02169 if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame()) 02170 FirstBinding = R; 02171 } 02172 02173 // AllocationNode is the last node in which the symbol was tracked. 02174 AllocationNode = N; 02175 02176 // AllocationNodeInCurrentContext, is the last node in the current context 02177 // in which the symbol was tracked. 02178 if (NContext == LeakContext) 02179 AllocationNodeInCurrentContext = N; 02180 02181 // Find the last init that was called on the given symbol and store the 02182 // init method's location context. 02183 if (!InitMethodContext) 02184 if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) { 02185 const Stmt *CE = CEP->getCallExpr(); 02186 if (const ObjCMessageExpr *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) { 02187 const Stmt *RecExpr = ME->getInstanceReceiver(); 02188 if (RecExpr) { 02189 SVal RecV = St->getSVal(RecExpr, NContext); 02190 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym) 02191 InitMethodContext = CEP->getCalleeContext(); 02192 } 02193 } 02194 } 02195 02196 N = N->pred_empty() ? nullptr : *(N->pred_begin()); 02197 } 02198 02199 // If we are reporting a leak of the object that was allocated with alloc, 02200 // mark its init method as interesting. 02201 const LocationContext *InterestingMethodContext = nullptr; 02202 if (InitMethodContext) { 02203 const ProgramPoint AllocPP = AllocationNode->getLocation(); 02204 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>()) 02205 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>()) 02206 if (ME->getMethodFamily() == OMF_alloc) 02207 InterestingMethodContext = InitMethodContext; 02208 } 02209 02210 // If allocation happened in a function different from the leak node context, 02211 // do not report the binding. 02212 assert(N && "Could not find allocation node"); 02213 if (N->getLocationContext() != LeakContext) { 02214 FirstBinding = nullptr; 02215 } 02216 02217 return AllocationInfo(AllocationNodeInCurrentContext, 02218 FirstBinding, 02219 InterestingMethodContext); 02220 } 02221 02222 std::unique_ptr<PathDiagnosticPiece> 02223 CFRefReportVisitor::getEndPath(BugReporterContext &BRC, 02224 const ExplodedNode *EndN, BugReport &BR) { 02225 BR.markInteresting(Sym); 02226 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR); 02227 } 02228 02229 std::unique_ptr<PathDiagnosticPiece> 02230 CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC, 02231 const ExplodedNode *EndN, BugReport &BR) { 02232 02233 // Tell the BugReporterContext to report cases when the tracked symbol is 02234 // assigned to different variables, etc. 02235 BR.markInteresting(Sym); 02236 02237 // We are reporting a leak. Walk up the graph to get to the first node where 02238 // the symbol appeared, and also get the first VarDecl that tracked object 02239 // is stored to. 02240 AllocationInfo AllocI = 02241 GetAllocationSite(BRC.getStateManager(), EndN, Sym); 02242 02243 const MemRegion* FirstBinding = AllocI.R; 02244 BR.markInteresting(AllocI.InterestingMethodContext); 02245 02246 SourceManager& SM = BRC.getSourceManager(); 02247 02248 // Compute an actual location for the leak. Sometimes a leak doesn't 02249 // occur at an actual statement (e.g., transition between blocks; end 02250 // of function) so we need to walk the graph and compute a real location. 02251 const ExplodedNode *LeakN = EndN; 02252 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM); 02253 02254 std::string sbuf; 02255 llvm::raw_string_ostream os(sbuf); 02256 02257 os << "Object leaked: "; 02258 02259 if (FirstBinding) { 02260 os << "object allocated and stored into '" 02261 << FirstBinding->getString() << '\''; 02262 } 02263 else 02264 os << "allocated object"; 02265 02266 // Get the retain count. 02267 const RefVal* RV = getRefBinding(EndN->getState(), Sym); 02268 assert(RV); 02269 02270 if (RV->getKind() == RefVal::ErrorLeakReturned) { 02271 // FIXME: Per comments in rdar://6320065, "create" only applies to CF 02272 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership 02273 // to the caller for NS objects. 02274 const Decl *D = &EndN->getCodeDecl(); 02275 02276 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method " 02277 : " is returned from a function "); 02278 02279 if (D->hasAttr<CFReturnsNotRetainedAttr>()) 02280 os << "that is annotated as CF_RETURNS_NOT_RETAINED"; 02281 else if (D->hasAttr<NSReturnsNotRetainedAttr>()) 02282 os << "that is annotated as NS_RETURNS_NOT_RETAINED"; 02283 else { 02284 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 02285 os << "whose name ('" << MD->getSelector().getAsString() 02286 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'." 02287 " This violates the naming convention rules" 02288 " given in the Memory Management Guide for Cocoa"; 02289 } 02290 else { 02291 const FunctionDecl *FD = cast<FunctionDecl>(D); 02292 os << "whose name ('" << *FD 02293 << "') does not contain 'Copy' or 'Create'. This violates the naming" 02294 " convention rules given in the Memory Management Guide for Core" 02295 " Foundation"; 02296 } 02297 } 02298 } 02299 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) { 02300 const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl()); 02301 os << " and returned from method '" << MD.getSelector().getAsString() 02302 << "' is potentially leaked when using garbage collection. Callers " 02303 "of this method do not expect a returned object with a +1 retain " 02304 "count since they expect the object to be managed by the garbage " 02305 "collector"; 02306 } 02307 else 02308 os << " is not referenced later in this execution path and has a retain " 02309 "count of +" << RV->getCount(); 02310 02311 return llvm::make_unique<PathDiagnosticEventPiece>(L, os.str()); 02312 } 02313 02314 CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, 02315 bool GCEnabled, const SummaryLogTy &Log, 02316 ExplodedNode *n, SymbolRef sym, 02317 CheckerContext &Ctx, 02318 bool IncludeAllocationLine) 02319 : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) { 02320 02321 // Most bug reports are cached at the location where they occurred. 02322 // With leaks, we want to unique them by the location where they were 02323 // allocated, and only report a single path. To do this, we need to find 02324 // the allocation site of a piece of tracked memory, which we do via a 02325 // call to GetAllocationSite. This will walk the ExplodedGraph backwards. 02326 // Note that this is *not* the trimmed graph; we are guaranteed, however, 02327 // that all ancestor nodes that represent the allocation site have the 02328 // same SourceLocation. 02329 const ExplodedNode *AllocNode = nullptr; 02330 02331 const SourceManager& SMgr = Ctx.getSourceManager(); 02332 02333 AllocationInfo AllocI = 02334 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym); 02335 02336 AllocNode = AllocI.N; 02337 AllocBinding = AllocI.R; 02338 markInteresting(AllocI.InterestingMethodContext); 02339 02340 // Get the SourceLocation for the allocation site. 02341 // FIXME: This will crash the analyzer if an allocation comes from an 02342 // implicit call (ex: a destructor call). 02343 // (Currently there are no such allocations in Cocoa, though.) 02344 const Stmt *AllocStmt = 0; 02345 ProgramPoint P = AllocNode->getLocation(); 02346 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>()) 02347 AllocStmt = Exit->getCalleeContext()->getCallSite(); 02348 else { 02349 // We are going to get a BlockEdge when the leak and allocation happen in 02350 // different, non-nested frames (contexts). For example, the case where an 02351 // allocation happens in a block that captures a reference to it and 02352 // that reference is overwritten/dropped by another call to the block. 02353 if (Optional<BlockEdge> Edge = P.getAs<BlockEdge>()) { 02354 if (Optional<CFGStmt> St = Edge->getDst()->front().getAs<CFGStmt>()) { 02355 AllocStmt = St->getStmt(); 02356 } 02357 } 02358 else { 02359 AllocStmt = P.castAs<PostStmt>().getStmt(); 02360 } 02361 } 02362 assert(AllocStmt && "Cannot find allocation statement"); 02363 02364 PathDiagnosticLocation AllocLocation = 02365 PathDiagnosticLocation::createBegin(AllocStmt, SMgr, 02366 AllocNode->getLocationContext()); 02367 Location = AllocLocation; 02368 02369 // Set uniqieing info, which will be used for unique the bug reports. The 02370 // leaks should be uniqued on the allocation site. 02371 UniqueingLocation = AllocLocation; 02372 UniqueingDecl = AllocNode->getLocationContext()->getDecl(); 02373 02374 // Fill in the description of the bug. 02375 Description.clear(); 02376 llvm::raw_string_ostream os(Description); 02377 os << "Potential leak "; 02378 if (GCEnabled) 02379 os << "(when using garbage collection) "; 02380 os << "of an object"; 02381 02382 if (AllocBinding) { 02383 os << " stored into '" << AllocBinding->getString() << '\''; 02384 if (IncludeAllocationLine) { 02385 FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager()); 02386 os << " (allocated on line " << SL.getSpellingLineNumber() << ")"; 02387 } 02388 } 02389 02390 addVisitor(llvm::make_unique<CFRefLeakReportVisitor>(sym, GCEnabled, Log)); 02391 } 02392 02393 //===----------------------------------------------------------------------===// 02394 // Main checker logic. 02395 //===----------------------------------------------------------------------===// 02396 02397 namespace { 02398 class RetainCountChecker 02399 : public Checker< check::Bind, 02400 check::DeadSymbols, 02401 check::EndAnalysis, 02402 check::EndFunction, 02403 check::PostStmt<BlockExpr>, 02404 check::PostStmt<CastExpr>, 02405 check::PostStmt<ObjCArrayLiteral>, 02406 check::PostStmt<ObjCDictionaryLiteral>, 02407 check::PostStmt<ObjCBoxedExpr>, 02408 check::PostStmt<ObjCIvarRefExpr>, 02409 check::PostCall, 02410 check::PreStmt<ReturnStmt>, 02411 check::RegionChanges, 02412 eval::Assume, 02413 eval::Call > { 02414 mutable std::unique_ptr<CFRefBug> useAfterRelease, releaseNotOwned; 02415 mutable std::unique_ptr<CFRefBug> deallocGC, deallocNotOwned; 02416 mutable std::unique_ptr<CFRefBug> overAutorelease, returnNotOwnedForOwned; 02417 mutable std::unique_ptr<CFRefBug> leakWithinFunction, leakAtReturn; 02418 mutable std::unique_ptr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC; 02419 02420 typedef llvm::DenseMap<SymbolRef, const CheckerProgramPointTag *> SymbolTagMap; 02421 02422 // This map is only used to ensure proper deletion of any allocated tags. 02423 mutable SymbolTagMap DeadSymbolTags; 02424 02425 mutable std::unique_ptr<RetainSummaryManager> Summaries; 02426 mutable std::unique_ptr<RetainSummaryManager> SummariesGC; 02427 mutable SummaryLogTy SummaryLog; 02428 mutable bool ShouldResetSummaryLog; 02429 02430 /// Optional setting to indicate if leak reports should include 02431 /// the allocation line. 02432 mutable bool IncludeAllocationLine; 02433 02434 public: 02435 RetainCountChecker(AnalyzerOptions &AO) 02436 : ShouldResetSummaryLog(false), 02437 IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {} 02438 02439 virtual ~RetainCountChecker() { 02440 DeleteContainerSeconds(DeadSymbolTags); 02441 } 02442 02443 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR, 02444 ExprEngine &Eng) const { 02445 // FIXME: This is a hack to make sure the summary log gets cleared between 02446 // analyses of different code bodies. 02447 // 02448 // Why is this necessary? Because a checker's lifetime is tied to a 02449 // translation unit, but an ExplodedGraph's lifetime is just a code body. 02450 // Once in a blue moon, a new ExplodedNode will have the same address as an 02451 // old one with an associated summary, and the bug report visitor gets very 02452 // confused. (To make things worse, the summary lifetime is currently also 02453 // tied to a code body, so we get a crash instead of incorrect results.) 02454 // 02455 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph 02456 // changes, things will start going wrong again. Really the lifetime of this 02457 // log needs to be tied to either the specific nodes in it or the entire 02458 // ExplodedGraph, not to a specific part of the code being analyzed. 02459 // 02460 // (Also, having stateful local data means that the same checker can't be 02461 // used from multiple threads, but a lot of checkers have incorrect 02462 // assumptions about that anyway. So that wasn't a priority at the time of 02463 // this fix.) 02464 // 02465 // This happens at the end of analysis, but bug reports are emitted /after/ 02466 // this point. So we can't just clear the summary log now. Instead, we mark 02467 // that the next time we access the summary log, it should be cleared. 02468 02469 // If we never reset the summary log during /this/ code body analysis, 02470 // there were no new summaries. There might still have been summaries from 02471 // the /last/ analysis, so clear them out to make sure the bug report 02472 // visitors don't get confused. 02473 if (ShouldResetSummaryLog) 02474 SummaryLog.clear(); 02475 02476 ShouldResetSummaryLog = !SummaryLog.empty(); 02477 } 02478 02479 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts, 02480 bool GCEnabled) const { 02481 if (GCEnabled) { 02482 if (!leakWithinFunctionGC) 02483 leakWithinFunctionGC.reset(new Leak(this, "Leak of object when using " 02484 "garbage collection")); 02485 return leakWithinFunctionGC.get(); 02486 } else { 02487 if (!leakWithinFunction) { 02488 if (LOpts.getGC() == LangOptions::HybridGC) { 02489 leakWithinFunction.reset(new Leak(this, 02490 "Leak of object when not using " 02491 "garbage collection (GC) in " 02492 "dual GC/non-GC code")); 02493 } else { 02494 leakWithinFunction.reset(new Leak(this, "Leak")); 02495 } 02496 } 02497 return leakWithinFunction.get(); 02498 } 02499 } 02500 02501 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const { 02502 if (GCEnabled) { 02503 if (!leakAtReturnGC) 02504 leakAtReturnGC.reset(new Leak(this, 02505 "Leak of returned object when using " 02506 "garbage collection")); 02507 return leakAtReturnGC.get(); 02508 } else { 02509 if (!leakAtReturn) { 02510 if (LOpts.getGC() == LangOptions::HybridGC) { 02511 leakAtReturn.reset(new Leak(this, 02512 "Leak of returned object when not using " 02513 "garbage collection (GC) in dual " 02514 "GC/non-GC code")); 02515 } else { 02516 leakAtReturn.reset(new Leak(this, "Leak of returned object")); 02517 } 02518 } 02519 return leakAtReturn.get(); 02520 } 02521 } 02522 02523 RetainSummaryManager &getSummaryManager(ASTContext &Ctx, 02524 bool GCEnabled) const { 02525 // FIXME: We don't support ARC being turned on and off during one analysis. 02526 // (nor, for that matter, do we support changing ASTContexts) 02527 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount; 02528 if (GCEnabled) { 02529 if (!SummariesGC) 02530 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled)); 02531 else 02532 assert(SummariesGC->isARCEnabled() == ARCEnabled); 02533 return *SummariesGC; 02534 } else { 02535 if (!Summaries) 02536 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled)); 02537 else 02538 assert(Summaries->isARCEnabled() == ARCEnabled); 02539 return *Summaries; 02540 } 02541 } 02542 02543 RetainSummaryManager &getSummaryManager(CheckerContext &C) const { 02544 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled()); 02545 } 02546 02547 void printState(raw_ostream &Out, ProgramStateRef State, 02548 const char *NL, const char *Sep) const override; 02549 02550 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const; 02551 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const; 02552 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const; 02553 02554 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const; 02555 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const; 02556 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const; 02557 02558 void checkPostStmt(const ObjCIvarRefExpr *IRE, CheckerContext &C) const; 02559 02560 void checkPostCall(const CallEvent &Call, CheckerContext &C) const; 02561 02562 void checkSummary(const RetainSummary &Summ, const CallEvent &Call, 02563 CheckerContext &C) const; 02564 02565 void processSummaryOfInlined(const RetainSummary &Summ, 02566 const CallEvent &Call, 02567 CheckerContext &C) const; 02568 02569 bool evalCall(const CallExpr *CE, CheckerContext &C) const; 02570 02571 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond, 02572 bool Assumption) const; 02573 02574 ProgramStateRef 02575 checkRegionChanges(ProgramStateRef state, 02576 const InvalidatedSymbols *invalidated, 02577 ArrayRef<const MemRegion *> ExplicitRegions, 02578 ArrayRef<const MemRegion *> Regions, 02579 const CallEvent *Call) const; 02580 02581 bool wantsRegionChangeUpdate(ProgramStateRef state) const { 02582 return true; 02583 } 02584 02585 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const; 02586 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C, 02587 ExplodedNode *Pred, RetEffect RE, RefVal X, 02588 SymbolRef Sym, ProgramStateRef state) const; 02589 02590 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const; 02591 void checkEndFunction(CheckerContext &C) const; 02592 02593 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym, 02594 RefVal V, ArgEffect E, RefVal::Kind &hasErr, 02595 CheckerContext &C) const; 02596 02597 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange, 02598 RefVal::Kind ErrorKind, SymbolRef Sym, 02599 CheckerContext &C) const; 02600 02601 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const; 02602 02603 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const; 02604 02605 ProgramStateRef handleSymbolDeath(ProgramStateRef state, 02606 SymbolRef sid, RefVal V, 02607 SmallVectorImpl<SymbolRef> &Leaked) const; 02608 02609 ProgramStateRef 02610 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred, 02611 const ProgramPointTag *Tag, CheckerContext &Ctx, 02612 SymbolRef Sym, RefVal V) const; 02613 02614 ExplodedNode *processLeaks(ProgramStateRef state, 02615 SmallVectorImpl<SymbolRef> &Leaked, 02616 CheckerContext &Ctx, 02617 ExplodedNode *Pred = nullptr) const; 02618 }; 02619 } // end anonymous namespace 02620 02621 namespace { 02622 class StopTrackingCallback : public SymbolVisitor { 02623 ProgramStateRef state; 02624 public: 02625 StopTrackingCallback(ProgramStateRef st) : state(st) {} 02626 ProgramStateRef getState() const { return state; } 02627 02628 bool VisitSymbol(SymbolRef sym) override { 02629 state = state->remove<RefBindings>(sym); 02630 return true; 02631 } 02632 }; 02633 } // end anonymous namespace 02634 02635 //===----------------------------------------------------------------------===// 02636 // Handle statements that may have an effect on refcounts. 02637 //===----------------------------------------------------------------------===// 02638 02639 void RetainCountChecker::checkPostStmt(const BlockExpr *BE, 02640 CheckerContext &C) const { 02641 02642 // Scan the BlockDecRefExprs for any object the retain count checker 02643 // may be tracking. 02644 if (!BE->getBlockDecl()->hasCaptures()) 02645 return; 02646 02647 ProgramStateRef state = C.getState(); 02648 const BlockDataRegion *R = 02649 cast<BlockDataRegion>(state->getSVal(BE, 02650 C.getLocationContext()).getAsRegion()); 02651 02652 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(), 02653 E = R->referenced_vars_end(); 02654 02655 if (I == E) 02656 return; 02657 02658 // FIXME: For now we invalidate the tracking of all symbols passed to blocks 02659 // via captured variables, even though captured variables result in a copy 02660 // and in implicit increment/decrement of a retain count. 02661 SmallVector<const MemRegion*, 10> Regions; 02662 const LocationContext *LC = C.getLocationContext(); 02663 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager(); 02664 02665 for ( ; I != E; ++I) { 02666 const VarRegion *VR = I.getCapturedRegion(); 02667 if (VR->getSuperRegion() == R) { 02668 VR = MemMgr.getVarRegion(VR->getDecl(), LC); 02669 } 02670 Regions.push_back(VR); 02671 } 02672 02673 state = 02674 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(), 02675 Regions.data() + Regions.size()).getState(); 02676 C.addTransition(state); 02677 } 02678 02679 void RetainCountChecker::checkPostStmt(const CastExpr *CE, 02680 CheckerContext &C) const { 02681 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE); 02682 if (!BE) 02683 return; 02684 02685 ArgEffect AE = IncRef; 02686 02687 switch (BE->getBridgeKind()) { 02688 case clang::OBC_Bridge: 02689 // Do nothing. 02690 return; 02691 case clang::OBC_BridgeRetained: 02692 AE = IncRef; 02693 break; 02694 case clang::OBC_BridgeTransfer: 02695 AE = DecRefBridgedTransferred; 02696 break; 02697 } 02698 02699 ProgramStateRef state = C.getState(); 02700 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol(); 02701 if (!Sym) 02702 return; 02703 const RefVal* T = getRefBinding(state, Sym); 02704 if (!T) 02705 return; 02706 02707 RefVal::Kind hasErr = (RefVal::Kind) 0; 02708 state = updateSymbol(state, Sym, *T, AE, hasErr, C); 02709 02710 if (hasErr) { 02711 // FIXME: If we get an error during a bridge cast, should we report it? 02712 // Should we assert that there is no error? 02713 return; 02714 } 02715 02716 C.addTransition(state); 02717 } 02718 02719 void RetainCountChecker::processObjCLiterals(CheckerContext &C, 02720 const Expr *Ex) const { 02721 ProgramStateRef state = C.getState(); 02722 const ExplodedNode *pred = C.getPredecessor(); 02723 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ; 02724 it != et ; ++it) { 02725 const Stmt *child = *it; 02726 SVal V = state->getSVal(child, pred->getLocationContext()); 02727 if (SymbolRef sym = V.getAsSymbol()) 02728 if (const RefVal* T = getRefBinding(state, sym)) { 02729 RefVal::Kind hasErr = (RefVal::Kind) 0; 02730 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C); 02731 if (hasErr) { 02732 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C); 02733 return; 02734 } 02735 } 02736 } 02737 02738 // Return the object as autoreleased. 02739 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC); 02740 if (SymbolRef sym = 02741 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) { 02742 QualType ResultTy = Ex->getType(); 02743 state = setRefBinding(state, sym, 02744 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy)); 02745 } 02746 02747 C.addTransition(state); 02748 } 02749 02750 void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL, 02751 CheckerContext &C) const { 02752 // Apply the 'MayEscape' to all values. 02753 processObjCLiterals(C, AL); 02754 } 02755 02756 void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL, 02757 CheckerContext &C) const { 02758 // Apply the 'MayEscape' to all keys and values. 02759 processObjCLiterals(C, DL); 02760 } 02761 02762 void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex, 02763 CheckerContext &C) const { 02764 const ExplodedNode *Pred = C.getPredecessor(); 02765 const LocationContext *LCtx = Pred->getLocationContext(); 02766 ProgramStateRef State = Pred->getState(); 02767 02768 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) { 02769 QualType ResultTy = Ex->getType(); 02770 State = setRefBinding(State, Sym, 02771 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy)); 02772 } 02773 02774 C.addTransition(State); 02775 } 02776 02777 void RetainCountChecker::checkPostStmt(const ObjCIvarRefExpr *IRE, 02778 CheckerContext &C) const { 02779 ProgramStateRef State = C.getState(); 02780 // If an instance variable was previously accessed through a property, 02781 // it may have a synthesized refcount of +0. Override right now that we're 02782 // doing direct access. 02783 if (Optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>()) 02784 if (SymbolRef Sym = State->getSVal(*IVarLoc).getAsSymbol()) 02785 if (const RefVal *RV = getRefBinding(State, Sym)) 02786 if (RV->isOverridable()) 02787 State = removeRefBinding(State, Sym); 02788 C.addTransition(State); 02789 } 02790 02791 void RetainCountChecker::checkPostCall(const CallEvent &Call, 02792 CheckerContext &C) const { 02793 RetainSummaryManager &Summaries = getSummaryManager(C); 02794 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState()); 02795 02796 if (C.wasInlined) { 02797 processSummaryOfInlined(*Summ, Call, C); 02798 return; 02799 } 02800 checkSummary(*Summ, Call, C); 02801 } 02802 02803 /// GetReturnType - Used to get the return type of a message expression or 02804 /// function call with the intention of affixing that type to a tracked symbol. 02805 /// While the return type can be queried directly from RetEx, when 02806 /// invoking class methods we augment to the return type to be that of 02807 /// a pointer to the class (as opposed it just being id). 02808 // FIXME: We may be able to do this with related result types instead. 02809 // This function is probably overestimating. 02810 static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) { 02811 QualType RetTy = RetE->getType(); 02812 // If RetE is not a message expression just return its type. 02813 // If RetE is a message expression, return its types if it is something 02814 /// more specific than id. 02815 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE)) 02816 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>()) 02817 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() || 02818 PT->isObjCClassType()) { 02819 // At this point we know the return type of the message expression is 02820 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this 02821 // is a call to a class method whose type we can resolve. In such 02822 // cases, promote the return type to XXX* (where XXX is the class). 02823 const ObjCInterfaceDecl *D = ME->getReceiverInterface(); 02824 return !D ? RetTy : 02825 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D)); 02826 } 02827 02828 return RetTy; 02829 } 02830 02831 static bool wasSynthesizedProperty(const ObjCMethodCall *Call, 02832 ExplodedNode *N) { 02833 if (!Call || !Call->getDecl()->isPropertyAccessor()) 02834 return false; 02835 02836 CallExitEnd PP = N->getLocation().castAs<CallExitEnd>(); 02837 const StackFrameContext *Frame = PP.getCalleeContext(); 02838 return Frame->getAnalysisDeclContext()->isBodyAutosynthesized(); 02839 } 02840 02841 // We don't always get the exact modeling of the function with regards to the 02842 // retain count checker even when the function is inlined. For example, we need 02843 // to stop tracking the symbols which were marked with StopTrackingHard. 02844 void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ, 02845 const CallEvent &CallOrMsg, 02846 CheckerContext &C) const { 02847 ProgramStateRef state = C.getState(); 02848 02849 // Evaluate the effect of the arguments. 02850 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) { 02851 if (Summ.getArg(idx) == StopTrackingHard) { 02852 SVal V = CallOrMsg.getArgSVal(idx); 02853 if (SymbolRef Sym = V.getAsLocSymbol()) { 02854 state = removeRefBinding(state, Sym); 02855 } 02856 } 02857 } 02858 02859 // Evaluate the effect on the message receiver. 02860 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg); 02861 if (MsgInvocation) { 02862 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) { 02863 if (Summ.getReceiverEffect() == StopTrackingHard) { 02864 state = removeRefBinding(state, Sym); 02865 } 02866 } 02867 } 02868 02869 // Consult the summary for the return value. 02870 RetEffect RE = Summ.getRetEffect(); 02871 if (RE.getKind() == RetEffect::NoRetHard) { 02872 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol(); 02873 if (Sym) 02874 state = removeRefBinding(state, Sym); 02875 } else if (RE.getKind() == RetEffect::NotOwnedSymbol) { 02876 if (wasSynthesizedProperty(MsgInvocation, C.getPredecessor())) { 02877 // Believe the summary if we synthesized the body of a property getter 02878 // and the return value is currently untracked. If the corresponding 02879 // instance variable is later accessed directly, however, we're going to 02880 // want to override this state, so that the owning object can perform 02881 // reference counting operations on its own ivars. 02882 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol(); 02883 if (Sym && !getRefBinding(state, Sym)) 02884 state = setRefBinding(state, Sym, 02885 RefVal::makeOverridableNotOwned(RE.getObjKind(), 02886 Sym->getType())); 02887 } 02888 } 02889 02890 C.addTransition(state); 02891 } 02892 02893 void RetainCountChecker::checkSummary(const RetainSummary &Summ, 02894 const CallEvent &CallOrMsg, 02895 CheckerContext &C) const { 02896 ProgramStateRef state = C.getState(); 02897 02898 // Evaluate the effect of the arguments. 02899 RefVal::Kind hasErr = (RefVal::Kind) 0; 02900 SourceRange ErrorRange; 02901 SymbolRef ErrorSym = nullptr; 02902 02903 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) { 02904 SVal V = CallOrMsg.getArgSVal(idx); 02905 02906 if (SymbolRef Sym = V.getAsLocSymbol()) { 02907 if (const RefVal *T = getRefBinding(state, Sym)) { 02908 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C); 02909 if (hasErr) { 02910 ErrorRange = CallOrMsg.getArgSourceRange(idx); 02911 ErrorSym = Sym; 02912 break; 02913 } 02914 } 02915 } 02916 } 02917 02918 // Evaluate the effect on the message receiver. 02919 bool ReceiverIsTracked = false; 02920 if (!hasErr) { 02921 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg); 02922 if (MsgInvocation) { 02923 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) { 02924 if (const RefVal *T = getRefBinding(state, Sym)) { 02925 ReceiverIsTracked = true; 02926 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(), 02927 hasErr, C); 02928 if (hasErr) { 02929 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange(); 02930 ErrorSym = Sym; 02931 } 02932 } 02933 } 02934 } 02935 } 02936 02937 // Process any errors. 02938 if (hasErr) { 02939 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C); 02940 return; 02941 } 02942 02943 // Consult the summary for the return value. 02944 RetEffect RE = Summ.getRetEffect(); 02945 02946 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) { 02947 if (ReceiverIsTracked) 02948 RE = getSummaryManager(C).getObjAllocRetEffect(); 02949 else 02950 RE = RetEffect::MakeNoRet(); 02951 } 02952 02953 switch (RE.getKind()) { 02954 default: 02955 llvm_unreachable("Unhandled RetEffect."); 02956 02957 case RetEffect::NoRet: 02958 case RetEffect::NoRetHard: 02959 // No work necessary. 02960 break; 02961 02962 case RetEffect::OwnedAllocatedSymbol: 02963 case RetEffect::OwnedSymbol: { 02964 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol(); 02965 if (!Sym) 02966 break; 02967 02968 // Use the result type from the CallEvent as it automatically adjusts 02969 // for methods/functions that return references. 02970 QualType ResultTy = CallOrMsg.getResultType(); 02971 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(), 02972 ResultTy)); 02973 02974 // FIXME: Add a flag to the checker where allocations are assumed to 02975 // *not* fail. 02976 break; 02977 } 02978 02979 case RetEffect::GCNotOwnedSymbol: 02980 case RetEffect::NotOwnedSymbol: { 02981 const Expr *Ex = CallOrMsg.getOriginExpr(); 02982 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol(); 02983 if (!Sym) 02984 break; 02985 assert(Ex); 02986 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *. 02987 QualType ResultTy = GetReturnType(Ex, C.getASTContext()); 02988 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(), 02989 ResultTy)); 02990 break; 02991 } 02992 } 02993 02994 // This check is actually necessary; otherwise the statement builder thinks 02995 // we've hit a previously-found path. 02996 // Normally addTransition takes care of this, but we want the node pointer. 02997 ExplodedNode *NewNode; 02998 if (state == C.getState()) { 02999 NewNode = C.getPredecessor(); 03000 } else { 03001 NewNode = C.addTransition(state); 03002 } 03003 03004 // Annotate the node with summary we used. 03005 if (NewNode) { 03006 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary. 03007 if (ShouldResetSummaryLog) { 03008 SummaryLog.clear(); 03009 ShouldResetSummaryLog = false; 03010 } 03011 SummaryLog[NewNode] = &Summ; 03012 } 03013 } 03014 03015 03016 ProgramStateRef 03017 RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym, 03018 RefVal V, ArgEffect E, RefVal::Kind &hasErr, 03019 CheckerContext &C) const { 03020 // In GC mode [... release] and [... retain] do nothing. 03021 // In ARC mode they shouldn't exist at all, but we just ignore them. 03022 bool IgnoreRetainMsg = C.isObjCGCEnabled(); 03023 if (!IgnoreRetainMsg) 03024 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount; 03025 03026 switch (E) { 03027 default: 03028 break; 03029 case IncRefMsg: 03030 E = IgnoreRetainMsg ? DoNothing : IncRef; 03031 break; 03032 case DecRefMsg: 03033 E = IgnoreRetainMsg ? DoNothing : DecRef; 03034 break; 03035 case DecRefMsgAndStopTrackingHard: 03036 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard; 03037 break; 03038 case MakeCollectable: 03039 E = C.isObjCGCEnabled() ? DecRef : DoNothing; 03040 break; 03041 } 03042 03043 // Handle all use-after-releases. 03044 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) { 03045 V = V ^ RefVal::ErrorUseAfterRelease; 03046 hasErr = V.getKind(); 03047 return setRefBinding(state, sym, V); 03048 } 03049 03050 switch (E) { 03051 case DecRefMsg: 03052 case IncRefMsg: 03053 case MakeCollectable: 03054 case DecRefMsgAndStopTrackingHard: 03055 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted"); 03056 03057 case Dealloc: 03058 // Any use of -dealloc in GC is *bad*. 03059 if (C.isObjCGCEnabled()) { 03060 V = V ^ RefVal::ErrorDeallocGC; 03061 hasErr = V.getKind(); 03062 break; 03063 } 03064 03065 switch (V.getKind()) { 03066 default: 03067 llvm_unreachable("Invalid RefVal state for an explicit dealloc."); 03068 case RefVal::Owned: 03069 // The object immediately transitions to the released state. 03070 V = V ^ RefVal::Released; 03071 V.clearCounts(); 03072 return setRefBinding(state, sym, V); 03073 case RefVal::NotOwned: 03074 V = V ^ RefVal::ErrorDeallocNotOwned; 03075 hasErr = V.getKind(); 03076 break; 03077 } 03078 break; 03079 03080 case MayEscape: 03081 if (V.getKind() == RefVal::Owned) { 03082 V = V ^ RefVal::NotOwned; 03083 break; 03084 } 03085 03086 // Fall-through. 03087 03088 case DoNothing: 03089 return state; 03090 03091 case Autorelease: 03092 if (C.isObjCGCEnabled()) 03093 return state; 03094 // Update the autorelease counts. 03095 V = V.autorelease(); 03096 break; 03097 03098 case StopTracking: 03099 case StopTrackingHard: 03100 return removeRefBinding(state, sym); 03101 03102 case IncRef: 03103 switch (V.getKind()) { 03104 default: 03105 llvm_unreachable("Invalid RefVal state for a retain."); 03106 case RefVal::Owned: 03107 case RefVal::NotOwned: 03108 V = V + 1; 03109 break; 03110 case RefVal::Released: 03111 // Non-GC cases are handled above. 03112 assert(C.isObjCGCEnabled()); 03113 V = (V ^ RefVal::Owned) + 1; 03114 break; 03115 } 03116 break; 03117 03118 case DecRef: 03119 case DecRefBridgedTransferred: 03120 case DecRefAndStopTrackingHard: 03121 switch (V.getKind()) { 03122 default: 03123 // case 'RefVal::Released' handled above. 03124 llvm_unreachable("Invalid RefVal state for a release."); 03125 03126 case RefVal::Owned: 03127 assert(V.getCount() > 0); 03128 if (V.getCount() == 1) 03129 V = V ^ (E == DecRefBridgedTransferred ? RefVal::NotOwned 03130 : RefVal::Released); 03131 else if (E == DecRefAndStopTrackingHard) 03132 return removeRefBinding(state, sym); 03133 03134 V = V - 1; 03135 break; 03136 03137 case RefVal::NotOwned: 03138 if (V.getCount() > 0) { 03139 if (E == DecRefAndStopTrackingHard) 03140 return removeRefBinding(state, sym); 03141 V = V - 1; 03142 } else { 03143 V = V ^ RefVal::ErrorReleaseNotOwned; 03144 hasErr = V.getKind(); 03145 } 03146 break; 03147 03148 case RefVal::Released: 03149 // Non-GC cases are handled above. 03150 assert(C.isObjCGCEnabled()); 03151 V = V ^ RefVal::ErrorUseAfterRelease; 03152 hasErr = V.getKind(); 03153 break; 03154 } 03155 break; 03156 } 03157 return setRefBinding(state, sym, V); 03158 } 03159 03160 void RetainCountChecker::processNonLeakError(ProgramStateRef St, 03161 SourceRange ErrorRange, 03162 RefVal::Kind ErrorKind, 03163 SymbolRef Sym, 03164 CheckerContext &C) const { 03165 ExplodedNode *N = C.generateSink(St); 03166 if (!N) 03167 return; 03168 03169 CFRefBug *BT; 03170 switch (ErrorKind) { 03171 default: 03172 llvm_unreachable("Unhandled error."); 03173 case RefVal::ErrorUseAfterRelease: 03174 if (!useAfterRelease) 03175 useAfterRelease.reset(new UseAfterRelease(this)); 03176 BT = &*useAfterRelease; 03177 break; 03178 case RefVal::ErrorReleaseNotOwned: 03179 if (!releaseNotOwned) 03180 releaseNotOwned.reset(new BadRelease(this)); 03181 BT = &*releaseNotOwned; 03182 break; 03183 case RefVal::ErrorDeallocGC: 03184 if (!deallocGC) 03185 deallocGC.reset(new DeallocGC(this)); 03186 BT = &*deallocGC; 03187 break; 03188 case RefVal::ErrorDeallocNotOwned: 03189 if (!deallocNotOwned) 03190 deallocNotOwned.reset(new DeallocNotOwned(this)); 03191 BT = &*deallocNotOwned; 03192 break; 03193 } 03194 03195 assert(BT); 03196 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(), 03197 C.isObjCGCEnabled(), SummaryLog, 03198 N, Sym); 03199 report->addRange(ErrorRange); 03200 C.emitReport(report); 03201 } 03202 03203 //===----------------------------------------------------------------------===// 03204 // Handle the return values of retain-count-related functions. 03205 //===----------------------------------------------------------------------===// 03206 03207 bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const { 03208 // Get the callee. We're only interested in simple C functions. 03209 ProgramStateRef state = C.getState(); 03210 const FunctionDecl *FD = C.getCalleeDecl(CE); 03211 if (!FD) 03212 return false; 03213 03214 IdentifierInfo *II = FD->getIdentifier(); 03215 if (!II) 03216 return false; 03217 03218 // For now, we're only handling the functions that return aliases of their 03219 // arguments: CFRetain and CFMakeCollectable (and their families). 03220 // Eventually we should add other functions we can model entirely, 03221 // such as CFRelease, which don't invalidate their arguments or globals. 03222 if (CE->getNumArgs() != 1) 03223 return false; 03224 03225 // Get the name of the function. 03226 StringRef FName = II->getName(); 03227 FName = FName.substr(FName.find_first_not_of('_')); 03228 03229 // See if it's one of the specific functions we know how to eval. 03230 bool canEval = false; 03231 03232 QualType ResultTy = CE->getCallReturnType(); 03233 if (ResultTy->isObjCIdType()) { 03234 // Handle: id NSMakeCollectable(CFTypeRef) 03235 canEval = II->isStr("NSMakeCollectable"); 03236 } else if (ResultTy->isPointerType()) { 03237 // Handle: (CF|CG)Retain 03238 // CFAutorelease 03239 // CFMakeCollectable 03240 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist). 03241 if (cocoa::isRefType(ResultTy, "CF", FName) || 03242 cocoa::isRefType(ResultTy, "CG", FName)) { 03243 canEval = isRetain(FD, FName) || isAutorelease(FD, FName) || 03244 isMakeCollectable(FD, FName); 03245 } 03246 } 03247 03248 if (!canEval) 03249 return false; 03250 03251 // Bind the return value. 03252 const LocationContext *LCtx = C.getLocationContext(); 03253 SVal RetVal = state->getSVal(CE->getArg(0), LCtx); 03254 if (RetVal.isUnknown()) { 03255 // If the receiver is unknown, conjure a return value. 03256 SValBuilder &SVB = C.getSValBuilder(); 03257 RetVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, ResultTy, C.blockCount()); 03258 } 03259 state = state->BindExpr(CE, LCtx, RetVal, false); 03260 03261 // FIXME: This should not be necessary, but otherwise the argument seems to be 03262 // considered alive during the next statement. 03263 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) { 03264 // Save the refcount status of the argument. 03265 SymbolRef Sym = RetVal.getAsLocSymbol(); 03266 const RefVal *Binding = nullptr; 03267 if (Sym) 03268 Binding = getRefBinding(state, Sym); 03269 03270 // Invalidate the argument region. 03271 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx, 03272 /*CausesPointerEscape*/ false); 03273 03274 // Restore the refcount status of the argument. 03275 if (Binding) 03276 state = setRefBinding(state, Sym, *Binding); 03277 } 03278 03279 C.addTransition(state); 03280 return true; 03281 } 03282 03283 //===----------------------------------------------------------------------===// 03284 // Handle return statements. 03285 //===----------------------------------------------------------------------===// 03286 03287 void RetainCountChecker::checkPreStmt(const ReturnStmt *S, 03288 CheckerContext &C) const { 03289 03290 // Only adjust the reference count if this is the top-level call frame, 03291 // and not the result of inlining. In the future, we should do 03292 // better checking even for inlined calls, and see if they match 03293 // with their expected semantics (e.g., the method should return a retained 03294 // object, etc.). 03295 if (!C.inTopFrame()) 03296 return; 03297 03298 const Expr *RetE = S->getRetValue(); 03299 if (!RetE) 03300 return; 03301 03302 ProgramStateRef state = C.getState(); 03303 SymbolRef Sym = 03304 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol(); 03305 if (!Sym) 03306 return; 03307 03308 // Get the reference count binding (if any). 03309 const RefVal *T = getRefBinding(state, Sym); 03310 if (!T) 03311 return; 03312 03313 // Change the reference count. 03314 RefVal X = *T; 03315 03316 switch (X.getKind()) { 03317 case RefVal::Owned: { 03318 unsigned cnt = X.getCount(); 03319 assert(cnt > 0); 03320 X.setCount(cnt - 1); 03321 X = X ^ RefVal::ReturnedOwned; 03322 break; 03323 } 03324 03325 case RefVal::NotOwned: { 03326 unsigned cnt = X.getCount(); 03327 if (cnt) { 03328 X.setCount(cnt - 1); 03329 X = X ^ RefVal::ReturnedOwned; 03330 } 03331 else { 03332 X = X ^ RefVal::ReturnedNotOwned; 03333 } 03334 break; 03335 } 03336 03337 default: 03338 return; 03339 } 03340 03341 // Update the binding. 03342 state = setRefBinding(state, Sym, X); 03343 ExplodedNode *Pred = C.addTransition(state); 03344 03345 // At this point we have updated the state properly. 03346 // Everything after this is merely checking to see if the return value has 03347 // been over- or under-retained. 03348 03349 // Did we cache out? 03350 if (!Pred) 03351 return; 03352 03353 // Update the autorelease counts. 03354 static CheckerProgramPointTag AutoreleaseTag(this, "Autorelease"); 03355 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X); 03356 03357 // Did we cache out? 03358 if (!state) 03359 return; 03360 03361 // Get the updated binding. 03362 T = getRefBinding(state, Sym); 03363 assert(T); 03364 X = *T; 03365 03366 // Consult the summary of the enclosing method. 03367 RetainSummaryManager &Summaries = getSummaryManager(C); 03368 const Decl *CD = &Pred->getCodeDecl(); 03369 RetEffect RE = RetEffect::MakeNoRet(); 03370 03371 // FIXME: What is the convention for blocks? Is there one? 03372 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) { 03373 const RetainSummary *Summ = Summaries.getMethodSummary(MD); 03374 RE = Summ->getRetEffect(); 03375 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) { 03376 if (!isa<CXXMethodDecl>(FD)) { 03377 const RetainSummary *Summ = Summaries.getFunctionSummary(FD); 03378 RE = Summ->getRetEffect(); 03379 } 03380 } 03381 03382 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state); 03383 } 03384 03385 void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S, 03386 CheckerContext &C, 03387 ExplodedNode *Pred, 03388 RetEffect RE, RefVal X, 03389 SymbolRef Sym, 03390 ProgramStateRef state) const { 03391 // Any leaks or other errors? 03392 if (X.isReturnedOwned() && X.getCount() == 0) { 03393 if (RE.getKind() != RetEffect::NoRet) { 03394 bool hasError = false; 03395 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) { 03396 // Things are more complicated with garbage collection. If the 03397 // returned object is suppose to be an Objective-C object, we have 03398 // a leak (as the caller expects a GC'ed object) because no 03399 // method should return ownership unless it returns a CF object. 03400 hasError = true; 03401 X = X ^ RefVal::ErrorGCLeakReturned; 03402 } 03403 else if (!RE.isOwned()) { 03404 // Either we are using GC and the returned object is a CF type 03405 // or we aren't using GC. In either case, we expect that the 03406 // enclosing method is expected to return ownership. 03407 hasError = true; 03408 X = X ^ RefVal::ErrorLeakReturned; 03409 } 03410 03411 if (hasError) { 03412 // Generate an error node. 03413 state = setRefBinding(state, Sym, X); 03414 03415 static CheckerProgramPointTag ReturnOwnLeakTag(this, "ReturnsOwnLeak"); 03416 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag); 03417 if (N) { 03418 const LangOptions &LOpts = C.getASTContext().getLangOpts(); 03419 bool GCEnabled = C.isObjCGCEnabled(); 03420 CFRefReport *report = 03421 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled), 03422 LOpts, GCEnabled, SummaryLog, 03423 N, Sym, C, IncludeAllocationLine); 03424 03425 C.emitReport(report); 03426 } 03427 } 03428 } 03429 } else if (X.isReturnedNotOwned()) { 03430 if (RE.isOwned()) { 03431 // Trying to return a not owned object to a caller expecting an 03432 // owned object. 03433 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned); 03434 03435 static CheckerProgramPointTag ReturnNotOwnedTag(this, 03436 "ReturnNotOwnedForOwned"); 03437 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag); 03438 if (N) { 03439 if (!returnNotOwnedForOwned) 03440 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned(this)); 03441 03442 CFRefReport *report = 03443 new CFRefReport(*returnNotOwnedForOwned, 03444 C.getASTContext().getLangOpts(), 03445 C.isObjCGCEnabled(), SummaryLog, N, Sym); 03446 C.emitReport(report); 03447 } 03448 } 03449 } 03450 } 03451 03452 //===----------------------------------------------------------------------===// 03453 // Check various ways a symbol can be invalidated. 03454 //===----------------------------------------------------------------------===// 03455 03456 void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S, 03457 CheckerContext &C) const { 03458 // Are we storing to something that causes the value to "escape"? 03459 bool escapes = true; 03460 03461 // A value escapes in three possible cases (this may change): 03462 // 03463 // (1) we are binding to something that is not a memory region. 03464 // (2) we are binding to a memregion that does not have stack storage 03465 // (3) we are binding to a memregion with stack storage that the store 03466 // does not understand. 03467 ProgramStateRef state = C.getState(); 03468 03469 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) { 03470 escapes = !regionLoc->getRegion()->hasStackStorage(); 03471 03472 if (!escapes) { 03473 // To test (3), generate a new state with the binding added. If it is 03474 // the same state, then it escapes (since the store cannot represent 03475 // the binding). 03476 // Do this only if we know that the store is not supposed to generate the 03477 // same state. 03478 SVal StoredVal = state->getSVal(regionLoc->getRegion()); 03479 if (StoredVal != val) 03480 escapes = (state == (state->bindLoc(*regionLoc, val))); 03481 } 03482 if (!escapes) { 03483 // Case 4: We do not currently model what happens when a symbol is 03484 // assigned to a struct field, so be conservative here and let the symbol 03485 // go. TODO: This could definitely be improved upon. 03486 escapes = !isa<VarRegion>(regionLoc->getRegion()); 03487 } 03488 } 03489 03490 // If we are storing the value into an auto function scope variable annotated 03491 // with (__attribute__((cleanup))), stop tracking the value to avoid leak 03492 // false positives. 03493 if (const VarRegion *LVR = dyn_cast_or_null<VarRegion>(loc.getAsRegion())) { 03494 const VarDecl *VD = LVR->getDecl(); 03495 if (VD->hasAttr<CleanupAttr>()) { 03496 escapes = true; 03497 } 03498 } 03499 03500 // If our store can represent the binding and we aren't storing to something 03501 // that doesn't have local storage then just return and have the simulation 03502 // state continue as is. 03503 if (!escapes) 03504 return; 03505 03506 // Otherwise, find all symbols referenced by 'val' that we are tracking 03507 // and stop tracking them. 03508 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState(); 03509 C.addTransition(state); 03510 } 03511 03512 ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state, 03513 SVal Cond, 03514 bool Assumption) const { 03515 03516 // FIXME: We may add to the interface of evalAssume the list of symbols 03517 // whose assumptions have changed. For now we just iterate through the 03518 // bindings and check if any of the tracked symbols are NULL. This isn't 03519 // too bad since the number of symbols we will track in practice are 03520 // probably small and evalAssume is only called at branches and a few 03521 // other places. 03522 RefBindingsTy B = state->get<RefBindings>(); 03523 03524 if (B.isEmpty()) 03525 return state; 03526 03527 bool changed = false; 03528 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>(); 03529 03530 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) { 03531 // Check if the symbol is null stop tracking the symbol. 03532 ConstraintManager &CMgr = state->getConstraintManager(); 03533 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey()); 03534 if (AllocFailed.isConstrainedTrue()) { 03535 changed = true; 03536 B = RefBFactory.remove(B, I.getKey()); 03537 } 03538 } 03539 03540 if (changed) 03541 state = state->set<RefBindings>(B); 03542 03543 return state; 03544 } 03545 03546 ProgramStateRef 03547 RetainCountChecker::checkRegionChanges(ProgramStateRef state, 03548 const InvalidatedSymbols *invalidated, 03549 ArrayRef<const MemRegion *> ExplicitRegions, 03550 ArrayRef<const MemRegion *> Regions, 03551 const CallEvent *Call) const { 03552 if (!invalidated) 03553 return state; 03554 03555 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols; 03556 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(), 03557 E = ExplicitRegions.end(); I != E; ++I) { 03558 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>()) 03559 WhitelistedSymbols.insert(SR->getSymbol()); 03560 } 03561 03562 for (InvalidatedSymbols::const_iterator I=invalidated->begin(), 03563 E = invalidated->end(); I!=E; ++I) { 03564 SymbolRef sym = *I; 03565 if (WhitelistedSymbols.count(sym)) 03566 continue; 03567 // Remove any existing reference-count binding. 03568 state = removeRefBinding(state, sym); 03569 } 03570 return state; 03571 } 03572 03573 //===----------------------------------------------------------------------===// 03574 // Handle dead symbols and end-of-path. 03575 //===----------------------------------------------------------------------===// 03576 03577 ProgramStateRef 03578 RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state, 03579 ExplodedNode *Pred, 03580 const ProgramPointTag *Tag, 03581 CheckerContext &Ctx, 03582 SymbolRef Sym, RefVal V) const { 03583 unsigned ACnt = V.getAutoreleaseCount(); 03584 03585 // No autorelease counts? Nothing to be done. 03586 if (!ACnt) 03587 return state; 03588 03589 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?"); 03590 unsigned Cnt = V.getCount(); 03591 03592 // FIXME: Handle sending 'autorelease' to already released object. 03593 03594 if (V.getKind() == RefVal::ReturnedOwned) 03595 ++Cnt; 03596 03597 if (ACnt <= Cnt) { 03598 if (ACnt == Cnt) { 03599 V.clearCounts(); 03600 if (V.getKind() == RefVal::ReturnedOwned) 03601 V = V ^ RefVal::ReturnedNotOwned; 03602 else 03603 V = V ^ RefVal::NotOwned; 03604 } else { 03605 V.setCount(V.getCount() - ACnt); 03606 V.setAutoreleaseCount(0); 03607 } 03608 return setRefBinding(state, Sym, V); 03609 } 03610 03611 // Woah! More autorelease counts then retain counts left. 03612 // Emit hard error. 03613 V = V ^ RefVal::ErrorOverAutorelease; 03614 state = setRefBinding(state, Sym, V); 03615 03616 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag); 03617 if (N) { 03618 SmallString<128> sbuf; 03619 llvm::raw_svector_ostream os(sbuf); 03620 os << "Object was autoreleased "; 03621 if (V.getAutoreleaseCount() > 1) 03622 os << V.getAutoreleaseCount() << " times but the object "; 03623 else 03624 os << "but "; 03625 os << "has a +" << V.getCount() << " retain count"; 03626 03627 if (!overAutorelease) 03628 overAutorelease.reset(new OverAutorelease(this)); 03629 03630 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts(); 03631 CFRefReport *report = 03632 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false, 03633 SummaryLog, N, Sym, os.str()); 03634 Ctx.emitReport(report); 03635 } 03636 03637 return nullptr; 03638 } 03639 03640 ProgramStateRef 03641 RetainCountChecker::handleSymbolDeath(ProgramStateRef state, 03642 SymbolRef sid, RefVal V, 03643 SmallVectorImpl<SymbolRef> &Leaked) const { 03644 bool hasLeak = false; 03645 if (V.isOwned()) 03646 hasLeak = true; 03647 else if (V.isNotOwned() || V.isReturnedOwned()) 03648 hasLeak = (V.getCount() > 0); 03649 03650 if (!hasLeak) 03651 return removeRefBinding(state, sid); 03652 03653 Leaked.push_back(sid); 03654 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak); 03655 } 03656 03657 ExplodedNode * 03658 RetainCountChecker::processLeaks(ProgramStateRef state, 03659 SmallVectorImpl<SymbolRef> &Leaked, 03660 CheckerContext &Ctx, 03661 ExplodedNode *Pred) const { 03662 // Generate an intermediate node representing the leak point. 03663 ExplodedNode *N = Ctx.addTransition(state, Pred); 03664 03665 if (N) { 03666 for (SmallVectorImpl<SymbolRef>::iterator 03667 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) { 03668 03669 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts(); 03670 bool GCEnabled = Ctx.isObjCGCEnabled(); 03671 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled) 03672 : getLeakAtReturnBug(LOpts, GCEnabled); 03673 assert(BT && "BugType not initialized."); 03674 03675 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled, 03676 SummaryLog, N, *I, Ctx, 03677 IncludeAllocationLine); 03678 Ctx.emitReport(report); 03679 } 03680 } 03681 03682 return N; 03683 } 03684 03685 void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const { 03686 ProgramStateRef state = Ctx.getState(); 03687 RefBindingsTy B = state->get<RefBindings>(); 03688 ExplodedNode *Pred = Ctx.getPredecessor(); 03689 03690 // Don't process anything within synthesized bodies. 03691 const LocationContext *LCtx = Pred->getLocationContext(); 03692 if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) { 03693 assert(LCtx->getParent()); 03694 return; 03695 } 03696 03697 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) { 03698 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/nullptr, Ctx, 03699 I->first, I->second); 03700 if (!state) 03701 return; 03702 } 03703 03704 // If the current LocationContext has a parent, don't check for leaks. 03705 // We will do that later. 03706 // FIXME: we should instead check for imbalances of the retain/releases, 03707 // and suggest annotations. 03708 if (LCtx->getParent()) 03709 return; 03710 03711 B = state->get<RefBindings>(); 03712 SmallVector<SymbolRef, 10> Leaked; 03713 03714 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) 03715 state = handleSymbolDeath(state, I->first, I->second, Leaked); 03716 03717 processLeaks(state, Leaked, Ctx, Pred); 03718 } 03719 03720 const ProgramPointTag * 03721 RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const { 03722 const CheckerProgramPointTag *&tag = DeadSymbolTags[sym]; 03723 if (!tag) { 03724 SmallString<64> buf; 03725 llvm::raw_svector_ostream out(buf); 03726 out << "Dead Symbol : "; 03727 sym->dumpToStream(out); 03728 tag = new CheckerProgramPointTag(this, out.str()); 03729 } 03730 return tag; 03731 } 03732 03733 void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper, 03734 CheckerContext &C) const { 03735 ExplodedNode *Pred = C.getPredecessor(); 03736 03737 ProgramStateRef state = C.getState(); 03738 RefBindingsTy B = state->get<RefBindings>(); 03739 SmallVector<SymbolRef, 10> Leaked; 03740 03741 // Update counts from autorelease pools 03742 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), 03743 E = SymReaper.dead_end(); I != E; ++I) { 03744 SymbolRef Sym = *I; 03745 if (const RefVal *T = B.lookup(Sym)){ 03746 // Use the symbol as the tag. 03747 // FIXME: This might not be as unique as we would like. 03748 const ProgramPointTag *Tag = getDeadSymbolTag(Sym); 03749 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T); 03750 if (!state) 03751 return; 03752 03753 // Fetch the new reference count from the state, and use it to handle 03754 // this symbol. 03755 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked); 03756 } 03757 } 03758 03759 if (Leaked.empty()) { 03760 C.addTransition(state); 03761 return; 03762 } 03763 03764 Pred = processLeaks(state, Leaked, C, Pred); 03765 03766 // Did we cache out? 03767 if (!Pred) 03768 return; 03769 03770 // Now generate a new node that nukes the old bindings. 03771 // The only bindings left at this point are the leaked symbols. 03772 RefBindingsTy::Factory &F = state->get_context<RefBindings>(); 03773 B = state->get<RefBindings>(); 03774 03775 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(), 03776 E = Leaked.end(); 03777 I != E; ++I) 03778 B = F.remove(B, *I); 03779 03780 state = state->set<RefBindings>(B); 03781 C.addTransition(state, Pred); 03782 } 03783 03784 void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State, 03785 const char *NL, const char *Sep) const { 03786 03787 RefBindingsTy B = State->get<RefBindings>(); 03788 03789 if (B.isEmpty()) 03790 return; 03791 03792 Out << Sep << NL; 03793 03794 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) { 03795 Out << I->first << " : "; 03796 I->second.print(Out); 03797 Out << NL; 03798 } 03799 } 03800 03801 //===----------------------------------------------------------------------===// 03802 // Checker registration. 03803 //===----------------------------------------------------------------------===// 03804 03805 void ento::registerRetainCountChecker(CheckerManager &Mgr) { 03806 Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions()); 03807 } 03808 03809 //===----------------------------------------------------------------------===// 03810 // Implementation of the CallEffects API. 03811 //===----------------------------------------------------------------------===// 03812 03813 namespace clang { namespace ento { namespace objc_retain { 03814 03815 // This is a bit gross, but it allows us to populate CallEffects without 03816 // creating a bunch of accessors. This kind is very localized, so the 03817 // damage of this macro is limited. 03818 #define createCallEffect(D, KIND)\ 03819 ASTContext &Ctx = D->getASTContext();\ 03820 LangOptions L = Ctx.getLangOpts();\ 03821 RetainSummaryManager M(Ctx, L.GCOnly, L.ObjCAutoRefCount);\ 03822 const RetainSummary *S = M.get ## KIND ## Summary(D);\ 03823 CallEffects CE(S->getRetEffect());\ 03824 CE.Receiver = S->getReceiverEffect();\ 03825 unsigned N = D->param_size();\ 03826 for (unsigned i = 0; i < N; ++i) {\ 03827 CE.Args.push_back(S->getArg(i));\ 03828 } 03829 03830 CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) { 03831 createCallEffect(MD, Method); 03832 return CE; 03833 } 03834 03835 CallEffects CallEffects::getEffect(const FunctionDecl *FD) { 03836 createCallEffect(FD, Function); 03837 return CE; 03838 } 03839 03840 #undef createCallEffect 03841 03842 }}}