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 "AllocationDiagnostics.h"
16 #include "ClangSACheckers.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"
44 using namespace clang;
46 using namespace objc_retain;
47 using llvm::StrInStrNoCase;
49 //===----------------------------------------------------------------------===//
50 // Adapters for FoldingSet.
51 //===----------------------------------------------------------------------===//
54 template <> struct FoldingSetTrait<ArgEffect> {
55 static inline void Profile(const ArgEffect X, FoldingSetNodeID &ID) {
56 ID.AddInteger((unsigned) X);
59 template <> struct FoldingSetTrait<RetEffect> {
60 static inline void Profile(const RetEffect &X, FoldingSetNodeID &ID) {
61 ID.AddInteger((unsigned) X.getKind());
62 ID.AddInteger((unsigned) X.getObjKind());
65 } // end llvm namespace
67 //===----------------------------------------------------------------------===//
68 // Reference-counting logic (typestate + counts).
69 //===----------------------------------------------------------------------===//
71 /// ArgEffects summarizes the effects of a function/method call on all of
73 typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
79 Owned = 0, // Owning reference.
80 NotOwned, // Reference is not owned by still valid (not freed).
81 Released, // Object has been released.
82 ReturnedOwned, // Returned object passes ownership to caller.
83 ReturnedNotOwned, // Return object does not pass ownership to caller.
85 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
86 ErrorDeallocGC, // Calling -dealloc with GC enabled.
87 ErrorUseAfterRelease, // Object used after released.
88 ErrorReleaseNotOwned, // Release of an object that was not owned.
90 ErrorLeak, // A memory leak due to excessive reference counts.
91 ErrorLeakReturned, // A memory leak due to the returning method not having
92 // the correct naming conventions.
98 /// Tracks how an object referenced by an ivar has been used.
100 /// This accounts for us not knowing if an arbitrary ivar is supposed to be
101 /// stored at +0 or +1.
102 enum class IvarAccessHistory {
105 ReleasedAfterDirectAccess
109 /// The number of outstanding retains.
111 /// The number of outstanding autoreleases.
113 /// The (static) type of the object at the time we started tracking it.
116 /// The current state of the object.
118 /// See the RefVal::Kind enum for possible values.
119 unsigned RawKind : 5;
121 /// The kind of object being tracked (CF or ObjC), if known.
123 /// See the RetEffect::ObjKind enum for possible values.
124 unsigned RawObjectKind : 2;
126 /// True if the current state and/or retain count may turn out to not be the
127 /// best possible approximation of the reference counting state.
129 /// If true, the checker may decide to throw away ("override") this state
130 /// in favor of something else when it sees the object being used in new ways.
132 /// This setting should not be propagated to state derived from this state.
133 /// Once we start deriving new states, it would be inconsistent to override
135 unsigned RawIvarAccessHistory : 2;
137 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t,
138 IvarAccessHistory IvarAccess)
139 : Cnt(cnt), ACnt(acnt), T(t), RawKind(static_cast<unsigned>(k)),
140 RawObjectKind(static_cast<unsigned>(o)),
141 RawIvarAccessHistory(static_cast<unsigned>(IvarAccess)) {
142 assert(getKind() == k && "not enough bits for the kind");
143 assert(getObjKind() == o && "not enough bits for the object kind");
144 assert(getIvarAccessHistory() == IvarAccess && "not enough bits");
148 Kind getKind() const { return static_cast<Kind>(RawKind); }
150 RetEffect::ObjKind getObjKind() const {
151 return static_cast<RetEffect::ObjKind>(RawObjectKind);
154 unsigned getCount() const { return Cnt; }
155 unsigned getAutoreleaseCount() const { return ACnt; }
156 unsigned getCombinedCounts() const { return Cnt + ACnt; }
161 void setCount(unsigned i) {
164 void setAutoreleaseCount(unsigned i) {
168 QualType getType() const { return T; }
170 /// Returns what the analyzer knows about direct accesses to a particular
171 /// instance variable.
173 /// If the object with this refcount wasn't originally from an Objective-C
174 /// ivar region, this should always return IvarAccessHistory::None.
175 IvarAccessHistory getIvarAccessHistory() const {
176 return static_cast<IvarAccessHistory>(RawIvarAccessHistory);
179 bool isOwned() const {
180 return getKind() == Owned;
183 bool isNotOwned() const {
184 return getKind() == NotOwned;
187 bool isReturnedOwned() const {
188 return getKind() == ReturnedOwned;
191 bool isReturnedNotOwned() const {
192 return getKind() == ReturnedNotOwned;
195 /// Create a state for an object whose lifetime is the responsibility of the
196 /// current function, at least partially.
198 /// Most commonly, this is an owned object with a retain count of +1.
199 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
200 unsigned Count = 1) {
201 return RefVal(Owned, o, Count, 0, t, IvarAccessHistory::None);
204 /// Create a state for an object whose lifetime is not the responsibility of
205 /// the current function.
207 /// Most commonly, this is an unowned object with a retain count of +0.
208 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
209 unsigned Count = 0) {
210 return RefVal(NotOwned, o, Count, 0, t, IvarAccessHistory::None);
213 RefVal operator-(size_t i) const {
214 return RefVal(getKind(), getObjKind(), getCount() - i,
215 getAutoreleaseCount(), getType(), getIvarAccessHistory());
218 RefVal operator+(size_t i) const {
219 return RefVal(getKind(), getObjKind(), getCount() + i,
220 getAutoreleaseCount(), getType(), getIvarAccessHistory());
223 RefVal operator^(Kind k) const {
224 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
225 getType(), getIvarAccessHistory());
228 RefVal autorelease() const {
229 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
230 getType(), getIvarAccessHistory());
233 RefVal withIvarAccess() const {
234 assert(getIvarAccessHistory() == IvarAccessHistory::None);
235 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount(),
236 getType(), IvarAccessHistory::AccessedDirectly);
239 RefVal releaseViaIvar() const {
240 assert(getIvarAccessHistory() == IvarAccessHistory::AccessedDirectly);
241 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount(),
242 getType(), IvarAccessHistory::ReleasedAfterDirectAccess);
245 // Comparison, profiling, and pretty-printing.
247 bool hasSameState(const RefVal &X) const {
248 return getKind() == X.getKind() && Cnt == X.Cnt && ACnt == X.ACnt &&
249 getIvarAccessHistory() == X.getIvarAccessHistory();
252 bool operator==(const RefVal& X) const {
253 return T == X.T && hasSameState(X) && getObjKind() == X.getObjKind();
256 void Profile(llvm::FoldingSetNodeID& ID) const {
258 ID.AddInteger(RawKind);
261 ID.AddInteger(RawObjectKind);
262 ID.AddInteger(RawIvarAccessHistory);
265 void print(raw_ostream &Out) const;
268 void RefVal::print(raw_ostream &Out) const {
270 Out << "Tracked " << T.getAsString() << '/';
273 default: llvm_unreachable("Invalid RefVal kind");
276 unsigned cnt = getCount();
277 if (cnt) Out << " (+ " << cnt << ")";
283 unsigned cnt = getCount();
284 if (cnt) Out << " (+ " << cnt << ")";
288 case ReturnedOwned: {
289 Out << "ReturnedOwned";
290 unsigned cnt = getCount();
291 if (cnt) Out << " (+ " << cnt << ")";
295 case ReturnedNotOwned: {
296 Out << "ReturnedNotOwned";
297 unsigned cnt = getCount();
298 if (cnt) Out << " (+ " << cnt << ")";
307 Out << "-dealloc (GC)";
310 case ErrorDeallocNotOwned:
311 Out << "-dealloc (not-owned)";
318 case ErrorLeakReturned:
319 Out << "Leaked (Bad naming)";
322 case ErrorGCLeakReturned:
323 Out << "Leaked (GC-ed at return)";
326 case ErrorUseAfterRelease:
327 Out << "Use-After-Release [ERROR]";
330 case ErrorReleaseNotOwned:
331 Out << "Release of Not-Owned [ERROR]";
334 case RefVal::ErrorOverAutorelease:
335 Out << "Over-autoreleased";
338 case RefVal::ErrorReturnedNotOwned:
339 Out << "Non-owned object returned instead of owned";
343 switch (getIvarAccessHistory()) {
344 case IvarAccessHistory::None:
346 case IvarAccessHistory::AccessedDirectly:
347 Out << " [direct ivar access]";
349 case IvarAccessHistory::ReleasedAfterDirectAccess:
350 Out << " [released after direct ivar access]";
354 Out << " [autorelease -" << ACnt << ']';
357 } //end anonymous namespace
359 //===----------------------------------------------------------------------===//
360 // RefBindings - State used to track object reference counts.
361 //===----------------------------------------------------------------------===//
363 REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
365 static inline const RefVal *getRefBinding(ProgramStateRef State,
367 return State->get<RefBindings>(Sym);
370 static inline ProgramStateRef setRefBinding(ProgramStateRef State,
371 SymbolRef Sym, RefVal Val) {
372 return State->set<RefBindings>(Sym, Val);
375 static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
376 return State->remove<RefBindings>(Sym);
379 //===----------------------------------------------------------------------===//
380 // Function/Method behavior summaries.
381 //===----------------------------------------------------------------------===//
384 class RetainSummary {
385 /// Args - a map of (index, ArgEffect) pairs, where index
386 /// specifies the argument (starting from 0). This can be sparsely
387 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
390 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
391 /// do not have an entry in Args.
392 ArgEffect DefaultArgEffect;
394 /// Receiver - If this summary applies to an Objective-C message expression,
395 /// this is the effect applied to the state of the receiver.
398 /// Ret - The effect on the return value. Used to indicate if the
399 /// function/method call returns a new tracked symbol.
403 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
404 ArgEffect ReceiverEff)
405 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
407 /// getArg - Return the argument effect on the argument specified by
408 /// idx (starting from 0).
409 ArgEffect getArg(unsigned idx) const {
410 if (const ArgEffect *AE = Args.lookup(idx))
413 return DefaultArgEffect;
416 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
417 Args = af.add(Args, idx, e);
420 /// setDefaultArgEffect - Set the default argument effect.
421 void setDefaultArgEffect(ArgEffect E) {
422 DefaultArgEffect = E;
425 /// getRetEffect - Returns the effect on the return value of the call.
426 RetEffect getRetEffect() const { return Ret; }
428 /// setRetEffect - Set the effect of the return value of the call.
429 void setRetEffect(RetEffect E) { Ret = E; }
432 /// Sets the effect on the receiver of the message.
433 void setReceiverEffect(ArgEffect e) { Receiver = e; }
435 /// getReceiverEffect - Returns the effect on the receiver of the call.
436 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
437 ArgEffect getReceiverEffect() const { return Receiver; }
439 /// Test if two retain summaries are identical. Note that merely equivalent
440 /// summaries are not necessarily identical (for example, if an explicit
441 /// argument effect matches the default effect).
442 bool operator==(const RetainSummary &Other) const {
443 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
444 Receiver == Other.Receiver && Ret == Other.Ret;
447 /// Profile this summary for inclusion in a FoldingSet.
448 void Profile(llvm::FoldingSetNodeID& ID) const {
450 ID.Add(DefaultArgEffect);
455 /// A retain summary is simple if it has no ArgEffects other than the default.
456 bool isSimple() const {
457 return Args.isEmpty();
461 ArgEffects getArgEffects() const { return Args; }
462 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
464 friend class RetainSummaryManager;
466 } // end anonymous namespace
468 //===----------------------------------------------------------------------===//
469 // Data structures for constructing summaries.
470 //===----------------------------------------------------------------------===//
473 class ObjCSummaryKey {
477 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
480 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
481 : II(d ? d->getIdentifier() : nullptr), S(s) {}
483 ObjCSummaryKey(Selector s)
484 : II(nullptr), S(s) {}
486 IdentifierInfo *getIdentifier() const { return II; }
487 Selector getSelector() const { return S; }
489 } // end anonymous namespace
492 template <> struct DenseMapInfo<ObjCSummaryKey> {
493 static inline ObjCSummaryKey getEmptyKey() {
494 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
495 DenseMapInfo<Selector>::getEmptyKey());
498 static inline ObjCSummaryKey getTombstoneKey() {
499 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
500 DenseMapInfo<Selector>::getTombstoneKey());
503 static unsigned getHashValue(const ObjCSummaryKey &V) {
504 typedef std::pair<IdentifierInfo*, Selector> PairTy;
505 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
509 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
510 return LHS.getIdentifier() == RHS.getIdentifier() &&
511 LHS.getSelector() == RHS.getSelector();
515 } // end llvm namespace
518 class ObjCSummaryCache {
519 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
522 ObjCSummaryCache() {}
524 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
525 // Do a lookup with the (D,S) pair. If we find a match return
527 ObjCSummaryKey K(D, S);
528 MapTy::iterator I = M.find(K);
535 // Walk the super chain. If we find a hit with a parent, we'll end
536 // up returning that summary. We actually allow that key (null,S), as
537 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
538 // generate initial summaries without having to worry about NSObject
540 // FIXME: We may change this at some point.
541 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
542 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
549 // Cache the summary with original key to make the next lookup faster
550 // and return the iterator.
551 const RetainSummary *Summ = I->second;
556 const RetainSummary *find(IdentifierInfo* II, Selector S) {
557 // FIXME: Class method lookup. Right now we dont' have a good way
558 // of going between IdentifierInfo* and the class hierarchy.
559 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
562 I = M.find(ObjCSummaryKey(S));
564 return I == M.end() ? nullptr : I->second;
567 const RetainSummary *& operator[](ObjCSummaryKey K) {
571 const RetainSummary *& operator[](Selector S) {
572 return M[ ObjCSummaryKey(S) ];
575 } // end anonymous namespace
577 //===----------------------------------------------------------------------===//
578 // Data structures for managing collections of summaries.
579 //===----------------------------------------------------------------------===//
582 class RetainSummaryManager {
584 //==-----------------------------------------------------------------==//
586 //==-----------------------------------------------------------------==//
588 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
591 typedef ObjCSummaryCache ObjCMethodSummariesTy;
593 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
595 //==-----------------------------------------------------------------==//
597 //==-----------------------------------------------------------------==//
599 /// Ctx - The ASTContext object for the analyzed ASTs.
602 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
603 const bool GCEnabled;
605 /// Records whether or not the analyzed code runs in ARC mode.
606 const bool ARCEnabled;
608 /// FuncSummaries - A map from FunctionDecls to summaries.
609 FuncSummariesTy FuncSummaries;
611 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
613 ObjCMethodSummariesTy ObjCClassMethodSummaries;
615 /// ObjCMethodSummaries - A map from selectors to summaries.
616 ObjCMethodSummariesTy ObjCMethodSummaries;
618 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
619 /// and all other data used by the checker.
620 llvm::BumpPtrAllocator BPAlloc;
622 /// AF - A factory for ArgEffects objects.
623 ArgEffects::Factory AF;
625 /// ScratchArgs - A holding buffer for construct ArgEffects.
626 ArgEffects ScratchArgs;
628 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
630 RetEffect ObjCAllocRetE;
632 /// ObjCInitRetE - Default return effect for init methods returning
633 /// Objective-C objects.
634 RetEffect ObjCInitRetE;
636 /// SimpleSummaries - Used for uniquing summaries that don't have special
638 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
640 //==-----------------------------------------------------------------==//
642 //==-----------------------------------------------------------------==//
644 /// getArgEffects - Returns a persistent ArgEffects object based on the
645 /// data in ScratchArgs.
646 ArgEffects getArgEffects();
648 enum UnaryFuncKind { cfretain, cfrelease, cfautorelease, cfmakecollectable };
650 const RetainSummary *getUnarySummary(const FunctionType* FT,
653 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
654 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
655 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
657 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
659 const RetainSummary *getPersistentSummary(RetEffect RetEff,
660 ArgEffect ReceiverEff = DoNothing,
661 ArgEffect DefaultEff = MayEscape) {
662 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
663 return getPersistentSummary(Summ);
666 const RetainSummary *getDoNothingSummary() {
667 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
670 const RetainSummary *getDefaultSummary() {
671 return getPersistentSummary(RetEffect::MakeNoRet(),
672 DoNothing, MayEscape);
675 const RetainSummary *getPersistentStopSummary() {
676 return getPersistentSummary(RetEffect::MakeNoRet(),
677 StopTracking, StopTracking);
680 void InitializeClassMethodSummaries();
681 void InitializeMethodSummaries();
683 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
684 ObjCClassMethodSummaries[S] = Summ;
687 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
688 ObjCMethodSummaries[S] = Summ;
691 void addClassMethSummary(const char* Cls, const char* name,
692 const RetainSummary *Summ, bool isNullary = true) {
693 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
694 Selector S = isNullary ? GetNullarySelector(name, Ctx)
695 : GetUnarySelector(name, Ctx);
696 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
699 void addInstMethSummary(const char* Cls, const char* nullaryName,
700 const RetainSummary *Summ) {
701 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
702 Selector S = GetNullarySelector(nullaryName, Ctx);
703 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
706 template <typename... Keywords>
707 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy &Summaries,
708 const RetainSummary *Summ, Keywords *... Kws) {
709 Selector S = getKeywordSelector(Ctx, Kws...);
710 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
713 template <typename... Keywords>
714 void addInstMethSummary(const char *Cls, const RetainSummary *Summ,
716 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, Kws...);
719 template <typename... Keywords>
720 void addClsMethSummary(const char *Cls, const RetainSummary *Summ,
722 addMethodSummary(&Ctx.Idents.get(Cls), ObjCClassMethodSummaries, Summ,
726 template <typename... Keywords>
727 void addClsMethSummary(IdentifierInfo *II, const RetainSummary *Summ,
729 addMethodSummary(II, ObjCClassMethodSummaries, Summ, Kws...);
734 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
736 GCEnabled(gcenabled),
738 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
739 ObjCAllocRetE(gcenabled
740 ? RetEffect::MakeGCNotOwned()
741 : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC)
742 : RetEffect::MakeOwned(RetEffect::ObjC))),
743 ObjCInitRetE(gcenabled
744 ? RetEffect::MakeGCNotOwned()
745 : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC)
746 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
747 InitializeClassMethodSummaries();
748 InitializeMethodSummaries();
751 const RetainSummary *getSummary(const CallEvent &Call,
752 ProgramStateRef State = nullptr);
754 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
756 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
757 const ObjCMethodDecl *MD,
759 ObjCMethodSummariesTy &CachedSummaries);
761 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
762 ProgramStateRef State);
764 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
765 assert(!M.isInstanceMessage());
766 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
768 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
769 M.getResultType(), ObjCClassMethodSummaries);
772 /// getMethodSummary - This version of getMethodSummary is used to query
773 /// the summary for the current method being analyzed.
774 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
775 const ObjCInterfaceDecl *ID = MD->getClassInterface();
776 Selector S = MD->getSelector();
777 QualType ResultTy = MD->getReturnType();
779 ObjCMethodSummariesTy *CachedSummaries;
780 if (MD->isInstanceMethod())
781 CachedSummaries = &ObjCMethodSummaries;
783 CachedSummaries = &ObjCClassMethodSummaries;
785 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
788 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
789 Selector S, QualType RetTy);
791 /// Determine if there is a special return effect for this function or method.
792 Optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy,
795 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
796 const ObjCMethodDecl *MD);
798 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
799 const FunctionDecl *FD);
801 void updateSummaryForCall(const RetainSummary *&Summ,
802 const CallEvent &Call);
804 bool isGCEnabled() const { return GCEnabled; }
806 bool isARCEnabled() const { return ARCEnabled; }
808 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
810 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
812 friend class RetainSummaryTemplate;
815 // Used to avoid allocating long-term (BPAlloc'd) memory for default retain
816 // summaries. If a function or method looks like it has a default summary, but
817 // it has annotations, the annotations are added to the stack-based template
818 // and then copied into managed memory.
819 class RetainSummaryTemplate {
820 RetainSummaryManager &Manager;
821 const RetainSummary *&RealSummary;
822 RetainSummary ScratchSummary;
825 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
826 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
828 ~RetainSummaryTemplate() {
830 RealSummary = Manager.getPersistentSummary(ScratchSummary);
833 RetainSummary &operator*() {
835 return ScratchSummary;
838 RetainSummary *operator->() {
840 return &ScratchSummary;
844 } // end anonymous namespace
846 //===----------------------------------------------------------------------===//
847 // Implementation of checker data structures.
848 //===----------------------------------------------------------------------===//
850 ArgEffects RetainSummaryManager::getArgEffects() {
851 ArgEffects AE = ScratchArgs;
852 ScratchArgs = AF.getEmptyMap();
856 const RetainSummary *
857 RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
858 // Unique "simple" summaries -- those without ArgEffects.
859 if (OldSumm.isSimple()) {
860 llvm::FoldingSetNodeID ID;
864 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
867 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
868 new (N) CachedSummaryNode(OldSumm);
869 SimpleSummaries.InsertNode(N, Pos);
872 return &N->getValue();
875 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
876 new (Summ) RetainSummary(OldSumm);
880 //===----------------------------------------------------------------------===//
881 // Summary creation for functions (largely uses of Core Foundation).
882 //===----------------------------------------------------------------------===//
884 static bool isRetain(const FunctionDecl *FD, StringRef FName) {
885 return FName.endswith("Retain");
888 static bool isRelease(const FunctionDecl *FD, StringRef FName) {
889 return FName.endswith("Release");
892 static bool isAutorelease(const FunctionDecl *FD, StringRef FName) {
893 return FName.endswith("Autorelease");
896 static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
897 // FIXME: Remove FunctionDecl parameter.
898 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
899 return FName.find("MakeCollectable") != StringRef::npos;
902 static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
906 case DecRefBridgedTransferred:
909 case MakeCollectable:
910 case UnretainedOutParameter:
911 case RetainedOutParameter:
914 case StopTrackingHard:
915 return StopTrackingHard;
917 case DecRefAndStopTrackingHard:
918 return DecRefAndStopTrackingHard;
920 case DecRefMsgAndStopTrackingHard:
921 return DecRefMsgAndStopTrackingHard;
926 llvm_unreachable("Unknown ArgEffect kind");
929 void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
930 const CallEvent &Call) {
931 if (Call.hasNonZeroCallbackArg()) {
932 ArgEffect RecEffect =
933 getStopTrackingHardEquivalent(S->getReceiverEffect());
934 ArgEffect DefEffect =
935 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
937 ArgEffects CustomArgEffects = S->getArgEffects();
938 for (ArgEffects::iterator I = CustomArgEffects.begin(),
939 E = CustomArgEffects.end();
941 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
942 if (Translated != DefEffect)
943 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
946 RetEffect RE = RetEffect::MakeNoRetHard();
948 // Special cases where the callback argument CANNOT free the return value.
949 // This can generally only happen if we know that the callback will only be
950 // called when the return value is already being deallocated.
951 if (const SimpleFunctionCall *FC = dyn_cast<SimpleFunctionCall>(&Call)) {
952 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
953 // When the CGBitmapContext is deallocated, the callback here will free
954 // the associated data buffer.
955 // The callback in dispatch_data_create frees the buffer, but not
957 if (Name->isStr("CGBitmapContextCreateWithData") ||
958 Name->isStr("dispatch_data_create"))
959 RE = S->getRetEffect();
963 S = getPersistentSummary(RE, RecEffect, DefEffect);
966 // Special case '[super init];' and '[self init];'
968 // Even though calling '[super init]' without assigning the result to self
969 // and checking if the parent returns 'nil' is a bad pattern, it is common.
970 // Additionally, our Self Init checker already warns about it. To avoid
971 // overwhelming the user with messages from both checkers, we model the case
972 // of '[super init]' in cases when it is not consumed by another expression
973 // as if the call preserves the value of 'self'; essentially, assuming it can
974 // never fail and return 'nil'.
975 // Note, we don't want to just stop tracking the value since we want the
976 // RetainCount checker to report leaks and use-after-free if SelfInit checker
978 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
979 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
981 // Check if the message is not consumed, we know it will not be used in
982 // an assignment, ex: "self = [super init]".
983 const Expr *ME = MC->getOriginExpr();
984 const LocationContext *LCtx = MC->getLocationContext();
985 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
986 if (!PM.isConsumedExpr(ME)) {
987 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
988 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
989 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
995 const RetainSummary *
996 RetainSummaryManager::getSummary(const CallEvent &Call,
997 ProgramStateRef State) {
998 const RetainSummary *Summ;
999 switch (Call.getKind()) {
1001 Summ = getFunctionSummary(cast<SimpleFunctionCall>(Call).getDecl());
1004 case CE_CXXMemberOperator:
1006 case CE_CXXConstructor:
1007 case CE_CXXDestructor:
1008 case CE_CXXAllocator:
1009 // FIXME: These calls are currently unsupported.
1010 return getPersistentStopSummary();
1011 case CE_ObjCMessage: {
1012 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
1013 if (Msg.isInstanceMessage())
1014 Summ = getInstanceMethodSummary(Msg, State);
1016 Summ = getClassMethodSummary(Msg);
1021 updateSummaryForCall(Summ, Call);
1023 assert(Summ && "Unknown call type?");
1027 const RetainSummary *
1028 RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
1029 // If we don't know what function we're calling, use our default summary.
1031 return getDefaultSummary();
1033 // Look up a summary in our cache of FunctionDecls -> Summaries.
1034 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
1035 if (I != FuncSummaries.end())
1038 // No summary? Generate one.
1039 const RetainSummary *S = nullptr;
1040 bool AllowAnnotations = true;
1043 // We generate "stop" summaries for implicitly defined functions.
1044 if (FD->isImplicit()) {
1045 S = getPersistentStopSummary();
1049 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
1051 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
1052 const IdentifierInfo *II = FD->getIdentifier();
1056 StringRef FName = II->getName();
1058 // Strip away preceding '_'. Doing this here will effect all the checks
1060 FName = FName.substr(FName.find_first_not_of('_'));
1062 // Inspect the result type.
1063 QualType RetTy = FT->getReturnType();
1065 // FIXME: This should all be refactored into a chain of "summary lookup"
1067 assert(ScratchArgs.isEmpty());
1069 if (FName == "pthread_create" || FName == "pthread_setspecific") {
1070 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1071 // This will be addressed better with IPA.
1072 S = getPersistentStopSummary();
1073 } else if (FName == "NSMakeCollectable") {
1074 // Handle: id NSMakeCollectable(CFTypeRef)
1075 S = (RetTy->isObjCIdType())
1076 ? getUnarySummary(FT, cfmakecollectable)
1077 : getPersistentStopSummary();
1078 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1079 // but we can fully model NSMakeCollectable ourselves.
1080 AllowAnnotations = false;
1081 } else if (FName == "CFPlugInInstanceCreate") {
1082 S = getPersistentSummary(RetEffect::MakeNoRet());
1083 } else if (FName == "IOBSDNameMatching" ||
1084 FName == "IOServiceMatching" ||
1085 FName == "IOServiceNameMatching" ||
1086 FName == "IORegistryEntrySearchCFProperty" ||
1087 FName == "IORegistryEntryIDMatching" ||
1088 FName == "IOOpenFirmwarePathMatching") {
1089 // Part of <rdar://problem/6961230>. (IOKit)
1090 // This should be addressed using a API table.
1091 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF),
1092 DoNothing, DoNothing);
1093 } else if (FName == "IOServiceGetMatchingService" ||
1094 FName == "IOServiceGetMatchingServices") {
1095 // FIXES: <rdar://problem/6326900>
1096 // This should be addressed using a API table. This strcmp is also
1097 // a little gross, but there is no need to super optimize here.
1098 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
1099 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1100 } else if (FName == "IOServiceAddNotification" ||
1101 FName == "IOServiceAddMatchingNotification") {
1102 // Part of <rdar://problem/6961230>. (IOKit)
1103 // This should be addressed using a API table.
1104 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
1105 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1106 } else if (FName == "CVPixelBufferCreateWithBytes") {
1107 // FIXES: <rdar://problem/7283567>
1108 // Eventually this can be improved by recognizing that the pixel
1109 // buffer passed to CVPixelBufferCreateWithBytes is released via
1110 // a callback and doing full IPA to make sure this is done correctly.
1111 // FIXME: This function has an out parameter that returns an
1112 // allocated object.
1113 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
1114 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1115 } else if (FName == "CGBitmapContextCreateWithData") {
1116 // FIXES: <rdar://problem/7358899>
1117 // Eventually this can be improved by recognizing that 'releaseInfo'
1118 // passed to CGBitmapContextCreateWithData is released via
1119 // a callback and doing full IPA to make sure this is done correctly.
1120 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
1121 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF),
1122 DoNothing, DoNothing);
1123 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1124 // FIXES: <rdar://problem/7283567>
1125 // Eventually this can be improved by recognizing that the pixel
1126 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1127 // via a callback and doing full IPA to make sure this is done
1129 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
1130 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1131 } else if (FName == "VTCompressionSessionEncodeFrame") {
1132 // The context argument passed to VTCompressionSessionEncodeFrame()
1133 // is passed to the callback specified when creating the session
1134 // (e.g. with VTCompressionSessionCreate()) which can release it.
1135 // To account for this possibility, conservatively stop tracking
1137 ScratchArgs = AF.add(ScratchArgs, 5, StopTracking);
1138 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1139 } else if (FName == "dispatch_set_context" ||
1140 FName == "xpc_connection_set_context") {
1141 // <rdar://problem/11059275> - The analyzer currently doesn't have
1142 // a good way to reason about the finalizer function for libdispatch.
1143 // If we pass a context object that is memory managed, stop tracking it.
1144 // <rdar://problem/13783514> - Same problem, but for XPC.
1145 // FIXME: this hack should possibly go away once we can handle
1146 // libdispatch and XPC finalizers.
1147 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1148 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1149 } else if (FName.startswith("NSLog")) {
1150 S = getDoNothingSummary();
1151 } else if (FName.startswith("NS") &&
1152 (FName.find("Insert") != StringRef::npos)) {
1153 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1154 // be deallocated by NSMapRemove. (radar://11152419)
1155 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1156 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1157 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1160 // Did we get a summary?
1164 if (RetTy->isPointerType()) {
1165 // For CoreFoundation ('CF') types.
1166 if (cocoa::isRefType(RetTy, "CF", FName)) {
1167 if (isRetain(FD, FName)) {
1168 S = getUnarySummary(FT, cfretain);
1169 } else if (isAutorelease(FD, FName)) {
1170 S = getUnarySummary(FT, cfautorelease);
1171 // The headers use cf_consumed, but we can fully model CFAutorelease
1173 AllowAnnotations = false;
1174 } else if (isMakeCollectable(FD, FName)) {
1175 S = getUnarySummary(FT, cfmakecollectable);
1176 AllowAnnotations = false;
1178 S = getCFCreateGetRuleSummary(FD);
1184 // For CoreGraphics ('CG') and CoreVideo ('CV') types.
1185 if (cocoa::isRefType(RetTy, "CG", FName) ||
1186 cocoa::isRefType(RetTy, "CV", FName)) {
1187 if (isRetain(FD, FName))
1188 S = getUnarySummary(FT, cfretain);
1190 S = getCFCreateGetRuleSummary(FD);
1195 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1196 if (cocoa::isRefType(RetTy, "DADisk") ||
1197 cocoa::isRefType(RetTy, "DADissenter") ||
1198 cocoa::isRefType(RetTy, "DASessionRef")) {
1199 S = getCFCreateGetRuleSummary(FD);
1203 if (FD->hasAttr<CFAuditedTransferAttr>()) {
1204 S = getCFCreateGetRuleSummary(FD);
1211 // Check for release functions, the only kind of functions that we care
1212 // about that don't return a pointer type.
1213 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
1215 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
1217 if (isRelease(FD, FName))
1218 S = getUnarySummary(FT, cfrelease);
1220 assert (ScratchArgs.isEmpty());
1221 // Remaining CoreFoundation and CoreGraphics functions.
1222 // We use to assume that they all strictly followed the ownership idiom
1223 // and that ownership cannot be transferred. While this is technically
1224 // correct, many methods allow a tracked object to escape. For example:
1226 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1227 // CFDictionaryAddValue(y, key, x);
1229 // ... it is okay to use 'x' since 'y' has a reference to it
1231 // We handle this and similar cases with the follow heuristic. If the
1232 // function name contains "InsertValue", "SetValue", "AddValue",
1233 // "AppendValue", or "SetAttribute", then we assume that arguments may
1234 // "escape." This means that something else holds on to the object,
1235 // allowing it be used even after its local retain count drops to 0.
1236 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1237 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1238 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1239 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
1240 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
1241 ? MayEscape : DoNothing;
1243 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
1249 // If we got all the way here without any luck, use a default summary.
1251 S = getDefaultSummary();
1253 // Annotations override defaults.
1254 if (AllowAnnotations)
1255 updateSummaryFromAnnotations(S, FD);
1257 FuncSummaries[FD] = S;
1261 const RetainSummary *
1262 RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1263 if (coreFoundation::followsCreateRule(FD))
1264 return getCFSummaryCreateRule(FD);
1266 return getCFSummaryGetRule(FD);
1269 const RetainSummary *
1270 RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1271 UnaryFuncKind func) {
1273 // Sanity check that this is *really* a unary function. This can
1274 // happen if people do weird things.
1275 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
1276 if (!FTP || FTP->getNumParams() != 1)
1277 return getPersistentStopSummary();
1279 assert (ScratchArgs.isEmpty());
1283 case cfretain: Effect = IncRef; break;
1284 case cfrelease: Effect = DecRef; break;
1285 case cfautorelease: Effect = Autorelease; break;
1286 case cfmakecollectable: Effect = MakeCollectable; break;
1289 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1290 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1293 const RetainSummary *
1294 RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
1295 assert (ScratchArgs.isEmpty());
1297 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF));
1300 const RetainSummary *
1301 RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
1302 assert (ScratchArgs.isEmpty());
1303 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1304 DoNothing, DoNothing);
1307 //===----------------------------------------------------------------------===//
1308 // Summary creation for Selectors.
1309 //===----------------------------------------------------------------------===//
1312 RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
1314 if (cocoa::isCocoaObjectRef(RetTy)) {
1315 if (D->hasAttr<NSReturnsRetainedAttr>())
1316 return ObjCAllocRetE;
1318 if (D->hasAttr<NSReturnsNotRetainedAttr>() ||
1319 D->hasAttr<NSReturnsAutoreleasedAttr>())
1320 return RetEffect::MakeNotOwned(RetEffect::ObjC);
1322 } else if (!RetTy->isPointerType()) {
1326 if (D->hasAttr<CFReturnsRetainedAttr>())
1327 return RetEffect::MakeOwned(RetEffect::CF);
1329 if (D->hasAttr<CFReturnsNotRetainedAttr>())
1330 return RetEffect::MakeNotOwned(RetEffect::CF);
1336 RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1337 const FunctionDecl *FD) {
1341 assert(Summ && "Must have a summary to add annotations to.");
1342 RetainSummaryTemplate Template(Summ, *this);
1344 // Effects on the parameters.
1345 unsigned parm_idx = 0;
1346 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
1347 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
1348 const ParmVarDecl *pd = *pi;
1349 if (pd->hasAttr<NSConsumedAttr>())
1350 Template->addArg(AF, parm_idx, DecRefMsg);
1351 else if (pd->hasAttr<CFConsumedAttr>())
1352 Template->addArg(AF, parm_idx, DecRef);
1353 else if (pd->hasAttr<CFReturnsRetainedAttr>()) {
1354 QualType PointeeTy = pd->getType()->getPointeeType();
1355 if (!PointeeTy.isNull())
1356 if (coreFoundation::isCFObjectRef(PointeeTy))
1357 Template->addArg(AF, parm_idx, RetainedOutParameter);
1358 } else if (pd->hasAttr<CFReturnsNotRetainedAttr>()) {
1359 QualType PointeeTy = pd->getType()->getPointeeType();
1360 if (!PointeeTy.isNull())
1361 if (coreFoundation::isCFObjectRef(PointeeTy))
1362 Template->addArg(AF, parm_idx, UnretainedOutParameter);
1366 QualType RetTy = FD->getReturnType();
1367 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
1368 Template->setRetEffect(*RetE);
1372 RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1373 const ObjCMethodDecl *MD) {
1377 assert(Summ && "Must have a valid summary to add annotations to");
1378 RetainSummaryTemplate Template(Summ, *this);
1380 // Effects on the receiver.
1381 if (MD->hasAttr<NSConsumesSelfAttr>())
1382 Template->setReceiverEffect(DecRefMsg);
1384 // Effects on the parameters.
1385 unsigned parm_idx = 0;
1386 for (ObjCMethodDecl::param_const_iterator
1387 pi=MD->param_begin(), pe=MD->param_end();
1388 pi != pe; ++pi, ++parm_idx) {
1389 const ParmVarDecl *pd = *pi;
1390 if (pd->hasAttr<NSConsumedAttr>())
1391 Template->addArg(AF, parm_idx, DecRefMsg);
1392 else if (pd->hasAttr<CFConsumedAttr>()) {
1393 Template->addArg(AF, parm_idx, DecRef);
1394 } else if (pd->hasAttr<CFReturnsRetainedAttr>()) {
1395 QualType PointeeTy = pd->getType()->getPointeeType();
1396 if (!PointeeTy.isNull())
1397 if (coreFoundation::isCFObjectRef(PointeeTy))
1398 Template->addArg(AF, parm_idx, RetainedOutParameter);
1399 } else if (pd->hasAttr<CFReturnsNotRetainedAttr>()) {
1400 QualType PointeeTy = pd->getType()->getPointeeType();
1401 if (!PointeeTy.isNull())
1402 if (coreFoundation::isCFObjectRef(PointeeTy))
1403 Template->addArg(AF, parm_idx, UnretainedOutParameter);
1407 QualType RetTy = MD->getReturnType();
1408 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1409 Template->setRetEffect(*RetE);
1412 const RetainSummary *
1413 RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1414 Selector S, QualType RetTy) {
1415 // Any special effects?
1416 ArgEffect ReceiverEff = DoNothing;
1417 RetEffect ResultEff = RetEffect::MakeNoRet();
1419 // Check the method family, and apply any default annotations.
1420 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1422 case OMF_initialize:
1423 case OMF_performSelector:
1424 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1425 // FIXME: Does the non-threaded performSelector family really belong here?
1426 // The selector could be, say, @selector(copy).
1427 if (cocoa::isCocoaObjectRef(RetTy))
1428 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1429 else if (coreFoundation::isCFObjectRef(RetTy)) {
1430 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1431 // values for alloc, new, copy, or mutableCopy, so we have to
1432 // double-check with the selector. This is ugly, but there aren't that
1433 // many Objective-C methods that return CF objects, right?
1435 switch (S.getMethodFamily()) {
1439 case OMF_mutableCopy:
1440 ResultEff = RetEffect::MakeOwned(RetEffect::CF);
1443 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1447 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1452 ResultEff = ObjCInitRetE;
1453 ReceiverEff = DecRefMsg;
1458 case OMF_mutableCopy:
1459 if (cocoa::isCocoaObjectRef(RetTy))
1460 ResultEff = ObjCAllocRetE;
1461 else if (coreFoundation::isCFObjectRef(RetTy))
1462 ResultEff = RetEffect::MakeOwned(RetEffect::CF);
1464 case OMF_autorelease:
1465 ReceiverEff = Autorelease;
1468 ReceiverEff = IncRefMsg;
1471 ReceiverEff = DecRefMsg;
1474 ReceiverEff = Dealloc;
1477 // -self is handled specially by the ExprEngine to propagate the receiver.
1479 case OMF_retainCount:
1481 // These methods don't return objects.
1485 // If one of the arguments in the selector has the keyword 'delegate' we
1486 // should stop tracking the reference count for the receiver. This is
1487 // because the reference count is quite possibly handled by a delegate
1489 if (S.isKeywordSelector()) {
1490 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1491 StringRef Slot = S.getNameForSlot(i);
1492 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1493 if (ResultEff == ObjCInitRetE)
1494 ResultEff = RetEffect::MakeNoRetHard();
1496 ReceiverEff = StopTrackingHard;
1501 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1502 ResultEff.getKind() == RetEffect::NoRet)
1503 return getDefaultSummary();
1505 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
1508 const RetainSummary *
1509 RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
1510 ProgramStateRef State) {
1511 const ObjCInterfaceDecl *ReceiverClass = nullptr;
1513 // We do better tracking of the type of the object than the core ExprEngine.
1514 // See if we have its type in our private state.
1515 // FIXME: Eventually replace the use of state->get<RefBindings> with
1516 // a generic API for reasoning about the Objective-C types of symbolic
1518 SVal ReceiverV = Msg.getReceiverSVal();
1519 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
1520 if (const RefVal *T = getRefBinding(State, Sym))
1521 if (const ObjCObjectPointerType *PT =
1522 T->getType()->getAs<ObjCObjectPointerType>())
1523 ReceiverClass = PT->getInterfaceDecl();
1525 // If we don't know what kind of object this is, fall back to its static type.
1527 ReceiverClass = Msg.getReceiverInterface();
1529 // FIXME: The receiver could be a reference to a class, meaning that
1530 // we should use the class method.
1531 // id x = [NSObject class];
1532 // [x performSelector:... withObject:... afterDelay:...];
1533 Selector S = Msg.getSelector();
1534 const ObjCMethodDecl *Method = Msg.getDecl();
1535 if (!Method && ReceiverClass)
1536 Method = ReceiverClass->getInstanceMethod(S);
1538 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1539 ObjCMethodSummaries);
1542 const RetainSummary *
1543 RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
1544 const ObjCMethodDecl *MD, QualType RetTy,
1545 ObjCMethodSummariesTy &CachedSummaries) {
1547 // Look up a summary in our summary cache.
1548 const RetainSummary *Summ = CachedSummaries.find(ID, S);
1551 Summ = getStandardMethodSummary(MD, S, RetTy);
1553 // Annotations override defaults.
1554 updateSummaryFromAnnotations(Summ, MD);
1556 // Memoize the summary.
1557 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
1563 void RetainSummaryManager::InitializeClassMethodSummaries() {
1564 assert(ScratchArgs.isEmpty());
1565 // Create the [NSAssertionHandler currentHander] summary.
1566 addClassMethSummary("NSAssertionHandler", "currentHandler",
1567 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
1569 // Create the [NSAutoreleasePool addObject:] summary.
1570 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
1571 addClassMethSummary("NSAutoreleasePool", "addObject",
1572 getPersistentSummary(RetEffect::MakeNoRet(),
1573 DoNothing, Autorelease));
1576 void RetainSummaryManager::InitializeMethodSummaries() {
1578 assert (ScratchArgs.isEmpty());
1580 // Create the "init" selector. It just acts as a pass-through for the
1582 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
1583 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1585 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1586 // claims the receiver and returns a retained object.
1587 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1590 // The next methods are allocators.
1591 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1592 const RetainSummary *CFAllocSumm =
1593 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF));
1595 // Create the "retain" selector.
1596 RetEffect NoRet = RetEffect::MakeNoRet();
1597 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
1598 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
1600 // Create the "release" selector.
1601 Summ = getPersistentSummary(NoRet, DecRefMsg);
1602 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
1604 // Create the -dealloc summary.
1605 Summ = getPersistentSummary(NoRet, Dealloc);
1606 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
1608 // Create the "autorelease" selector.
1609 Summ = getPersistentSummary(NoRet, Autorelease);
1610 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
1612 // For NSWindow, allocated objects are (initially) self-owned.
1613 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1614 // self-own themselves. However, they only do this once they are displayed.
1615 // Thus, we need to track an NSWindow's display status.
1616 // This is tracked in <rdar://problem/6062711>.
1617 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
1618 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1622 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1624 // For NSPanel (which subclasses NSWindow), allocated objects are not
1626 // FIXME: For now we don't track NSPanels. object for the same reason
1627 // as for NSWindow objects.
1628 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1630 // For NSNull, objects returned by +null are singletons that ignore
1631 // retain/release semantics. Just don't track them.
1632 // <rdar://problem/12858915>
1633 addClassMethSummary("NSNull", "null", NoTrackYet);
1635 // Don't track allocated autorelease pools, as it is okay to prematurely
1637 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
1638 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
1639 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
1641 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1642 addInstMethSummary("QCRenderer", AllocSumm, "createSnapshotImageOfType");
1643 addInstMethSummary("QCView", AllocSumm, "createSnapshotImageOfType");
1645 // Create summaries for CIContext, 'createCGImage' and
1646 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1647 // automatically garbage collected.
1648 addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect");
1649 addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect",
1650 "format", "colorSpace");
1651 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info");
1654 //===----------------------------------------------------------------------===//
1656 //===----------------------------------------------------------------------===//
1658 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1661 //===-------------===//
1662 // Bug Descriptions. //
1663 //===-------------===//
1665 class CFRefBug : public BugType {
1667 CFRefBug(const CheckerBase *checker, StringRef name)
1668 : BugType(checker, name, categories::MemoryCoreFoundationObjectiveC) {}
1672 // FIXME: Eventually remove.
1673 virtual const char *getDescription() const = 0;
1675 virtual bool isLeak() const { return false; }
1678 class UseAfterRelease : public CFRefBug {
1680 UseAfterRelease(const CheckerBase *checker)
1681 : CFRefBug(checker, "Use-after-release") {}
1683 const char *getDescription() const override {
1684 return "Reference-counted object is used after it is released";
1688 class BadRelease : public CFRefBug {
1690 BadRelease(const CheckerBase *checker) : CFRefBug(checker, "Bad release") {}
1692 const char *getDescription() const override {
1693 return "Incorrect decrement of the reference count of an object that is "
1694 "not owned at this point by the caller";
1698 class DeallocGC : public CFRefBug {
1700 DeallocGC(const CheckerBase *checker)
1701 : CFRefBug(checker, "-dealloc called while using garbage collection") {}
1703 const char *getDescription() const override {
1704 return "-dealloc called while using garbage collection";
1708 class DeallocNotOwned : public CFRefBug {
1710 DeallocNotOwned(const CheckerBase *checker)
1711 : CFRefBug(checker, "-dealloc sent to non-exclusively owned object") {}
1713 const char *getDescription() const override {
1714 return "-dealloc sent to object that may be referenced elsewhere";
1718 class OverAutorelease : public CFRefBug {
1720 OverAutorelease(const CheckerBase *checker)
1721 : CFRefBug(checker, "Object autoreleased too many times") {}
1723 const char *getDescription() const override {
1724 return "Object autoreleased too many times";
1728 class ReturnedNotOwnedForOwned : public CFRefBug {
1730 ReturnedNotOwnedForOwned(const CheckerBase *checker)
1731 : CFRefBug(checker, "Method should return an owned object") {}
1733 const char *getDescription() const override {
1734 return "Object with a +0 retain count returned to caller where a +1 "
1735 "(owning) retain count is expected";
1739 class Leak : public CFRefBug {
1741 Leak(const CheckerBase *checker, StringRef name) : CFRefBug(checker, name) {
1742 // Leaks should not be reported if they are post-dominated by a sink.
1743 setSuppressOnSink(true);
1746 const char *getDescription() const override { return ""; }
1748 bool isLeak() const override { return true; }
1755 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
1758 const SummaryLogTy &SummaryLog;
1762 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1763 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
1765 void Profile(llvm::FoldingSetNodeID &ID) const override {
1771 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
1772 const ExplodedNode *PrevN,
1773 BugReporterContext &BRC,
1774 BugReport &BR) override;
1776 std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
1777 const ExplodedNode *N,
1778 BugReport &BR) override;
1781 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1783 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
1784 const SummaryLogTy &log)
1785 : CFRefReportVisitor(sym, GCEnabled, log) {}
1787 std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
1788 const ExplodedNode *N,
1789 BugReport &BR) override;
1791 std::unique_ptr<BugReporterVisitor> clone() const override {
1792 // The curiously-recurring template pattern only works for one level of
1793 // subclassing. Rather than make a new template base for
1794 // CFRefReportVisitor, we simply override clone() to do the right thing.
1795 // This could be trouble someday if BugReporterVisitorImpl is ever
1796 // used for something else besides a convenient implementation of clone().
1797 return llvm::make_unique<CFRefLeakReportVisitor>(*this);
1801 class CFRefReport : public BugReport {
1802 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
1805 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1806 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1807 bool registerVisitor = true)
1808 : BugReport(D, D.getDescription(), n) {
1809 if (registerVisitor)
1810 addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log));
1811 addGCModeDescription(LOpts, GCEnabled);
1814 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1815 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1817 : BugReport(D, D.getDescription(), endText, n) {
1818 addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log));
1819 addGCModeDescription(LOpts, GCEnabled);
1822 llvm::iterator_range<ranges_iterator> getRanges() override {
1823 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1824 if (!BugTy.isLeak())
1825 return BugReport::getRanges();
1826 return llvm::make_range(ranges_iterator(), ranges_iterator());
1830 class CFRefLeakReport : public CFRefReport {
1831 const MemRegion* AllocBinding;
1833 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1834 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1835 CheckerContext &Ctx,
1836 bool IncludeAllocationLine);
1838 PathDiagnosticLocation getLocation(const SourceManager &SM) const override {
1839 assert(Location.isValid());
1843 } // end anonymous namespace
1845 void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1847 const char *GCModeDescription = nullptr;
1849 switch (LOpts.getGC()) {
1850 case LangOptions::GCOnly:
1852 GCModeDescription = "Code is compiled to only use garbage collection";
1855 case LangOptions::NonGC:
1857 GCModeDescription = "Code is compiled to use reference counts";
1860 case LangOptions::HybridGC:
1862 GCModeDescription = "Code is compiled to use either garbage collection "
1863 "(GC) or reference counts (non-GC). The bug occurs "
1867 GCModeDescription = "Code is compiled to use either garbage collection "
1868 "(GC) or reference counts (non-GC). The bug occurs "
1874 assert(GCModeDescription && "invalid/unknown GC mode");
1875 addExtraText(GCModeDescription);
1878 static bool isNumericLiteralExpression(const Expr *E) {
1879 // FIXME: This set of cases was copied from SemaExprObjC.
1880 return isa<IntegerLiteral>(E) ||
1881 isa<CharacterLiteral>(E) ||
1882 isa<FloatingLiteral>(E) ||
1883 isa<ObjCBoolLiteralExpr>(E) ||
1884 isa<CXXBoolLiteralExpr>(E);
1887 /// Returns true if this stack frame is for an Objective-C method that is a
1888 /// property getter or setter whose body has been synthesized by the analyzer.
1889 static bool isSynthesizedAccessor(const StackFrameContext *SFC) {
1890 auto Method = dyn_cast_or_null<ObjCMethodDecl>(SFC->getDecl());
1891 if (!Method || !Method->isPropertyAccessor())
1894 return SFC->getAnalysisDeclContext()->isBodyAutosynthesized();
1897 std::shared_ptr<PathDiagnosticPiece>
1898 CFRefReportVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *PrevN,
1899 BugReporterContext &BRC, BugReport &BR) {
1900 // FIXME: We will eventually need to handle non-statement-based events
1901 // (__attribute__((cleanup))).
1902 if (!N->getLocation().getAs<StmtPoint>())
1905 // Check if the type state has changed.
1906 ProgramStateRef PrevSt = PrevN->getState();
1907 ProgramStateRef CurrSt = N->getState();
1908 const LocationContext *LCtx = N->getLocationContext();
1910 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
1911 if (!CurrT) return nullptr;
1913 const RefVal &CurrV = *CurrT;
1914 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
1916 // Create a string buffer to constain all the useful things we want
1917 // to tell the user.
1919 llvm::raw_string_ostream os(sbuf);
1921 // This is the allocation site since the previous node had no bindings
1924 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
1926 if (isa<ObjCIvarRefExpr>(S) &&
1927 isSynthesizedAccessor(LCtx->getCurrentStackFrame())) {
1928 S = LCtx->getCurrentStackFrame()->getCallSite();
1931 if (isa<ObjCArrayLiteral>(S)) {
1932 os << "NSArray literal is an object with a +0 retain count";
1934 else if (isa<ObjCDictionaryLiteral>(S)) {
1935 os << "NSDictionary literal is an object with a +0 retain count";
1937 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1938 if (isNumericLiteralExpression(BL->getSubExpr()))
1939 os << "NSNumber literal is an object with a +0 retain count";
1941 const ObjCInterfaceDecl *BoxClass = nullptr;
1942 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1943 BoxClass = Method->getClassInterface();
1945 // We should always be able to find the boxing class interface,
1946 // but consider this future-proofing.
1948 os << *BoxClass << " b";
1952 os << "oxed expression produces an object with a +0 retain count";
1955 else if (isa<ObjCIvarRefExpr>(S)) {
1956 os << "Object loaded from instance variable";
1959 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1960 // Get the name of the callee (if it is available).
1961 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1962 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1963 os << "Call to function '" << *FD << '\'';
1965 os << "function call";
1968 assert(isa<ObjCMessageExpr>(S));
1969 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1970 CallEventRef<ObjCMethodCall> Call
1971 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1973 switch (Call->getMessageKind()) {
1977 case OCM_PropertyAccess:
1986 if (CurrV.getObjKind() == RetEffect::CF) {
1987 if (Sym->getType().isNull()) {
1988 os << " returns a Core Foundation object with a ";
1990 os << " returns a Core Foundation object of type "
1991 << Sym->getType().getAsString() << " with a ";
1995 assert (CurrV.getObjKind() == RetEffect::ObjC);
1996 QualType T = Sym->getType();
1997 if (T.isNull() || !isa<ObjCObjectPointerType>(T)) {
1998 os << " returns an Objective-C object with a ";
2000 const ObjCObjectPointerType *PT = cast<ObjCObjectPointerType>(T);
2001 os << " returns an instance of "
2002 << PT->getPointeeType().getAsString() << " with a ";
2006 if (CurrV.isOwned()) {
2007 os << "+1 retain count";
2010 assert(CurrV.getObjKind() == RetEffect::CF);
2012 "Core Foundation objects are not automatically garbage collected.";
2016 assert (CurrV.isNotOwned());
2017 os << "+0 retain count";
2021 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2022 N->getLocationContext());
2023 return std::make_shared<PathDiagnosticEventPiece>(Pos, os.str());
2026 // Gather up the effects that were performed on the object at this
2028 SmallVector<ArgEffect, 2> AEffects;
2030 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
2031 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
2032 // We only have summaries attached to nodes after evaluating CallExpr and
2033 // ObjCMessageExprs.
2034 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
2036 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
2037 // Iterate through the parameter expressions and see if the symbol
2038 // was ever passed as an argument.
2041 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2042 AI!=AE; ++AI, ++i) {
2044 // Retrieve the value of the argument. Is it the symbol
2045 // we are interested in?
2046 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
2049 // We have an argument. Get the effect!
2050 AEffects.push_back(Summ->getArg(i));
2053 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2054 if (const Expr *receiver = ME->getInstanceReceiver())
2055 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2056 .getAsLocSymbol() == Sym) {
2057 // The symbol we are tracking is the receiver.
2058 AEffects.push_back(Summ->getReceiverEffect());
2064 // Get the previous type state.
2065 RefVal PrevV = *PrevT;
2067 // Specially handle -dealloc.
2068 if (!GCEnabled && std::find(AEffects.begin(), AEffects.end(), Dealloc) !=
2070 // Determine if the object's reference count was pushed to zero.
2071 assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
2072 // We may not have transitioned to 'release' if we hit an error.
2073 // This case is handled elsewhere.
2074 if (CurrV.getKind() == RefVal::Released) {
2075 assert(CurrV.getCombinedCounts() == 0);
2076 os << "Object released by directly sending the '-dealloc' message";
2081 // Specially handle CFMakeCollectable and friends.
2082 if (std::find(AEffects.begin(), AEffects.end(), MakeCollectable) !=
2084 // Get the name of the function.
2085 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
2087 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
2088 const FunctionDecl *FD = X.getAsFunctionDecl();
2091 // Determine if the object's reference count was pushed to zero.
2092 assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
2094 os << "In GC mode a call to '" << *FD
2095 << "' decrements an object's retain count and registers the "
2096 "object with the garbage collector. ";
2098 if (CurrV.getKind() == RefVal::Released) {
2099 assert(CurrV.getCount() == 0);
2100 os << "Since it now has a 0 retain count the object can be "
2101 "automatically collected by the garbage collector.";
2104 os << "An object must have a 0 retain count to be garbage collected. "
2105 "After this call its retain count is +" << CurrV.getCount()
2109 os << "When GC is not enabled a call to '" << *FD
2110 << "' has no effect on its argument.";
2112 // Nothing more to say.
2116 // Determine if the typestate has changed.
2117 if (!PrevV.hasSameState(CurrV))
2118 switch (CurrV.getKind()) {
2120 case RefVal::NotOwned:
2121 if (PrevV.getCount() == CurrV.getCount()) {
2122 // Did an autorelease message get sent?
2123 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2126 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
2127 os << "Object autoreleased";
2131 if (PrevV.getCount() > CurrV.getCount())
2132 os << "Reference count decremented.";
2134 os << "Reference count incremented.";
2136 if (unsigned Count = CurrV.getCount())
2137 os << " The object now has a +" << Count << " retain count.";
2139 if (PrevV.getKind() == RefVal::Released) {
2140 assert(GCEnabled && CurrV.getCount() > 0);
2141 os << " The object is not eligible for garbage collection until "
2142 "the retain count reaches 0 again.";
2147 case RefVal::Released:
2148 if (CurrV.getIvarAccessHistory() ==
2149 RefVal::IvarAccessHistory::ReleasedAfterDirectAccess &&
2150 CurrV.getIvarAccessHistory() != PrevV.getIvarAccessHistory()) {
2151 os << "Strong instance variable relinquished. ";
2153 os << "Object released.";
2156 case RefVal::ReturnedOwned:
2157 // Autoreleases can be applied after marking a node ReturnedOwned.
2158 if (CurrV.getAutoreleaseCount())
2161 os << "Object returned to caller as an owning reference (single "
2162 "retain count transferred to caller)";
2165 case RefVal::ReturnedNotOwned:
2166 os << "Object returned to caller with a +0 retain count";
2173 // Emit any remaining diagnostics for the argument effects (if any).
2174 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2175 E=AEffects.end(); I != E; ++I) {
2177 // A bunch of things have alternate behavior under GC.
2182 os << "In GC mode an 'autorelease' has no effect.";
2185 os << "In GC mode the 'retain' message has no effect.";
2188 os << "In GC mode the 'release' message has no effect.";
2194 if (os.str().empty())
2195 return nullptr; // We have nothing to say!
2197 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
2198 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2199 N->getLocationContext());
2200 auto P = std::make_shared<PathDiagnosticEventPiece>(Pos, os.str());
2202 // Add the range by scanning the children of the statement for any bindings
2204 for (const Stmt *Child : S->children())
2205 if (const Expr *Exp = dyn_cast_or_null<Expr>(Child))
2206 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
2207 P->addRange(Exp->getSourceRange());
2211 return std::move(P);
2215 // Find the first node in the current function context that referred to the
2216 // tracked symbol and the memory location that value was stored to. Note, the
2217 // value is only reported if the allocation occurred in the same function as
2218 // the leak. The function can also return a location context, which should be
2219 // treated as interesting.
2220 struct AllocationInfo {
2221 const ExplodedNode* N;
2223 const LocationContext *InterestingMethodContext;
2224 AllocationInfo(const ExplodedNode *InN,
2225 const MemRegion *InR,
2226 const LocationContext *InInterestingMethodContext) :
2227 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
2229 } // end anonymous namespace
2231 static AllocationInfo
2232 GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
2234 const ExplodedNode *AllocationNode = N;
2235 const ExplodedNode *AllocationNodeInCurrentOrParentContext = N;
2236 const MemRegion *FirstBinding = nullptr;
2237 const LocationContext *LeakContext = N->getLocationContext();
2239 // The location context of the init method called on the leaked object, if
2241 const LocationContext *InitMethodContext = nullptr;
2244 ProgramStateRef St = N->getState();
2245 const LocationContext *NContext = N->getLocationContext();
2247 if (!getRefBinding(St, Sym))
2250 StoreManager::FindUniqueBinding FB(Sym);
2251 StateMgr.iterBindings(St, FB);
2254 const MemRegion *R = FB.getRegion();
2255 const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>();
2256 // Do not show local variables belonging to a function other than
2257 // where the error is reported.
2258 if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame())
2262 // AllocationNode is the last node in which the symbol was tracked.
2265 // AllocationNodeInCurrentContext, is the last node in the current or
2266 // parent context in which the symbol was tracked.
2268 // Note that the allocation site might be in the parent conext. For example,
2269 // the case where an allocation happens in a block that captures a reference
2270 // to it and that reference is overwritten/dropped by another call to
2272 if (NContext == LeakContext || NContext->isParentOf(LeakContext))
2273 AllocationNodeInCurrentOrParentContext = N;
2275 // Find the last init that was called on the given symbol and store the
2276 // init method's location context.
2277 if (!InitMethodContext)
2278 if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) {
2279 const Stmt *CE = CEP->getCallExpr();
2280 if (const ObjCMessageExpr *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
2281 const Stmt *RecExpr = ME->getInstanceReceiver();
2283 SVal RecV = St->getSVal(RecExpr, NContext);
2284 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
2285 InitMethodContext = CEP->getCalleeContext();
2290 N = N->pred_empty() ? nullptr : *(N->pred_begin());
2293 // If we are reporting a leak of the object that was allocated with alloc,
2294 // mark its init method as interesting.
2295 const LocationContext *InterestingMethodContext = nullptr;
2296 if (InitMethodContext) {
2297 const ProgramPoint AllocPP = AllocationNode->getLocation();
2298 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
2299 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
2300 if (ME->getMethodFamily() == OMF_alloc)
2301 InterestingMethodContext = InitMethodContext;
2304 // If allocation happened in a function different from the leak node context,
2305 // do not report the binding.
2306 assert(N && "Could not find allocation node");
2307 if (N->getLocationContext() != LeakContext) {
2308 FirstBinding = nullptr;
2311 return AllocationInfo(AllocationNodeInCurrentOrParentContext,
2313 InterestingMethodContext);
2316 std::unique_ptr<PathDiagnosticPiece>
2317 CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2318 const ExplodedNode *EndN, BugReport &BR) {
2319 BR.markInteresting(Sym);
2320 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
2323 std::unique_ptr<PathDiagnosticPiece>
2324 CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2325 const ExplodedNode *EndN, BugReport &BR) {
2327 // Tell the BugReporterContext to report cases when the tracked symbol is
2328 // assigned to different variables, etc.
2329 BR.markInteresting(Sym);
2331 // We are reporting a leak. Walk up the graph to get to the first node where
2332 // the symbol appeared, and also get the first VarDecl that tracked object
2334 AllocationInfo AllocI =
2335 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
2337 const MemRegion* FirstBinding = AllocI.R;
2338 BR.markInteresting(AllocI.InterestingMethodContext);
2340 SourceManager& SM = BRC.getSourceManager();
2342 // Compute an actual location for the leak. Sometimes a leak doesn't
2343 // occur at an actual statement (e.g., transition between blocks; end
2344 // of function) so we need to walk the graph and compute a real location.
2345 const ExplodedNode *LeakN = EndN;
2346 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
2349 llvm::raw_string_ostream os(sbuf);
2351 os << "Object leaked: ";
2354 os << "object allocated and stored into '"
2355 << FirstBinding->getString() << '\'';
2358 os << "allocated object";
2360 // Get the retain count.
2361 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
2364 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2365 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2366 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
2367 // to the caller for NS objects.
2368 const Decl *D = &EndN->getCodeDecl();
2370 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2371 : " is returned from a function ");
2373 if (D->hasAttr<CFReturnsNotRetainedAttr>())
2374 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
2375 else if (D->hasAttr<NSReturnsNotRetainedAttr>())
2376 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
2378 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2379 if (BRC.getASTContext().getLangOpts().ObjCAutoRefCount) {
2380 os << "managed by Automatic Reference Counting";
2382 os << "whose name ('" << MD->getSelector().getAsString()
2383 << "') does not start with "
2384 "'copy', 'mutableCopy', 'alloc' or 'new'."
2385 " This violates the naming convention rules"
2386 " given in the Memory Management Guide for Cocoa";
2390 const FunctionDecl *FD = cast<FunctionDecl>(D);
2391 os << "whose name ('" << *FD
2392 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2393 " convention rules given in the Memory Management Guide for Core"
2398 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2399 const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
2400 os << " and returned from method '" << MD.getSelector().getAsString()
2401 << "' is potentially leaked when using garbage collection. Callers "
2402 "of this method do not expect a returned object with a +1 retain "
2403 "count since they expect the object to be managed by the garbage "
2407 os << " is not referenced later in this execution path and has a retain "
2408 "count of +" << RV->getCount();
2410 return llvm::make_unique<PathDiagnosticEventPiece>(L, os.str());
2413 CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2414 bool GCEnabled, const SummaryLogTy &Log,
2415 ExplodedNode *n, SymbolRef sym,
2416 CheckerContext &Ctx,
2417 bool IncludeAllocationLine)
2418 : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
2420 // Most bug reports are cached at the location where they occurred.
2421 // With leaks, we want to unique them by the location where they were
2422 // allocated, and only report a single path. To do this, we need to find
2423 // the allocation site of a piece of tracked memory, which we do via a
2424 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2425 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2426 // that all ancestor nodes that represent the allocation site have the
2427 // same SourceLocation.
2428 const ExplodedNode *AllocNode = nullptr;
2430 const SourceManager& SMgr = Ctx.getSourceManager();
2432 AllocationInfo AllocI =
2433 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
2435 AllocNode = AllocI.N;
2436 AllocBinding = AllocI.R;
2437 markInteresting(AllocI.InterestingMethodContext);
2439 // Get the SourceLocation for the allocation site.
2440 // FIXME: This will crash the analyzer if an allocation comes from an
2441 // implicit call (ex: a destructor call).
2442 // (Currently there are no such allocations in Cocoa, though.)
2443 const Stmt *AllocStmt = PathDiagnosticLocation::getStmt(AllocNode);
2444 assert(AllocStmt && "Cannot find allocation statement");
2446 PathDiagnosticLocation AllocLocation =
2447 PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2448 AllocNode->getLocationContext());
2449 Location = AllocLocation;
2451 // Set uniqieing info, which will be used for unique the bug reports. The
2452 // leaks should be uniqued on the allocation site.
2453 UniqueingLocation = AllocLocation;
2454 UniqueingDecl = AllocNode->getLocationContext()->getDecl();
2456 // Fill in the description of the bug.
2457 Description.clear();
2458 llvm::raw_string_ostream os(Description);
2459 os << "Potential leak ";
2461 os << "(when using garbage collection) ";
2462 os << "of an object";
2465 os << " stored into '" << AllocBinding->getString() << '\'';
2466 if (IncludeAllocationLine) {
2467 FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager());
2468 os << " (allocated on line " << SL.getSpellingLineNumber() << ")";
2472 addVisitor(llvm::make_unique<CFRefLeakReportVisitor>(sym, GCEnabled, Log));
2475 //===----------------------------------------------------------------------===//
2476 // Main checker logic.
2477 //===----------------------------------------------------------------------===//
2480 class RetainCountChecker
2481 : public Checker< check::Bind,
2485 check::PostStmt<BlockExpr>,
2486 check::PostStmt<CastExpr>,
2487 check::PostStmt<ObjCArrayLiteral>,
2488 check::PostStmt<ObjCDictionaryLiteral>,
2489 check::PostStmt<ObjCBoxedExpr>,
2490 check::PostStmt<ObjCIvarRefExpr>,
2492 check::PreStmt<ReturnStmt>,
2493 check::RegionChanges,
2496 mutable std::unique_ptr<CFRefBug> useAfterRelease, releaseNotOwned;
2497 mutable std::unique_ptr<CFRefBug> deallocGC, deallocNotOwned;
2498 mutable std::unique_ptr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2499 mutable std::unique_ptr<CFRefBug> leakWithinFunction, leakAtReturn;
2500 mutable std::unique_ptr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
2502 typedef llvm::DenseMap<SymbolRef, const CheckerProgramPointTag *> SymbolTagMap;
2504 // This map is only used to ensure proper deletion of any allocated tags.
2505 mutable SymbolTagMap DeadSymbolTags;
2507 mutable std::unique_ptr<RetainSummaryManager> Summaries;
2508 mutable std::unique_ptr<RetainSummaryManager> SummariesGC;
2509 mutable SummaryLogTy SummaryLog;
2510 mutable bool ShouldResetSummaryLog;
2512 /// Optional setting to indicate if leak reports should include
2513 /// the allocation line.
2514 mutable bool IncludeAllocationLine;
2517 RetainCountChecker(AnalyzerOptions &AO)
2518 : ShouldResetSummaryLog(false),
2519 IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {}
2521 ~RetainCountChecker() override { DeleteContainerSeconds(DeadSymbolTags); }
2523 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2524 ExprEngine &Eng) const {
2525 // FIXME: This is a hack to make sure the summary log gets cleared between
2526 // analyses of different code bodies.
2528 // Why is this necessary? Because a checker's lifetime is tied to a
2529 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2530 // Once in a blue moon, a new ExplodedNode will have the same address as an
2531 // old one with an associated summary, and the bug report visitor gets very
2532 // confused. (To make things worse, the summary lifetime is currently also
2533 // tied to a code body, so we get a crash instead of incorrect results.)
2535 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2536 // changes, things will start going wrong again. Really the lifetime of this
2537 // log needs to be tied to either the specific nodes in it or the entire
2538 // ExplodedGraph, not to a specific part of the code being analyzed.
2540 // (Also, having stateful local data means that the same checker can't be
2541 // used from multiple threads, but a lot of checkers have incorrect
2542 // assumptions about that anyway. So that wasn't a priority at the time of
2545 // This happens at the end of analysis, but bug reports are emitted /after/
2546 // this point. So we can't just clear the summary log now. Instead, we mark
2547 // that the next time we access the summary log, it should be cleared.
2549 // If we never reset the summary log during /this/ code body analysis,
2550 // there were no new summaries. There might still have been summaries from
2551 // the /last/ analysis, so clear them out to make sure the bug report
2552 // visitors don't get confused.
2553 if (ShouldResetSummaryLog)
2556 ShouldResetSummaryLog = !SummaryLog.empty();
2559 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2560 bool GCEnabled) const {
2562 if (!leakWithinFunctionGC)
2563 leakWithinFunctionGC.reset(new Leak(this, "Leak of object when using "
2564 "garbage collection"));
2565 return leakWithinFunctionGC.get();
2567 if (!leakWithinFunction) {
2568 if (LOpts.getGC() == LangOptions::HybridGC) {
2569 leakWithinFunction.reset(new Leak(this,
2570 "Leak of object when not using "
2571 "garbage collection (GC) in "
2572 "dual GC/non-GC code"));
2574 leakWithinFunction.reset(new Leak(this, "Leak"));
2577 return leakWithinFunction.get();
2581 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2583 if (!leakAtReturnGC)
2584 leakAtReturnGC.reset(new Leak(this,
2585 "Leak of returned object when using "
2586 "garbage collection"));
2587 return leakAtReturnGC.get();
2589 if (!leakAtReturn) {
2590 if (LOpts.getGC() == LangOptions::HybridGC) {
2591 leakAtReturn.reset(new Leak(this,
2592 "Leak of returned object when not using "
2593 "garbage collection (GC) in dual "
2596 leakAtReturn.reset(new Leak(this, "Leak of returned object"));
2599 return leakAtReturn.get();
2603 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2604 bool GCEnabled) const {
2605 // FIXME: We don't support ARC being turned on and off during one analysis.
2606 // (nor, for that matter, do we support changing ASTContexts)
2607 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
2610 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
2612 assert(SummariesGC->isARCEnabled() == ARCEnabled);
2613 return *SummariesGC;
2616 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
2618 assert(Summaries->isARCEnabled() == ARCEnabled);
2623 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2624 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2627 void printState(raw_ostream &Out, ProgramStateRef State,
2628 const char *NL, const char *Sep) const override;
2630 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
2631 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2632 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
2634 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2635 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
2636 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2638 void checkPostStmt(const ObjCIvarRefExpr *IRE, CheckerContext &C) const;
2640 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
2642 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
2643 CheckerContext &C) const;
2645 void processSummaryOfInlined(const RetainSummary &Summ,
2646 const CallEvent &Call,
2647 CheckerContext &C) const;
2649 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2651 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
2652 bool Assumption) const;
2655 checkRegionChanges(ProgramStateRef state,
2656 const InvalidatedSymbols *invalidated,
2657 ArrayRef<const MemRegion *> ExplicitRegions,
2658 ArrayRef<const MemRegion *> Regions,
2659 const LocationContext* LCtx,
2660 const CallEvent *Call) const;
2662 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2663 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2664 ExplodedNode *Pred, RetEffect RE, RefVal X,
2665 SymbolRef Sym, ProgramStateRef state) const;
2667 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
2668 void checkEndFunction(CheckerContext &C) const;
2670 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
2671 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2672 CheckerContext &C) const;
2674 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
2675 RefVal::Kind ErrorKind, SymbolRef Sym,
2676 CheckerContext &C) const;
2678 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
2680 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2682 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
2683 SymbolRef sid, RefVal V,
2684 SmallVectorImpl<SymbolRef> &Leaked) const;
2687 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2688 const ProgramPointTag *Tag, CheckerContext &Ctx,
2689 SymbolRef Sym, RefVal V) const;
2691 ExplodedNode *processLeaks(ProgramStateRef state,
2692 SmallVectorImpl<SymbolRef> &Leaked,
2693 CheckerContext &Ctx,
2694 ExplodedNode *Pred = nullptr) const;
2696 } // end anonymous namespace
2699 class StopTrackingCallback final : public SymbolVisitor {
2700 ProgramStateRef state;
2702 StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
2703 ProgramStateRef getState() const { return state; }
2705 bool VisitSymbol(SymbolRef sym) override {
2706 state = state->remove<RefBindings>(sym);
2710 } // end anonymous namespace
2712 //===----------------------------------------------------------------------===//
2713 // Handle statements that may have an effect on refcounts.
2714 //===----------------------------------------------------------------------===//
2716 void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2717 CheckerContext &C) const {
2719 // Scan the BlockDecRefExprs for any object the retain count checker
2721 if (!BE->getBlockDecl()->hasCaptures())
2724 ProgramStateRef state = C.getState();
2725 const BlockDataRegion *R =
2726 cast<BlockDataRegion>(state->getSVal(BE,
2727 C.getLocationContext()).getAsRegion());
2729 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2730 E = R->referenced_vars_end();
2735 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2736 // via captured variables, even though captured variables result in a copy
2737 // and in implicit increment/decrement of a retain count.
2738 SmallVector<const MemRegion*, 10> Regions;
2739 const LocationContext *LC = C.getLocationContext();
2740 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2742 for ( ; I != E; ++I) {
2743 const VarRegion *VR = I.getCapturedRegion();
2744 if (VR->getSuperRegion() == R) {
2745 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2747 Regions.push_back(VR);
2751 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2752 Regions.data() + Regions.size()).getState();
2753 C.addTransition(state);
2756 void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2757 CheckerContext &C) const {
2758 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2762 ArgEffect AE = IncRef;
2764 switch (BE->getBridgeKind()) {
2765 case clang::OBC_Bridge:
2768 case clang::OBC_BridgeRetained:
2771 case clang::OBC_BridgeTransfer:
2772 AE = DecRefBridgedTransferred;
2776 ProgramStateRef state = C.getState();
2777 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
2780 const RefVal* T = getRefBinding(state, Sym);
2784 RefVal::Kind hasErr = (RefVal::Kind) 0;
2785 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
2788 // FIXME: If we get an error during a bridge cast, should we report it?
2792 C.addTransition(state);
2795 void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2796 const Expr *Ex) const {
2797 ProgramStateRef state = C.getState();
2798 const ExplodedNode *pred = C.getPredecessor();
2799 for (const Stmt *Child : Ex->children()) {
2800 SVal V = state->getSVal(Child, pred->getLocationContext());
2801 if (SymbolRef sym = V.getAsSymbol())
2802 if (const RefVal* T = getRefBinding(state, sym)) {
2803 RefVal::Kind hasErr = (RefVal::Kind) 0;
2804 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2806 processNonLeakError(state, Child->getSourceRange(), hasErr, sym, C);
2812 // Return the object as autoreleased.
2813 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2815 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2816 QualType ResultTy = Ex->getType();
2817 state = setRefBinding(state, sym,
2818 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
2821 C.addTransition(state);
2824 void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2825 CheckerContext &C) const {
2826 // Apply the 'MayEscape' to all values.
2827 processObjCLiterals(C, AL);
2830 void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2831 CheckerContext &C) const {
2832 // Apply the 'MayEscape' to all keys and values.
2833 processObjCLiterals(C, DL);
2836 void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2837 CheckerContext &C) const {
2838 const ExplodedNode *Pred = C.getPredecessor();
2839 const LocationContext *LCtx = Pred->getLocationContext();
2840 ProgramStateRef State = Pred->getState();
2842 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2843 QualType ResultTy = Ex->getType();
2844 State = setRefBinding(State, Sym,
2845 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
2848 C.addTransition(State);
2851 void RetainCountChecker::checkPostStmt(const ObjCIvarRefExpr *IRE,
2852 CheckerContext &C) const {
2853 Optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>();
2857 ProgramStateRef State = C.getState();
2858 SymbolRef Sym = State->getSVal(*IVarLoc).getAsSymbol();
2859 if (!Sym || !dyn_cast_or_null<ObjCIvarRegion>(Sym->getOriginRegion()))
2862 // Accessing an ivar directly is unusual. If we've done that, be more
2863 // forgiving about what the surrounding code is allowed to do.
2865 QualType Ty = Sym->getType();
2866 RetEffect::ObjKind Kind;
2867 if (Ty->isObjCRetainableType())
2868 Kind = RetEffect::ObjC;
2869 else if (coreFoundation::isCFObjectRef(Ty))
2870 Kind = RetEffect::CF;
2874 // If the value is already known to be nil, don't bother tracking it.
2875 ConstraintManager &CMgr = State->getConstraintManager();
2876 if (CMgr.isNull(State, Sym).isConstrainedTrue())
2879 if (const RefVal *RV = getRefBinding(State, Sym)) {
2880 // If we've seen this symbol before, or we're only seeing it now because
2881 // of something the analyzer has synthesized, don't do anything.
2882 if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None ||
2883 isSynthesizedAccessor(C.getStackFrame())) {
2887 // Note that this value has been loaded from an ivar.
2888 C.addTransition(setRefBinding(State, Sym, RV->withIvarAccess()));
2892 RefVal PlusZero = RefVal::makeNotOwned(Kind, Ty);
2894 // In a synthesized accessor, the effective retain count is +0.
2895 if (isSynthesizedAccessor(C.getStackFrame())) {
2896 C.addTransition(setRefBinding(State, Sym, PlusZero));
2900 State = setRefBinding(State, Sym, PlusZero.withIvarAccess());
2901 C.addTransition(State);
2904 void RetainCountChecker::checkPostCall(const CallEvent &Call,
2905 CheckerContext &C) const {
2906 RetainSummaryManager &Summaries = getSummaryManager(C);
2907 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
2910 processSummaryOfInlined(*Summ, Call, C);
2913 checkSummary(*Summ, Call, C);
2916 /// GetReturnType - Used to get the return type of a message expression or
2917 /// function call with the intention of affixing that type to a tracked symbol.
2918 /// While the return type can be queried directly from RetEx, when
2919 /// invoking class methods we augment to the return type to be that of
2920 /// a pointer to the class (as opposed it just being id).
2921 // FIXME: We may be able to do this with related result types instead.
2922 // This function is probably overestimating.
2923 static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2924 QualType RetTy = RetE->getType();
2925 // If RetE is not a message expression just return its type.
2926 // If RetE is a message expression, return its types if it is something
2927 /// more specific than id.
2928 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2929 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2930 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2931 PT->isObjCClassType()) {
2932 // At this point we know the return type of the message expression is
2933 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2934 // is a call to a class method whose type we can resolve. In such
2935 // cases, promote the return type to XXX* (where XXX is the class).
2936 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2938 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2944 // We don't always get the exact modeling of the function with regards to the
2945 // retain count checker even when the function is inlined. For example, we need
2946 // to stop tracking the symbols which were marked with StopTrackingHard.
2947 void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2948 const CallEvent &CallOrMsg,
2949 CheckerContext &C) const {
2950 ProgramStateRef state = C.getState();
2952 // Evaluate the effect of the arguments.
2953 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2954 if (Summ.getArg(idx) == StopTrackingHard) {
2955 SVal V = CallOrMsg.getArgSVal(idx);
2956 if (SymbolRef Sym = V.getAsLocSymbol()) {
2957 state = removeRefBinding(state, Sym);
2962 // Evaluate the effect on the message receiver.
2963 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2964 if (MsgInvocation) {
2965 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2966 if (Summ.getReceiverEffect() == StopTrackingHard) {
2967 state = removeRefBinding(state, Sym);
2972 // Consult the summary for the return value.
2973 RetEffect RE = Summ.getRetEffect();
2974 if (RE.getKind() == RetEffect::NoRetHard) {
2975 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
2977 state = removeRefBinding(state, Sym);
2980 C.addTransition(state);
2983 static ProgramStateRef updateOutParameter(ProgramStateRef State,
2986 auto *ArgRegion = dyn_cast_or_null<TypedValueRegion>(ArgVal.getAsRegion());
2990 QualType PointeeTy = ArgRegion->getValueType();
2991 if (!coreFoundation::isCFObjectRef(PointeeTy))
2994 SVal PointeeVal = State->getSVal(ArgRegion);
2995 SymbolRef Pointee = PointeeVal.getAsLocSymbol();
3000 case UnretainedOutParameter:
3001 State = setRefBinding(State, Pointee,
3002 RefVal::makeNotOwned(RetEffect::CF, PointeeTy));
3004 case RetainedOutParameter:
3005 // Do nothing. Retained out parameters will either point to a +1 reference
3006 // or NULL, but the way you check for failure differs depending on the API.
3007 // Consequently, we don't have a good way to track them yet.
3011 llvm_unreachable("only for out parameters");
3017 void RetainCountChecker::checkSummary(const RetainSummary &Summ,
3018 const CallEvent &CallOrMsg,
3019 CheckerContext &C) const {
3020 ProgramStateRef state = C.getState();
3022 // Evaluate the effect of the arguments.
3023 RefVal::Kind hasErr = (RefVal::Kind) 0;
3024 SourceRange ErrorRange;
3025 SymbolRef ErrorSym = nullptr;
3027 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
3028 SVal V = CallOrMsg.getArgSVal(idx);
3030 ArgEffect Effect = Summ.getArg(idx);
3031 if (Effect == RetainedOutParameter || Effect == UnretainedOutParameter) {
3032 state = updateOutParameter(state, V, Effect);
3033 } else if (SymbolRef Sym = V.getAsLocSymbol()) {
3034 if (const RefVal *T = getRefBinding(state, Sym)) {
3035 state = updateSymbol(state, Sym, *T, Effect, hasErr, C);
3037 ErrorRange = CallOrMsg.getArgSourceRange(idx);
3045 // Evaluate the effect on the message receiver.
3046 bool ReceiverIsTracked = false;
3048 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
3049 if (MsgInvocation) {
3050 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
3051 if (const RefVal *T = getRefBinding(state, Sym)) {
3052 ReceiverIsTracked = true;
3053 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
3056 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
3064 // Process any errors.
3066 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
3070 // Consult the summary for the return value.
3071 RetEffect RE = Summ.getRetEffect();
3073 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
3074 if (ReceiverIsTracked)
3075 RE = getSummaryManager(C).getObjAllocRetEffect();
3077 RE = RetEffect::MakeNoRet();
3080 switch (RE.getKind()) {
3082 llvm_unreachable("Unhandled RetEffect.");
3084 case RetEffect::NoRet:
3085 case RetEffect::NoRetHard:
3086 // No work necessary.
3089 case RetEffect::OwnedSymbol: {
3090 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
3094 // Use the result type from the CallEvent as it automatically adjusts
3095 // for methods/functions that return references.
3096 QualType ResultTy = CallOrMsg.getResultType();
3097 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
3100 // FIXME: Add a flag to the checker where allocations are assumed to
3105 case RetEffect::GCNotOwnedSymbol:
3106 case RetEffect::NotOwnedSymbol: {
3107 const Expr *Ex = CallOrMsg.getOriginExpr();
3108 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
3112 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
3113 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
3114 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
3120 // This check is actually necessary; otherwise the statement builder thinks
3121 // we've hit a previously-found path.
3122 // Normally addTransition takes care of this, but we want the node pointer.
3123 ExplodedNode *NewNode;
3124 if (state == C.getState()) {
3125 NewNode = C.getPredecessor();
3127 NewNode = C.addTransition(state);
3130 // Annotate the node with summary we used.
3132 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
3133 if (ShouldResetSummaryLog) {
3135 ShouldResetSummaryLog = false;
3137 SummaryLog[NewNode] = &Summ;
3142 RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
3143 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
3144 CheckerContext &C) const {
3145 // In GC mode [... release] and [... retain] do nothing.
3146 // In ARC mode they shouldn't exist at all, but we just ignore them.
3147 bool IgnoreRetainMsg = C.isObjCGCEnabled();
3148 if (!IgnoreRetainMsg)
3149 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
3155 E = IgnoreRetainMsg ? DoNothing : IncRef;
3158 E = IgnoreRetainMsg ? DoNothing : DecRef;
3160 case DecRefMsgAndStopTrackingHard:
3161 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
3163 case MakeCollectable:
3164 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
3168 // Handle all use-after-releases.
3169 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
3170 V = V ^ RefVal::ErrorUseAfterRelease;
3171 hasErr = V.getKind();
3172 return setRefBinding(state, sym, V);
3178 case MakeCollectable:
3179 case DecRefMsgAndStopTrackingHard:
3180 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
3182 case UnretainedOutParameter:
3183 case RetainedOutParameter:
3184 llvm_unreachable("Applies to pointer-to-pointer parameters, which should "
3185 "not have ref state.");
3188 // Any use of -dealloc in GC is *bad*.
3189 if (C.isObjCGCEnabled()) {
3190 V = V ^ RefVal::ErrorDeallocGC;
3191 hasErr = V.getKind();
3195 switch (V.getKind()) {
3197 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
3199 // The object immediately transitions to the released state.
3200 V = V ^ RefVal::Released;
3202 return setRefBinding(state, sym, V);
3203 case RefVal::NotOwned:
3204 V = V ^ RefVal::ErrorDeallocNotOwned;
3205 hasErr = V.getKind();
3211 if (V.getKind() == RefVal::Owned) {
3212 V = V ^ RefVal::NotOwned;
3222 if (C.isObjCGCEnabled())
3224 // Update the autorelease counts.
3225 V = V.autorelease();
3229 case StopTrackingHard:
3230 return removeRefBinding(state, sym);
3233 switch (V.getKind()) {
3235 llvm_unreachable("Invalid RefVal state for a retain.");
3237 case RefVal::NotOwned:
3240 case RefVal::Released:
3241 // Non-GC cases are handled above.
3242 assert(C.isObjCGCEnabled());
3243 V = (V ^ RefVal::Owned) + 1;
3249 case DecRefBridgedTransferred:
3250 case DecRefAndStopTrackingHard:
3251 switch (V.getKind()) {
3253 // case 'RefVal::Released' handled above.
3254 llvm_unreachable("Invalid RefVal state for a release.");
3257 assert(V.getCount() > 0);
3258 if (V.getCount() == 1) {
3259 if (E == DecRefBridgedTransferred ||
3260 V.getIvarAccessHistory() ==
3261 RefVal::IvarAccessHistory::AccessedDirectly)
3262 V = V ^ RefVal::NotOwned;
3264 V = V ^ RefVal::Released;
3265 } else if (E == DecRefAndStopTrackingHard) {
3266 return removeRefBinding(state, sym);
3272 case RefVal::NotOwned:
3273 if (V.getCount() > 0) {
3274 if (E == DecRefAndStopTrackingHard)
3275 return removeRefBinding(state, sym);
3277 } else if (V.getIvarAccessHistory() ==
3278 RefVal::IvarAccessHistory::AccessedDirectly) {
3279 // Assume that the instance variable was holding on the object at
3280 // +1, and we just didn't know.
3281 if (E == DecRefAndStopTrackingHard)
3282 return removeRefBinding(state, sym);
3283 V = V.releaseViaIvar() ^ RefVal::Released;
3285 V = V ^ RefVal::ErrorReleaseNotOwned;
3286 hasErr = V.getKind();
3290 case RefVal::Released:
3291 // Non-GC cases are handled above.
3292 assert(C.isObjCGCEnabled());
3293 V = V ^ RefVal::ErrorUseAfterRelease;
3294 hasErr = V.getKind();
3299 return setRefBinding(state, sym, V);
3302 void RetainCountChecker::processNonLeakError(ProgramStateRef St,
3303 SourceRange ErrorRange,
3304 RefVal::Kind ErrorKind,
3306 CheckerContext &C) const {
3307 // HACK: Ignore retain-count issues on values accessed through ivars,
3308 // because of cases like this:
3309 // [_contentView retain];
3310 // [_contentView removeFromSuperview];
3311 // [self addSubview:_contentView]; // invalidates 'self'
3312 // [_contentView release];
3313 if (const RefVal *RV = getRefBinding(St, Sym))
3314 if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3317 ExplodedNode *N = C.generateErrorNode(St);
3322 switch (ErrorKind) {
3324 llvm_unreachable("Unhandled error.");
3325 case RefVal::ErrorUseAfterRelease:
3326 if (!useAfterRelease)
3327 useAfterRelease.reset(new UseAfterRelease(this));
3328 BT = useAfterRelease.get();
3330 case RefVal::ErrorReleaseNotOwned:
3331 if (!releaseNotOwned)
3332 releaseNotOwned.reset(new BadRelease(this));
3333 BT = releaseNotOwned.get();
3335 case RefVal::ErrorDeallocGC:
3337 deallocGC.reset(new DeallocGC(this));
3338 BT = deallocGC.get();
3340 case RefVal::ErrorDeallocNotOwned:
3341 if (!deallocNotOwned)
3342 deallocNotOwned.reset(new DeallocNotOwned(this));
3343 BT = deallocNotOwned.get();
3348 auto report = std::unique_ptr<BugReport>(
3349 new CFRefReport(*BT, C.getASTContext().getLangOpts(), C.isObjCGCEnabled(),
3350 SummaryLog, N, Sym));
3351 report->addRange(ErrorRange);
3352 C.emitReport(std::move(report));
3355 //===----------------------------------------------------------------------===//
3356 // Handle the return values of retain-count-related functions.
3357 //===----------------------------------------------------------------------===//
3359 bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
3360 // Get the callee. We're only interested in simple C functions.
3361 ProgramStateRef state = C.getState();
3362 const FunctionDecl *FD = C.getCalleeDecl(CE);
3366 IdentifierInfo *II = FD->getIdentifier();
3370 // For now, we're only handling the functions that return aliases of their
3371 // arguments: CFRetain and CFMakeCollectable (and their families).
3372 // Eventually we should add other functions we can model entirely,
3373 // such as CFRelease, which don't invalidate their arguments or globals.
3374 if (CE->getNumArgs() != 1)
3377 // Get the name of the function.
3378 StringRef FName = II->getName();
3379 FName = FName.substr(FName.find_first_not_of('_'));
3381 // See if it's one of the specific functions we know how to eval.
3382 bool canEval = false;
3384 QualType ResultTy = CE->getCallReturnType(C.getASTContext());
3385 if (ResultTy->isObjCIdType()) {
3386 // Handle: id NSMakeCollectable(CFTypeRef)
3387 canEval = II->isStr("NSMakeCollectable");
3388 } else if (ResultTy->isPointerType()) {
3389 // Handle: (CF|CG|CV)Retain
3391 // CFMakeCollectable
3392 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3393 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3394 cocoa::isRefType(ResultTy, "CG", FName) ||
3395 cocoa::isRefType(ResultTy, "CV", FName)) {
3396 canEval = isRetain(FD, FName) || isAutorelease(FD, FName) ||
3397 isMakeCollectable(FD, FName);
3404 // Bind the return value.
3405 const LocationContext *LCtx = C.getLocationContext();
3406 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
3407 if (RetVal.isUnknown()) {
3408 // If the receiver is unknown, conjure a return value.
3409 SValBuilder &SVB = C.getSValBuilder();
3410 RetVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, ResultTy, C.blockCount());
3412 state = state->BindExpr(CE, LCtx, RetVal, false);
3414 // FIXME: This should not be necessary, but otherwise the argument seems to be
3415 // considered alive during the next statement.
3416 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3417 // Save the refcount status of the argument.
3418 SymbolRef Sym = RetVal.getAsLocSymbol();
3419 const RefVal *Binding = nullptr;
3421 Binding = getRefBinding(state, Sym);
3423 // Invalidate the argument region.
3424 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
3425 /*CausesPointerEscape*/ false);
3427 // Restore the refcount status of the argument.
3429 state = setRefBinding(state, Sym, *Binding);
3432 C.addTransition(state);
3436 //===----------------------------------------------------------------------===//
3437 // Handle return statements.
3438 //===----------------------------------------------------------------------===//
3440 void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3441 CheckerContext &C) const {
3443 // Only adjust the reference count if this is the top-level call frame,
3444 // and not the result of inlining. In the future, we should do
3445 // better checking even for inlined calls, and see if they match
3446 // with their expected semantics (e.g., the method should return a retained
3448 if (!C.inTopFrame())
3451 const Expr *RetE = S->getRetValue();
3455 ProgramStateRef state = C.getState();
3457 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
3461 // Get the reference count binding (if any).
3462 const RefVal *T = getRefBinding(state, Sym);
3466 // Change the reference count.
3469 switch (X.getKind()) {
3470 case RefVal::Owned: {
3471 unsigned cnt = X.getCount();
3473 X.setCount(cnt - 1);
3474 X = X ^ RefVal::ReturnedOwned;
3478 case RefVal::NotOwned: {
3479 unsigned cnt = X.getCount();
3481 X.setCount(cnt - 1);
3482 X = X ^ RefVal::ReturnedOwned;
3485 X = X ^ RefVal::ReturnedNotOwned;
3494 // Update the binding.
3495 state = setRefBinding(state, Sym, X);
3496 ExplodedNode *Pred = C.addTransition(state);
3498 // At this point we have updated the state properly.
3499 // Everything after this is merely checking to see if the return value has
3500 // been over- or under-retained.
3502 // Did we cache out?
3506 // Update the autorelease counts.
3507 static CheckerProgramPointTag AutoreleaseTag(this, "Autorelease");
3508 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
3510 // Did we cache out?
3514 // Get the updated binding.
3515 T = getRefBinding(state, Sym);
3519 // Consult the summary of the enclosing method.
3520 RetainSummaryManager &Summaries = getSummaryManager(C);
3521 const Decl *CD = &Pred->getCodeDecl();
3522 RetEffect RE = RetEffect::MakeNoRet();
3524 // FIXME: What is the convention for blocks? Is there one?
3525 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
3526 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
3527 RE = Summ->getRetEffect();
3528 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3529 if (!isa<CXXMethodDecl>(FD)) {
3530 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3531 RE = Summ->getRetEffect();
3535 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
3538 void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3541 RetEffect RE, RefVal X,
3543 ProgramStateRef state) const {
3544 // HACK: Ignore retain-count issues on values accessed through ivars,
3545 // because of cases like this:
3546 // [_contentView retain];
3547 // [_contentView removeFromSuperview];
3548 // [self addSubview:_contentView]; // invalidates 'self'
3549 // [_contentView release];
3550 if (X.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3553 // Any leaks or other errors?
3554 if (X.isReturnedOwned() && X.getCount() == 0) {
3555 if (RE.getKind() != RetEffect::NoRet) {
3556 bool hasError = false;
3557 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3558 // Things are more complicated with garbage collection. If the
3559 // returned object is suppose to be an Objective-C object, we have
3560 // a leak (as the caller expects a GC'ed object) because no
3561 // method should return ownership unless it returns a CF object.
3563 X = X ^ RefVal::ErrorGCLeakReturned;
3565 else if (!RE.isOwned()) {
3566 // Either we are using GC and the returned object is a CF type
3567 // or we aren't using GC. In either case, we expect that the
3568 // enclosing method is expected to return ownership.
3570 X = X ^ RefVal::ErrorLeakReturned;
3574 // Generate an error node.
3575 state = setRefBinding(state, Sym, X);
3577 static CheckerProgramPointTag ReturnOwnLeakTag(this, "ReturnsOwnLeak");
3578 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
3580 const LangOptions &LOpts = C.getASTContext().getLangOpts();
3581 bool GCEnabled = C.isObjCGCEnabled();
3582 C.emitReport(std::unique_ptr<BugReport>(new CFRefLeakReport(
3583 *getLeakAtReturnBug(LOpts, GCEnabled), LOpts, GCEnabled,
3584 SummaryLog, N, Sym, C, IncludeAllocationLine)));
3588 } else if (X.isReturnedNotOwned()) {
3590 if (X.getIvarAccessHistory() ==
3591 RefVal::IvarAccessHistory::AccessedDirectly) {
3592 // Assume the method was trying to transfer a +1 reference from a
3593 // strong ivar to the caller.
3594 state = setRefBinding(state, Sym,
3595 X.releaseViaIvar() ^ RefVal::ReturnedOwned);
3597 // Trying to return a not owned object to a caller expecting an
3599 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
3601 static CheckerProgramPointTag
3602 ReturnNotOwnedTag(this, "ReturnNotOwnedForOwned");
3604 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
3606 if (!returnNotOwnedForOwned)
3607 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned(this));
3609 C.emitReport(std::unique_ptr<BugReport>(new CFRefReport(
3610 *returnNotOwnedForOwned, C.getASTContext().getLangOpts(),
3611 C.isObjCGCEnabled(), SummaryLog, N, Sym)));
3618 //===----------------------------------------------------------------------===//
3619 // Check various ways a symbol can be invalidated.
3620 //===----------------------------------------------------------------------===//
3622 void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
3623 CheckerContext &C) const {
3624 // Are we storing to something that causes the value to "escape"?
3625 bool escapes = true;
3627 // A value escapes in three possible cases (this may change):
3629 // (1) we are binding to something that is not a memory region.
3630 // (2) we are binding to a memregion that does not have stack storage
3631 // (3) we are binding to a memregion with stack storage that the store
3632 // does not understand.
3633 ProgramStateRef state = C.getState();
3635 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
3636 escapes = !regionLoc->getRegion()->hasStackStorage();
3639 // To test (3), generate a new state with the binding added. If it is
3640 // the same state, then it escapes (since the store cannot represent
3642 // Do this only if we know that the store is not supposed to generate the
3644 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3645 if (StoredVal != val)
3646 escapes = (state == (state->bindLoc(*regionLoc, val, C.getLocationContext())));
3649 // Case 4: We do not currently model what happens when a symbol is
3650 // assigned to a struct field, so be conservative here and let the symbol
3651 // go. TODO: This could definitely be improved upon.
3652 escapes = !isa<VarRegion>(regionLoc->getRegion());
3656 // If we are storing the value into an auto function scope variable annotated
3657 // with (__attribute__((cleanup))), stop tracking the value to avoid leak
3659 if (const VarRegion *LVR = dyn_cast_or_null<VarRegion>(loc.getAsRegion())) {
3660 const VarDecl *VD = LVR->getDecl();
3661 if (VD->hasAttr<CleanupAttr>()) {
3666 // If our store can represent the binding and we aren't storing to something
3667 // that doesn't have local storage then just return and have the simulation
3668 // state continue as is.
3672 // Otherwise, find all symbols referenced by 'val' that we are tracking
3673 // and stop tracking them.
3674 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
3675 C.addTransition(state);
3678 ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
3680 bool Assumption) const {
3681 // FIXME: We may add to the interface of evalAssume the list of symbols
3682 // whose assumptions have changed. For now we just iterate through the
3683 // bindings and check if any of the tracked symbols are NULL. This isn't
3684 // too bad since the number of symbols we will track in practice are
3685 // probably small and evalAssume is only called at branches and a few
3687 RefBindingsTy B = state->get<RefBindings>();
3692 bool changed = false;
3693 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
3695 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3696 // Check if the symbol is null stop tracking the symbol.
3697 ConstraintManager &CMgr = state->getConstraintManager();
3698 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3699 if (AllocFailed.isConstrainedTrue()) {
3701 B = RefBFactory.remove(B, I.getKey());
3706 state = state->set<RefBindings>(B);
3712 RetainCountChecker::checkRegionChanges(ProgramStateRef state,
3713 const InvalidatedSymbols *invalidated,
3714 ArrayRef<const MemRegion *> ExplicitRegions,
3715 ArrayRef<const MemRegion *> Regions,
3716 const LocationContext *LCtx,
3717 const CallEvent *Call) const {
3721 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3722 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3723 E = ExplicitRegions.end(); I != E; ++I) {
3724 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3725 WhitelistedSymbols.insert(SR->getSymbol());
3728 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
3729 E = invalidated->end(); I!=E; ++I) {
3731 if (WhitelistedSymbols.count(sym))
3733 // Remove any existing reference-count binding.
3734 state = removeRefBinding(state, sym);
3739 //===----------------------------------------------------------------------===//
3740 // Handle dead symbols and end-of-path.
3741 //===----------------------------------------------------------------------===//
3744 RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
3746 const ProgramPointTag *Tag,
3747 CheckerContext &Ctx,
3748 SymbolRef Sym, RefVal V) const {
3749 unsigned ACnt = V.getAutoreleaseCount();
3751 // No autorelease counts? Nothing to be done.
3755 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
3756 unsigned Cnt = V.getCount();
3758 // FIXME: Handle sending 'autorelease' to already released object.
3760 if (V.getKind() == RefVal::ReturnedOwned)
3763 // If we would over-release here, but we know the value came from an ivar,
3764 // assume it was a strong ivar that's just been relinquished.
3766 V.getIvarAccessHistory() == RefVal::IvarAccessHistory::AccessedDirectly) {
3767 V = V.releaseViaIvar();
3774 if (V.getKind() == RefVal::ReturnedOwned)
3775 V = V ^ RefVal::ReturnedNotOwned;
3777 V = V ^ RefVal::NotOwned;
3779 V.setCount(V.getCount() - ACnt);
3780 V.setAutoreleaseCount(0);
3782 return setRefBinding(state, Sym, V);
3785 // HACK: Ignore retain-count issues on values accessed through ivars,
3786 // because of cases like this:
3787 // [_contentView retain];
3788 // [_contentView removeFromSuperview];
3789 // [self addSubview:_contentView]; // invalidates 'self'
3790 // [_contentView release];
3791 if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3794 // Woah! More autorelease counts then retain counts left.
3796 V = V ^ RefVal::ErrorOverAutorelease;
3797 state = setRefBinding(state, Sym, V);
3799 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
3801 SmallString<128> sbuf;
3802 llvm::raw_svector_ostream os(sbuf);
3803 os << "Object was autoreleased ";
3804 if (V.getAutoreleaseCount() > 1)
3805 os << V.getAutoreleaseCount() << " times but the object ";
3808 os << "has a +" << V.getCount() << " retain count";
3810 if (!overAutorelease)
3811 overAutorelease.reset(new OverAutorelease(this));
3813 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3814 Ctx.emitReport(std::unique_ptr<BugReport>(
3815 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3816 SummaryLog, N, Sym, os.str())));
3823 RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
3824 SymbolRef sid, RefVal V,
3825 SmallVectorImpl<SymbolRef> &Leaked) const {
3828 // HACK: Ignore retain-count issues on values accessed through ivars,
3829 // because of cases like this:
3830 // [_contentView retain];
3831 // [_contentView removeFromSuperview];
3832 // [self addSubview:_contentView]; // invalidates 'self'
3833 // [_contentView release];
3834 if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3836 else if (V.isOwned())
3838 else if (V.isNotOwned() || V.isReturnedOwned())
3839 hasLeak = (V.getCount() > 0);
3844 return removeRefBinding(state, sid);
3846 Leaked.push_back(sid);
3847 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
3851 RetainCountChecker::processLeaks(ProgramStateRef state,
3852 SmallVectorImpl<SymbolRef> &Leaked,
3853 CheckerContext &Ctx,
3854 ExplodedNode *Pred) const {
3855 // Generate an intermediate node representing the leak point.
3856 ExplodedNode *N = Ctx.addTransition(state, Pred);
3859 for (SmallVectorImpl<SymbolRef>::iterator
3860 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3862 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3863 bool GCEnabled = Ctx.isObjCGCEnabled();
3864 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3865 : getLeakAtReturnBug(LOpts, GCEnabled);
3866 assert(BT && "BugType not initialized.");
3868 Ctx.emitReport(std::unique_ptr<BugReport>(
3869 new CFRefLeakReport(*BT, LOpts, GCEnabled, SummaryLog, N, *I, Ctx,
3870 IncludeAllocationLine)));
3877 void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
3878 ProgramStateRef state = Ctx.getState();
3879 RefBindingsTy B = state->get<RefBindings>();
3880 ExplodedNode *Pred = Ctx.getPredecessor();
3882 // Don't process anything within synthesized bodies.
3883 const LocationContext *LCtx = Pred->getLocationContext();
3884 if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
3885 assert(!LCtx->inTopFrame());
3889 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3890 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/nullptr, Ctx,
3891 I->first, I->second);
3896 // If the current LocationContext has a parent, don't check for leaks.
3897 // We will do that later.
3898 // FIXME: we should instead check for imbalances of the retain/releases,
3899 // and suggest annotations.
3900 if (LCtx->getParent())
3903 B = state->get<RefBindings>();
3904 SmallVector<SymbolRef, 10> Leaked;
3906 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
3907 state = handleSymbolDeath(state, I->first, I->second, Leaked);
3909 processLeaks(state, Leaked, Ctx, Pred);
3912 const ProgramPointTag *
3913 RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
3914 const CheckerProgramPointTag *&tag = DeadSymbolTags[sym];
3916 SmallString<64> buf;
3917 llvm::raw_svector_ostream out(buf);
3918 out << "Dead Symbol : ";
3919 sym->dumpToStream(out);
3920 tag = new CheckerProgramPointTag(this, out.str());
3925 void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3926 CheckerContext &C) const {
3927 ExplodedNode *Pred = C.getPredecessor();
3929 ProgramStateRef state = C.getState();
3930 RefBindingsTy B = state->get<RefBindings>();
3931 SmallVector<SymbolRef, 10> Leaked;
3933 // Update counts from autorelease pools
3934 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3935 E = SymReaper.dead_end(); I != E; ++I) {
3937 if (const RefVal *T = B.lookup(Sym)){
3938 // Use the symbol as the tag.
3939 // FIXME: This might not be as unique as we would like.
3940 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
3941 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
3945 // Fetch the new reference count from the state, and use it to handle
3947 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
3951 if (Leaked.empty()) {
3952 C.addTransition(state);
3956 Pred = processLeaks(state, Leaked, C, Pred);
3958 // Did we cache out?
3962 // Now generate a new node that nukes the old bindings.
3963 // The only bindings left at this point are the leaked symbols.
3964 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
3965 B = state->get<RefBindings>();
3967 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3970 B = F.remove(B, *I);
3972 state = state->set<RefBindings>(B);
3973 C.addTransition(state, Pred);
3976 void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
3977 const char *NL, const char *Sep) const {
3979 RefBindingsTy B = State->get<RefBindings>();
3986 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3987 Out << I->first << " : ";
3988 I->second.print(Out);
3993 //===----------------------------------------------------------------------===//
3994 // Checker registration.
3995 //===----------------------------------------------------------------------===//
3997 void ento::registerRetainCountChecker(CheckerManager &Mgr) {
3998 Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
4001 //===----------------------------------------------------------------------===//
4002 // Implementation of the CallEffects API.
4003 //===----------------------------------------------------------------------===//
4007 namespace objc_retain {
4009 // This is a bit gross, but it allows us to populate CallEffects without
4010 // creating a bunch of accessors. This kind is very localized, so the
4011 // damage of this macro is limited.
4012 #define createCallEffect(D, KIND)\
4013 ASTContext &Ctx = D->getASTContext();\
4014 LangOptions L = Ctx.getLangOpts();\
4015 RetainSummaryManager M(Ctx, L.GCOnly, L.ObjCAutoRefCount);\
4016 const RetainSummary *S = M.get ## KIND ## Summary(D);\
4017 CallEffects CE(S->getRetEffect());\
4018 CE.Receiver = S->getReceiverEffect();\
4019 unsigned N = D->param_size();\
4020 for (unsigned i = 0; i < N; ++i) {\
4021 CE.Args.push_back(S->getArg(i));\
4024 CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) {
4025 createCallEffect(MD, Method);
4029 CallEffects CallEffects::getEffect(const FunctionDecl *FD) {
4030 createCallEffect(FD, Function);
4034 #undef createCallEffect
4036 } // end namespace objc_retain
4037 } // end namespace ento
4038 } // end namespace clang