1 //==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- C++ -*--//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the methods for RetainCountChecker, which implements
11 // a reference count checker for Core Foundation and Cocoa on (Mac OS X).
13 //===----------------------------------------------------------------------===//
15 #include "ClangSACheckers.h"
16 #include "AllocationDiagnostics.h"
17 #include "SelectorExtras.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/ParentMap.h"
22 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
23 #include "clang/Basic/LangOptions.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
26 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
27 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
28 #include "clang/StaticAnalyzer/Core/Checker.h"
29 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
30 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
31 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
32 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
33 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/FoldingSet.h"
36 #include "llvm/ADT/ImmutableList.h"
37 #include "llvm/ADT/ImmutableMap.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SmallString.h"
40 #include "llvm/ADT/StringExtras.h"
43 using namespace clang;
45 using namespace objc_retain;
46 using llvm::StrInStrNoCase;
48 //===----------------------------------------------------------------------===//
49 // Adapters for FoldingSet.
50 //===----------------------------------------------------------------------===//
53 template <> struct FoldingSetTrait<ArgEffect> {
54 static inline void Profile(const ArgEffect X, FoldingSetNodeID &ID) {
55 ID.AddInteger((unsigned) X);
58 template <> struct FoldingSetTrait<RetEffect> {
59 static inline void Profile(const RetEffect &X, FoldingSetNodeID &ID) {
60 ID.AddInteger((unsigned) X.getKind());
61 ID.AddInteger((unsigned) X.getObjKind());
64 } // end llvm namespace
66 //===----------------------------------------------------------------------===//
67 // Reference-counting logic (typestate + counts).
68 //===----------------------------------------------------------------------===//
70 /// ArgEffects summarizes the effects of a function/method call on all of
72 typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
78 Owned = 0, // Owning reference.
79 NotOwned, // Reference is not owned by still valid (not freed).
80 Released, // Object has been released.
81 ReturnedOwned, // Returned object passes ownership to caller.
82 ReturnedNotOwned, // Return object does not pass ownership to caller.
84 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
85 ErrorDeallocGC, // Calling -dealloc with GC enabled.
86 ErrorUseAfterRelease, // Object used after released.
87 ErrorReleaseNotOwned, // Release of an object that was not owned.
89 ErrorLeak, // A memory leak due to excessive reference counts.
90 ErrorLeakReturned, // A memory leak due to the returning method not having
91 // the correct naming conventions.
97 /// Tracks how an object referenced by an ivar has been used.
99 /// This accounts for us not knowing if an arbitrary ivar is supposed to be
100 /// stored at +0 or +1.
101 enum class IvarAccessHistory {
104 ReleasedAfterDirectAccess
108 /// The number of outstanding retains.
110 /// The number of outstanding autoreleases.
112 /// The (static) type of the object at the time we started tracking it.
115 /// The current state of the object.
117 /// See the RefVal::Kind enum for possible values.
118 unsigned RawKind : 5;
120 /// The kind of object being tracked (CF or ObjC), if known.
122 /// See the RetEffect::ObjKind enum for possible values.
123 unsigned RawObjectKind : 2;
125 /// True if the current state and/or retain count may turn out to not be the
126 /// best possible approximation of the reference counting state.
128 /// If true, the checker may decide to throw away ("override") this state
129 /// in favor of something else when it sees the object being used in new ways.
131 /// This setting should not be propagated to state derived from this state.
132 /// Once we start deriving new states, it would be inconsistent to override
134 unsigned RawIvarAccessHistory : 2;
136 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t,
137 IvarAccessHistory IvarAccess)
138 : Cnt(cnt), ACnt(acnt), T(t), RawKind(static_cast<unsigned>(k)),
139 RawObjectKind(static_cast<unsigned>(o)),
140 RawIvarAccessHistory(static_cast<unsigned>(IvarAccess)) {
141 assert(getKind() == k && "not enough bits for the kind");
142 assert(getObjKind() == o && "not enough bits for the object kind");
143 assert(getIvarAccessHistory() == IvarAccess && "not enough bits");
147 Kind getKind() const { return static_cast<Kind>(RawKind); }
149 RetEffect::ObjKind getObjKind() const {
150 return static_cast<RetEffect::ObjKind>(RawObjectKind);
153 unsigned getCount() const { return Cnt; }
154 unsigned getAutoreleaseCount() const { return ACnt; }
155 unsigned getCombinedCounts() const { return Cnt + ACnt; }
160 void setCount(unsigned i) {
163 void setAutoreleaseCount(unsigned i) {
167 QualType getType() const { return T; }
169 /// Returns what the analyzer knows about direct accesses to a particular
170 /// instance variable.
172 /// If the object with this refcount wasn't originally from an Objective-C
173 /// ivar region, this should always return IvarAccessHistory::None.
174 IvarAccessHistory getIvarAccessHistory() const {
175 return static_cast<IvarAccessHistory>(RawIvarAccessHistory);
178 bool isOwned() const {
179 return getKind() == Owned;
182 bool isNotOwned() const {
183 return getKind() == NotOwned;
186 bool isReturnedOwned() const {
187 return getKind() == ReturnedOwned;
190 bool isReturnedNotOwned() const {
191 return getKind() == ReturnedNotOwned;
194 /// Create a state for an object whose lifetime is the responsibility of the
195 /// current function, at least partially.
197 /// Most commonly, this is an owned object with a retain count of +1.
198 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
199 unsigned Count = 1) {
200 return RefVal(Owned, o, Count, 0, t, IvarAccessHistory::None);
203 /// Create a state for an object whose lifetime is not the responsibility of
204 /// the current function.
206 /// Most commonly, this is an unowned object with a retain count of +0.
207 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
208 unsigned Count = 0) {
209 return RefVal(NotOwned, o, Count, 0, t, IvarAccessHistory::None);
212 RefVal operator-(size_t i) const {
213 return RefVal(getKind(), getObjKind(), getCount() - i,
214 getAutoreleaseCount(), getType(), getIvarAccessHistory());
217 RefVal operator+(size_t i) const {
218 return RefVal(getKind(), getObjKind(), getCount() + i,
219 getAutoreleaseCount(), getType(), getIvarAccessHistory());
222 RefVal operator^(Kind k) const {
223 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
224 getType(), getIvarAccessHistory());
227 RefVal autorelease() const {
228 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
229 getType(), getIvarAccessHistory());
232 RefVal withIvarAccess() const {
233 assert(getIvarAccessHistory() == IvarAccessHistory::None);
234 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount(),
235 getType(), IvarAccessHistory::AccessedDirectly);
237 RefVal releaseViaIvar() const {
238 assert(getIvarAccessHistory() == IvarAccessHistory::AccessedDirectly);
239 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount(),
240 getType(), IvarAccessHistory::ReleasedAfterDirectAccess);
243 // Comparison, profiling, and pretty-printing.
245 bool hasSameState(const RefVal &X) const {
246 return getKind() == X.getKind() && Cnt == X.Cnt && ACnt == X.ACnt &&
247 getIvarAccessHistory() == X.getIvarAccessHistory();
250 bool operator==(const RefVal& X) const {
251 return T == X.T && hasSameState(X) && getObjKind() == X.getObjKind();
254 void Profile(llvm::FoldingSetNodeID& ID) const {
256 ID.AddInteger(RawKind);
259 ID.AddInteger(RawObjectKind);
260 ID.AddInteger(RawIvarAccessHistory);
263 void print(raw_ostream &Out) const;
266 void RefVal::print(raw_ostream &Out) const {
268 Out << "Tracked " << T.getAsString() << '/';
271 default: llvm_unreachable("Invalid RefVal kind");
274 unsigned cnt = getCount();
275 if (cnt) Out << " (+ " << cnt << ")";
281 unsigned cnt = getCount();
282 if (cnt) Out << " (+ " << cnt << ")";
286 case ReturnedOwned: {
287 Out << "ReturnedOwned";
288 unsigned cnt = getCount();
289 if (cnt) Out << " (+ " << cnt << ")";
293 case ReturnedNotOwned: {
294 Out << "ReturnedNotOwned";
295 unsigned cnt = getCount();
296 if (cnt) Out << " (+ " << cnt << ")";
305 Out << "-dealloc (GC)";
308 case ErrorDeallocNotOwned:
309 Out << "-dealloc (not-owned)";
316 case ErrorLeakReturned:
317 Out << "Leaked (Bad naming)";
320 case ErrorGCLeakReturned:
321 Out << "Leaked (GC-ed at return)";
324 case ErrorUseAfterRelease:
325 Out << "Use-After-Release [ERROR]";
328 case ErrorReleaseNotOwned:
329 Out << "Release of Not-Owned [ERROR]";
332 case RefVal::ErrorOverAutorelease:
333 Out << "Over-autoreleased";
336 case RefVal::ErrorReturnedNotOwned:
337 Out << "Non-owned object returned instead of owned";
341 switch (getIvarAccessHistory()) {
342 case IvarAccessHistory::None:
344 case IvarAccessHistory::AccessedDirectly:
345 Out << " [direct ivar access]";
347 case IvarAccessHistory::ReleasedAfterDirectAccess:
348 Out << " [released after direct ivar access]";
352 Out << " [autorelease -" << ACnt << ']';
355 } //end anonymous namespace
357 //===----------------------------------------------------------------------===//
358 // RefBindings - State used to track object reference counts.
359 //===----------------------------------------------------------------------===//
361 REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
363 static inline const RefVal *getRefBinding(ProgramStateRef State,
365 return State->get<RefBindings>(Sym);
368 static inline ProgramStateRef setRefBinding(ProgramStateRef State,
369 SymbolRef Sym, RefVal Val) {
370 return State->set<RefBindings>(Sym, Val);
373 static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
374 return State->remove<RefBindings>(Sym);
377 //===----------------------------------------------------------------------===//
378 // Function/Method behavior summaries.
379 //===----------------------------------------------------------------------===//
382 class RetainSummary {
383 /// Args - a map of (index, ArgEffect) pairs, where index
384 /// specifies the argument (starting from 0). This can be sparsely
385 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
388 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
389 /// do not have an entry in Args.
390 ArgEffect DefaultArgEffect;
392 /// Receiver - If this summary applies to an Objective-C message expression,
393 /// this is the effect applied to the state of the receiver.
396 /// Ret - The effect on the return value. Used to indicate if the
397 /// function/method call returns a new tracked symbol.
401 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
402 ArgEffect ReceiverEff)
403 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
405 /// getArg - Return the argument effect on the argument specified by
406 /// idx (starting from 0).
407 ArgEffect getArg(unsigned idx) const {
408 if (const ArgEffect *AE = Args.lookup(idx))
411 return DefaultArgEffect;
414 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
415 Args = af.add(Args, idx, e);
418 /// setDefaultArgEffect - Set the default argument effect.
419 void setDefaultArgEffect(ArgEffect E) {
420 DefaultArgEffect = E;
423 /// getRetEffect - Returns the effect on the return value of the call.
424 RetEffect getRetEffect() const { return Ret; }
426 /// setRetEffect - Set the effect of the return value of the call.
427 void setRetEffect(RetEffect E) { Ret = E; }
430 /// Sets the effect on the receiver of the message.
431 void setReceiverEffect(ArgEffect e) { Receiver = e; }
433 /// getReceiverEffect - Returns the effect on the receiver of the call.
434 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
435 ArgEffect getReceiverEffect() const { return Receiver; }
437 /// Test if two retain summaries are identical. Note that merely equivalent
438 /// summaries are not necessarily identical (for example, if an explicit
439 /// argument effect matches the default effect).
440 bool operator==(const RetainSummary &Other) const {
441 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
442 Receiver == Other.Receiver && Ret == Other.Ret;
445 /// Profile this summary for inclusion in a FoldingSet.
446 void Profile(llvm::FoldingSetNodeID& ID) const {
448 ID.Add(DefaultArgEffect);
453 /// A retain summary is simple if it has no ArgEffects other than the default.
454 bool isSimple() const {
455 return Args.isEmpty();
459 ArgEffects getArgEffects() const { return Args; }
460 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
462 friend class RetainSummaryManager;
464 } // end anonymous namespace
466 //===----------------------------------------------------------------------===//
467 // Data structures for constructing summaries.
468 //===----------------------------------------------------------------------===//
471 class ObjCSummaryKey {
475 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
478 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
479 : II(d ? d->getIdentifier() : nullptr), S(s) {}
481 ObjCSummaryKey(Selector s)
482 : II(nullptr), S(s) {}
484 IdentifierInfo *getIdentifier() const { return II; }
485 Selector getSelector() const { return S; }
490 template <> struct DenseMapInfo<ObjCSummaryKey> {
491 static inline ObjCSummaryKey getEmptyKey() {
492 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
493 DenseMapInfo<Selector>::getEmptyKey());
496 static inline ObjCSummaryKey getTombstoneKey() {
497 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
498 DenseMapInfo<Selector>::getTombstoneKey());
501 static unsigned getHashValue(const ObjCSummaryKey &V) {
502 typedef std::pair<IdentifierInfo*, Selector> PairTy;
503 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
507 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
508 return LHS.getIdentifier() == RHS.getIdentifier() &&
509 LHS.getSelector() == RHS.getSelector();
513 } // end llvm namespace
516 class ObjCSummaryCache {
517 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
520 ObjCSummaryCache() {}
522 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
523 // Do a lookup with the (D,S) pair. If we find a match return
525 ObjCSummaryKey K(D, S);
526 MapTy::iterator I = M.find(K);
533 // Walk the super chain. If we find a hit with a parent, we'll end
534 // up returning that summary. We actually allow that key (null,S), as
535 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
536 // generate initial summaries without having to worry about NSObject
538 // FIXME: We may change this at some point.
539 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
540 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
547 // Cache the summary with original key to make the next lookup faster
548 // and return the iterator.
549 const RetainSummary *Summ = I->second;
554 const RetainSummary *find(IdentifierInfo* II, Selector S) {
555 // FIXME: Class method lookup. Right now we dont' have a good way
556 // of going between IdentifierInfo* and the class hierarchy.
557 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
560 I = M.find(ObjCSummaryKey(S));
562 return I == M.end() ? nullptr : I->second;
565 const RetainSummary *& operator[](ObjCSummaryKey K) {
569 const RetainSummary *& operator[](Selector S) {
570 return M[ ObjCSummaryKey(S) ];
573 } // end anonymous namespace
575 //===----------------------------------------------------------------------===//
576 // Data structures for managing collections of summaries.
577 //===----------------------------------------------------------------------===//
580 class RetainSummaryManager {
582 //==-----------------------------------------------------------------==//
584 //==-----------------------------------------------------------------==//
586 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
589 typedef ObjCSummaryCache ObjCMethodSummariesTy;
591 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
593 //==-----------------------------------------------------------------==//
595 //==-----------------------------------------------------------------==//
597 /// Ctx - The ASTContext object for the analyzed ASTs.
600 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
601 const bool GCEnabled;
603 /// Records whether or not the analyzed code runs in ARC mode.
604 const bool ARCEnabled;
606 /// FuncSummaries - A map from FunctionDecls to summaries.
607 FuncSummariesTy FuncSummaries;
609 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
611 ObjCMethodSummariesTy ObjCClassMethodSummaries;
613 /// ObjCMethodSummaries - A map from selectors to summaries.
614 ObjCMethodSummariesTy ObjCMethodSummaries;
616 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
617 /// and all other data used by the checker.
618 llvm::BumpPtrAllocator BPAlloc;
620 /// AF - A factory for ArgEffects objects.
621 ArgEffects::Factory AF;
623 /// ScratchArgs - A holding buffer for construct ArgEffects.
624 ArgEffects ScratchArgs;
626 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
628 RetEffect ObjCAllocRetE;
630 /// ObjCInitRetE - Default return effect for init methods returning
631 /// Objective-C objects.
632 RetEffect ObjCInitRetE;
634 /// SimpleSummaries - Used for uniquing summaries that don't have special
636 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
638 //==-----------------------------------------------------------------==//
640 //==-----------------------------------------------------------------==//
642 /// getArgEffects - Returns a persistent ArgEffects object based on the
643 /// data in ScratchArgs.
644 ArgEffects getArgEffects();
646 enum UnaryFuncKind { cfretain, cfrelease, cfautorelease, cfmakecollectable };
648 const RetainSummary *getUnarySummary(const FunctionType* FT,
651 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
652 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
653 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
655 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
657 const RetainSummary *getPersistentSummary(RetEffect RetEff,
658 ArgEffect ReceiverEff = DoNothing,
659 ArgEffect DefaultEff = MayEscape) {
660 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
661 return getPersistentSummary(Summ);
664 const RetainSummary *getDoNothingSummary() {
665 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
668 const RetainSummary *getDefaultSummary() {
669 return getPersistentSummary(RetEffect::MakeNoRet(),
670 DoNothing, MayEscape);
673 const RetainSummary *getPersistentStopSummary() {
674 return getPersistentSummary(RetEffect::MakeNoRet(),
675 StopTracking, StopTracking);
678 void InitializeClassMethodSummaries();
679 void InitializeMethodSummaries();
681 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
682 ObjCClassMethodSummaries[S] = Summ;
685 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
686 ObjCMethodSummaries[S] = Summ;
689 void addClassMethSummary(const char* Cls, const char* name,
690 const RetainSummary *Summ, bool isNullary = true) {
691 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
692 Selector S = isNullary ? GetNullarySelector(name, Ctx)
693 : GetUnarySelector(name, Ctx);
694 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
697 void addInstMethSummary(const char* Cls, const char* nullaryName,
698 const RetainSummary *Summ) {
699 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
700 Selector S = GetNullarySelector(nullaryName, Ctx);
701 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
704 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy &Summaries,
705 const RetainSummary *Summ, va_list argp) {
706 Selector S = getKeywordSelector(Ctx, argp);
707 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
710 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
712 va_start(argp, Summ);
713 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
717 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
719 va_start(argp, Summ);
720 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
724 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
726 va_start(argp, Summ);
727 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
733 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
735 GCEnabled(gcenabled),
737 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
738 ObjCAllocRetE(gcenabled
739 ? RetEffect::MakeGCNotOwned()
740 : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC)
741 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
742 ObjCInitRetE(gcenabled
743 ? RetEffect::MakeGCNotOwned()
744 : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC)
745 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
746 InitializeClassMethodSummaries();
747 InitializeMethodSummaries();
750 const RetainSummary *getSummary(const CallEvent &Call,
751 ProgramStateRef State = nullptr);
753 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
755 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
756 const ObjCMethodDecl *MD,
758 ObjCMethodSummariesTy &CachedSummaries);
760 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
761 ProgramStateRef State);
763 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
764 assert(!M.isInstanceMessage());
765 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
767 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
768 M.getResultType(), ObjCClassMethodSummaries);
771 /// getMethodSummary - This version of getMethodSummary is used to query
772 /// the summary for the current method being analyzed.
773 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
774 const ObjCInterfaceDecl *ID = MD->getClassInterface();
775 Selector S = MD->getSelector();
776 QualType ResultTy = MD->getReturnType();
778 ObjCMethodSummariesTy *CachedSummaries;
779 if (MD->isInstanceMethod())
780 CachedSummaries = &ObjCMethodSummaries;
782 CachedSummaries = &ObjCClassMethodSummaries;
784 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
787 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
788 Selector S, QualType RetTy);
790 /// Determine if there is a special return effect for this function or method.
791 Optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy,
794 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
795 const ObjCMethodDecl *MD);
797 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
798 const FunctionDecl *FD);
800 void updateSummaryForCall(const RetainSummary *&Summ,
801 const CallEvent &Call);
803 bool isGCEnabled() const { return GCEnabled; }
805 bool isARCEnabled() const { return ARCEnabled; }
807 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
809 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
811 friend class RetainSummaryTemplate;
814 // Used to avoid allocating long-term (BPAlloc'd) memory for default retain
815 // summaries. If a function or method looks like it has a default summary, but
816 // it has annotations, the annotations are added to the stack-based template
817 // and then copied into managed memory.
818 class RetainSummaryTemplate {
819 RetainSummaryManager &Manager;
820 const RetainSummary *&RealSummary;
821 RetainSummary ScratchSummary;
824 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
825 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
827 ~RetainSummaryTemplate() {
829 RealSummary = Manager.getPersistentSummary(ScratchSummary);
832 RetainSummary &operator*() {
834 return ScratchSummary;
837 RetainSummary *operator->() {
839 return &ScratchSummary;
843 } // end anonymous namespace
845 //===----------------------------------------------------------------------===//
846 // Implementation of checker data structures.
847 //===----------------------------------------------------------------------===//
849 ArgEffects RetainSummaryManager::getArgEffects() {
850 ArgEffects AE = ScratchArgs;
851 ScratchArgs = AF.getEmptyMap();
855 const RetainSummary *
856 RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
857 // Unique "simple" summaries -- those without ArgEffects.
858 if (OldSumm.isSimple()) {
859 llvm::FoldingSetNodeID ID;
863 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
866 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
867 new (N) CachedSummaryNode(OldSumm);
868 SimpleSummaries.InsertNode(N, Pos);
871 return &N->getValue();
874 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
875 new (Summ) RetainSummary(OldSumm);
879 //===----------------------------------------------------------------------===//
880 // Summary creation for functions (largely uses of Core Foundation).
881 //===----------------------------------------------------------------------===//
883 static bool isRetain(const FunctionDecl *FD, StringRef FName) {
884 return FName.endswith("Retain");
887 static bool isRelease(const FunctionDecl *FD, StringRef FName) {
888 return FName.endswith("Release");
891 static bool isAutorelease(const FunctionDecl *FD, StringRef FName) {
892 return FName.endswith("Autorelease");
895 static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
896 // FIXME: Remove FunctionDecl parameter.
897 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
898 return FName.find("MakeCollectable") != StringRef::npos;
901 static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
905 case DecRefBridgedTransferred:
908 case MakeCollectable:
909 case UnretainedOutParameter:
910 case RetainedOutParameter:
913 case StopTrackingHard:
914 return StopTrackingHard;
916 case DecRefAndStopTrackingHard:
917 return DecRefAndStopTrackingHard;
919 case DecRefMsgAndStopTrackingHard:
920 return DecRefMsgAndStopTrackingHard;
925 llvm_unreachable("Unknown ArgEffect kind");
928 void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
929 const CallEvent &Call) {
930 if (Call.hasNonZeroCallbackArg()) {
931 ArgEffect RecEffect =
932 getStopTrackingHardEquivalent(S->getReceiverEffect());
933 ArgEffect DefEffect =
934 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
936 ArgEffects CustomArgEffects = S->getArgEffects();
937 for (ArgEffects::iterator I = CustomArgEffects.begin(),
938 E = CustomArgEffects.end();
940 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
941 if (Translated != DefEffect)
942 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
945 RetEffect RE = RetEffect::MakeNoRetHard();
947 // Special cases where the callback argument CANNOT free the return value.
948 // This can generally only happen if we know that the callback will only be
949 // called when the return value is already being deallocated.
950 if (const SimpleFunctionCall *FC = dyn_cast<SimpleFunctionCall>(&Call)) {
951 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
952 // When the CGBitmapContext is deallocated, the callback here will free
953 // the associated data buffer.
954 if (Name->isStr("CGBitmapContextCreateWithData"))
955 RE = S->getRetEffect();
959 S = getPersistentSummary(RE, RecEffect, DefEffect);
962 // Special case '[super init];' and '[self init];'
964 // Even though calling '[super init]' without assigning the result to self
965 // and checking if the parent returns 'nil' is a bad pattern, it is common.
966 // Additionally, our Self Init checker already warns about it. To avoid
967 // overwhelming the user with messages from both checkers, we model the case
968 // of '[super init]' in cases when it is not consumed by another expression
969 // as if the call preserves the value of 'self'; essentially, assuming it can
970 // never fail and return 'nil'.
971 // Note, we don't want to just stop tracking the value since we want the
972 // RetainCount checker to report leaks and use-after-free if SelfInit checker
974 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
975 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
977 // Check if the message is not consumed, we know it will not be used in
978 // an assignment, ex: "self = [super init]".
979 const Expr *ME = MC->getOriginExpr();
980 const LocationContext *LCtx = MC->getLocationContext();
981 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
982 if (!PM.isConsumedExpr(ME)) {
983 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
984 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
985 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
992 const RetainSummary *
993 RetainSummaryManager::getSummary(const CallEvent &Call,
994 ProgramStateRef State) {
995 const RetainSummary *Summ;
996 switch (Call.getKind()) {
998 Summ = getFunctionSummary(cast<SimpleFunctionCall>(Call).getDecl());
1001 case CE_CXXMemberOperator:
1003 case CE_CXXConstructor:
1004 case CE_CXXDestructor:
1005 case CE_CXXAllocator:
1006 // FIXME: These calls are currently unsupported.
1007 return getPersistentStopSummary();
1008 case CE_ObjCMessage: {
1009 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
1010 if (Msg.isInstanceMessage())
1011 Summ = getInstanceMethodSummary(Msg, State);
1013 Summ = getClassMethodSummary(Msg);
1018 updateSummaryForCall(Summ, Call);
1020 assert(Summ && "Unknown call type?");
1024 const RetainSummary *
1025 RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
1026 // If we don't know what function we're calling, use our default summary.
1028 return getDefaultSummary();
1030 // Look up a summary in our cache of FunctionDecls -> Summaries.
1031 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
1032 if (I != FuncSummaries.end())
1035 // No summary? Generate one.
1036 const RetainSummary *S = nullptr;
1037 bool AllowAnnotations = true;
1040 // We generate "stop" summaries for implicitly defined functions.
1041 if (FD->isImplicit()) {
1042 S = getPersistentStopSummary();
1046 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
1048 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
1049 const IdentifierInfo *II = FD->getIdentifier();
1053 StringRef FName = II->getName();
1055 // Strip away preceding '_'. Doing this here will effect all the checks
1057 FName = FName.substr(FName.find_first_not_of('_'));
1059 // Inspect the result type.
1060 QualType RetTy = FT->getReturnType();
1062 // FIXME: This should all be refactored into a chain of "summary lookup"
1064 assert(ScratchArgs.isEmpty());
1066 if (FName == "pthread_create" || FName == "pthread_setspecific") {
1067 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1068 // This will be addressed better with IPA.
1069 S = getPersistentStopSummary();
1070 } else if (FName == "NSMakeCollectable") {
1071 // Handle: id NSMakeCollectable(CFTypeRef)
1072 S = (RetTy->isObjCIdType())
1073 ? getUnarySummary(FT, cfmakecollectable)
1074 : getPersistentStopSummary();
1075 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1076 // but we can fully model NSMakeCollectable ourselves.
1077 AllowAnnotations = false;
1078 } else if (FName == "CFPlugInInstanceCreate") {
1079 S = getPersistentSummary(RetEffect::MakeNoRet());
1080 } else if (FName == "IOBSDNameMatching" ||
1081 FName == "IOServiceMatching" ||
1082 FName == "IOServiceNameMatching" ||
1083 FName == "IORegistryEntrySearchCFProperty" ||
1084 FName == "IORegistryEntryIDMatching" ||
1085 FName == "IOOpenFirmwarePathMatching") {
1086 // Part of <rdar://problem/6961230>. (IOKit)
1087 // This should be addressed using a API table.
1088 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1089 DoNothing, DoNothing);
1090 } else if (FName == "IOServiceGetMatchingService" ||
1091 FName == "IOServiceGetMatchingServices") {
1092 // FIXES: <rdar://problem/6326900>
1093 // This should be addressed using a API table. This strcmp is also
1094 // a little gross, but there is no need to super optimize here.
1095 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
1096 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1097 } else if (FName == "IOServiceAddNotification" ||
1098 FName == "IOServiceAddMatchingNotification") {
1099 // Part of <rdar://problem/6961230>. (IOKit)
1100 // This should be addressed using a API table.
1101 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
1102 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1103 } else if (FName == "CVPixelBufferCreateWithBytes") {
1104 // FIXES: <rdar://problem/7283567>
1105 // Eventually this can be improved by recognizing that the pixel
1106 // buffer passed to CVPixelBufferCreateWithBytes is released via
1107 // a callback and doing full IPA to make sure this is done correctly.
1108 // FIXME: This function has an out parameter that returns an
1109 // allocated object.
1110 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
1111 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1112 } else if (FName == "CGBitmapContextCreateWithData") {
1113 // FIXES: <rdar://problem/7358899>
1114 // Eventually this can be improved by recognizing that 'releaseInfo'
1115 // passed to CGBitmapContextCreateWithData is released via
1116 // a callback and doing full IPA to make sure this is done correctly.
1117 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
1118 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1119 DoNothing, DoNothing);
1120 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1121 // FIXES: <rdar://problem/7283567>
1122 // Eventually this can be improved by recognizing that the pixel
1123 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1124 // via a callback and doing full IPA to make sure this is done
1126 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
1127 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1128 } else if (FName == "dispatch_set_context" ||
1129 FName == "xpc_connection_set_context") {
1130 // <rdar://problem/11059275> - The analyzer currently doesn't have
1131 // a good way to reason about the finalizer function for libdispatch.
1132 // If we pass a context object that is memory managed, stop tracking it.
1133 // <rdar://problem/13783514> - Same problem, but for XPC.
1134 // FIXME: this hack should possibly go away once we can handle
1135 // libdispatch and XPC finalizers.
1136 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1137 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1138 } else if (FName.startswith("NSLog")) {
1139 S = getDoNothingSummary();
1140 } else if (FName.startswith("NS") &&
1141 (FName.find("Insert") != StringRef::npos)) {
1142 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1143 // be deallocated by NSMapRemove. (radar://11152419)
1144 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1145 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1146 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1149 // Did we get a summary?
1153 if (RetTy->isPointerType()) {
1154 // For CoreFoundation ('CF') types.
1155 if (cocoa::isRefType(RetTy, "CF", FName)) {
1156 if (isRetain(FD, FName)) {
1157 S = getUnarySummary(FT, cfretain);
1158 } else if (isAutorelease(FD, FName)) {
1159 S = getUnarySummary(FT, cfautorelease);
1160 // The headers use cf_consumed, but we can fully model CFAutorelease
1162 AllowAnnotations = false;
1163 } else if (isMakeCollectable(FD, FName)) {
1164 S = getUnarySummary(FT, cfmakecollectable);
1165 AllowAnnotations = false;
1167 S = getCFCreateGetRuleSummary(FD);
1173 // For CoreGraphics ('CG') types.
1174 if (cocoa::isRefType(RetTy, "CG", FName)) {
1175 if (isRetain(FD, FName))
1176 S = getUnarySummary(FT, cfretain);
1178 S = getCFCreateGetRuleSummary(FD);
1183 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1184 if (cocoa::isRefType(RetTy, "DADisk") ||
1185 cocoa::isRefType(RetTy, "DADissenter") ||
1186 cocoa::isRefType(RetTy, "DASessionRef")) {
1187 S = getCFCreateGetRuleSummary(FD);
1191 if (FD->hasAttr<CFAuditedTransferAttr>()) {
1192 S = getCFCreateGetRuleSummary(FD);
1199 // Check for release functions, the only kind of functions that we care
1200 // about that don't return a pointer type.
1201 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
1203 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
1205 if (isRelease(FD, FName))
1206 S = getUnarySummary(FT, cfrelease);
1208 assert (ScratchArgs.isEmpty());
1209 // Remaining CoreFoundation and CoreGraphics functions.
1210 // We use to assume that they all strictly followed the ownership idiom
1211 // and that ownership cannot be transferred. While this is technically
1212 // correct, many methods allow a tracked object to escape. For example:
1214 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1215 // CFDictionaryAddValue(y, key, x);
1217 // ... it is okay to use 'x' since 'y' has a reference to it
1219 // We handle this and similar cases with the follow heuristic. If the
1220 // function name contains "InsertValue", "SetValue", "AddValue",
1221 // "AppendValue", or "SetAttribute", then we assume that arguments may
1222 // "escape." This means that something else holds on to the object,
1223 // allowing it be used even after its local retain count drops to 0.
1224 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1225 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1226 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1227 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
1228 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
1229 ? MayEscape : DoNothing;
1231 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
1237 // If we got all the way here without any luck, use a default summary.
1239 S = getDefaultSummary();
1241 // Annotations override defaults.
1242 if (AllowAnnotations)
1243 updateSummaryFromAnnotations(S, FD);
1245 FuncSummaries[FD] = S;
1249 const RetainSummary *
1250 RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1251 if (coreFoundation::followsCreateRule(FD))
1252 return getCFSummaryCreateRule(FD);
1254 return getCFSummaryGetRule(FD);
1257 const RetainSummary *
1258 RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1259 UnaryFuncKind func) {
1261 // Sanity check that this is *really* a unary function. This can
1262 // happen if people do weird things.
1263 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
1264 if (!FTP || FTP->getNumParams() != 1)
1265 return getPersistentStopSummary();
1267 assert (ScratchArgs.isEmpty());
1271 case cfretain: Effect = IncRef; break;
1272 case cfrelease: Effect = DecRef; break;
1273 case cfautorelease: Effect = Autorelease; break;
1274 case cfmakecollectable: Effect = MakeCollectable; break;
1277 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1278 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1281 const RetainSummary *
1282 RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
1283 assert (ScratchArgs.isEmpty());
1285 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
1288 const RetainSummary *
1289 RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
1290 assert (ScratchArgs.isEmpty());
1291 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1292 DoNothing, DoNothing);
1295 //===----------------------------------------------------------------------===//
1296 // Summary creation for Selectors.
1297 //===----------------------------------------------------------------------===//
1300 RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
1302 if (cocoa::isCocoaObjectRef(RetTy)) {
1303 if (D->hasAttr<NSReturnsRetainedAttr>())
1304 return ObjCAllocRetE;
1306 if (D->hasAttr<NSReturnsNotRetainedAttr>() ||
1307 D->hasAttr<NSReturnsAutoreleasedAttr>())
1308 return RetEffect::MakeNotOwned(RetEffect::ObjC);
1310 } else if (!RetTy->isPointerType()) {
1314 if (D->hasAttr<CFReturnsRetainedAttr>())
1315 return RetEffect::MakeOwned(RetEffect::CF, true);
1317 if (D->hasAttr<CFReturnsNotRetainedAttr>())
1318 return RetEffect::MakeNotOwned(RetEffect::CF);
1324 RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1325 const FunctionDecl *FD) {
1329 assert(Summ && "Must have a summary to add annotations to.");
1330 RetainSummaryTemplate Template(Summ, *this);
1332 // Effects on the parameters.
1333 unsigned parm_idx = 0;
1334 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
1335 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
1336 const ParmVarDecl *pd = *pi;
1337 if (pd->hasAttr<NSConsumedAttr>())
1338 Template->addArg(AF, parm_idx, DecRefMsg);
1339 else if (pd->hasAttr<CFConsumedAttr>())
1340 Template->addArg(AF, parm_idx, DecRef);
1341 else if (pd->hasAttr<CFReturnsRetainedAttr>()) {
1342 QualType PointeeTy = pd->getType()->getPointeeType();
1343 if (!PointeeTy.isNull())
1344 if (coreFoundation::isCFObjectRef(PointeeTy))
1345 Template->addArg(AF, parm_idx, RetainedOutParameter);
1346 } else if (pd->hasAttr<CFReturnsNotRetainedAttr>()) {
1347 QualType PointeeTy = pd->getType()->getPointeeType();
1348 if (!PointeeTy.isNull())
1349 if (coreFoundation::isCFObjectRef(PointeeTy))
1350 Template->addArg(AF, parm_idx, UnretainedOutParameter);
1354 QualType RetTy = FD->getReturnType();
1355 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
1356 Template->setRetEffect(*RetE);
1360 RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1361 const ObjCMethodDecl *MD) {
1365 assert(Summ && "Must have a valid summary to add annotations to");
1366 RetainSummaryTemplate Template(Summ, *this);
1368 // Effects on the receiver.
1369 if (MD->hasAttr<NSConsumesSelfAttr>())
1370 Template->setReceiverEffect(DecRefMsg);
1372 // Effects on the parameters.
1373 unsigned parm_idx = 0;
1374 for (ObjCMethodDecl::param_const_iterator
1375 pi=MD->param_begin(), pe=MD->param_end();
1376 pi != pe; ++pi, ++parm_idx) {
1377 const ParmVarDecl *pd = *pi;
1378 if (pd->hasAttr<NSConsumedAttr>())
1379 Template->addArg(AF, parm_idx, DecRefMsg);
1380 else if (pd->hasAttr<CFConsumedAttr>()) {
1381 Template->addArg(AF, parm_idx, DecRef);
1382 } else if (pd->hasAttr<CFReturnsRetainedAttr>()) {
1383 QualType PointeeTy = pd->getType()->getPointeeType();
1384 if (!PointeeTy.isNull())
1385 if (coreFoundation::isCFObjectRef(PointeeTy))
1386 Template->addArg(AF, parm_idx, RetainedOutParameter);
1387 } else if (pd->hasAttr<CFReturnsNotRetainedAttr>()) {
1388 QualType PointeeTy = pd->getType()->getPointeeType();
1389 if (!PointeeTy.isNull())
1390 if (coreFoundation::isCFObjectRef(PointeeTy))
1391 Template->addArg(AF, parm_idx, UnretainedOutParameter);
1395 QualType RetTy = MD->getReturnType();
1396 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1397 Template->setRetEffect(*RetE);
1400 const RetainSummary *
1401 RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1402 Selector S, QualType RetTy) {
1403 // Any special effects?
1404 ArgEffect ReceiverEff = DoNothing;
1405 RetEffect ResultEff = RetEffect::MakeNoRet();
1407 // Check the method family, and apply any default annotations.
1408 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1410 case OMF_initialize:
1411 case OMF_performSelector:
1412 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1413 // FIXME: Does the non-threaded performSelector family really belong here?
1414 // The selector could be, say, @selector(copy).
1415 if (cocoa::isCocoaObjectRef(RetTy))
1416 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1417 else if (coreFoundation::isCFObjectRef(RetTy)) {
1418 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1419 // values for alloc, new, copy, or mutableCopy, so we have to
1420 // double-check with the selector. This is ugly, but there aren't that
1421 // many Objective-C methods that return CF objects, right?
1423 switch (S.getMethodFamily()) {
1427 case OMF_mutableCopy:
1428 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1431 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1435 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1440 ResultEff = ObjCInitRetE;
1441 ReceiverEff = DecRefMsg;
1446 case OMF_mutableCopy:
1447 if (cocoa::isCocoaObjectRef(RetTy))
1448 ResultEff = ObjCAllocRetE;
1449 else if (coreFoundation::isCFObjectRef(RetTy))
1450 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1452 case OMF_autorelease:
1453 ReceiverEff = Autorelease;
1456 ReceiverEff = IncRefMsg;
1459 ReceiverEff = DecRefMsg;
1462 ReceiverEff = Dealloc;
1465 // -self is handled specially by the ExprEngine to propagate the receiver.
1467 case OMF_retainCount:
1469 // These methods don't return objects.
1473 // If one of the arguments in the selector has the keyword 'delegate' we
1474 // should stop tracking the reference count for the receiver. This is
1475 // because the reference count is quite possibly handled by a delegate
1477 if (S.isKeywordSelector()) {
1478 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1479 StringRef Slot = S.getNameForSlot(i);
1480 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1481 if (ResultEff == ObjCInitRetE)
1482 ResultEff = RetEffect::MakeNoRetHard();
1484 ReceiverEff = StopTrackingHard;
1489 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1490 ResultEff.getKind() == RetEffect::NoRet)
1491 return getDefaultSummary();
1493 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
1496 const RetainSummary *
1497 RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
1498 ProgramStateRef State) {
1499 const ObjCInterfaceDecl *ReceiverClass = nullptr;
1501 // We do better tracking of the type of the object than the core ExprEngine.
1502 // See if we have its type in our private state.
1503 // FIXME: Eventually replace the use of state->get<RefBindings> with
1504 // a generic API for reasoning about the Objective-C types of symbolic
1506 SVal ReceiverV = Msg.getReceiverSVal();
1507 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
1508 if (const RefVal *T = getRefBinding(State, Sym))
1509 if (const ObjCObjectPointerType *PT =
1510 T->getType()->getAs<ObjCObjectPointerType>())
1511 ReceiverClass = PT->getInterfaceDecl();
1513 // If we don't know what kind of object this is, fall back to its static type.
1515 ReceiverClass = Msg.getReceiverInterface();
1517 // FIXME: The receiver could be a reference to a class, meaning that
1518 // we should use the class method.
1519 // id x = [NSObject class];
1520 // [x performSelector:... withObject:... afterDelay:...];
1521 Selector S = Msg.getSelector();
1522 const ObjCMethodDecl *Method = Msg.getDecl();
1523 if (!Method && ReceiverClass)
1524 Method = ReceiverClass->getInstanceMethod(S);
1526 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1527 ObjCMethodSummaries);
1530 const RetainSummary *
1531 RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
1532 const ObjCMethodDecl *MD, QualType RetTy,
1533 ObjCMethodSummariesTy &CachedSummaries) {
1535 // Look up a summary in our summary cache.
1536 const RetainSummary *Summ = CachedSummaries.find(ID, S);
1539 Summ = getStandardMethodSummary(MD, S, RetTy);
1541 // Annotations override defaults.
1542 updateSummaryFromAnnotations(Summ, MD);
1544 // Memoize the summary.
1545 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
1551 void RetainSummaryManager::InitializeClassMethodSummaries() {
1552 assert(ScratchArgs.isEmpty());
1553 // Create the [NSAssertionHandler currentHander] summary.
1554 addClassMethSummary("NSAssertionHandler", "currentHandler",
1555 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
1557 // Create the [NSAutoreleasePool addObject:] summary.
1558 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
1559 addClassMethSummary("NSAutoreleasePool", "addObject",
1560 getPersistentSummary(RetEffect::MakeNoRet(),
1561 DoNothing, Autorelease));
1564 void RetainSummaryManager::InitializeMethodSummaries() {
1566 assert (ScratchArgs.isEmpty());
1568 // Create the "init" selector. It just acts as a pass-through for the
1570 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
1571 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1573 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1574 // claims the receiver and returns a retained object.
1575 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1578 // The next methods are allocators.
1579 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1580 const RetainSummary *CFAllocSumm =
1581 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
1583 // Create the "retain" selector.
1584 RetEffect NoRet = RetEffect::MakeNoRet();
1585 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
1586 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
1588 // Create the "release" selector.
1589 Summ = getPersistentSummary(NoRet, DecRefMsg);
1590 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
1592 // Create the -dealloc summary.
1593 Summ = getPersistentSummary(NoRet, Dealloc);
1594 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
1596 // Create the "autorelease" selector.
1597 Summ = getPersistentSummary(NoRet, Autorelease);
1598 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
1600 // For NSWindow, allocated objects are (initially) self-owned.
1601 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1602 // self-own themselves. However, they only do this once they are displayed.
1603 // Thus, we need to track an NSWindow's display status.
1604 // This is tracked in <rdar://problem/6062711>.
1605 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
1606 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1610 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1612 // For NSPanel (which subclasses NSWindow), allocated objects are not
1614 // FIXME: For now we don't track NSPanels. object for the same reason
1615 // as for NSWindow objects.
1616 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1618 // For NSNull, objects returned by +null are singletons that ignore
1619 // retain/release semantics. Just don't track them.
1620 // <rdar://problem/12858915>
1621 addClassMethSummary("NSNull", "null", NoTrackYet);
1623 // Don't track allocated autorelease pools, as it is okay to prematurely
1625 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
1626 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
1627 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
1629 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1630 addInstMethSummary("QCRenderer", AllocSumm,
1631 "createSnapshotImageOfType", nullptr);
1632 addInstMethSummary("QCView", AllocSumm,
1633 "createSnapshotImageOfType", nullptr);
1635 // Create summaries for CIContext, 'createCGImage' and
1636 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1637 // automatically garbage collected.
1638 addInstMethSummary("CIContext", CFAllocSumm,
1639 "createCGImage", "fromRect", nullptr);
1640 addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect",
1641 "format", "colorSpace", nullptr);
1642 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info",
1646 //===----------------------------------------------------------------------===//
1648 //===----------------------------------------------------------------------===//
1650 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1653 //===-------------===//
1654 // Bug Descriptions. //
1655 //===-------------===//
1657 class CFRefBug : public BugType {
1659 CFRefBug(const CheckerBase *checker, StringRef name)
1660 : BugType(checker, name, categories::MemoryCoreFoundationObjectiveC) {}
1664 // FIXME: Eventually remove.
1665 virtual const char *getDescription() const = 0;
1667 virtual bool isLeak() const { return false; }
1670 class UseAfterRelease : public CFRefBug {
1672 UseAfterRelease(const CheckerBase *checker)
1673 : CFRefBug(checker, "Use-after-release") {}
1675 const char *getDescription() const override {
1676 return "Reference-counted object is used after it is released";
1680 class BadRelease : public CFRefBug {
1682 BadRelease(const CheckerBase *checker) : CFRefBug(checker, "Bad release") {}
1684 const char *getDescription() const override {
1685 return "Incorrect decrement of the reference count of an object that is "
1686 "not owned at this point by the caller";
1690 class DeallocGC : public CFRefBug {
1692 DeallocGC(const CheckerBase *checker)
1693 : CFRefBug(checker, "-dealloc called while using garbage collection") {}
1695 const char *getDescription() const override {
1696 return "-dealloc called while using garbage collection";
1700 class DeallocNotOwned : public CFRefBug {
1702 DeallocNotOwned(const CheckerBase *checker)
1703 : CFRefBug(checker, "-dealloc sent to non-exclusively owned object") {}
1705 const char *getDescription() const override {
1706 return "-dealloc sent to object that may be referenced elsewhere";
1710 class OverAutorelease : public CFRefBug {
1712 OverAutorelease(const CheckerBase *checker)
1713 : CFRefBug(checker, "Object autoreleased too many times") {}
1715 const char *getDescription() const override {
1716 return "Object autoreleased too many times";
1720 class ReturnedNotOwnedForOwned : public CFRefBug {
1722 ReturnedNotOwnedForOwned(const CheckerBase *checker)
1723 : CFRefBug(checker, "Method should return an owned object") {}
1725 const char *getDescription() const override {
1726 return "Object with a +0 retain count returned to caller where a +1 "
1727 "(owning) retain count is expected";
1731 class Leak : public CFRefBug {
1733 Leak(const CheckerBase *checker, StringRef name) : CFRefBug(checker, name) {
1734 // Leaks should not be reported if they are post-dominated by a sink.
1735 setSuppressOnSink(true);
1738 const char *getDescription() const override { return ""; }
1740 bool isLeak() const override { return true; }
1747 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
1750 const SummaryLogTy &SummaryLog;
1754 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1755 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
1757 void Profile(llvm::FoldingSetNodeID &ID) const override {
1763 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1764 const ExplodedNode *PrevN,
1765 BugReporterContext &BRC,
1766 BugReport &BR) override;
1768 std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
1769 const ExplodedNode *N,
1770 BugReport &BR) override;
1773 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1775 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
1776 const SummaryLogTy &log)
1777 : CFRefReportVisitor(sym, GCEnabled, log) {}
1779 std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
1780 const ExplodedNode *N,
1781 BugReport &BR) override;
1783 std::unique_ptr<BugReporterVisitor> clone() const override {
1784 // The curiously-recurring template pattern only works for one level of
1785 // subclassing. Rather than make a new template base for
1786 // CFRefReportVisitor, we simply override clone() to do the right thing.
1787 // This could be trouble someday if BugReporterVisitorImpl is ever
1788 // used for something else besides a convenient implementation of clone().
1789 return llvm::make_unique<CFRefLeakReportVisitor>(*this);
1793 class CFRefReport : public BugReport {
1794 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
1797 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1798 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1799 bool registerVisitor = true)
1800 : BugReport(D, D.getDescription(), n) {
1801 if (registerVisitor)
1802 addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log));
1803 addGCModeDescription(LOpts, GCEnabled);
1806 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1807 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1809 : BugReport(D, D.getDescription(), endText, n) {
1810 addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log));
1811 addGCModeDescription(LOpts, GCEnabled);
1814 llvm::iterator_range<ranges_iterator> getRanges() override {
1815 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1816 if (!BugTy.isLeak())
1817 return BugReport::getRanges();
1818 return llvm::make_range(ranges_iterator(), ranges_iterator());
1822 class CFRefLeakReport : public CFRefReport {
1823 const MemRegion* AllocBinding;
1825 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1826 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1827 CheckerContext &Ctx,
1828 bool IncludeAllocationLine);
1830 PathDiagnosticLocation getLocation(const SourceManager &SM) const override {
1831 assert(Location.isValid());
1835 } // end anonymous namespace
1837 void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1839 const char *GCModeDescription = nullptr;
1841 switch (LOpts.getGC()) {
1842 case LangOptions::GCOnly:
1844 GCModeDescription = "Code is compiled to only use garbage collection";
1847 case LangOptions::NonGC:
1849 GCModeDescription = "Code is compiled to use reference counts";
1852 case LangOptions::HybridGC:
1854 GCModeDescription = "Code is compiled to use either garbage collection "
1855 "(GC) or reference counts (non-GC). The bug occurs "
1859 GCModeDescription = "Code is compiled to use either garbage collection "
1860 "(GC) or reference counts (non-GC). The bug occurs "
1866 assert(GCModeDescription && "invalid/unknown GC mode");
1867 addExtraText(GCModeDescription);
1870 static bool isNumericLiteralExpression(const Expr *E) {
1871 // FIXME: This set of cases was copied from SemaExprObjC.
1872 return isa<IntegerLiteral>(E) ||
1873 isa<CharacterLiteral>(E) ||
1874 isa<FloatingLiteral>(E) ||
1875 isa<ObjCBoolLiteralExpr>(E) ||
1876 isa<CXXBoolLiteralExpr>(E);
1879 /// Returns true if this stack frame is for an Objective-C method that is a
1880 /// property getter or setter whose body has been synthesized by the analyzer.
1881 static bool isSynthesizedAccessor(const StackFrameContext *SFC) {
1882 auto Method = dyn_cast_or_null<ObjCMethodDecl>(SFC->getDecl());
1883 if (!Method || !Method->isPropertyAccessor())
1886 return SFC->getAnalysisDeclContext()->isBodyAutosynthesized();
1889 PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1890 const ExplodedNode *PrevN,
1891 BugReporterContext &BRC,
1893 // FIXME: We will eventually need to handle non-statement-based events
1894 // (__attribute__((cleanup))).
1895 if (!N->getLocation().getAs<StmtPoint>())
1898 // Check if the type state has changed.
1899 ProgramStateRef PrevSt = PrevN->getState();
1900 ProgramStateRef CurrSt = N->getState();
1901 const LocationContext *LCtx = N->getLocationContext();
1903 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
1904 if (!CurrT) return nullptr;
1906 const RefVal &CurrV = *CurrT;
1907 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
1909 // Create a string buffer to constain all the useful things we want
1910 // to tell the user.
1912 llvm::raw_string_ostream os(sbuf);
1914 // This is the allocation site since the previous node had no bindings
1917 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
1919 if (isa<ObjCIvarRefExpr>(S) &&
1920 isSynthesizedAccessor(LCtx->getCurrentStackFrame())) {
1921 S = LCtx->getCurrentStackFrame()->getCallSite();
1924 if (isa<ObjCArrayLiteral>(S)) {
1925 os << "NSArray literal is an object with a +0 retain count";
1927 else if (isa<ObjCDictionaryLiteral>(S)) {
1928 os << "NSDictionary literal is an object with a +0 retain count";
1930 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1931 if (isNumericLiteralExpression(BL->getSubExpr()))
1932 os << "NSNumber literal is an object with a +0 retain count";
1934 const ObjCInterfaceDecl *BoxClass = nullptr;
1935 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1936 BoxClass = Method->getClassInterface();
1938 // We should always be able to find the boxing class interface,
1939 // but consider this future-proofing.
1941 os << *BoxClass << " b";
1945 os << "oxed expression produces an object with a +0 retain count";
1948 else if (isa<ObjCIvarRefExpr>(S)) {
1949 os << "Object loaded from instance variable";
1952 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1953 // Get the name of the callee (if it is available).
1954 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1955 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1956 os << "Call to function '" << *FD << '\'';
1958 os << "function call";
1961 assert(isa<ObjCMessageExpr>(S));
1962 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1963 CallEventRef<ObjCMethodCall> Call
1964 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1966 switch (Call->getMessageKind()) {
1970 case OCM_PropertyAccess:
1979 if (CurrV.getObjKind() == RetEffect::CF) {
1980 os << " returns a Core Foundation object with a ";
1983 assert (CurrV.getObjKind() == RetEffect::ObjC);
1984 os << " returns an Objective-C object with a ";
1987 if (CurrV.isOwned()) {
1988 os << "+1 retain count";
1991 assert(CurrV.getObjKind() == RetEffect::CF);
1993 "Core Foundation objects are not automatically garbage collected.";
1997 assert (CurrV.isNotOwned());
1998 os << "+0 retain count";
2002 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2003 N->getLocationContext());
2004 return new PathDiagnosticEventPiece(Pos, os.str());
2007 // Gather up the effects that were performed on the object at this
2009 SmallVector<ArgEffect, 2> AEffects;
2011 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
2012 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
2013 // We only have summaries attached to nodes after evaluating CallExpr and
2014 // ObjCMessageExprs.
2015 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
2017 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
2018 // Iterate through the parameter expressions and see if the symbol
2019 // was ever passed as an argument.
2022 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2023 AI!=AE; ++AI, ++i) {
2025 // Retrieve the value of the argument. Is it the symbol
2026 // we are interested in?
2027 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
2030 // We have an argument. Get the effect!
2031 AEffects.push_back(Summ->getArg(i));
2034 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2035 if (const Expr *receiver = ME->getInstanceReceiver())
2036 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2037 .getAsLocSymbol() == Sym) {
2038 // The symbol we are tracking is the receiver.
2039 AEffects.push_back(Summ->getReceiverEffect());
2045 // Get the previous type state.
2046 RefVal PrevV = *PrevT;
2048 // Specially handle -dealloc.
2049 if (!GCEnabled && std::find(AEffects.begin(), AEffects.end(), Dealloc) !=
2051 // Determine if the object's reference count was pushed to zero.
2052 assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
2053 // We may not have transitioned to 'release' if we hit an error.
2054 // This case is handled elsewhere.
2055 if (CurrV.getKind() == RefVal::Released) {
2056 assert(CurrV.getCombinedCounts() == 0);
2057 os << "Object released by directly sending the '-dealloc' message";
2062 // Specially handle CFMakeCollectable and friends.
2063 if (std::find(AEffects.begin(), AEffects.end(), MakeCollectable) !=
2065 // Get the name of the function.
2066 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
2068 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
2069 const FunctionDecl *FD = X.getAsFunctionDecl();
2072 // Determine if the object's reference count was pushed to zero.
2073 assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
2075 os << "In GC mode a call to '" << *FD
2076 << "' decrements an object's retain count and registers the "
2077 "object with the garbage collector. ";
2079 if (CurrV.getKind() == RefVal::Released) {
2080 assert(CurrV.getCount() == 0);
2081 os << "Since it now has a 0 retain count the object can be "
2082 "automatically collected by the garbage collector.";
2085 os << "An object must have a 0 retain count to be garbage collected. "
2086 "After this call its retain count is +" << CurrV.getCount()
2090 os << "When GC is not enabled a call to '" << *FD
2091 << "' has no effect on its argument.";
2093 // Nothing more to say.
2097 // Determine if the typestate has changed.
2098 if (!PrevV.hasSameState(CurrV))
2099 switch (CurrV.getKind()) {
2101 case RefVal::NotOwned:
2102 if (PrevV.getCount() == CurrV.getCount()) {
2103 // Did an autorelease message get sent?
2104 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2107 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
2108 os << "Object autoreleased";
2112 if (PrevV.getCount() > CurrV.getCount())
2113 os << "Reference count decremented.";
2115 os << "Reference count incremented.";
2117 if (unsigned Count = CurrV.getCount())
2118 os << " The object now has a +" << Count << " retain count.";
2120 if (PrevV.getKind() == RefVal::Released) {
2121 assert(GCEnabled && CurrV.getCount() > 0);
2122 os << " The object is not eligible for garbage collection until "
2123 "the retain count reaches 0 again.";
2128 case RefVal::Released:
2129 if (CurrV.getIvarAccessHistory() ==
2130 RefVal::IvarAccessHistory::ReleasedAfterDirectAccess &&
2131 CurrV.getIvarAccessHistory() != PrevV.getIvarAccessHistory()) {
2132 os << "Strong instance variable relinquished. ";
2134 os << "Object released.";
2137 case RefVal::ReturnedOwned:
2138 // Autoreleases can be applied after marking a node ReturnedOwned.
2139 if (CurrV.getAutoreleaseCount())
2142 os << "Object returned to caller as an owning reference (single "
2143 "retain count transferred to caller)";
2146 case RefVal::ReturnedNotOwned:
2147 os << "Object returned to caller with a +0 retain count";
2154 // Emit any remaining diagnostics for the argument effects (if any).
2155 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2156 E=AEffects.end(); I != E; ++I) {
2158 // A bunch of things have alternate behavior under GC.
2163 os << "In GC mode an 'autorelease' has no effect.";
2166 os << "In GC mode the 'retain' message has no effect.";
2169 os << "In GC mode the 'release' message has no effect.";
2175 if (os.str().empty())
2176 return nullptr; // We have nothing to say!
2178 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
2179 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2180 N->getLocationContext());
2181 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
2183 // Add the range by scanning the children of the statement for any bindings
2185 for (const Stmt *Child : S->children())
2186 if (const Expr *Exp = dyn_cast_or_null<Expr>(Child))
2187 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
2188 P->addRange(Exp->getSourceRange());
2195 // Find the first node in the current function context that referred to the
2196 // tracked symbol and the memory location that value was stored to. Note, the
2197 // value is only reported if the allocation occurred in the same function as
2198 // the leak. The function can also return a location context, which should be
2199 // treated as interesting.
2200 struct AllocationInfo {
2201 const ExplodedNode* N;
2203 const LocationContext *InterestingMethodContext;
2204 AllocationInfo(const ExplodedNode *InN,
2205 const MemRegion *InR,
2206 const LocationContext *InInterestingMethodContext) :
2207 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
2210 static AllocationInfo
2211 GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
2213 const ExplodedNode *AllocationNode = N;
2214 const ExplodedNode *AllocationNodeInCurrentOrParentContext = N;
2215 const MemRegion *FirstBinding = nullptr;
2216 const LocationContext *LeakContext = N->getLocationContext();
2218 // The location context of the init method called on the leaked object, if
2220 const LocationContext *InitMethodContext = nullptr;
2223 ProgramStateRef St = N->getState();
2224 const LocationContext *NContext = N->getLocationContext();
2226 if (!getRefBinding(St, Sym))
2229 StoreManager::FindUniqueBinding FB(Sym);
2230 StateMgr.iterBindings(St, FB);
2233 const MemRegion *R = FB.getRegion();
2234 const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>();
2235 // Do not show local variables belonging to a function other than
2236 // where the error is reported.
2237 if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame())
2241 // AllocationNode is the last node in which the symbol was tracked.
2244 // AllocationNodeInCurrentContext, is the last node in the current or
2245 // parent context in which the symbol was tracked.
2247 // Note that the allocation site might be in the parent conext. For example,
2248 // the case where an allocation happens in a block that captures a reference
2249 // to it and that reference is overwritten/dropped by another call to
2251 if (NContext == LeakContext || NContext->isParentOf(LeakContext))
2252 AllocationNodeInCurrentOrParentContext = N;
2254 // Find the last init that was called on the given symbol and store the
2255 // init method's location context.
2256 if (!InitMethodContext)
2257 if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) {
2258 const Stmt *CE = CEP->getCallExpr();
2259 if (const ObjCMessageExpr *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
2260 const Stmt *RecExpr = ME->getInstanceReceiver();
2262 SVal RecV = St->getSVal(RecExpr, NContext);
2263 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
2264 InitMethodContext = CEP->getCalleeContext();
2269 N = N->pred_empty() ? nullptr : *(N->pred_begin());
2272 // If we are reporting a leak of the object that was allocated with alloc,
2273 // mark its init method as interesting.
2274 const LocationContext *InterestingMethodContext = nullptr;
2275 if (InitMethodContext) {
2276 const ProgramPoint AllocPP = AllocationNode->getLocation();
2277 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
2278 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
2279 if (ME->getMethodFamily() == OMF_alloc)
2280 InterestingMethodContext = InitMethodContext;
2283 // If allocation happened in a function different from the leak node context,
2284 // do not report the binding.
2285 assert(N && "Could not find allocation node");
2286 if (N->getLocationContext() != LeakContext) {
2287 FirstBinding = nullptr;
2290 return AllocationInfo(AllocationNodeInCurrentOrParentContext,
2292 InterestingMethodContext);
2295 std::unique_ptr<PathDiagnosticPiece>
2296 CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2297 const ExplodedNode *EndN, BugReport &BR) {
2298 BR.markInteresting(Sym);
2299 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
2302 std::unique_ptr<PathDiagnosticPiece>
2303 CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2304 const ExplodedNode *EndN, BugReport &BR) {
2306 // Tell the BugReporterContext to report cases when the tracked symbol is
2307 // assigned to different variables, etc.
2308 BR.markInteresting(Sym);
2310 // We are reporting a leak. Walk up the graph to get to the first node where
2311 // the symbol appeared, and also get the first VarDecl that tracked object
2313 AllocationInfo AllocI =
2314 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
2316 const MemRegion* FirstBinding = AllocI.R;
2317 BR.markInteresting(AllocI.InterestingMethodContext);
2319 SourceManager& SM = BRC.getSourceManager();
2321 // Compute an actual location for the leak. Sometimes a leak doesn't
2322 // occur at an actual statement (e.g., transition between blocks; end
2323 // of function) so we need to walk the graph and compute a real location.
2324 const ExplodedNode *LeakN = EndN;
2325 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
2328 llvm::raw_string_ostream os(sbuf);
2330 os << "Object leaked: ";
2333 os << "object allocated and stored into '"
2334 << FirstBinding->getString() << '\'';
2337 os << "allocated object";
2339 // Get the retain count.
2340 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
2343 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2344 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2345 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
2346 // to the caller for NS objects.
2347 const Decl *D = &EndN->getCodeDecl();
2349 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2350 : " is returned from a function ");
2352 if (D->hasAttr<CFReturnsNotRetainedAttr>())
2353 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
2354 else if (D->hasAttr<NSReturnsNotRetainedAttr>())
2355 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
2357 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2358 os << "whose name ('" << MD->getSelector().getAsString()
2359 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2360 " This violates the naming convention rules"
2361 " given in the Memory Management Guide for Cocoa";
2364 const FunctionDecl *FD = cast<FunctionDecl>(D);
2365 os << "whose name ('" << *FD
2366 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2367 " convention rules given in the Memory Management Guide for Core"
2372 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2373 const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
2374 os << " and returned from method '" << MD.getSelector().getAsString()
2375 << "' is potentially leaked when using garbage collection. Callers "
2376 "of this method do not expect a returned object with a +1 retain "
2377 "count since they expect the object to be managed by the garbage "
2381 os << " is not referenced later in this execution path and has a retain "
2382 "count of +" << RV->getCount();
2384 return llvm::make_unique<PathDiagnosticEventPiece>(L, os.str());
2387 CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2388 bool GCEnabled, const SummaryLogTy &Log,
2389 ExplodedNode *n, SymbolRef sym,
2390 CheckerContext &Ctx,
2391 bool IncludeAllocationLine)
2392 : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
2394 // Most bug reports are cached at the location where they occurred.
2395 // With leaks, we want to unique them by the location where they were
2396 // allocated, and only report a single path. To do this, we need to find
2397 // the allocation site of a piece of tracked memory, which we do via a
2398 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2399 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2400 // that all ancestor nodes that represent the allocation site have the
2401 // same SourceLocation.
2402 const ExplodedNode *AllocNode = nullptr;
2404 const SourceManager& SMgr = Ctx.getSourceManager();
2406 AllocationInfo AllocI =
2407 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
2409 AllocNode = AllocI.N;
2410 AllocBinding = AllocI.R;
2411 markInteresting(AllocI.InterestingMethodContext);
2413 // Get the SourceLocation for the allocation site.
2414 // FIXME: This will crash the analyzer if an allocation comes from an
2415 // implicit call (ex: a destructor call).
2416 // (Currently there are no such allocations in Cocoa, though.)
2417 const Stmt *AllocStmt = 0;
2418 ProgramPoint P = AllocNode->getLocation();
2419 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
2420 AllocStmt = Exit->getCalleeContext()->getCallSite();
2422 AllocStmt = P.castAs<PostStmt>().getStmt();
2423 assert(AllocStmt && "Cannot find allocation statement");
2425 PathDiagnosticLocation AllocLocation =
2426 PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2427 AllocNode->getLocationContext());
2428 Location = AllocLocation;
2430 // Set uniqieing info, which will be used for unique the bug reports. The
2431 // leaks should be uniqued on the allocation site.
2432 UniqueingLocation = AllocLocation;
2433 UniqueingDecl = AllocNode->getLocationContext()->getDecl();
2435 // Fill in the description of the bug.
2436 Description.clear();
2437 llvm::raw_string_ostream os(Description);
2438 os << "Potential leak ";
2440 os << "(when using garbage collection) ";
2441 os << "of an object";
2444 os << " stored into '" << AllocBinding->getString() << '\'';
2445 if (IncludeAllocationLine) {
2446 FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager());
2447 os << " (allocated on line " << SL.getSpellingLineNumber() << ")";
2451 addVisitor(llvm::make_unique<CFRefLeakReportVisitor>(sym, GCEnabled, Log));
2454 //===----------------------------------------------------------------------===//
2455 // Main checker logic.
2456 //===----------------------------------------------------------------------===//
2459 class RetainCountChecker
2460 : public Checker< check::Bind,
2464 check::PostStmt<BlockExpr>,
2465 check::PostStmt<CastExpr>,
2466 check::PostStmt<ObjCArrayLiteral>,
2467 check::PostStmt<ObjCDictionaryLiteral>,
2468 check::PostStmt<ObjCBoxedExpr>,
2469 check::PostStmt<ObjCIvarRefExpr>,
2471 check::PreStmt<ReturnStmt>,
2472 check::RegionChanges,
2475 mutable std::unique_ptr<CFRefBug> useAfterRelease, releaseNotOwned;
2476 mutable std::unique_ptr<CFRefBug> deallocGC, deallocNotOwned;
2477 mutable std::unique_ptr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2478 mutable std::unique_ptr<CFRefBug> leakWithinFunction, leakAtReturn;
2479 mutable std::unique_ptr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
2481 typedef llvm::DenseMap<SymbolRef, const CheckerProgramPointTag *> SymbolTagMap;
2483 // This map is only used to ensure proper deletion of any allocated tags.
2484 mutable SymbolTagMap DeadSymbolTags;
2486 mutable std::unique_ptr<RetainSummaryManager> Summaries;
2487 mutable std::unique_ptr<RetainSummaryManager> SummariesGC;
2488 mutable SummaryLogTy SummaryLog;
2489 mutable bool ShouldResetSummaryLog;
2491 /// Optional setting to indicate if leak reports should include
2492 /// the allocation line.
2493 mutable bool IncludeAllocationLine;
2496 RetainCountChecker(AnalyzerOptions &AO)
2497 : ShouldResetSummaryLog(false),
2498 IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {}
2500 ~RetainCountChecker() override { DeleteContainerSeconds(DeadSymbolTags); }
2502 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2503 ExprEngine &Eng) const {
2504 // FIXME: This is a hack to make sure the summary log gets cleared between
2505 // analyses of different code bodies.
2507 // Why is this necessary? Because a checker's lifetime is tied to a
2508 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2509 // Once in a blue moon, a new ExplodedNode will have the same address as an
2510 // old one with an associated summary, and the bug report visitor gets very
2511 // confused. (To make things worse, the summary lifetime is currently also
2512 // tied to a code body, so we get a crash instead of incorrect results.)
2514 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2515 // changes, things will start going wrong again. Really the lifetime of this
2516 // log needs to be tied to either the specific nodes in it or the entire
2517 // ExplodedGraph, not to a specific part of the code being analyzed.
2519 // (Also, having stateful local data means that the same checker can't be
2520 // used from multiple threads, but a lot of checkers have incorrect
2521 // assumptions about that anyway. So that wasn't a priority at the time of
2524 // This happens at the end of analysis, but bug reports are emitted /after/
2525 // this point. So we can't just clear the summary log now. Instead, we mark
2526 // that the next time we access the summary log, it should be cleared.
2528 // If we never reset the summary log during /this/ code body analysis,
2529 // there were no new summaries. There might still have been summaries from
2530 // the /last/ analysis, so clear them out to make sure the bug report
2531 // visitors don't get confused.
2532 if (ShouldResetSummaryLog)
2535 ShouldResetSummaryLog = !SummaryLog.empty();
2538 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2539 bool GCEnabled) const {
2541 if (!leakWithinFunctionGC)
2542 leakWithinFunctionGC.reset(new Leak(this, "Leak of object when using "
2543 "garbage collection"));
2544 return leakWithinFunctionGC.get();
2546 if (!leakWithinFunction) {
2547 if (LOpts.getGC() == LangOptions::HybridGC) {
2548 leakWithinFunction.reset(new Leak(this,
2549 "Leak of object when not using "
2550 "garbage collection (GC) in "
2551 "dual GC/non-GC code"));
2553 leakWithinFunction.reset(new Leak(this, "Leak"));
2556 return leakWithinFunction.get();
2560 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2562 if (!leakAtReturnGC)
2563 leakAtReturnGC.reset(new Leak(this,
2564 "Leak of returned object when using "
2565 "garbage collection"));
2566 return leakAtReturnGC.get();
2568 if (!leakAtReturn) {
2569 if (LOpts.getGC() == LangOptions::HybridGC) {
2570 leakAtReturn.reset(new Leak(this,
2571 "Leak of returned object when not using "
2572 "garbage collection (GC) in dual "
2575 leakAtReturn.reset(new Leak(this, "Leak of returned object"));
2578 return leakAtReturn.get();
2582 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2583 bool GCEnabled) const {
2584 // FIXME: We don't support ARC being turned on and off during one analysis.
2585 // (nor, for that matter, do we support changing ASTContexts)
2586 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
2589 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
2591 assert(SummariesGC->isARCEnabled() == ARCEnabled);
2592 return *SummariesGC;
2595 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
2597 assert(Summaries->isARCEnabled() == ARCEnabled);
2602 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2603 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2606 void printState(raw_ostream &Out, ProgramStateRef State,
2607 const char *NL, const char *Sep) const override;
2609 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
2610 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2611 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
2613 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2614 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
2615 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2617 void checkPostStmt(const ObjCIvarRefExpr *IRE, CheckerContext &C) const;
2619 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
2621 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
2622 CheckerContext &C) const;
2624 void processSummaryOfInlined(const RetainSummary &Summ,
2625 const CallEvent &Call,
2626 CheckerContext &C) const;
2628 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2630 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
2631 bool Assumption) const;
2634 checkRegionChanges(ProgramStateRef state,
2635 const InvalidatedSymbols *invalidated,
2636 ArrayRef<const MemRegion *> ExplicitRegions,
2637 ArrayRef<const MemRegion *> Regions,
2638 const CallEvent *Call) const;
2640 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
2644 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2645 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2646 ExplodedNode *Pred, RetEffect RE, RefVal X,
2647 SymbolRef Sym, ProgramStateRef state) const;
2649 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
2650 void checkEndFunction(CheckerContext &C) const;
2652 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
2653 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2654 CheckerContext &C) const;
2656 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
2657 RefVal::Kind ErrorKind, SymbolRef Sym,
2658 CheckerContext &C) const;
2660 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
2662 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2664 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
2665 SymbolRef sid, RefVal V,
2666 SmallVectorImpl<SymbolRef> &Leaked) const;
2669 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2670 const ProgramPointTag *Tag, CheckerContext &Ctx,
2671 SymbolRef Sym, RefVal V) const;
2673 ExplodedNode *processLeaks(ProgramStateRef state,
2674 SmallVectorImpl<SymbolRef> &Leaked,
2675 CheckerContext &Ctx,
2676 ExplodedNode *Pred = nullptr) const;
2678 } // end anonymous namespace
2681 class StopTrackingCallback : public SymbolVisitor {
2682 ProgramStateRef state;
2684 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2685 ProgramStateRef getState() const { return state; }
2687 bool VisitSymbol(SymbolRef sym) override {
2688 state = state->remove<RefBindings>(sym);
2692 } // end anonymous namespace
2694 //===----------------------------------------------------------------------===//
2695 // Handle statements that may have an effect on refcounts.
2696 //===----------------------------------------------------------------------===//
2698 void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2699 CheckerContext &C) const {
2701 // Scan the BlockDecRefExprs for any object the retain count checker
2703 if (!BE->getBlockDecl()->hasCaptures())
2706 ProgramStateRef state = C.getState();
2707 const BlockDataRegion *R =
2708 cast<BlockDataRegion>(state->getSVal(BE,
2709 C.getLocationContext()).getAsRegion());
2711 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2712 E = R->referenced_vars_end();
2717 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2718 // via captured variables, even though captured variables result in a copy
2719 // and in implicit increment/decrement of a retain count.
2720 SmallVector<const MemRegion*, 10> Regions;
2721 const LocationContext *LC = C.getLocationContext();
2722 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2724 for ( ; I != E; ++I) {
2725 const VarRegion *VR = I.getCapturedRegion();
2726 if (VR->getSuperRegion() == R) {
2727 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2729 Regions.push_back(VR);
2733 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2734 Regions.data() + Regions.size()).getState();
2735 C.addTransition(state);
2738 void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2739 CheckerContext &C) const {
2740 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2744 ArgEffect AE = IncRef;
2746 switch (BE->getBridgeKind()) {
2747 case clang::OBC_Bridge:
2750 case clang::OBC_BridgeRetained:
2753 case clang::OBC_BridgeTransfer:
2754 AE = DecRefBridgedTransferred;
2758 ProgramStateRef state = C.getState();
2759 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
2762 const RefVal* T = getRefBinding(state, Sym);
2766 RefVal::Kind hasErr = (RefVal::Kind) 0;
2767 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
2770 // FIXME: If we get an error during a bridge cast, should we report it?
2774 C.addTransition(state);
2777 void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2778 const Expr *Ex) const {
2779 ProgramStateRef state = C.getState();
2780 const ExplodedNode *pred = C.getPredecessor();
2781 for (const Stmt *Child : Ex->children()) {
2782 SVal V = state->getSVal(Child, pred->getLocationContext());
2783 if (SymbolRef sym = V.getAsSymbol())
2784 if (const RefVal* T = getRefBinding(state, sym)) {
2785 RefVal::Kind hasErr = (RefVal::Kind) 0;
2786 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2788 processNonLeakError(state, Child->getSourceRange(), hasErr, sym, C);
2794 // Return the object as autoreleased.
2795 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2797 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2798 QualType ResultTy = Ex->getType();
2799 state = setRefBinding(state, sym,
2800 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
2803 C.addTransition(state);
2806 void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2807 CheckerContext &C) const {
2808 // Apply the 'MayEscape' to all values.
2809 processObjCLiterals(C, AL);
2812 void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2813 CheckerContext &C) const {
2814 // Apply the 'MayEscape' to all keys and values.
2815 processObjCLiterals(C, DL);
2818 void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2819 CheckerContext &C) const {
2820 const ExplodedNode *Pred = C.getPredecessor();
2821 const LocationContext *LCtx = Pred->getLocationContext();
2822 ProgramStateRef State = Pred->getState();
2824 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2825 QualType ResultTy = Ex->getType();
2826 State = setRefBinding(State, Sym,
2827 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
2830 C.addTransition(State);
2833 static bool wasLoadedFromIvar(SymbolRef Sym) {
2834 if (auto DerivedVal = dyn_cast<SymbolDerived>(Sym))
2835 return isa<ObjCIvarRegion>(DerivedVal->getRegion());
2836 if (auto RegionVal = dyn_cast<SymbolRegionValue>(Sym))
2837 return isa<ObjCIvarRegion>(RegionVal->getRegion());
2841 void RetainCountChecker::checkPostStmt(const ObjCIvarRefExpr *IRE,
2842 CheckerContext &C) const {
2843 Optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>();
2847 ProgramStateRef State = C.getState();
2848 SymbolRef Sym = State->getSVal(*IVarLoc).getAsSymbol();
2849 if (!Sym || !wasLoadedFromIvar(Sym))
2852 // Accessing an ivar directly is unusual. If we've done that, be more
2853 // forgiving about what the surrounding code is allowed to do.
2855 QualType Ty = Sym->getType();
2856 RetEffect::ObjKind Kind;
2857 if (Ty->isObjCRetainableType())
2858 Kind = RetEffect::ObjC;
2859 else if (coreFoundation::isCFObjectRef(Ty))
2860 Kind = RetEffect::CF;
2864 // If the value is already known to be nil, don't bother tracking it.
2865 ConstraintManager &CMgr = State->getConstraintManager();
2866 if (CMgr.isNull(State, Sym).isConstrainedTrue())
2869 if (const RefVal *RV = getRefBinding(State, Sym)) {
2870 // If we've seen this symbol before, or we're only seeing it now because
2871 // of something the analyzer has synthesized, don't do anything.
2872 if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None ||
2873 isSynthesizedAccessor(C.getStackFrame())) {
2877 // Note that this value has been loaded from an ivar.
2878 C.addTransition(setRefBinding(State, Sym, RV->withIvarAccess()));
2882 RefVal PlusZero = RefVal::makeNotOwned(Kind, Ty);
2884 // In a synthesized accessor, the effective retain count is +0.
2885 if (isSynthesizedAccessor(C.getStackFrame())) {
2886 C.addTransition(setRefBinding(State, Sym, PlusZero));
2890 State = setRefBinding(State, Sym, PlusZero.withIvarAccess());
2891 C.addTransition(State);
2894 void RetainCountChecker::checkPostCall(const CallEvent &Call,
2895 CheckerContext &C) const {
2896 RetainSummaryManager &Summaries = getSummaryManager(C);
2897 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
2900 processSummaryOfInlined(*Summ, Call, C);
2903 checkSummary(*Summ, Call, C);
2906 /// GetReturnType - Used to get the return type of a message expression or
2907 /// function call with the intention of affixing that type to a tracked symbol.
2908 /// While the return type can be queried directly from RetEx, when
2909 /// invoking class methods we augment to the return type to be that of
2910 /// a pointer to the class (as opposed it just being id).
2911 // FIXME: We may be able to do this with related result types instead.
2912 // This function is probably overestimating.
2913 static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2914 QualType RetTy = RetE->getType();
2915 // If RetE is not a message expression just return its type.
2916 // If RetE is a message expression, return its types if it is something
2917 /// more specific than id.
2918 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2919 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2920 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2921 PT->isObjCClassType()) {
2922 // At this point we know the return type of the message expression is
2923 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2924 // is a call to a class method whose type we can resolve. In such
2925 // cases, promote the return type to XXX* (where XXX is the class).
2926 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2928 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2934 // We don't always get the exact modeling of the function with regards to the
2935 // retain count checker even when the function is inlined. For example, we need
2936 // to stop tracking the symbols which were marked with StopTrackingHard.
2937 void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2938 const CallEvent &CallOrMsg,
2939 CheckerContext &C) const {
2940 ProgramStateRef state = C.getState();
2942 // Evaluate the effect of the arguments.
2943 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2944 if (Summ.getArg(idx) == StopTrackingHard) {
2945 SVal V = CallOrMsg.getArgSVal(idx);
2946 if (SymbolRef Sym = V.getAsLocSymbol()) {
2947 state = removeRefBinding(state, Sym);
2952 // Evaluate the effect on the message receiver.
2953 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2954 if (MsgInvocation) {
2955 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2956 if (Summ.getReceiverEffect() == StopTrackingHard) {
2957 state = removeRefBinding(state, Sym);
2962 // Consult the summary for the return value.
2963 RetEffect RE = Summ.getRetEffect();
2964 if (RE.getKind() == RetEffect::NoRetHard) {
2965 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
2967 state = removeRefBinding(state, Sym);
2970 C.addTransition(state);
2973 static ProgramStateRef updateOutParameter(ProgramStateRef State,
2976 auto *ArgRegion = dyn_cast_or_null<TypedValueRegion>(ArgVal.getAsRegion());
2980 QualType PointeeTy = ArgRegion->getValueType();
2981 if (!coreFoundation::isCFObjectRef(PointeeTy))
2984 SVal PointeeVal = State->getSVal(ArgRegion);
2985 SymbolRef Pointee = PointeeVal.getAsLocSymbol();
2990 case UnretainedOutParameter:
2991 State = setRefBinding(State, Pointee,
2992 RefVal::makeNotOwned(RetEffect::CF, PointeeTy));
2994 case RetainedOutParameter:
2995 // Do nothing. Retained out parameters will either point to a +1 reference
2996 // or NULL, but the way you check for failure differs depending on the API.
2997 // Consequently, we don't have a good way to track them yet.
3001 llvm_unreachable("only for out parameters");
3007 void RetainCountChecker::checkSummary(const RetainSummary &Summ,
3008 const CallEvent &CallOrMsg,
3009 CheckerContext &C) const {
3010 ProgramStateRef state = C.getState();
3012 // Evaluate the effect of the arguments.
3013 RefVal::Kind hasErr = (RefVal::Kind) 0;
3014 SourceRange ErrorRange;
3015 SymbolRef ErrorSym = nullptr;
3017 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
3018 SVal V = CallOrMsg.getArgSVal(idx);
3020 ArgEffect Effect = Summ.getArg(idx);
3021 if (Effect == RetainedOutParameter || Effect == UnretainedOutParameter) {
3022 state = updateOutParameter(state, V, Effect);
3023 } else if (SymbolRef Sym = V.getAsLocSymbol()) {
3024 if (const RefVal *T = getRefBinding(state, Sym)) {
3025 state = updateSymbol(state, Sym, *T, Effect, hasErr, C);
3027 ErrorRange = CallOrMsg.getArgSourceRange(idx);
3035 // Evaluate the effect on the message receiver.
3036 bool ReceiverIsTracked = false;
3038 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
3039 if (MsgInvocation) {
3040 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
3041 if (const RefVal *T = getRefBinding(state, Sym)) {
3042 ReceiverIsTracked = true;
3043 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
3046 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
3054 // Process any errors.
3056 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
3060 // Consult the summary for the return value.
3061 RetEffect RE = Summ.getRetEffect();
3063 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
3064 if (ReceiverIsTracked)
3065 RE = getSummaryManager(C).getObjAllocRetEffect();
3067 RE = RetEffect::MakeNoRet();
3070 switch (RE.getKind()) {
3072 llvm_unreachable("Unhandled RetEffect.");
3074 case RetEffect::NoRet:
3075 case RetEffect::NoRetHard:
3076 // No work necessary.
3079 case RetEffect::OwnedAllocatedSymbol:
3080 case RetEffect::OwnedSymbol: {
3081 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
3085 // Use the result type from the CallEvent as it automatically adjusts
3086 // for methods/functions that return references.
3087 QualType ResultTy = CallOrMsg.getResultType();
3088 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
3091 // FIXME: Add a flag to the checker where allocations are assumed to
3096 case RetEffect::GCNotOwnedSymbol:
3097 case RetEffect::NotOwnedSymbol: {
3098 const Expr *Ex = CallOrMsg.getOriginExpr();
3099 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
3103 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
3104 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
3105 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
3111 // This check is actually necessary; otherwise the statement builder thinks
3112 // we've hit a previously-found path.
3113 // Normally addTransition takes care of this, but we want the node pointer.
3114 ExplodedNode *NewNode;
3115 if (state == C.getState()) {
3116 NewNode = C.getPredecessor();
3118 NewNode = C.addTransition(state);
3121 // Annotate the node with summary we used.
3123 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
3124 if (ShouldResetSummaryLog) {
3126 ShouldResetSummaryLog = false;
3128 SummaryLog[NewNode] = &Summ;
3134 RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
3135 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
3136 CheckerContext &C) const {
3137 // In GC mode [... release] and [... retain] do nothing.
3138 // In ARC mode they shouldn't exist at all, but we just ignore them.
3139 bool IgnoreRetainMsg = C.isObjCGCEnabled();
3140 if (!IgnoreRetainMsg)
3141 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
3147 E = IgnoreRetainMsg ? DoNothing : IncRef;
3150 E = IgnoreRetainMsg ? DoNothing : DecRef;
3152 case DecRefMsgAndStopTrackingHard:
3153 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
3155 case MakeCollectable:
3156 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
3160 // Handle all use-after-releases.
3161 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
3162 V = V ^ RefVal::ErrorUseAfterRelease;
3163 hasErr = V.getKind();
3164 return setRefBinding(state, sym, V);
3170 case MakeCollectable:
3171 case DecRefMsgAndStopTrackingHard:
3172 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
3174 case UnretainedOutParameter:
3175 case RetainedOutParameter:
3176 llvm_unreachable("Applies to pointer-to-pointer parameters, which should "
3177 "not have ref state.");
3180 // Any use of -dealloc in GC is *bad*.
3181 if (C.isObjCGCEnabled()) {
3182 V = V ^ RefVal::ErrorDeallocGC;
3183 hasErr = V.getKind();
3187 switch (V.getKind()) {
3189 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
3191 // The object immediately transitions to the released state.
3192 V = V ^ RefVal::Released;
3194 return setRefBinding(state, sym, V);
3195 case RefVal::NotOwned:
3196 V = V ^ RefVal::ErrorDeallocNotOwned;
3197 hasErr = V.getKind();
3203 if (V.getKind() == RefVal::Owned) {
3204 V = V ^ RefVal::NotOwned;
3214 if (C.isObjCGCEnabled())
3216 // Update the autorelease counts.
3217 V = V.autorelease();
3221 case StopTrackingHard:
3222 return removeRefBinding(state, sym);
3225 switch (V.getKind()) {
3227 llvm_unreachable("Invalid RefVal state for a retain.");
3229 case RefVal::NotOwned:
3232 case RefVal::Released:
3233 // Non-GC cases are handled above.
3234 assert(C.isObjCGCEnabled());
3235 V = (V ^ RefVal::Owned) + 1;
3241 case DecRefBridgedTransferred:
3242 case DecRefAndStopTrackingHard:
3243 switch (V.getKind()) {
3245 // case 'RefVal::Released' handled above.
3246 llvm_unreachable("Invalid RefVal state for a release.");
3249 assert(V.getCount() > 0);
3250 if (V.getCount() == 1) {
3251 if (E == DecRefBridgedTransferred ||
3252 V.getIvarAccessHistory() ==
3253 RefVal::IvarAccessHistory::AccessedDirectly)
3254 V = V ^ RefVal::NotOwned;
3256 V = V ^ RefVal::Released;
3257 } else if (E == DecRefAndStopTrackingHard) {
3258 return removeRefBinding(state, sym);
3264 case RefVal::NotOwned:
3265 if (V.getCount() > 0) {
3266 if (E == DecRefAndStopTrackingHard)
3267 return removeRefBinding(state, sym);
3269 } else if (V.getIvarAccessHistory() ==
3270 RefVal::IvarAccessHistory::AccessedDirectly) {
3271 // Assume that the instance variable was holding on the object at
3272 // +1, and we just didn't know.
3273 if (E == DecRefAndStopTrackingHard)
3274 return removeRefBinding(state, sym);
3275 V = V.releaseViaIvar() ^ RefVal::Released;
3277 V = V ^ RefVal::ErrorReleaseNotOwned;
3278 hasErr = V.getKind();
3282 case RefVal::Released:
3283 // Non-GC cases are handled above.
3284 assert(C.isObjCGCEnabled());
3285 V = V ^ RefVal::ErrorUseAfterRelease;
3286 hasErr = V.getKind();
3291 return setRefBinding(state, sym, V);
3294 void RetainCountChecker::processNonLeakError(ProgramStateRef St,
3295 SourceRange ErrorRange,
3296 RefVal::Kind ErrorKind,
3298 CheckerContext &C) const {
3299 // HACK: Ignore retain-count issues on values accessed through ivars,
3300 // because of cases like this:
3301 // [_contentView retain];
3302 // [_contentView removeFromSuperview];
3303 // [self addSubview:_contentView]; // invalidates 'self'
3304 // [_contentView release];
3305 if (const RefVal *RV = getRefBinding(St, Sym))
3306 if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3309 ExplodedNode *N = C.generateSink(St);
3314 switch (ErrorKind) {
3316 llvm_unreachable("Unhandled error.");
3317 case RefVal::ErrorUseAfterRelease:
3318 if (!useAfterRelease)
3319 useAfterRelease.reset(new UseAfterRelease(this));
3320 BT = useAfterRelease.get();
3322 case RefVal::ErrorReleaseNotOwned:
3323 if (!releaseNotOwned)
3324 releaseNotOwned.reset(new BadRelease(this));
3325 BT = releaseNotOwned.get();
3327 case RefVal::ErrorDeallocGC:
3329 deallocGC.reset(new DeallocGC(this));
3330 BT = deallocGC.get();
3332 case RefVal::ErrorDeallocNotOwned:
3333 if (!deallocNotOwned)
3334 deallocNotOwned.reset(new DeallocNotOwned(this));
3335 BT = deallocNotOwned.get();
3340 auto report = std::unique_ptr<BugReport>(
3341 new CFRefReport(*BT, C.getASTContext().getLangOpts(), C.isObjCGCEnabled(),
3342 SummaryLog, N, Sym));
3343 report->addRange(ErrorRange);
3344 C.emitReport(std::move(report));
3347 //===----------------------------------------------------------------------===//
3348 // Handle the return values of retain-count-related functions.
3349 //===----------------------------------------------------------------------===//
3351 bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
3352 // Get the callee. We're only interested in simple C functions.
3353 ProgramStateRef state = C.getState();
3354 const FunctionDecl *FD = C.getCalleeDecl(CE);
3358 IdentifierInfo *II = FD->getIdentifier();
3362 // For now, we're only handling the functions that return aliases of their
3363 // arguments: CFRetain and CFMakeCollectable (and their families).
3364 // Eventually we should add other functions we can model entirely,
3365 // such as CFRelease, which don't invalidate their arguments or globals.
3366 if (CE->getNumArgs() != 1)
3369 // Get the name of the function.
3370 StringRef FName = II->getName();
3371 FName = FName.substr(FName.find_first_not_of('_'));
3373 // See if it's one of the specific functions we know how to eval.
3374 bool canEval = false;
3376 QualType ResultTy = CE->getCallReturnType(C.getASTContext());
3377 if (ResultTy->isObjCIdType()) {
3378 // Handle: id NSMakeCollectable(CFTypeRef)
3379 canEval = II->isStr("NSMakeCollectable");
3380 } else if (ResultTy->isPointerType()) {
3381 // Handle: (CF|CG)Retain
3383 // CFMakeCollectable
3384 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3385 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3386 cocoa::isRefType(ResultTy, "CG", FName)) {
3387 canEval = isRetain(FD, FName) || isAutorelease(FD, FName) ||
3388 isMakeCollectable(FD, FName);
3395 // Bind the return value.
3396 const LocationContext *LCtx = C.getLocationContext();
3397 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
3398 if (RetVal.isUnknown()) {
3399 // If the receiver is unknown, conjure a return value.
3400 SValBuilder &SVB = C.getSValBuilder();
3401 RetVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, ResultTy, C.blockCount());
3403 state = state->BindExpr(CE, LCtx, RetVal, false);
3405 // FIXME: This should not be necessary, but otherwise the argument seems to be
3406 // considered alive during the next statement.
3407 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3408 // Save the refcount status of the argument.
3409 SymbolRef Sym = RetVal.getAsLocSymbol();
3410 const RefVal *Binding = nullptr;
3412 Binding = getRefBinding(state, Sym);
3414 // Invalidate the argument region.
3415 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
3416 /*CausesPointerEscape*/ false);
3418 // Restore the refcount status of the argument.
3420 state = setRefBinding(state, Sym, *Binding);
3423 C.addTransition(state);
3427 //===----------------------------------------------------------------------===//
3428 // Handle return statements.
3429 //===----------------------------------------------------------------------===//
3431 void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3432 CheckerContext &C) const {
3434 // Only adjust the reference count if this is the top-level call frame,
3435 // and not the result of inlining. In the future, we should do
3436 // better checking even for inlined calls, and see if they match
3437 // with their expected semantics (e.g., the method should return a retained
3439 if (!C.inTopFrame())
3442 const Expr *RetE = S->getRetValue();
3446 ProgramStateRef state = C.getState();
3448 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
3452 // Get the reference count binding (if any).
3453 const RefVal *T = getRefBinding(state, Sym);
3457 // Change the reference count.
3460 switch (X.getKind()) {
3461 case RefVal::Owned: {
3462 unsigned cnt = X.getCount();
3464 X.setCount(cnt - 1);
3465 X = X ^ RefVal::ReturnedOwned;
3469 case RefVal::NotOwned: {
3470 unsigned cnt = X.getCount();
3472 X.setCount(cnt - 1);
3473 X = X ^ RefVal::ReturnedOwned;
3476 X = X ^ RefVal::ReturnedNotOwned;
3485 // Update the binding.
3486 state = setRefBinding(state, Sym, X);
3487 ExplodedNode *Pred = C.addTransition(state);
3489 // At this point we have updated the state properly.
3490 // Everything after this is merely checking to see if the return value has
3491 // been over- or under-retained.
3493 // Did we cache out?
3497 // Update the autorelease counts.
3498 static CheckerProgramPointTag AutoreleaseTag(this, "Autorelease");
3499 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
3501 // Did we cache out?
3505 // Get the updated binding.
3506 T = getRefBinding(state, Sym);
3510 // Consult the summary of the enclosing method.
3511 RetainSummaryManager &Summaries = getSummaryManager(C);
3512 const Decl *CD = &Pred->getCodeDecl();
3513 RetEffect RE = RetEffect::MakeNoRet();
3515 // FIXME: What is the convention for blocks? Is there one?
3516 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
3517 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
3518 RE = Summ->getRetEffect();
3519 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3520 if (!isa<CXXMethodDecl>(FD)) {
3521 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3522 RE = Summ->getRetEffect();
3526 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
3529 void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3532 RetEffect RE, RefVal X,
3534 ProgramStateRef state) const {
3535 // HACK: Ignore retain-count issues on values accessed through ivars,
3536 // because of cases like this:
3537 // [_contentView retain];
3538 // [_contentView removeFromSuperview];
3539 // [self addSubview:_contentView]; // invalidates 'self'
3540 // [_contentView release];
3541 if (X.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3544 // Any leaks or other errors?
3545 if (X.isReturnedOwned() && X.getCount() == 0) {
3546 if (RE.getKind() != RetEffect::NoRet) {
3547 bool hasError = false;
3548 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3549 // Things are more complicated with garbage collection. If the
3550 // returned object is suppose to be an Objective-C object, we have
3551 // a leak (as the caller expects a GC'ed object) because no
3552 // method should return ownership unless it returns a CF object.
3554 X = X ^ RefVal::ErrorGCLeakReturned;
3556 else if (!RE.isOwned()) {
3557 // Either we are using GC and the returned object is a CF type
3558 // or we aren't using GC. In either case, we expect that the
3559 // enclosing method is expected to return ownership.
3561 X = X ^ RefVal::ErrorLeakReturned;
3565 // Generate an error node.
3566 state = setRefBinding(state, Sym, X);
3568 static CheckerProgramPointTag ReturnOwnLeakTag(this, "ReturnsOwnLeak");
3569 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
3571 const LangOptions &LOpts = C.getASTContext().getLangOpts();
3572 bool GCEnabled = C.isObjCGCEnabled();
3573 C.emitReport(std::unique_ptr<BugReport>(new CFRefLeakReport(
3574 *getLeakAtReturnBug(LOpts, GCEnabled), LOpts, GCEnabled,
3575 SummaryLog, N, Sym, C, IncludeAllocationLine)));
3579 } else if (X.isReturnedNotOwned()) {
3581 if (X.getIvarAccessHistory() ==
3582 RefVal::IvarAccessHistory::AccessedDirectly) {
3583 // Assume the method was trying to transfer a +1 reference from a
3584 // strong ivar to the caller.
3585 state = setRefBinding(state, Sym,
3586 X.releaseViaIvar() ^ RefVal::ReturnedOwned);
3588 // Trying to return a not owned object to a caller expecting an
3590 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
3592 static CheckerProgramPointTag
3593 ReturnNotOwnedTag(this, "ReturnNotOwnedForOwned");
3595 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
3597 if (!returnNotOwnedForOwned)
3598 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned(this));
3600 C.emitReport(std::unique_ptr<BugReport>(new CFRefReport(
3601 *returnNotOwnedForOwned, C.getASTContext().getLangOpts(),
3602 C.isObjCGCEnabled(), SummaryLog, N, Sym)));
3609 //===----------------------------------------------------------------------===//
3610 // Check various ways a symbol can be invalidated.
3611 //===----------------------------------------------------------------------===//
3613 void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
3614 CheckerContext &C) const {
3615 // Are we storing to something that causes the value to "escape"?
3616 bool escapes = true;
3618 // A value escapes in three possible cases (this may change):
3620 // (1) we are binding to something that is not a memory region.
3621 // (2) we are binding to a memregion that does not have stack storage
3622 // (3) we are binding to a memregion with stack storage that the store
3623 // does not understand.
3624 ProgramStateRef state = C.getState();
3626 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
3627 escapes = !regionLoc->getRegion()->hasStackStorage();
3630 // To test (3), generate a new state with the binding added. If it is
3631 // the same state, then it escapes (since the store cannot represent
3633 // Do this only if we know that the store is not supposed to generate the
3635 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3636 if (StoredVal != val)
3637 escapes = (state == (state->bindLoc(*regionLoc, val)));
3640 // Case 4: We do not currently model what happens when a symbol is
3641 // assigned to a struct field, so be conservative here and let the symbol
3642 // go. TODO: This could definitely be improved upon.
3643 escapes = !isa<VarRegion>(regionLoc->getRegion());
3647 // If we are storing the value into an auto function scope variable annotated
3648 // with (__attribute__((cleanup))), stop tracking the value to avoid leak
3650 if (const VarRegion *LVR = dyn_cast_or_null<VarRegion>(loc.getAsRegion())) {
3651 const VarDecl *VD = LVR->getDecl();
3652 if (VD->hasAttr<CleanupAttr>()) {
3657 // If our store can represent the binding and we aren't storing to something
3658 // that doesn't have local storage then just return and have the simulation
3659 // state continue as is.
3663 // Otherwise, find all symbols referenced by 'val' that we are tracking
3664 // and stop tracking them.
3665 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
3666 C.addTransition(state);
3669 ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
3671 bool Assumption) const {
3673 // FIXME: We may add to the interface of evalAssume the list of symbols
3674 // whose assumptions have changed. For now we just iterate through the
3675 // bindings and check if any of the tracked symbols are NULL. This isn't
3676 // too bad since the number of symbols we will track in practice are
3677 // probably small and evalAssume is only called at branches and a few
3679 RefBindingsTy B = state->get<RefBindings>();
3684 bool changed = false;
3685 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
3687 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3688 // Check if the symbol is null stop tracking the symbol.
3689 ConstraintManager &CMgr = state->getConstraintManager();
3690 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3691 if (AllocFailed.isConstrainedTrue()) {
3693 B = RefBFactory.remove(B, I.getKey());
3698 state = state->set<RefBindings>(B);
3704 RetainCountChecker::checkRegionChanges(ProgramStateRef state,
3705 const InvalidatedSymbols *invalidated,
3706 ArrayRef<const MemRegion *> ExplicitRegions,
3707 ArrayRef<const MemRegion *> Regions,
3708 const CallEvent *Call) const {
3712 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3713 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3714 E = ExplicitRegions.end(); I != E; ++I) {
3715 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3716 WhitelistedSymbols.insert(SR->getSymbol());
3719 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
3720 E = invalidated->end(); I!=E; ++I) {
3722 if (WhitelistedSymbols.count(sym))
3724 // Remove any existing reference-count binding.
3725 state = removeRefBinding(state, sym);
3730 //===----------------------------------------------------------------------===//
3731 // Handle dead symbols and end-of-path.
3732 //===----------------------------------------------------------------------===//
3735 RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
3737 const ProgramPointTag *Tag,
3738 CheckerContext &Ctx,
3739 SymbolRef Sym, RefVal V) const {
3740 unsigned ACnt = V.getAutoreleaseCount();
3742 // No autorelease counts? Nothing to be done.
3746 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
3747 unsigned Cnt = V.getCount();
3749 // FIXME: Handle sending 'autorelease' to already released object.
3751 if (V.getKind() == RefVal::ReturnedOwned)
3754 // If we would over-release here, but we know the value came from an ivar,
3755 // assume it was a strong ivar that's just been relinquished.
3757 V.getIvarAccessHistory() == RefVal::IvarAccessHistory::AccessedDirectly) {
3758 V = V.releaseViaIvar();
3765 if (V.getKind() == RefVal::ReturnedOwned)
3766 V = V ^ RefVal::ReturnedNotOwned;
3768 V = V ^ RefVal::NotOwned;
3770 V.setCount(V.getCount() - ACnt);
3771 V.setAutoreleaseCount(0);
3773 return setRefBinding(state, Sym, V);
3776 // HACK: Ignore retain-count issues on values accessed through ivars,
3777 // because of cases like this:
3778 // [_contentView retain];
3779 // [_contentView removeFromSuperview];
3780 // [self addSubview:_contentView]; // invalidates 'self'
3781 // [_contentView release];
3782 if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3785 // Woah! More autorelease counts then retain counts left.
3787 V = V ^ RefVal::ErrorOverAutorelease;
3788 state = setRefBinding(state, Sym, V);
3790 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
3792 SmallString<128> sbuf;
3793 llvm::raw_svector_ostream os(sbuf);
3794 os << "Object was autoreleased ";
3795 if (V.getAutoreleaseCount() > 1)
3796 os << V.getAutoreleaseCount() << " times but the object ";
3799 os << "has a +" << V.getCount() << " retain count";
3801 if (!overAutorelease)
3802 overAutorelease.reset(new OverAutorelease(this));
3804 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3805 Ctx.emitReport(std::unique_ptr<BugReport>(
3806 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3807 SummaryLog, N, Sym, os.str())));
3814 RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
3815 SymbolRef sid, RefVal V,
3816 SmallVectorImpl<SymbolRef> &Leaked) const {
3819 // HACK: Ignore retain-count issues on values accessed through ivars,
3820 // because of cases like this:
3821 // [_contentView retain];
3822 // [_contentView removeFromSuperview];
3823 // [self addSubview:_contentView]; // invalidates 'self'
3824 // [_contentView release];
3825 if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3827 else if (V.isOwned())
3829 else if (V.isNotOwned() || V.isReturnedOwned())
3830 hasLeak = (V.getCount() > 0);
3835 return removeRefBinding(state, sid);
3837 Leaked.push_back(sid);
3838 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
3842 RetainCountChecker::processLeaks(ProgramStateRef state,
3843 SmallVectorImpl<SymbolRef> &Leaked,
3844 CheckerContext &Ctx,
3845 ExplodedNode *Pred) const {
3846 // Generate an intermediate node representing the leak point.
3847 ExplodedNode *N = Ctx.addTransition(state, Pred);
3850 for (SmallVectorImpl<SymbolRef>::iterator
3851 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3853 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3854 bool GCEnabled = Ctx.isObjCGCEnabled();
3855 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3856 : getLeakAtReturnBug(LOpts, GCEnabled);
3857 assert(BT && "BugType not initialized.");
3859 Ctx.emitReport(std::unique_ptr<BugReport>(
3860 new CFRefLeakReport(*BT, LOpts, GCEnabled, SummaryLog, N, *I, Ctx,
3861 IncludeAllocationLine)));
3868 void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
3869 ProgramStateRef state = Ctx.getState();
3870 RefBindingsTy B = state->get<RefBindings>();
3871 ExplodedNode *Pred = Ctx.getPredecessor();
3873 // Don't process anything within synthesized bodies.
3874 const LocationContext *LCtx = Pred->getLocationContext();
3875 if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
3876 assert(LCtx->getParent());
3880 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3881 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/nullptr, Ctx,
3882 I->first, I->second);
3887 // If the current LocationContext has a parent, don't check for leaks.
3888 // We will do that later.
3889 // FIXME: we should instead check for imbalances of the retain/releases,
3890 // and suggest annotations.
3891 if (LCtx->getParent())
3894 B = state->get<RefBindings>();
3895 SmallVector<SymbolRef, 10> Leaked;
3897 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
3898 state = handleSymbolDeath(state, I->first, I->second, Leaked);
3900 processLeaks(state, Leaked, Ctx, Pred);
3903 const ProgramPointTag *
3904 RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
3905 const CheckerProgramPointTag *&tag = DeadSymbolTags[sym];
3907 SmallString<64> buf;
3908 llvm::raw_svector_ostream out(buf);
3909 out << "Dead Symbol : ";
3910 sym->dumpToStream(out);
3911 tag = new CheckerProgramPointTag(this, out.str());
3916 void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3917 CheckerContext &C) const {
3918 ExplodedNode *Pred = C.getPredecessor();
3920 ProgramStateRef state = C.getState();
3921 RefBindingsTy B = state->get<RefBindings>();
3922 SmallVector<SymbolRef, 10> Leaked;
3924 // Update counts from autorelease pools
3925 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3926 E = SymReaper.dead_end(); I != E; ++I) {
3928 if (const RefVal *T = B.lookup(Sym)){
3929 // Use the symbol as the tag.
3930 // FIXME: This might not be as unique as we would like.
3931 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
3932 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
3936 // Fetch the new reference count from the state, and use it to handle
3938 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
3942 if (Leaked.empty()) {
3943 C.addTransition(state);
3947 Pred = processLeaks(state, Leaked, C, Pred);
3949 // Did we cache out?
3953 // Now generate a new node that nukes the old bindings.
3954 // The only bindings left at this point are the leaked symbols.
3955 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
3956 B = state->get<RefBindings>();
3958 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3961 B = F.remove(B, *I);
3963 state = state->set<RefBindings>(B);
3964 C.addTransition(state, Pred);
3967 void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
3968 const char *NL, const char *Sep) const {
3970 RefBindingsTy B = State->get<RefBindings>();
3977 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3978 Out << I->first << " : ";
3979 I->second.print(Out);
3984 //===----------------------------------------------------------------------===//
3985 // Checker registration.
3986 //===----------------------------------------------------------------------===//
3988 void ento::registerRetainCountChecker(CheckerManager &Mgr) {
3989 Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
3992 //===----------------------------------------------------------------------===//
3993 // Implementation of the CallEffects API.
3994 //===----------------------------------------------------------------------===//
3996 namespace clang { namespace ento { namespace objc_retain {
3998 // This is a bit gross, but it allows us to populate CallEffects without
3999 // creating a bunch of accessors. This kind is very localized, so the
4000 // damage of this macro is limited.
4001 #define createCallEffect(D, KIND)\
4002 ASTContext &Ctx = D->getASTContext();\
4003 LangOptions L = Ctx.getLangOpts();\
4004 RetainSummaryManager M(Ctx, L.GCOnly, L.ObjCAutoRefCount);\
4005 const RetainSummary *S = M.get ## KIND ## Summary(D);\
4006 CallEffects CE(S->getRetEffect());\
4007 CE.Receiver = S->getReceiverEffect();\
4008 unsigned N = D->param_size();\
4009 for (unsigned i = 0; i < N; ++i) {\
4010 CE.Args.push_back(S->getArg(i));\
4013 CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) {
4014 createCallEffect(MD, Method);
4018 CallEffects CallEffects::getEffect(const FunctionDecl *FD) {
4019 createCallEffect(FD, Function);
4023 #undef createCallEffect