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;
465 friend class RetainCountChecker;
467 } // end anonymous namespace
469 //===----------------------------------------------------------------------===//
470 // Data structures for constructing summaries.
471 //===----------------------------------------------------------------------===//
474 class ObjCSummaryKey {
478 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
481 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
482 : II(d ? d->getIdentifier() : nullptr), S(s) {}
484 ObjCSummaryKey(Selector s)
485 : II(nullptr), S(s) {}
487 IdentifierInfo *getIdentifier() const { return II; }
488 Selector getSelector() const { return S; }
490 } // end anonymous namespace
493 template <> struct DenseMapInfo<ObjCSummaryKey> {
494 static inline ObjCSummaryKey getEmptyKey() {
495 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
496 DenseMapInfo<Selector>::getEmptyKey());
499 static inline ObjCSummaryKey getTombstoneKey() {
500 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
501 DenseMapInfo<Selector>::getTombstoneKey());
504 static unsigned getHashValue(const ObjCSummaryKey &V) {
505 typedef std::pair<IdentifierInfo*, Selector> PairTy;
506 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
510 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
511 return LHS.getIdentifier() == RHS.getIdentifier() &&
512 LHS.getSelector() == RHS.getSelector();
516 } // end llvm namespace
519 class ObjCSummaryCache {
520 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
523 ObjCSummaryCache() {}
525 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
526 // Do a lookup with the (D,S) pair. If we find a match return
528 ObjCSummaryKey K(D, S);
529 MapTy::iterator I = M.find(K);
536 // Walk the super chain. If we find a hit with a parent, we'll end
537 // up returning that summary. We actually allow that key (null,S), as
538 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
539 // generate initial summaries without having to worry about NSObject
541 // FIXME: We may change this at some point.
542 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
543 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
550 // Cache the summary with original key to make the next lookup faster
551 // and return the iterator.
552 const RetainSummary *Summ = I->second;
557 const RetainSummary *find(IdentifierInfo* II, Selector S) {
558 // FIXME: Class method lookup. Right now we don't have a good way
559 // of going between IdentifierInfo* and the class hierarchy.
560 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
563 I = M.find(ObjCSummaryKey(S));
565 return I == M.end() ? nullptr : I->second;
568 const RetainSummary *& operator[](ObjCSummaryKey K) {
572 const RetainSummary *& operator[](Selector S) {
573 return M[ ObjCSummaryKey(S) ];
576 } // end anonymous namespace
578 //===----------------------------------------------------------------------===//
579 // Data structures for managing collections of summaries.
580 //===----------------------------------------------------------------------===//
583 class RetainSummaryManager {
585 //==-----------------------------------------------------------------==//
587 //==-----------------------------------------------------------------==//
589 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
592 typedef ObjCSummaryCache ObjCMethodSummariesTy;
594 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
596 //==-----------------------------------------------------------------==//
598 //==-----------------------------------------------------------------==//
600 /// Ctx - The ASTContext object for the analyzed ASTs.
603 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
604 const bool GCEnabled;
606 /// Records whether or not the analyzed code runs in ARC mode.
607 const bool ARCEnabled;
609 /// FuncSummaries - A map from FunctionDecls to summaries.
610 FuncSummariesTy FuncSummaries;
612 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
614 ObjCMethodSummariesTy ObjCClassMethodSummaries;
616 /// ObjCMethodSummaries - A map from selectors to summaries.
617 ObjCMethodSummariesTy ObjCMethodSummaries;
619 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
620 /// and all other data used by the checker.
621 llvm::BumpPtrAllocator BPAlloc;
623 /// AF - A factory for ArgEffects objects.
624 ArgEffects::Factory AF;
626 /// ScratchArgs - A holding buffer for construct ArgEffects.
627 ArgEffects ScratchArgs;
629 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
631 RetEffect ObjCAllocRetE;
633 /// ObjCInitRetE - Default return effect for init methods returning
634 /// Objective-C objects.
635 RetEffect ObjCInitRetE;
637 /// SimpleSummaries - Used for uniquing summaries that don't have special
639 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
641 //==-----------------------------------------------------------------==//
643 //==-----------------------------------------------------------------==//
645 /// getArgEffects - Returns a persistent ArgEffects object based on the
646 /// data in ScratchArgs.
647 ArgEffects getArgEffects();
649 enum UnaryFuncKind { cfretain, cfrelease, cfautorelease, cfmakecollectable };
651 const RetainSummary *getUnarySummary(const FunctionType* FT,
654 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
655 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
656 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
658 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
660 const RetainSummary *getPersistentSummary(RetEffect RetEff,
661 ArgEffect ReceiverEff = DoNothing,
662 ArgEffect DefaultEff = MayEscape) {
663 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
664 return getPersistentSummary(Summ);
667 const RetainSummary *getDoNothingSummary() {
668 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
671 const RetainSummary *getDefaultSummary() {
672 return getPersistentSummary(RetEffect::MakeNoRet(),
673 DoNothing, MayEscape);
676 const RetainSummary *getPersistentStopSummary() {
677 return getPersistentSummary(RetEffect::MakeNoRet(),
678 StopTracking, StopTracking);
681 void InitializeClassMethodSummaries();
682 void InitializeMethodSummaries();
684 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
685 ObjCClassMethodSummaries[S] = Summ;
688 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
689 ObjCMethodSummaries[S] = Summ;
692 void addClassMethSummary(const char* Cls, const char* name,
693 const RetainSummary *Summ, bool isNullary = true) {
694 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
695 Selector S = isNullary ? GetNullarySelector(name, Ctx)
696 : GetUnarySelector(name, Ctx);
697 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
700 void addInstMethSummary(const char* Cls, const char* nullaryName,
701 const RetainSummary *Summ) {
702 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
703 Selector S = GetNullarySelector(nullaryName, Ctx);
704 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
707 template <typename... Keywords>
708 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy &Summaries,
709 const RetainSummary *Summ, Keywords *... Kws) {
710 Selector S = getKeywordSelector(Ctx, Kws...);
711 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
714 template <typename... Keywords>
715 void addInstMethSummary(const char *Cls, const RetainSummary *Summ,
717 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, Kws...);
720 template <typename... Keywords>
721 void addClsMethSummary(const char *Cls, const RetainSummary *Summ,
723 addMethodSummary(&Ctx.Idents.get(Cls), ObjCClassMethodSummaries, Summ,
727 template <typename... Keywords>
728 void addClsMethSummary(IdentifierInfo *II, const RetainSummary *Summ,
730 addMethodSummary(II, ObjCClassMethodSummaries, Summ, Kws...);
735 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
737 GCEnabled(gcenabled),
739 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
740 ObjCAllocRetE(gcenabled
741 ? RetEffect::MakeGCNotOwned()
742 : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC)
743 : RetEffect::MakeOwned(RetEffect::ObjC))),
744 ObjCInitRetE(gcenabled
745 ? RetEffect::MakeGCNotOwned()
746 : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC)
747 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
748 InitializeClassMethodSummaries();
749 InitializeMethodSummaries();
752 const RetainSummary *getSummary(const CallEvent &Call,
753 ProgramStateRef State = nullptr);
755 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
757 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
758 const ObjCMethodDecl *MD,
760 ObjCMethodSummariesTy &CachedSummaries);
762 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
763 ProgramStateRef State);
765 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
766 assert(!M.isInstanceMessage());
767 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
769 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
770 M.getResultType(), ObjCClassMethodSummaries);
773 /// getMethodSummary - This version of getMethodSummary is used to query
774 /// the summary for the current method being analyzed.
775 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
776 const ObjCInterfaceDecl *ID = MD->getClassInterface();
777 Selector S = MD->getSelector();
778 QualType ResultTy = MD->getReturnType();
780 ObjCMethodSummariesTy *CachedSummaries;
781 if (MD->isInstanceMethod())
782 CachedSummaries = &ObjCMethodSummaries;
784 CachedSummaries = &ObjCClassMethodSummaries;
786 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
789 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
790 Selector S, QualType RetTy);
792 /// Determine if there is a special return effect for this function or method.
793 Optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy,
796 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
797 const ObjCMethodDecl *MD);
799 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
800 const FunctionDecl *FD);
802 void updateSummaryForCall(const RetainSummary *&Summ,
803 const CallEvent &Call);
805 bool isGCEnabled() const { return GCEnabled; }
807 bool isARCEnabled() const { return ARCEnabled; }
809 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
811 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
813 friend class RetainSummaryTemplate;
816 // Used to avoid allocating long-term (BPAlloc'd) memory for default retain
817 // summaries. If a function or method looks like it has a default summary, but
818 // it has annotations, the annotations are added to the stack-based template
819 // and then copied into managed memory.
820 class RetainSummaryTemplate {
821 RetainSummaryManager &Manager;
822 const RetainSummary *&RealSummary;
823 RetainSummary ScratchSummary;
826 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
827 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
829 ~RetainSummaryTemplate() {
831 RealSummary = Manager.getPersistentSummary(ScratchSummary);
834 RetainSummary &operator*() {
836 return ScratchSummary;
839 RetainSummary *operator->() {
841 return &ScratchSummary;
845 } // end anonymous namespace
847 //===----------------------------------------------------------------------===//
848 // Implementation of checker data structures.
849 //===----------------------------------------------------------------------===//
851 ArgEffects RetainSummaryManager::getArgEffects() {
852 ArgEffects AE = ScratchArgs;
853 ScratchArgs = AF.getEmptyMap();
857 const RetainSummary *
858 RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
859 // Unique "simple" summaries -- those without ArgEffects.
860 if (OldSumm.isSimple()) {
861 llvm::FoldingSetNodeID ID;
865 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
868 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
869 new (N) CachedSummaryNode(OldSumm);
870 SimpleSummaries.InsertNode(N, Pos);
873 return &N->getValue();
876 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
877 new (Summ) RetainSummary(OldSumm);
881 //===----------------------------------------------------------------------===//
882 // Summary creation for functions (largely uses of Core Foundation).
883 //===----------------------------------------------------------------------===//
885 static bool isRetain(const FunctionDecl *FD, StringRef FName) {
886 return FName.startswith_lower("retain") || FName.endswith_lower("retain");
889 static bool isRelease(const FunctionDecl *FD, StringRef FName) {
890 return FName.startswith_lower("release") || FName.endswith_lower("release");
893 static bool isAutorelease(const FunctionDecl *FD, StringRef FName) {
894 return FName.startswith_lower("autorelease") ||
895 FName.endswith_lower("autorelease");
898 static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
899 // FIXME: Remove FunctionDecl parameter.
900 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
901 return FName.find_lower("MakeCollectable") != StringRef::npos;
904 static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
908 case DecRefBridgedTransferred:
911 case MakeCollectable:
912 case UnretainedOutParameter:
913 case RetainedOutParameter:
916 case StopTrackingHard:
917 return StopTrackingHard;
919 case DecRefAndStopTrackingHard:
920 return DecRefAndStopTrackingHard;
922 case DecRefMsgAndStopTrackingHard:
923 return DecRefMsgAndStopTrackingHard;
928 llvm_unreachable("Unknown ArgEffect kind");
931 void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
932 const CallEvent &Call) {
933 if (Call.hasNonZeroCallbackArg()) {
934 ArgEffect RecEffect =
935 getStopTrackingHardEquivalent(S->getReceiverEffect());
936 ArgEffect DefEffect =
937 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
939 ArgEffects CustomArgEffects = S->getArgEffects();
940 for (ArgEffects::iterator I = CustomArgEffects.begin(),
941 E = CustomArgEffects.end();
943 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
944 if (Translated != DefEffect)
945 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
948 RetEffect RE = RetEffect::MakeNoRetHard();
950 // Special cases where the callback argument CANNOT free the return value.
951 // This can generally only happen if we know that the callback will only be
952 // called when the return value is already being deallocated.
953 if (const SimpleFunctionCall *FC = dyn_cast<SimpleFunctionCall>(&Call)) {
954 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
955 // When the CGBitmapContext is deallocated, the callback here will free
956 // the associated data buffer.
957 // The callback in dispatch_data_create frees the buffer, but not
959 if (Name->isStr("CGBitmapContextCreateWithData") ||
960 Name->isStr("dispatch_data_create"))
961 RE = S->getRetEffect();
965 S = getPersistentSummary(RE, RecEffect, DefEffect);
968 // Special case '[super init];' and '[self init];'
970 // Even though calling '[super init]' without assigning the result to self
971 // and checking if the parent returns 'nil' is a bad pattern, it is common.
972 // Additionally, our Self Init checker already warns about it. To avoid
973 // overwhelming the user with messages from both checkers, we model the case
974 // of '[super init]' in cases when it is not consumed by another expression
975 // as if the call preserves the value of 'self'; essentially, assuming it can
976 // never fail and return 'nil'.
977 // Note, we don't want to just stop tracking the value since we want the
978 // RetainCount checker to report leaks and use-after-free if SelfInit checker
980 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
981 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
983 // Check if the message is not consumed, we know it will not be used in
984 // an assignment, ex: "self = [super init]".
985 const Expr *ME = MC->getOriginExpr();
986 const LocationContext *LCtx = MC->getLocationContext();
987 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
988 if (!PM.isConsumedExpr(ME)) {
989 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
990 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
991 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
997 const RetainSummary *
998 RetainSummaryManager::getSummary(const CallEvent &Call,
999 ProgramStateRef State) {
1000 const RetainSummary *Summ;
1001 switch (Call.getKind()) {
1003 Summ = getFunctionSummary(cast<SimpleFunctionCall>(Call).getDecl());
1006 case CE_CXXMemberOperator:
1008 case CE_CXXConstructor:
1009 case CE_CXXDestructor:
1010 case CE_CXXAllocator:
1011 // FIXME: These calls are currently unsupported.
1012 return getPersistentStopSummary();
1013 case CE_ObjCMessage: {
1014 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
1015 if (Msg.isInstanceMessage())
1016 Summ = getInstanceMethodSummary(Msg, State);
1018 Summ = getClassMethodSummary(Msg);
1023 updateSummaryForCall(Summ, Call);
1025 assert(Summ && "Unknown call type?");
1029 const RetainSummary *
1030 RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
1031 // If we don't know what function we're calling, use our default summary.
1033 return getDefaultSummary();
1035 // Look up a summary in our cache of FunctionDecls -> Summaries.
1036 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
1037 if (I != FuncSummaries.end())
1040 // No summary? Generate one.
1041 const RetainSummary *S = nullptr;
1042 bool AllowAnnotations = true;
1045 // We generate "stop" summaries for implicitly defined functions.
1046 if (FD->isImplicit()) {
1047 S = getPersistentStopSummary();
1051 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
1053 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
1054 const IdentifierInfo *II = FD->getIdentifier();
1058 StringRef FName = II->getName();
1060 // Strip away preceding '_'. Doing this here will effect all the checks
1062 FName = FName.substr(FName.find_first_not_of('_'));
1064 // Inspect the result type.
1065 QualType RetTy = FT->getReturnType();
1066 std::string RetTyName = RetTy.getAsString();
1068 // FIXME: This should all be refactored into a chain of "summary lookup"
1070 assert(ScratchArgs.isEmpty());
1072 if (FName == "pthread_create" || FName == "pthread_setspecific") {
1073 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1074 // This will be addressed better with IPA.
1075 S = getPersistentStopSummary();
1076 } else if (FName == "NSMakeCollectable") {
1077 // Handle: id NSMakeCollectable(CFTypeRef)
1078 S = (RetTy->isObjCIdType())
1079 ? getUnarySummary(FT, cfmakecollectable)
1080 : getPersistentStopSummary();
1081 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1082 // but we can fully model NSMakeCollectable ourselves.
1083 AllowAnnotations = false;
1084 } else if (FName == "CFPlugInInstanceCreate") {
1085 S = getPersistentSummary(RetEffect::MakeNoRet());
1086 } else if (FName == "IORegistryEntrySearchCFProperty"
1087 || (RetTyName == "CFMutableDictionaryRef" && (
1088 FName == "IOBSDNameMatching" ||
1089 FName == "IOServiceMatching" ||
1090 FName == "IOServiceNameMatching" ||
1091 FName == "IORegistryEntryIDMatching" ||
1092 FName == "IOOpenFirmwarePathMatching"
1094 // Part of <rdar://problem/6961230>. (IOKit)
1095 // This should be addressed using a API table.
1096 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF),
1097 DoNothing, DoNothing);
1098 } else if (FName == "IOServiceGetMatchingService" ||
1099 FName == "IOServiceGetMatchingServices") {
1100 // FIXES: <rdar://problem/6326900>
1101 // This should be addressed using a API table. This strcmp is also
1102 // a little gross, but there is no need to super optimize here.
1103 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
1104 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1105 } else if (FName == "IOServiceAddNotification" ||
1106 FName == "IOServiceAddMatchingNotification") {
1107 // Part of <rdar://problem/6961230>. (IOKit)
1108 // This should be addressed using a API table.
1109 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
1110 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1111 } else if (FName == "CVPixelBufferCreateWithBytes") {
1112 // FIXES: <rdar://problem/7283567>
1113 // Eventually this can be improved by recognizing that the pixel
1114 // buffer passed to CVPixelBufferCreateWithBytes is released via
1115 // a callback and doing full IPA to make sure this is done correctly.
1116 // FIXME: This function has an out parameter that returns an
1117 // allocated object.
1118 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
1119 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1120 } else if (FName == "CGBitmapContextCreateWithData") {
1121 // FIXES: <rdar://problem/7358899>
1122 // Eventually this can be improved by recognizing that 'releaseInfo'
1123 // passed to CGBitmapContextCreateWithData is released via
1124 // a callback and doing full IPA to make sure this is done correctly.
1125 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
1126 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF),
1127 DoNothing, DoNothing);
1128 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1129 // FIXES: <rdar://problem/7283567>
1130 // Eventually this can be improved by recognizing that the pixel
1131 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1132 // via a callback and doing full IPA to make sure this is done
1134 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
1135 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1136 } else if (FName == "VTCompressionSessionEncodeFrame") {
1137 // The context argument passed to VTCompressionSessionEncodeFrame()
1138 // is passed to the callback specified when creating the session
1139 // (e.g. with VTCompressionSessionCreate()) which can release it.
1140 // To account for this possibility, conservatively stop tracking
1142 ScratchArgs = AF.add(ScratchArgs, 5, StopTracking);
1143 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1144 } else if (FName == "dispatch_set_context" ||
1145 FName == "xpc_connection_set_context") {
1146 // <rdar://problem/11059275> - The analyzer currently doesn't have
1147 // a good way to reason about the finalizer function for libdispatch.
1148 // If we pass a context object that is memory managed, stop tracking it.
1149 // <rdar://problem/13783514> - Same problem, but for XPC.
1150 // FIXME: this hack should possibly go away once we can handle
1151 // libdispatch and XPC finalizers.
1152 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1153 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1154 } else if (FName.startswith("NSLog")) {
1155 S = getDoNothingSummary();
1156 } else if (FName.startswith("NS") &&
1157 (FName.find("Insert") != StringRef::npos)) {
1158 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1159 // be deallocated by NSMapRemove. (radar://11152419)
1160 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1161 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1162 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1165 // Did we get a summary?
1169 if (RetTy->isPointerType()) {
1170 // For CoreFoundation ('CF') types.
1171 if (cocoa::isRefType(RetTy, "CF", FName)) {
1172 if (isRetain(FD, FName)) {
1173 S = getUnarySummary(FT, cfretain);
1174 // CFRetain isn't supposed to be annotated. However, this may as well
1175 // be a user-made "safe" CFRetain function that is incorrectly
1176 // annotated as cf_returns_retained due to lack of better options.
1177 // We want to ignore such annotation.
1178 AllowAnnotations = false;
1179 } else if (isAutorelease(FD, FName)) {
1180 S = getUnarySummary(FT, cfautorelease);
1181 // The headers use cf_consumed, but we can fully model CFAutorelease
1183 AllowAnnotations = false;
1184 } else if (isMakeCollectable(FD, FName)) {
1185 S = getUnarySummary(FT, cfmakecollectable);
1186 AllowAnnotations = false;
1188 S = getCFCreateGetRuleSummary(FD);
1194 // For CoreGraphics ('CG') and CoreVideo ('CV') types.
1195 if (cocoa::isRefType(RetTy, "CG", FName) ||
1196 cocoa::isRefType(RetTy, "CV", FName)) {
1197 if (isRetain(FD, FName))
1198 S = getUnarySummary(FT, cfretain);
1200 S = getCFCreateGetRuleSummary(FD);
1205 // For all other CF-style types, use the Create/Get
1206 // rule for summaries but don't support Retain functions
1207 // with framework-specific prefixes.
1208 if (coreFoundation::isCFObjectRef(RetTy)) {
1209 S = getCFCreateGetRuleSummary(FD);
1213 if (FD->hasAttr<CFAuditedTransferAttr>()) {
1214 S = getCFCreateGetRuleSummary(FD);
1221 // Check for release functions, the only kind of functions that we care
1222 // about that don't return a pointer type.
1223 if (FName.size() >= 2 &&
1224 FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
1226 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
1228 if (isRelease(FD, FName))
1229 S = getUnarySummary(FT, cfrelease);
1231 assert (ScratchArgs.isEmpty());
1232 // Remaining CoreFoundation and CoreGraphics functions.
1233 // We use to assume that they all strictly followed the ownership idiom
1234 // and that ownership cannot be transferred. While this is technically
1235 // correct, many methods allow a tracked object to escape. For example:
1237 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1238 // CFDictionaryAddValue(y, key, x);
1240 // ... it is okay to use 'x' since 'y' has a reference to it
1242 // We handle this and similar cases with the follow heuristic. If the
1243 // function name contains "InsertValue", "SetValue", "AddValue",
1244 // "AppendValue", or "SetAttribute", then we assume that arguments may
1245 // "escape." This means that something else holds on to the object,
1246 // allowing it be used even after its local retain count drops to 0.
1247 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1248 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1249 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1250 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
1251 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
1252 ? MayEscape : DoNothing;
1254 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
1260 // If we got all the way here without any luck, use a default summary.
1262 S = getDefaultSummary();
1264 // Annotations override defaults.
1265 if (AllowAnnotations)
1266 updateSummaryFromAnnotations(S, FD);
1268 FuncSummaries[FD] = S;
1272 const RetainSummary *
1273 RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1274 if (coreFoundation::followsCreateRule(FD))
1275 return getCFSummaryCreateRule(FD);
1277 return getCFSummaryGetRule(FD);
1280 const RetainSummary *
1281 RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1282 UnaryFuncKind func) {
1284 // Sanity check that this is *really* a unary function. This can
1285 // happen if people do weird things.
1286 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
1287 if (!FTP || FTP->getNumParams() != 1)
1288 return getPersistentStopSummary();
1290 assert (ScratchArgs.isEmpty());
1294 case cfretain: Effect = IncRef; break;
1295 case cfrelease: Effect = DecRef; break;
1296 case cfautorelease: Effect = Autorelease; break;
1297 case cfmakecollectable: Effect = MakeCollectable; break;
1300 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1301 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1304 const RetainSummary *
1305 RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
1306 assert (ScratchArgs.isEmpty());
1308 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF));
1311 const RetainSummary *
1312 RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
1313 assert (ScratchArgs.isEmpty());
1314 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1315 DoNothing, DoNothing);
1318 /// Returns true if the declaration 'D' is annotated with 'rcAnnotation'.
1319 static bool hasRCAnnotation(const Decl *D, StringRef rcAnnotation) {
1320 for (const auto *Ann : D->specific_attrs<AnnotateAttr>()) {
1321 if (Ann->getAnnotation() == rcAnnotation)
1327 /// Returns true if the function declaration 'FD' contains
1328 /// 'rc_ownership_trusted_implementation' annotate attribute.
1329 static bool isTrustedReferenceCountImplementation(const FunctionDecl *FD) {
1330 return hasRCAnnotation(FD, "rc_ownership_trusted_implementation");
1333 static bool isGeneralizedObjectRef(QualType Ty) {
1334 if (Ty.getAsString().substr(0, 4) == "isl_")
1340 //===----------------------------------------------------------------------===//
1341 // Summary creation for Selectors.
1342 //===----------------------------------------------------------------------===//
1345 RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
1347 if (cocoa::isCocoaObjectRef(RetTy)) {
1348 if (D->hasAttr<NSReturnsRetainedAttr>())
1349 return ObjCAllocRetE;
1351 if (D->hasAttr<NSReturnsNotRetainedAttr>() ||
1352 D->hasAttr<NSReturnsAutoreleasedAttr>())
1353 return RetEffect::MakeNotOwned(RetEffect::ObjC);
1355 } else if (!RetTy->isPointerType()) {
1359 if (D->hasAttr<CFReturnsRetainedAttr>())
1360 return RetEffect::MakeOwned(RetEffect::CF);
1361 else if (hasRCAnnotation(D, "rc_ownership_returns_retained"))
1362 return RetEffect::MakeOwned(RetEffect::Generalized);
1364 if (D->hasAttr<CFReturnsNotRetainedAttr>())
1365 return RetEffect::MakeNotOwned(RetEffect::CF);
1371 RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1372 const FunctionDecl *FD) {
1376 assert(Summ && "Must have a summary to add annotations to.");
1377 RetainSummaryTemplate Template(Summ, *this);
1379 // Effects on the parameters.
1380 unsigned parm_idx = 0;
1381 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
1382 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
1383 const ParmVarDecl *pd = *pi;
1384 if (pd->hasAttr<NSConsumedAttr>())
1385 Template->addArg(AF, parm_idx, DecRefMsg);
1386 else if (pd->hasAttr<CFConsumedAttr>() ||
1387 hasRCAnnotation(pd, "rc_ownership_consumed"))
1388 Template->addArg(AF, parm_idx, DecRef);
1389 else if (pd->hasAttr<CFReturnsRetainedAttr>() ||
1390 hasRCAnnotation(pd, "rc_ownership_returns_retained")) {
1391 QualType PointeeTy = pd->getType()->getPointeeType();
1392 if (!PointeeTy.isNull())
1393 if (coreFoundation::isCFObjectRef(PointeeTy))
1394 Template->addArg(AF, parm_idx, RetainedOutParameter);
1395 } else if (pd->hasAttr<CFReturnsNotRetainedAttr>()) {
1396 QualType PointeeTy = pd->getType()->getPointeeType();
1397 if (!PointeeTy.isNull())
1398 if (coreFoundation::isCFObjectRef(PointeeTy))
1399 Template->addArg(AF, parm_idx, UnretainedOutParameter);
1403 QualType RetTy = FD->getReturnType();
1404 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
1405 Template->setRetEffect(*RetE);
1409 RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1410 const ObjCMethodDecl *MD) {
1414 assert(Summ && "Must have a valid summary to add annotations to");
1415 RetainSummaryTemplate Template(Summ, *this);
1417 // Effects on the receiver.
1418 if (MD->hasAttr<NSConsumesSelfAttr>())
1419 Template->setReceiverEffect(DecRefMsg);
1421 // Effects on the parameters.
1422 unsigned parm_idx = 0;
1423 for (ObjCMethodDecl::param_const_iterator
1424 pi=MD->param_begin(), pe=MD->param_end();
1425 pi != pe; ++pi, ++parm_idx) {
1426 const ParmVarDecl *pd = *pi;
1427 if (pd->hasAttr<NSConsumedAttr>())
1428 Template->addArg(AF, parm_idx, DecRefMsg);
1429 else if (pd->hasAttr<CFConsumedAttr>()) {
1430 Template->addArg(AF, parm_idx, DecRef);
1431 } else if (pd->hasAttr<CFReturnsRetainedAttr>()) {
1432 QualType PointeeTy = pd->getType()->getPointeeType();
1433 if (!PointeeTy.isNull())
1434 if (coreFoundation::isCFObjectRef(PointeeTy))
1435 Template->addArg(AF, parm_idx, RetainedOutParameter);
1436 } else if (pd->hasAttr<CFReturnsNotRetainedAttr>()) {
1437 QualType PointeeTy = pd->getType()->getPointeeType();
1438 if (!PointeeTy.isNull())
1439 if (coreFoundation::isCFObjectRef(PointeeTy))
1440 Template->addArg(AF, parm_idx, UnretainedOutParameter);
1444 QualType RetTy = MD->getReturnType();
1445 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1446 Template->setRetEffect(*RetE);
1449 const RetainSummary *
1450 RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1451 Selector S, QualType RetTy) {
1452 // Any special effects?
1453 ArgEffect ReceiverEff = DoNothing;
1454 RetEffect ResultEff = RetEffect::MakeNoRet();
1456 // Check the method family, and apply any default annotations.
1457 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1459 case OMF_initialize:
1460 case OMF_performSelector:
1461 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1462 // FIXME: Does the non-threaded performSelector family really belong here?
1463 // The selector could be, say, @selector(copy).
1464 if (cocoa::isCocoaObjectRef(RetTy))
1465 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1466 else if (coreFoundation::isCFObjectRef(RetTy)) {
1467 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1468 // values for alloc, new, copy, or mutableCopy, so we have to
1469 // double-check with the selector. This is ugly, but there aren't that
1470 // many Objective-C methods that return CF objects, right?
1472 switch (S.getMethodFamily()) {
1476 case OMF_mutableCopy:
1477 ResultEff = RetEffect::MakeOwned(RetEffect::CF);
1480 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1484 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1489 ResultEff = ObjCInitRetE;
1490 ReceiverEff = DecRefMsg;
1495 case OMF_mutableCopy:
1496 if (cocoa::isCocoaObjectRef(RetTy))
1497 ResultEff = ObjCAllocRetE;
1498 else if (coreFoundation::isCFObjectRef(RetTy))
1499 ResultEff = RetEffect::MakeOwned(RetEffect::CF);
1501 case OMF_autorelease:
1502 ReceiverEff = Autorelease;
1505 ReceiverEff = IncRefMsg;
1508 ReceiverEff = DecRefMsg;
1511 ReceiverEff = Dealloc;
1514 // -self is handled specially by the ExprEngine to propagate the receiver.
1516 case OMF_retainCount:
1518 // These methods don't return objects.
1522 // If one of the arguments in the selector has the keyword 'delegate' we
1523 // should stop tracking the reference count for the receiver. This is
1524 // because the reference count is quite possibly handled by a delegate
1526 if (S.isKeywordSelector()) {
1527 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1528 StringRef Slot = S.getNameForSlot(i);
1529 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1530 if (ResultEff == ObjCInitRetE)
1531 ResultEff = RetEffect::MakeNoRetHard();
1533 ReceiverEff = StopTrackingHard;
1538 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1539 ResultEff.getKind() == RetEffect::NoRet)
1540 return getDefaultSummary();
1542 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
1545 const RetainSummary *
1546 RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
1547 ProgramStateRef State) {
1548 const ObjCInterfaceDecl *ReceiverClass = nullptr;
1550 // We do better tracking of the type of the object than the core ExprEngine.
1551 // See if we have its type in our private state.
1552 // FIXME: Eventually replace the use of state->get<RefBindings> with
1553 // a generic API for reasoning about the Objective-C types of symbolic
1555 SVal ReceiverV = Msg.getReceiverSVal();
1556 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
1557 if (const RefVal *T = getRefBinding(State, Sym))
1558 if (const ObjCObjectPointerType *PT =
1559 T->getType()->getAs<ObjCObjectPointerType>())
1560 ReceiverClass = PT->getInterfaceDecl();
1562 // If we don't know what kind of object this is, fall back to its static type.
1564 ReceiverClass = Msg.getReceiverInterface();
1566 // FIXME: The receiver could be a reference to a class, meaning that
1567 // we should use the class method.
1568 // id x = [NSObject class];
1569 // [x performSelector:... withObject:... afterDelay:...];
1570 Selector S = Msg.getSelector();
1571 const ObjCMethodDecl *Method = Msg.getDecl();
1572 if (!Method && ReceiverClass)
1573 Method = ReceiverClass->getInstanceMethod(S);
1575 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1576 ObjCMethodSummaries);
1579 const RetainSummary *
1580 RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
1581 const ObjCMethodDecl *MD, QualType RetTy,
1582 ObjCMethodSummariesTy &CachedSummaries) {
1584 // Look up a summary in our summary cache.
1585 const RetainSummary *Summ = CachedSummaries.find(ID, S);
1588 Summ = getStandardMethodSummary(MD, S, RetTy);
1590 // Annotations override defaults.
1591 updateSummaryFromAnnotations(Summ, MD);
1593 // Memoize the summary.
1594 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
1600 void RetainSummaryManager::InitializeClassMethodSummaries() {
1601 assert(ScratchArgs.isEmpty());
1602 // Create the [NSAssertionHandler currentHander] summary.
1603 addClassMethSummary("NSAssertionHandler", "currentHandler",
1604 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
1606 // Create the [NSAutoreleasePool addObject:] summary.
1607 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
1608 addClassMethSummary("NSAutoreleasePool", "addObject",
1609 getPersistentSummary(RetEffect::MakeNoRet(),
1610 DoNothing, Autorelease));
1613 void RetainSummaryManager::InitializeMethodSummaries() {
1615 assert (ScratchArgs.isEmpty());
1617 // Create the "init" selector. It just acts as a pass-through for the
1619 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
1620 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1622 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1623 // claims the receiver and returns a retained object.
1624 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1627 // The next methods are allocators.
1628 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1629 const RetainSummary *CFAllocSumm =
1630 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF));
1632 // Create the "retain" selector.
1633 RetEffect NoRet = RetEffect::MakeNoRet();
1634 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
1635 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
1637 // Create the "release" selector.
1638 Summ = getPersistentSummary(NoRet, DecRefMsg);
1639 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
1641 // Create the -dealloc summary.
1642 Summ = getPersistentSummary(NoRet, Dealloc);
1643 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
1645 // Create the "autorelease" selector.
1646 Summ = getPersistentSummary(NoRet, Autorelease);
1647 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
1649 // For NSWindow, allocated objects are (initially) self-owned.
1650 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1651 // self-own themselves. However, they only do this once they are displayed.
1652 // Thus, we need to track an NSWindow's display status.
1653 // This is tracked in <rdar://problem/6062711>.
1654 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
1655 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1659 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1661 // For NSPanel (which subclasses NSWindow), allocated objects are not
1663 // FIXME: For now we don't track NSPanels. object for the same reason
1664 // as for NSWindow objects.
1665 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1667 // For NSNull, objects returned by +null are singletons that ignore
1668 // retain/release semantics. Just don't track them.
1669 // <rdar://problem/12858915>
1670 addClassMethSummary("NSNull", "null", NoTrackYet);
1672 // Don't track allocated autorelease pools, as it is okay to prematurely
1674 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
1675 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
1676 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
1678 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1679 addInstMethSummary("QCRenderer", AllocSumm, "createSnapshotImageOfType");
1680 addInstMethSummary("QCView", AllocSumm, "createSnapshotImageOfType");
1682 // Create summaries for CIContext, 'createCGImage' and
1683 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1684 // automatically garbage collected.
1685 addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect");
1686 addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect",
1687 "format", "colorSpace");
1688 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info");
1691 //===----------------------------------------------------------------------===//
1693 //===----------------------------------------------------------------------===//
1695 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1698 //===-------------===//
1699 // Bug Descriptions. //
1700 //===-------------===//
1702 class CFRefBug : public BugType {
1704 CFRefBug(const CheckerBase *checker, StringRef name)
1705 : BugType(checker, name, categories::MemoryCoreFoundationObjectiveC) {}
1709 // FIXME: Eventually remove.
1710 virtual const char *getDescription() const = 0;
1712 virtual bool isLeak() const { return false; }
1715 class UseAfterRelease : public CFRefBug {
1717 UseAfterRelease(const CheckerBase *checker)
1718 : CFRefBug(checker, "Use-after-release") {}
1720 const char *getDescription() const override {
1721 return "Reference-counted object is used after it is released";
1725 class BadRelease : public CFRefBug {
1727 BadRelease(const CheckerBase *checker) : CFRefBug(checker, "Bad release") {}
1729 const char *getDescription() const override {
1730 return "Incorrect decrement of the reference count of an object that is "
1731 "not owned at this point by the caller";
1735 class DeallocGC : public CFRefBug {
1737 DeallocGC(const CheckerBase *checker)
1738 : CFRefBug(checker, "-dealloc called while using garbage collection") {}
1740 const char *getDescription() const override {
1741 return "-dealloc called while using garbage collection";
1745 class DeallocNotOwned : public CFRefBug {
1747 DeallocNotOwned(const CheckerBase *checker)
1748 : CFRefBug(checker, "-dealloc sent to non-exclusively owned object") {}
1750 const char *getDescription() const override {
1751 return "-dealloc sent to object that may be referenced elsewhere";
1755 class OverAutorelease : public CFRefBug {
1757 OverAutorelease(const CheckerBase *checker)
1758 : CFRefBug(checker, "Object autoreleased too many times") {}
1760 const char *getDescription() const override {
1761 return "Object autoreleased too many times";
1765 class ReturnedNotOwnedForOwned : public CFRefBug {
1767 ReturnedNotOwnedForOwned(const CheckerBase *checker)
1768 : CFRefBug(checker, "Method should return an owned object") {}
1770 const char *getDescription() const override {
1771 return "Object with a +0 retain count returned to caller where a +1 "
1772 "(owning) retain count is expected";
1776 class Leak : public CFRefBug {
1778 Leak(const CheckerBase *checker, StringRef name) : CFRefBug(checker, name) {
1779 // Leaks should not be reported if they are post-dominated by a sink.
1780 setSuppressOnSink(true);
1783 const char *getDescription() const override { return ""; }
1785 bool isLeak() const override { return true; }
1791 class CFRefReportVisitor : public BugReporterVisitor {
1794 const SummaryLogTy &SummaryLog;
1798 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1799 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
1801 void Profile(llvm::FoldingSetNodeID &ID) const override {
1807 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
1808 const ExplodedNode *PrevN,
1809 BugReporterContext &BRC,
1810 BugReport &BR) override;
1812 std::shared_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
1813 const ExplodedNode *N,
1814 BugReport &BR) override;
1817 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1819 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
1820 const SummaryLogTy &log)
1821 : CFRefReportVisitor(sym, GCEnabled, log) {}
1823 std::shared_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
1824 const ExplodedNode *N,
1825 BugReport &BR) override;
1828 class CFRefReport : public BugReport {
1829 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
1832 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1833 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1834 bool registerVisitor = true)
1835 : BugReport(D, D.getDescription(), n) {
1836 if (registerVisitor)
1837 addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log));
1838 addGCModeDescription(LOpts, GCEnabled);
1841 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1842 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1844 : BugReport(D, D.getDescription(), endText, n) {
1845 addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log));
1846 addGCModeDescription(LOpts, GCEnabled);
1849 llvm::iterator_range<ranges_iterator> getRanges() override {
1850 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1851 if (!BugTy.isLeak())
1852 return BugReport::getRanges();
1853 return llvm::make_range(ranges_iterator(), ranges_iterator());
1857 class CFRefLeakReport : public CFRefReport {
1858 const MemRegion* AllocBinding;
1859 const Stmt *AllocStmt;
1861 // Finds the function declaration where a leak warning for the parameter 'sym' should be raised.
1862 void deriveParamLocation(CheckerContext &Ctx, SymbolRef sym);
1863 // Finds the location where a leak warning for 'sym' should be raised.
1864 void deriveAllocLocation(CheckerContext &Ctx, SymbolRef sym);
1865 // Produces description of a leak warning which is printed on the console.
1866 void createDescription(CheckerContext &Ctx, bool GCEnabled, bool IncludeAllocationLine);
1869 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1870 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1871 CheckerContext &Ctx,
1872 bool IncludeAllocationLine);
1874 PathDiagnosticLocation getLocation(const SourceManager &SM) const override {
1875 assert(Location.isValid());
1879 } // end anonymous namespace
1881 void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1883 const char *GCModeDescription = nullptr;
1885 switch (LOpts.getGC()) {
1886 case LangOptions::GCOnly:
1888 GCModeDescription = "Code is compiled to only use garbage collection";
1891 case LangOptions::NonGC:
1893 GCModeDescription = "Code is compiled to use reference counts";
1896 case LangOptions::HybridGC:
1898 GCModeDescription = "Code is compiled to use either garbage collection "
1899 "(GC) or reference counts (non-GC). The bug occurs "
1903 GCModeDescription = "Code is compiled to use either garbage collection "
1904 "(GC) or reference counts (non-GC). The bug occurs "
1910 assert(GCModeDescription && "invalid/unknown GC mode");
1911 addExtraText(GCModeDescription);
1914 static bool isNumericLiteralExpression(const Expr *E) {
1915 // FIXME: This set of cases was copied from SemaExprObjC.
1916 return isa<IntegerLiteral>(E) ||
1917 isa<CharacterLiteral>(E) ||
1918 isa<FloatingLiteral>(E) ||
1919 isa<ObjCBoolLiteralExpr>(E) ||
1920 isa<CXXBoolLiteralExpr>(E);
1923 static Optional<std::string> describeRegion(const MemRegion *MR) {
1924 if (const auto *VR = dyn_cast_or_null<VarRegion>(MR))
1925 return std::string(VR->getDecl()->getName());
1926 // Once we support more storage locations for bindings,
1927 // this would need to be improved.
1931 /// Returns true if this stack frame is for an Objective-C method that is a
1932 /// property getter or setter whose body has been synthesized by the analyzer.
1933 static bool isSynthesizedAccessor(const StackFrameContext *SFC) {
1934 auto Method = dyn_cast_or_null<ObjCMethodDecl>(SFC->getDecl());
1935 if (!Method || !Method->isPropertyAccessor())
1938 return SFC->getAnalysisDeclContext()->isBodyAutosynthesized();
1941 std::shared_ptr<PathDiagnosticPiece>
1942 CFRefReportVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *PrevN,
1943 BugReporterContext &BRC, BugReport &BR) {
1944 // FIXME: We will eventually need to handle non-statement-based events
1945 // (__attribute__((cleanup))).
1946 if (!N->getLocation().getAs<StmtPoint>())
1949 // Check if the type state has changed.
1950 ProgramStateRef PrevSt = PrevN->getState();
1951 ProgramStateRef CurrSt = N->getState();
1952 const LocationContext *LCtx = N->getLocationContext();
1954 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
1955 if (!CurrT) return nullptr;
1957 const RefVal &CurrV = *CurrT;
1958 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
1960 // Create a string buffer to constain all the useful things we want
1961 // to tell the user.
1963 llvm::raw_string_ostream os(sbuf);
1965 // This is the allocation site since the previous node had no bindings
1968 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
1970 if (isa<ObjCIvarRefExpr>(S) &&
1971 isSynthesizedAccessor(LCtx->getStackFrame())) {
1972 S = LCtx->getStackFrame()->getCallSite();
1975 if (isa<ObjCArrayLiteral>(S)) {
1976 os << "NSArray literal is an object with a +0 retain count";
1978 else if (isa<ObjCDictionaryLiteral>(S)) {
1979 os << "NSDictionary literal is an object with a +0 retain count";
1981 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1982 if (isNumericLiteralExpression(BL->getSubExpr()))
1983 os << "NSNumber literal is an object with a +0 retain count";
1985 const ObjCInterfaceDecl *BoxClass = nullptr;
1986 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1987 BoxClass = Method->getClassInterface();
1989 // We should always be able to find the boxing class interface,
1990 // but consider this future-proofing.
1992 os << *BoxClass << " b";
1996 os << "oxed expression produces an object with a +0 retain count";
1999 else if (isa<ObjCIvarRefExpr>(S)) {
2000 os << "Object loaded from instance variable";
2003 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
2004 // Get the name of the callee (if it is available).
2005 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
2006 if (const FunctionDecl *FD = X.getAsFunctionDecl())
2007 os << "Call to function '" << *FD << '\'';
2009 os << "function call";
2012 assert(isa<ObjCMessageExpr>(S));
2013 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
2014 CallEventRef<ObjCMethodCall> Call
2015 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
2017 switch (Call->getMessageKind()) {
2021 case OCM_PropertyAccess:
2030 if (CurrV.getObjKind() == RetEffect::CF) {
2031 os << " returns a Core Foundation object of type "
2032 << Sym->getType().getAsString() << " with a ";
2033 } else if (CurrV.getObjKind() == RetEffect::Generalized) {
2034 os << " returns an object of type " << Sym->getType().getAsString()
2037 assert (CurrV.getObjKind() == RetEffect::ObjC);
2038 QualType T = Sym->getType();
2039 if (!isa<ObjCObjectPointerType>(T)) {
2040 os << " returns an Objective-C object with a ";
2042 const ObjCObjectPointerType *PT = cast<ObjCObjectPointerType>(T);
2043 os << " returns an instance of "
2044 << PT->getPointeeType().getAsString() << " with a ";
2048 if (CurrV.isOwned()) {
2049 os << "+1 retain count";
2052 assert(CurrV.getObjKind() == RetEffect::CF);
2054 "Core Foundation objects are not automatically garbage collected.";
2058 assert (CurrV.isNotOwned());
2059 os << "+0 retain count";
2063 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2064 N->getLocationContext());
2065 return std::make_shared<PathDiagnosticEventPiece>(Pos, os.str());
2068 // Gather up the effects that were performed on the object at this
2070 SmallVector<ArgEffect, 2> AEffects;
2072 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
2073 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
2074 // We only have summaries attached to nodes after evaluating CallExpr and
2075 // ObjCMessageExprs.
2076 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
2078 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
2079 // Iterate through the parameter expressions and see if the symbol
2080 // was ever passed as an argument.
2083 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2084 AI!=AE; ++AI, ++i) {
2086 // Retrieve the value of the argument. Is it the symbol
2087 // we are interested in?
2088 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
2091 // We have an argument. Get the effect!
2092 AEffects.push_back(Summ->getArg(i));
2095 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2096 if (const Expr *receiver = ME->getInstanceReceiver())
2097 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2098 .getAsLocSymbol() == Sym) {
2099 // The symbol we are tracking is the receiver.
2100 AEffects.push_back(Summ->getReceiverEffect());
2106 // Get the previous type state.
2107 RefVal PrevV = *PrevT;
2109 // Specially handle -dealloc.
2110 if (!GCEnabled && std::find(AEffects.begin(), AEffects.end(), Dealloc) !=
2112 // Determine if the object's reference count was pushed to zero.
2113 assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
2114 // We may not have transitioned to 'release' if we hit an error.
2115 // This case is handled elsewhere.
2116 if (CurrV.getKind() == RefVal::Released) {
2117 assert(CurrV.getCombinedCounts() == 0);
2118 os << "Object released by directly sending the '-dealloc' message";
2123 // Specially handle CFMakeCollectable and friends.
2124 if (std::find(AEffects.begin(), AEffects.end(), MakeCollectable) !=
2126 // Get the name of the function.
2127 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
2129 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
2130 const FunctionDecl *FD = X.getAsFunctionDecl();
2133 // Determine if the object's reference count was pushed to zero.
2134 assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
2136 os << "In GC mode a call to '" << *FD
2137 << "' decrements an object's retain count and registers the "
2138 "object with the garbage collector. ";
2140 if (CurrV.getKind() == RefVal::Released) {
2141 assert(CurrV.getCount() == 0);
2142 os << "Since it now has a 0 retain count the object can be "
2143 "automatically collected by the garbage collector.";
2146 os << "An object must have a 0 retain count to be garbage collected. "
2147 "After this call its retain count is +" << CurrV.getCount()
2151 os << "When GC is not enabled a call to '" << *FD
2152 << "' has no effect on its argument.";
2154 // Nothing more to say.
2158 // Determine if the typestate has changed.
2159 if (!PrevV.hasSameState(CurrV))
2160 switch (CurrV.getKind()) {
2162 case RefVal::NotOwned:
2163 if (PrevV.getCount() == CurrV.getCount()) {
2164 // Did an autorelease message get sent?
2165 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2168 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
2169 os << "Object autoreleased";
2173 if (PrevV.getCount() > CurrV.getCount())
2174 os << "Reference count decremented.";
2176 os << "Reference count incremented.";
2178 if (unsigned Count = CurrV.getCount())
2179 os << " The object now has a +" << Count << " retain count.";
2181 if (PrevV.getKind() == RefVal::Released) {
2182 assert(GCEnabled && CurrV.getCount() > 0);
2183 os << " The object is not eligible for garbage collection until "
2184 "the retain count reaches 0 again.";
2189 case RefVal::Released:
2190 if (CurrV.getIvarAccessHistory() ==
2191 RefVal::IvarAccessHistory::ReleasedAfterDirectAccess &&
2192 CurrV.getIvarAccessHistory() != PrevV.getIvarAccessHistory()) {
2193 os << "Strong instance variable relinquished. ";
2195 os << "Object released.";
2198 case RefVal::ReturnedOwned:
2199 // Autoreleases can be applied after marking a node ReturnedOwned.
2200 if (CurrV.getAutoreleaseCount())
2203 os << "Object returned to caller as an owning reference (single "
2204 "retain count transferred to caller)";
2207 case RefVal::ReturnedNotOwned:
2208 os << "Object returned to caller with a +0 retain count";
2215 // Emit any remaining diagnostics for the argument effects (if any).
2216 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2217 E=AEffects.end(); I != E; ++I) {
2219 // A bunch of things have alternate behavior under GC.
2224 os << "In GC mode an 'autorelease' has no effect.";
2227 os << "In GC mode the 'retain' message has no effect.";
2230 os << "In GC mode the 'release' message has no effect.";
2236 if (os.str().empty())
2237 return nullptr; // We have nothing to say!
2239 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
2240 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2241 N->getLocationContext());
2242 auto P = std::make_shared<PathDiagnosticEventPiece>(Pos, os.str());
2244 // Add the range by scanning the children of the statement for any bindings
2246 for (const Stmt *Child : S->children())
2247 if (const Expr *Exp = dyn_cast_or_null<Expr>(Child))
2248 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
2249 P->addRange(Exp->getSourceRange());
2253 return std::move(P);
2257 // Find the first node in the current function context that referred to the
2258 // tracked symbol and the memory location that value was stored to. Note, the
2259 // value is only reported if the allocation occurred in the same function as
2260 // the leak. The function can also return a location context, which should be
2261 // treated as interesting.
2262 struct AllocationInfo {
2263 const ExplodedNode* N;
2265 const LocationContext *InterestingMethodContext;
2266 AllocationInfo(const ExplodedNode *InN,
2267 const MemRegion *InR,
2268 const LocationContext *InInterestingMethodContext) :
2269 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
2271 } // end anonymous namespace
2273 static AllocationInfo
2274 GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
2276 const ExplodedNode *AllocationNode = N;
2277 const ExplodedNode *AllocationNodeInCurrentOrParentContext = N;
2278 const MemRegion *FirstBinding = nullptr;
2279 const LocationContext *LeakContext = N->getLocationContext();
2281 // The location context of the init method called on the leaked object, if
2283 const LocationContext *InitMethodContext = nullptr;
2286 ProgramStateRef St = N->getState();
2287 const LocationContext *NContext = N->getLocationContext();
2289 if (!getRefBinding(St, Sym))
2292 StoreManager::FindUniqueBinding FB(Sym);
2293 StateMgr.iterBindings(St, FB);
2296 const MemRegion *R = FB.getRegion();
2297 const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>();
2298 // Do not show local variables belonging to a function other than
2299 // where the error is reported.
2300 if (!VR || VR->getStackFrame() == LeakContext->getStackFrame())
2304 // AllocationNode is the last node in which the symbol was tracked.
2307 // AllocationNodeInCurrentContext, is the last node in the current or
2308 // parent context in which the symbol was tracked.
2310 // Note that the allocation site might be in the parent conext. For example,
2311 // the case where an allocation happens in a block that captures a reference
2312 // to it and that reference is overwritten/dropped by another call to
2314 if (NContext == LeakContext || NContext->isParentOf(LeakContext))
2315 AllocationNodeInCurrentOrParentContext = N;
2317 // Find the last init that was called on the given symbol and store the
2318 // init method's location context.
2319 if (!InitMethodContext)
2320 if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) {
2321 const Stmt *CE = CEP->getCallExpr();
2322 if (const ObjCMessageExpr *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
2323 const Stmt *RecExpr = ME->getInstanceReceiver();
2325 SVal RecV = St->getSVal(RecExpr, NContext);
2326 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
2327 InitMethodContext = CEP->getCalleeContext();
2332 N = N->pred_empty() ? nullptr : *(N->pred_begin());
2335 // If we are reporting a leak of the object that was allocated with alloc,
2336 // mark its init method as interesting.
2337 const LocationContext *InterestingMethodContext = nullptr;
2338 if (InitMethodContext) {
2339 const ProgramPoint AllocPP = AllocationNode->getLocation();
2340 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
2341 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
2342 if (ME->getMethodFamily() == OMF_alloc)
2343 InterestingMethodContext = InitMethodContext;
2346 // If allocation happened in a function different from the leak node context,
2347 // do not report the binding.
2348 assert(N && "Could not find allocation node");
2349 if (N->getLocationContext() != LeakContext) {
2350 FirstBinding = nullptr;
2353 return AllocationInfo(AllocationNodeInCurrentOrParentContext,
2355 InterestingMethodContext);
2358 std::shared_ptr<PathDiagnosticPiece>
2359 CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2360 const ExplodedNode *EndN, BugReport &BR) {
2361 BR.markInteresting(Sym);
2362 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
2365 std::shared_ptr<PathDiagnosticPiece>
2366 CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2367 const ExplodedNode *EndN, BugReport &BR) {
2369 // Tell the BugReporterContext to report cases when the tracked symbol is
2370 // assigned to different variables, etc.
2371 BR.markInteresting(Sym);
2373 // We are reporting a leak. Walk up the graph to get to the first node where
2374 // the symbol appeared, and also get the first VarDecl that tracked object
2376 AllocationInfo AllocI =
2377 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
2379 const MemRegion* FirstBinding = AllocI.R;
2380 BR.markInteresting(AllocI.InterestingMethodContext);
2382 SourceManager& SM = BRC.getSourceManager();
2384 // Compute an actual location for the leak. Sometimes a leak doesn't
2385 // occur at an actual statement (e.g., transition between blocks; end
2386 // of function) so we need to walk the graph and compute a real location.
2387 const ExplodedNode *LeakN = EndN;
2388 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
2391 llvm::raw_string_ostream os(sbuf);
2393 os << "Object leaked: ";
2395 Optional<std::string> RegionDescription = describeRegion(FirstBinding);
2396 if (RegionDescription) {
2397 os << "object allocated and stored into '" << *RegionDescription << '\'';
2400 os << "allocated object";
2402 // Get the retain count.
2403 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
2406 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2407 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2408 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
2409 // to the caller for NS objects.
2410 const Decl *D = &EndN->getCodeDecl();
2412 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2413 : " is returned from a function ");
2415 if (D->hasAttr<CFReturnsNotRetainedAttr>())
2416 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
2417 else if (D->hasAttr<NSReturnsNotRetainedAttr>())
2418 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
2420 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2421 if (BRC.getASTContext().getLangOpts().ObjCAutoRefCount) {
2422 os << "managed by Automatic Reference Counting";
2424 os << "whose name ('" << MD->getSelector().getAsString()
2425 << "') does not start with "
2426 "'copy', 'mutableCopy', 'alloc' or 'new'."
2427 " This violates the naming convention rules"
2428 " given in the Memory Management Guide for Cocoa";
2432 const FunctionDecl *FD = cast<FunctionDecl>(D);
2433 os << "whose name ('" << *FD
2434 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2435 " convention rules given in the Memory Management Guide for Core"
2440 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2441 const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
2442 os << " and returned from method '" << MD.getSelector().getAsString()
2443 << "' is potentially leaked when using garbage collection. Callers "
2444 "of this method do not expect a returned object with a +1 retain "
2445 "count since they expect the object to be managed by the garbage "
2449 os << " is not referenced later in this execution path and has a retain "
2450 "count of +" << RV->getCount();
2452 return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
2455 void CFRefLeakReport::deriveParamLocation(CheckerContext &Ctx, SymbolRef sym) {
2456 const SourceManager& SMgr = Ctx.getSourceManager();
2458 if (!sym->getOriginRegion())
2461 auto *Region = dyn_cast<DeclRegion>(sym->getOriginRegion());
2463 const Decl *PDecl = Region->getDecl();
2464 if (PDecl && isa<ParmVarDecl>(PDecl)) {
2465 PathDiagnosticLocation ParamLocation = PathDiagnosticLocation::create(PDecl, SMgr);
2466 Location = ParamLocation;
2467 UniqueingLocation = ParamLocation;
2468 UniqueingDecl = Ctx.getLocationContext()->getDecl();
2473 void CFRefLeakReport::deriveAllocLocation(CheckerContext &Ctx,SymbolRef sym) {
2474 // Most bug reports are cached at the location where they occurred.
2475 // With leaks, we want to unique them by the location where they were
2476 // allocated, and only report a single path. To do this, we need to find
2477 // the allocation site of a piece of tracked memory, which we do via a
2478 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2479 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2480 // that all ancestor nodes that represent the allocation site have the
2481 // same SourceLocation.
2482 const ExplodedNode *AllocNode = nullptr;
2484 const SourceManager& SMgr = Ctx.getSourceManager();
2486 AllocationInfo AllocI =
2487 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
2489 AllocNode = AllocI.N;
2490 AllocBinding = AllocI.R;
2491 markInteresting(AllocI.InterestingMethodContext);
2493 // Get the SourceLocation for the allocation site.
2494 // FIXME: This will crash the analyzer if an allocation comes from an
2495 // implicit call (ex: a destructor call).
2496 // (Currently there are no such allocations in Cocoa, though.)
2497 AllocStmt = PathDiagnosticLocation::getStmt(AllocNode);
2500 AllocBinding = nullptr;
2504 PathDiagnosticLocation AllocLocation =
2505 PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2506 AllocNode->getLocationContext());
2507 Location = AllocLocation;
2509 // Set uniqieing info, which will be used for unique the bug reports. The
2510 // leaks should be uniqued on the allocation site.
2511 UniqueingLocation = AllocLocation;
2512 UniqueingDecl = AllocNode->getLocationContext()->getDecl();
2515 void CFRefLeakReport::createDescription(CheckerContext &Ctx, bool GCEnabled,
2516 bool IncludeAllocationLine) {
2517 assert(Location.isValid() && UniqueingDecl && UniqueingLocation.isValid());
2518 Description.clear();
2519 llvm::raw_string_ostream os(Description);
2520 os << "Potential leak ";
2522 os << "(when using garbage collection) ";
2523 os << "of an object";
2525 Optional<std::string> RegionDescription = describeRegion(AllocBinding);
2526 if (RegionDescription) {
2527 os << " stored into '" << *RegionDescription << '\'';
2528 if (IncludeAllocationLine) {
2529 FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager());
2530 os << " (allocated on line " << SL.getSpellingLineNumber() << ")";
2535 CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2536 bool GCEnabled, const SummaryLogTy &Log,
2537 ExplodedNode *n, SymbolRef sym,
2538 CheckerContext &Ctx,
2539 bool IncludeAllocationLine)
2540 : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
2542 deriveAllocLocation(Ctx, sym);
2544 deriveParamLocation(Ctx, sym);
2546 createDescription(Ctx, GCEnabled, IncludeAllocationLine);
2548 addVisitor(llvm::make_unique<CFRefLeakReportVisitor>(sym, GCEnabled, Log));
2551 //===----------------------------------------------------------------------===//
2552 // Main checker logic.
2553 //===----------------------------------------------------------------------===//
2556 class RetainCountChecker
2557 : public Checker< check::Bind,
2560 check::BeginFunction,
2562 check::PostStmt<BlockExpr>,
2563 check::PostStmt<CastExpr>,
2564 check::PostStmt<ObjCArrayLiteral>,
2565 check::PostStmt<ObjCDictionaryLiteral>,
2566 check::PostStmt<ObjCBoxedExpr>,
2567 check::PostStmt<ObjCIvarRefExpr>,
2569 check::PreStmt<ReturnStmt>,
2570 check::RegionChanges,
2573 mutable std::unique_ptr<CFRefBug> useAfterRelease, releaseNotOwned;
2574 mutable std::unique_ptr<CFRefBug> deallocGC, deallocNotOwned;
2575 mutable std::unique_ptr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2576 mutable std::unique_ptr<CFRefBug> leakWithinFunction, leakAtReturn;
2577 mutable std::unique_ptr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
2579 typedef llvm::DenseMap<SymbolRef, const CheckerProgramPointTag *> SymbolTagMap;
2581 // This map is only used to ensure proper deletion of any allocated tags.
2582 mutable SymbolTagMap DeadSymbolTags;
2584 mutable std::unique_ptr<RetainSummaryManager> Summaries;
2585 mutable std::unique_ptr<RetainSummaryManager> SummariesGC;
2586 mutable SummaryLogTy SummaryLog;
2587 mutable bool ShouldResetSummaryLog;
2589 /// Optional setting to indicate if leak reports should include
2590 /// the allocation line.
2591 mutable bool IncludeAllocationLine;
2594 RetainCountChecker(AnalyzerOptions &AO)
2595 : ShouldResetSummaryLog(false),
2596 IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {}
2598 ~RetainCountChecker() override { DeleteContainerSeconds(DeadSymbolTags); }
2600 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2601 ExprEngine &Eng) const {
2602 // FIXME: This is a hack to make sure the summary log gets cleared between
2603 // analyses of different code bodies.
2605 // Why is this necessary? Because a checker's lifetime is tied to a
2606 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2607 // Once in a blue moon, a new ExplodedNode will have the same address as an
2608 // old one with an associated summary, and the bug report visitor gets very
2609 // confused. (To make things worse, the summary lifetime is currently also
2610 // tied to a code body, so we get a crash instead of incorrect results.)
2612 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2613 // changes, things will start going wrong again. Really the lifetime of this
2614 // log needs to be tied to either the specific nodes in it or the entire
2615 // ExplodedGraph, not to a specific part of the code being analyzed.
2617 // (Also, having stateful local data means that the same checker can't be
2618 // used from multiple threads, but a lot of checkers have incorrect
2619 // assumptions about that anyway. So that wasn't a priority at the time of
2622 // This happens at the end of analysis, but bug reports are emitted /after/
2623 // this point. So we can't just clear the summary log now. Instead, we mark
2624 // that the next time we access the summary log, it should be cleared.
2626 // If we never reset the summary log during /this/ code body analysis,
2627 // there were no new summaries. There might still have been summaries from
2628 // the /last/ analysis, so clear them out to make sure the bug report
2629 // visitors don't get confused.
2630 if (ShouldResetSummaryLog)
2633 ShouldResetSummaryLog = !SummaryLog.empty();
2636 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2637 bool GCEnabled) const {
2639 if (!leakWithinFunctionGC)
2640 leakWithinFunctionGC.reset(new Leak(this, "Leak of object when using "
2641 "garbage collection"));
2642 return leakWithinFunctionGC.get();
2644 if (!leakWithinFunction) {
2645 if (LOpts.getGC() == LangOptions::HybridGC) {
2646 leakWithinFunction.reset(new Leak(this,
2647 "Leak of object when not using "
2648 "garbage collection (GC) in "
2649 "dual GC/non-GC code"));
2651 leakWithinFunction.reset(new Leak(this, "Leak"));
2654 return leakWithinFunction.get();
2658 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2660 if (!leakAtReturnGC)
2661 leakAtReturnGC.reset(new Leak(this,
2662 "Leak of returned object when using "
2663 "garbage collection"));
2664 return leakAtReturnGC.get();
2666 if (!leakAtReturn) {
2667 if (LOpts.getGC() == LangOptions::HybridGC) {
2668 leakAtReturn.reset(new Leak(this,
2669 "Leak of returned object when not using "
2670 "garbage collection (GC) in dual "
2673 leakAtReturn.reset(new Leak(this, "Leak of returned object"));
2676 return leakAtReturn.get();
2680 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2681 bool GCEnabled) const {
2682 // FIXME: We don't support ARC being turned on and off during one analysis.
2683 // (nor, for that matter, do we support changing ASTContexts)
2684 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
2687 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
2689 assert(SummariesGC->isARCEnabled() == ARCEnabled);
2690 return *SummariesGC;
2693 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
2695 assert(Summaries->isARCEnabled() == ARCEnabled);
2700 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2701 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2704 void printState(raw_ostream &Out, ProgramStateRef State,
2705 const char *NL, const char *Sep) const override;
2707 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
2708 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2709 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
2711 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2712 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
2713 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2715 void checkPostStmt(const ObjCIvarRefExpr *IRE, CheckerContext &C) const;
2717 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
2719 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
2720 CheckerContext &C) const;
2722 void processSummaryOfInlined(const RetainSummary &Summ,
2723 const CallEvent &Call,
2724 CheckerContext &C) const;
2726 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2728 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
2729 bool Assumption) const;
2732 checkRegionChanges(ProgramStateRef state,
2733 const InvalidatedSymbols *invalidated,
2734 ArrayRef<const MemRegion *> ExplicitRegions,
2735 ArrayRef<const MemRegion *> Regions,
2736 const LocationContext* LCtx,
2737 const CallEvent *Call) const;
2739 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2740 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2741 ExplodedNode *Pred, RetEffect RE, RefVal X,
2742 SymbolRef Sym, ProgramStateRef state) const;
2744 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
2745 void checkBeginFunction(CheckerContext &C) const;
2746 void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const;
2748 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
2749 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2750 CheckerContext &C) const;
2752 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
2753 RefVal::Kind ErrorKind, SymbolRef Sym,
2754 CheckerContext &C) const;
2756 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
2758 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2760 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
2761 SymbolRef sid, RefVal V,
2762 SmallVectorImpl<SymbolRef> &Leaked) const;
2765 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2766 const ProgramPointTag *Tag, CheckerContext &Ctx,
2767 SymbolRef Sym, RefVal V) const;
2769 ExplodedNode *processLeaks(ProgramStateRef state,
2770 SmallVectorImpl<SymbolRef> &Leaked,
2771 CheckerContext &Ctx,
2772 ExplodedNode *Pred = nullptr) const;
2774 } // end anonymous namespace
2777 class StopTrackingCallback final : public SymbolVisitor {
2778 ProgramStateRef state;
2780 StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
2781 ProgramStateRef getState() const { return state; }
2783 bool VisitSymbol(SymbolRef sym) override {
2784 state = state->remove<RefBindings>(sym);
2788 } // end anonymous namespace
2790 //===----------------------------------------------------------------------===//
2791 // Handle statements that may have an effect on refcounts.
2792 //===----------------------------------------------------------------------===//
2794 void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2795 CheckerContext &C) const {
2797 // Scan the BlockDecRefExprs for any object the retain count checker
2799 if (!BE->getBlockDecl()->hasCaptures())
2802 ProgramStateRef state = C.getState();
2803 auto *R = cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
2805 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2806 E = R->referenced_vars_end();
2811 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2812 // via captured variables, even though captured variables result in a copy
2813 // and in implicit increment/decrement of a retain count.
2814 SmallVector<const MemRegion*, 10> Regions;
2815 const LocationContext *LC = C.getLocationContext();
2816 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2818 for ( ; I != E; ++I) {
2819 const VarRegion *VR = I.getCapturedRegion();
2820 if (VR->getSuperRegion() == R) {
2821 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2823 Regions.push_back(VR);
2827 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2828 Regions.data() + Regions.size()).getState();
2829 C.addTransition(state);
2832 void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2833 CheckerContext &C) const {
2834 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2838 ArgEffect AE = IncRef;
2840 switch (BE->getBridgeKind()) {
2841 case clang::OBC_Bridge:
2844 case clang::OBC_BridgeRetained:
2847 case clang::OBC_BridgeTransfer:
2848 AE = DecRefBridgedTransferred;
2852 ProgramStateRef state = C.getState();
2853 SymbolRef Sym = C.getSVal(CE).getAsLocSymbol();
2856 const RefVal* T = getRefBinding(state, Sym);
2860 RefVal::Kind hasErr = (RefVal::Kind) 0;
2861 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
2864 // FIXME: If we get an error during a bridge cast, should we report it?
2868 C.addTransition(state);
2871 void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2872 const Expr *Ex) const {
2873 ProgramStateRef state = C.getState();
2874 const ExplodedNode *pred = C.getPredecessor();
2875 for (const Stmt *Child : Ex->children()) {
2876 SVal V = pred->getSVal(Child);
2877 if (SymbolRef sym = V.getAsSymbol())
2878 if (const RefVal* T = getRefBinding(state, sym)) {
2879 RefVal::Kind hasErr = (RefVal::Kind) 0;
2880 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2882 processNonLeakError(state, Child->getSourceRange(), hasErr, sym, C);
2888 // Return the object as autoreleased.
2889 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2891 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2892 QualType ResultTy = Ex->getType();
2893 state = setRefBinding(state, sym,
2894 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
2897 C.addTransition(state);
2900 void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2901 CheckerContext &C) const {
2902 // Apply the 'MayEscape' to all values.
2903 processObjCLiterals(C, AL);
2906 void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2907 CheckerContext &C) const {
2908 // Apply the 'MayEscape' to all keys and values.
2909 processObjCLiterals(C, DL);
2912 void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2913 CheckerContext &C) const {
2914 const ExplodedNode *Pred = C.getPredecessor();
2915 ProgramStateRef State = Pred->getState();
2917 if (SymbolRef Sym = Pred->getSVal(Ex).getAsSymbol()) {
2918 QualType ResultTy = Ex->getType();
2919 State = setRefBinding(State, Sym,
2920 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
2923 C.addTransition(State);
2926 void RetainCountChecker::checkPostStmt(const ObjCIvarRefExpr *IRE,
2927 CheckerContext &C) const {
2928 Optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>();
2932 ProgramStateRef State = C.getState();
2933 SymbolRef Sym = State->getSVal(*IVarLoc).getAsSymbol();
2934 if (!Sym || !dyn_cast_or_null<ObjCIvarRegion>(Sym->getOriginRegion()))
2937 // Accessing an ivar directly is unusual. If we've done that, be more
2938 // forgiving about what the surrounding code is allowed to do.
2940 QualType Ty = Sym->getType();
2941 RetEffect::ObjKind Kind;
2942 if (Ty->isObjCRetainableType())
2943 Kind = RetEffect::ObjC;
2944 else if (coreFoundation::isCFObjectRef(Ty))
2945 Kind = RetEffect::CF;
2949 // If the value is already known to be nil, don't bother tracking it.
2950 ConstraintManager &CMgr = State->getConstraintManager();
2951 if (CMgr.isNull(State, Sym).isConstrainedTrue())
2954 if (const RefVal *RV = getRefBinding(State, Sym)) {
2955 // If we've seen this symbol before, or we're only seeing it now because
2956 // of something the analyzer has synthesized, don't do anything.
2957 if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None ||
2958 isSynthesizedAccessor(C.getStackFrame())) {
2962 // Note that this value has been loaded from an ivar.
2963 C.addTransition(setRefBinding(State, Sym, RV->withIvarAccess()));
2967 RefVal PlusZero = RefVal::makeNotOwned(Kind, Ty);
2969 // In a synthesized accessor, the effective retain count is +0.
2970 if (isSynthesizedAccessor(C.getStackFrame())) {
2971 C.addTransition(setRefBinding(State, Sym, PlusZero));
2975 State = setRefBinding(State, Sym, PlusZero.withIvarAccess());
2976 C.addTransition(State);
2979 void RetainCountChecker::checkPostCall(const CallEvent &Call,
2980 CheckerContext &C) const {
2981 RetainSummaryManager &Summaries = getSummaryManager(C);
2982 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
2985 processSummaryOfInlined(*Summ, Call, C);
2988 checkSummary(*Summ, Call, C);
2991 /// GetReturnType - Used to get the return type of a message expression or
2992 /// function call with the intention of affixing that type to a tracked symbol.
2993 /// While the return type can be queried directly from RetEx, when
2994 /// invoking class methods we augment to the return type to be that of
2995 /// a pointer to the class (as opposed it just being id).
2996 // FIXME: We may be able to do this with related result types instead.
2997 // This function is probably overestimating.
2998 static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2999 QualType RetTy = RetE->getType();
3000 // If RetE is not a message expression just return its type.
3001 // If RetE is a message expression, return its types if it is something
3002 /// more specific than id.
3003 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
3004 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
3005 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
3006 PT->isObjCClassType()) {
3007 // At this point we know the return type of the message expression is
3008 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
3009 // is a call to a class method whose type we can resolve. In such
3010 // cases, promote the return type to XXX* (where XXX is the class).
3011 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
3013 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
3019 // We don't always get the exact modeling of the function with regards to the
3020 // retain count checker even when the function is inlined. For example, we need
3021 // to stop tracking the symbols which were marked with StopTrackingHard.
3022 void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
3023 const CallEvent &CallOrMsg,
3024 CheckerContext &C) const {
3025 ProgramStateRef state = C.getState();
3027 // Evaluate the effect of the arguments.
3028 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
3029 if (Summ.getArg(idx) == StopTrackingHard) {
3030 SVal V = CallOrMsg.getArgSVal(idx);
3031 if (SymbolRef Sym = V.getAsLocSymbol()) {
3032 state = removeRefBinding(state, Sym);
3037 // Evaluate the effect on the message receiver.
3038 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
3039 if (MsgInvocation) {
3040 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
3041 if (Summ.getReceiverEffect() == StopTrackingHard) {
3042 state = removeRefBinding(state, Sym);
3047 // Consult the summary for the return value.
3048 RetEffect RE = Summ.getRetEffect();
3049 if (RE.getKind() == RetEffect::NoRetHard) {
3050 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
3052 state = removeRefBinding(state, Sym);
3055 C.addTransition(state);
3058 static ProgramStateRef updateOutParameter(ProgramStateRef State,
3061 auto *ArgRegion = dyn_cast_or_null<TypedValueRegion>(ArgVal.getAsRegion());
3065 QualType PointeeTy = ArgRegion->getValueType();
3066 if (!coreFoundation::isCFObjectRef(PointeeTy))
3069 SVal PointeeVal = State->getSVal(ArgRegion);
3070 SymbolRef Pointee = PointeeVal.getAsLocSymbol();
3075 case UnretainedOutParameter:
3076 State = setRefBinding(State, Pointee,
3077 RefVal::makeNotOwned(RetEffect::CF, PointeeTy));
3079 case RetainedOutParameter:
3080 // Do nothing. Retained out parameters will either point to a +1 reference
3081 // or NULL, but the way you check for failure differs depending on the API.
3082 // Consequently, we don't have a good way to track them yet.
3086 llvm_unreachable("only for out parameters");
3092 void RetainCountChecker::checkSummary(const RetainSummary &Summ,
3093 const CallEvent &CallOrMsg,
3094 CheckerContext &C) const {
3095 ProgramStateRef state = C.getState();
3097 // Evaluate the effect of the arguments.
3098 RefVal::Kind hasErr = (RefVal::Kind) 0;
3099 SourceRange ErrorRange;
3100 SymbolRef ErrorSym = nullptr;
3102 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
3103 SVal V = CallOrMsg.getArgSVal(idx);
3105 ArgEffect Effect = Summ.getArg(idx);
3106 if (Effect == RetainedOutParameter || Effect == UnretainedOutParameter) {
3107 state = updateOutParameter(state, V, Effect);
3108 } else if (SymbolRef Sym = V.getAsLocSymbol()) {
3109 if (const RefVal *T = getRefBinding(state, Sym)) {
3110 state = updateSymbol(state, Sym, *T, Effect, hasErr, C);
3112 ErrorRange = CallOrMsg.getArgSourceRange(idx);
3120 // Evaluate the effect on the message receiver.
3121 bool ReceiverIsTracked = false;
3123 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
3124 if (MsgInvocation) {
3125 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
3126 if (const RefVal *T = getRefBinding(state, Sym)) {
3127 ReceiverIsTracked = true;
3128 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
3131 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
3139 // Process any errors.
3141 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
3145 // Consult the summary for the return value.
3146 RetEffect RE = Summ.getRetEffect();
3148 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
3149 if (ReceiverIsTracked)
3150 RE = getSummaryManager(C).getObjAllocRetEffect();
3152 RE = RetEffect::MakeNoRet();
3155 switch (RE.getKind()) {
3157 llvm_unreachable("Unhandled RetEffect.");
3159 case RetEffect::NoRet:
3160 case RetEffect::NoRetHard:
3161 // No work necessary.
3164 case RetEffect::OwnedSymbol: {
3165 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
3169 // Use the result type from the CallEvent as it automatically adjusts
3170 // for methods/functions that return references.
3171 QualType ResultTy = CallOrMsg.getResultType();
3172 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
3175 // FIXME: Add a flag to the checker where allocations are assumed to
3180 case RetEffect::GCNotOwnedSymbol:
3181 case RetEffect::NotOwnedSymbol: {
3182 const Expr *Ex = CallOrMsg.getOriginExpr();
3183 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
3187 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
3188 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
3189 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
3195 // This check is actually necessary; otherwise the statement builder thinks
3196 // we've hit a previously-found path.
3197 // Normally addTransition takes care of this, but we want the node pointer.
3198 ExplodedNode *NewNode;
3199 if (state == C.getState()) {
3200 NewNode = C.getPredecessor();
3202 NewNode = C.addTransition(state);
3205 // Annotate the node with summary we used.
3207 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
3208 if (ShouldResetSummaryLog) {
3210 ShouldResetSummaryLog = false;
3212 SummaryLog[NewNode] = &Summ;
3217 RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
3218 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
3219 CheckerContext &C) const {
3220 // In GC mode [... release] and [... retain] do nothing.
3221 // In ARC mode they shouldn't exist at all, but we just ignore them.
3222 bool IgnoreRetainMsg = C.isObjCGCEnabled();
3223 if (!IgnoreRetainMsg)
3224 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
3230 E = IgnoreRetainMsg ? DoNothing : IncRef;
3233 E = IgnoreRetainMsg ? DoNothing : DecRef;
3235 case DecRefMsgAndStopTrackingHard:
3236 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
3238 case MakeCollectable:
3239 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
3243 // Handle all use-after-releases.
3244 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
3245 V = V ^ RefVal::ErrorUseAfterRelease;
3246 hasErr = V.getKind();
3247 return setRefBinding(state, sym, V);
3253 case MakeCollectable:
3254 case DecRefMsgAndStopTrackingHard:
3255 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
3257 case UnretainedOutParameter:
3258 case RetainedOutParameter:
3259 llvm_unreachable("Applies to pointer-to-pointer parameters, which should "
3260 "not have ref state.");
3263 // Any use of -dealloc in GC is *bad*.
3264 if (C.isObjCGCEnabled()) {
3265 V = V ^ RefVal::ErrorDeallocGC;
3266 hasErr = V.getKind();
3270 switch (V.getKind()) {
3272 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
3274 // The object immediately transitions to the released state.
3275 V = V ^ RefVal::Released;
3277 return setRefBinding(state, sym, V);
3278 case RefVal::NotOwned:
3279 V = V ^ RefVal::ErrorDeallocNotOwned;
3280 hasErr = V.getKind();
3286 if (V.getKind() == RefVal::Owned) {
3287 V = V ^ RefVal::NotOwned;
3297 if (C.isObjCGCEnabled())
3299 // Update the autorelease counts.
3300 V = V.autorelease();
3304 case StopTrackingHard:
3305 return removeRefBinding(state, sym);
3308 switch (V.getKind()) {
3310 llvm_unreachable("Invalid RefVal state for a retain.");
3312 case RefVal::NotOwned:
3315 case RefVal::Released:
3316 // Non-GC cases are handled above.
3317 assert(C.isObjCGCEnabled());
3318 V = (V ^ RefVal::Owned) + 1;
3324 case DecRefBridgedTransferred:
3325 case DecRefAndStopTrackingHard:
3326 switch (V.getKind()) {
3328 // case 'RefVal::Released' handled above.
3329 llvm_unreachable("Invalid RefVal state for a release.");
3332 assert(V.getCount() > 0);
3333 if (V.getCount() == 1) {
3334 if (E == DecRefBridgedTransferred ||
3335 V.getIvarAccessHistory() ==
3336 RefVal::IvarAccessHistory::AccessedDirectly)
3337 V = V ^ RefVal::NotOwned;
3339 V = V ^ RefVal::Released;
3340 } else if (E == DecRefAndStopTrackingHard) {
3341 return removeRefBinding(state, sym);
3347 case RefVal::NotOwned:
3348 if (V.getCount() > 0) {
3349 if (E == DecRefAndStopTrackingHard)
3350 return removeRefBinding(state, sym);
3352 } else if (V.getIvarAccessHistory() ==
3353 RefVal::IvarAccessHistory::AccessedDirectly) {
3354 // Assume that the instance variable was holding on the object at
3355 // +1, and we just didn't know.
3356 if (E == DecRefAndStopTrackingHard)
3357 return removeRefBinding(state, sym);
3358 V = V.releaseViaIvar() ^ RefVal::Released;
3360 V = V ^ RefVal::ErrorReleaseNotOwned;
3361 hasErr = V.getKind();
3365 case RefVal::Released:
3366 // Non-GC cases are handled above.
3367 assert(C.isObjCGCEnabled());
3368 V = V ^ RefVal::ErrorUseAfterRelease;
3369 hasErr = V.getKind();
3374 return setRefBinding(state, sym, V);
3377 void RetainCountChecker::processNonLeakError(ProgramStateRef St,
3378 SourceRange ErrorRange,
3379 RefVal::Kind ErrorKind,
3381 CheckerContext &C) const {
3382 // HACK: Ignore retain-count issues on values accessed through ivars,
3383 // because of cases like this:
3384 // [_contentView retain];
3385 // [_contentView removeFromSuperview];
3386 // [self addSubview:_contentView]; // invalidates 'self'
3387 // [_contentView release];
3388 if (const RefVal *RV = getRefBinding(St, Sym))
3389 if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3392 ExplodedNode *N = C.generateErrorNode(St);
3397 switch (ErrorKind) {
3399 llvm_unreachable("Unhandled error.");
3400 case RefVal::ErrorUseAfterRelease:
3401 if (!useAfterRelease)
3402 useAfterRelease.reset(new UseAfterRelease(this));
3403 BT = useAfterRelease.get();
3405 case RefVal::ErrorReleaseNotOwned:
3406 if (!releaseNotOwned)
3407 releaseNotOwned.reset(new BadRelease(this));
3408 BT = releaseNotOwned.get();
3410 case RefVal::ErrorDeallocGC:
3412 deallocGC.reset(new DeallocGC(this));
3413 BT = deallocGC.get();
3415 case RefVal::ErrorDeallocNotOwned:
3416 if (!deallocNotOwned)
3417 deallocNotOwned.reset(new DeallocNotOwned(this));
3418 BT = deallocNotOwned.get();
3423 auto report = std::unique_ptr<BugReport>(
3424 new CFRefReport(*BT, C.getASTContext().getLangOpts(), C.isObjCGCEnabled(),
3425 SummaryLog, N, Sym));
3426 report->addRange(ErrorRange);
3427 C.emitReport(std::move(report));
3430 //===----------------------------------------------------------------------===//
3431 // Handle the return values of retain-count-related functions.
3432 //===----------------------------------------------------------------------===//
3434 bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
3435 // Get the callee. We're only interested in simple C functions.
3436 ProgramStateRef state = C.getState();
3437 const FunctionDecl *FD = C.getCalleeDecl(CE);
3441 IdentifierInfo *II = FD->getIdentifier();
3445 // For now, we're only handling the functions that return aliases of their
3446 // arguments: CFRetain and CFMakeCollectable (and their families).
3447 // Eventually we should add other functions we can model entirely,
3448 // such as CFRelease, which don't invalidate their arguments or globals.
3449 if (CE->getNumArgs() != 1)
3452 // Get the name of the function.
3453 StringRef FName = II->getName();
3454 FName = FName.substr(FName.find_first_not_of('_'));
3456 // See if it's one of the specific functions we know how to eval.
3457 bool canEval = false;
3458 // See if the function has 'rc_ownership_trusted_implementation'
3459 // annotate attribute. If it does, we will not inline it.
3460 bool hasTrustedImplementationAnnotation = false;
3462 QualType ResultTy = CE->getCallReturnType(C.getASTContext());
3463 if (ResultTy->isObjCIdType()) {
3464 // Handle: id NSMakeCollectable(CFTypeRef)
3465 canEval = II->isStr("NSMakeCollectable");
3466 } else if (ResultTy->isPointerType()) {
3467 // Handle: (CF|CG|CV)Retain
3469 // CFMakeCollectable
3470 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3471 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3472 cocoa::isRefType(ResultTy, "CG", FName) ||
3473 cocoa::isRefType(ResultTy, "CV", FName)) {
3474 canEval = isRetain(FD, FName) || isAutorelease(FD, FName) ||
3475 isMakeCollectable(FD, FName);
3477 if (FD->getDefinition()) {
3478 canEval = isTrustedReferenceCountImplementation(FD->getDefinition());
3479 hasTrustedImplementationAnnotation = canEval;
3487 // Bind the return value.
3488 const LocationContext *LCtx = C.getLocationContext();
3489 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
3490 if (RetVal.isUnknown() ||
3491 (hasTrustedImplementationAnnotation && !ResultTy.isNull())) {
3492 // If the receiver is unknown or the function has
3493 // 'rc_ownership_trusted_implementation' annotate attribute, conjure a
3495 SValBuilder &SVB = C.getSValBuilder();
3496 RetVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, ResultTy, C.blockCount());
3498 state = state->BindExpr(CE, LCtx, RetVal, false);
3500 // FIXME: This should not be necessary, but otherwise the argument seems to be
3501 // considered alive during the next statement.
3502 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3503 // Save the refcount status of the argument.
3504 SymbolRef Sym = RetVal.getAsLocSymbol();
3505 const RefVal *Binding = nullptr;
3507 Binding = getRefBinding(state, Sym);
3509 // Invalidate the argument region.
3510 state = state->invalidateRegions(
3511 ArgRegion, CE, C.blockCount(), LCtx,
3512 /*CausesPointerEscape*/ hasTrustedImplementationAnnotation);
3514 // Restore the refcount status of the argument.
3516 state = setRefBinding(state, Sym, *Binding);
3519 C.addTransition(state);
3523 //===----------------------------------------------------------------------===//
3524 // Handle return statements.
3525 //===----------------------------------------------------------------------===//
3527 void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3528 CheckerContext &C) const {
3530 // Only adjust the reference count if this is the top-level call frame,
3531 // and not the result of inlining. In the future, we should do
3532 // better checking even for inlined calls, and see if they match
3533 // with their expected semantics (e.g., the method should return a retained
3535 if (!C.inTopFrame())
3538 const Expr *RetE = S->getRetValue();
3542 ProgramStateRef state = C.getState();
3544 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
3548 // Get the reference count binding (if any).
3549 const RefVal *T = getRefBinding(state, Sym);
3553 // Change the reference count.
3556 switch (X.getKind()) {
3557 case RefVal::Owned: {
3558 unsigned cnt = X.getCount();
3560 X.setCount(cnt - 1);
3561 X = X ^ RefVal::ReturnedOwned;
3565 case RefVal::NotOwned: {
3566 unsigned cnt = X.getCount();
3568 X.setCount(cnt - 1);
3569 X = X ^ RefVal::ReturnedOwned;
3572 X = X ^ RefVal::ReturnedNotOwned;
3581 // Update the binding.
3582 state = setRefBinding(state, Sym, X);
3583 ExplodedNode *Pred = C.addTransition(state);
3585 // At this point we have updated the state properly.
3586 // Everything after this is merely checking to see if the return value has
3587 // been over- or under-retained.
3589 // Did we cache out?
3593 // Update the autorelease counts.
3594 static CheckerProgramPointTag AutoreleaseTag(this, "Autorelease");
3595 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
3597 // Did we cache out?
3601 // Get the updated binding.
3602 T = getRefBinding(state, Sym);
3606 // Consult the summary of the enclosing method.
3607 RetainSummaryManager &Summaries = getSummaryManager(C);
3608 const Decl *CD = &Pred->getCodeDecl();
3609 RetEffect RE = RetEffect::MakeNoRet();
3611 // FIXME: What is the convention for blocks? Is there one?
3612 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
3613 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
3614 RE = Summ->getRetEffect();
3615 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3616 if (!isa<CXXMethodDecl>(FD)) {
3617 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3618 RE = Summ->getRetEffect();
3622 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
3625 void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3628 RetEffect RE, RefVal X,
3630 ProgramStateRef state) const {
3631 // HACK: Ignore retain-count issues on values accessed through ivars,
3632 // because of cases like this:
3633 // [_contentView retain];
3634 // [_contentView removeFromSuperview];
3635 // [self addSubview:_contentView]; // invalidates 'self'
3636 // [_contentView release];
3637 if (X.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3640 // Any leaks or other errors?
3641 if (X.isReturnedOwned() && X.getCount() == 0) {
3642 if (RE.getKind() != RetEffect::NoRet) {
3643 bool hasError = false;
3644 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3645 // Things are more complicated with garbage collection. If the
3646 // returned object is suppose to be an Objective-C object, we have
3647 // a leak (as the caller expects a GC'ed object) because no
3648 // method should return ownership unless it returns a CF object.
3650 X = X ^ RefVal::ErrorGCLeakReturned;
3652 else if (!RE.isOwned()) {
3653 // Either we are using GC and the returned object is a CF type
3654 // or we aren't using GC. In either case, we expect that the
3655 // enclosing method is expected to return ownership.
3657 X = X ^ RefVal::ErrorLeakReturned;
3661 // Generate an error node.
3662 state = setRefBinding(state, Sym, X);
3664 static CheckerProgramPointTag ReturnOwnLeakTag(this, "ReturnsOwnLeak");
3665 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
3667 const LangOptions &LOpts = C.getASTContext().getLangOpts();
3668 bool GCEnabled = C.isObjCGCEnabled();
3669 C.emitReport(std::unique_ptr<BugReport>(new CFRefLeakReport(
3670 *getLeakAtReturnBug(LOpts, GCEnabled), LOpts, GCEnabled,
3671 SummaryLog, N, Sym, C, IncludeAllocationLine)));
3675 } else if (X.isReturnedNotOwned()) {
3677 if (X.getIvarAccessHistory() ==
3678 RefVal::IvarAccessHistory::AccessedDirectly) {
3679 // Assume the method was trying to transfer a +1 reference from a
3680 // strong ivar to the caller.
3681 state = setRefBinding(state, Sym,
3682 X.releaseViaIvar() ^ RefVal::ReturnedOwned);
3684 // Trying to return a not owned object to a caller expecting an
3686 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
3688 static CheckerProgramPointTag
3689 ReturnNotOwnedTag(this, "ReturnNotOwnedForOwned");
3691 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
3693 if (!returnNotOwnedForOwned)
3694 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned(this));
3696 C.emitReport(std::unique_ptr<BugReport>(new CFRefReport(
3697 *returnNotOwnedForOwned, C.getASTContext().getLangOpts(),
3698 C.isObjCGCEnabled(), SummaryLog, N, Sym)));
3705 //===----------------------------------------------------------------------===//
3706 // Check various ways a symbol can be invalidated.
3707 //===----------------------------------------------------------------------===//
3709 void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
3710 CheckerContext &C) const {
3711 // Are we storing to something that causes the value to "escape"?
3712 bool escapes = true;
3714 // A value escapes in three possible cases (this may change):
3716 // (1) we are binding to something that is not a memory region.
3717 // (2) we are binding to a memregion that does not have stack storage
3718 // (3) we are binding to a memregion with stack storage that the store
3719 // does not understand.
3720 ProgramStateRef state = C.getState();
3722 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
3723 escapes = !regionLoc->getRegion()->hasStackStorage();
3726 // To test (3), generate a new state with the binding added. If it is
3727 // the same state, then it escapes (since the store cannot represent
3729 // Do this only if we know that the store is not supposed to generate the
3731 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3732 if (StoredVal != val)
3733 escapes = (state == (state->bindLoc(*regionLoc, val, C.getLocationContext())));
3736 // Case 4: We do not currently model what happens when a symbol is
3737 // assigned to a struct field, so be conservative here and let the symbol
3738 // go. TODO: This could definitely be improved upon.
3739 escapes = !isa<VarRegion>(regionLoc->getRegion());
3743 // If we are storing the value into an auto function scope variable annotated
3744 // with (__attribute__((cleanup))), stop tracking the value to avoid leak
3746 if (const VarRegion *LVR = dyn_cast_or_null<VarRegion>(loc.getAsRegion())) {
3747 const VarDecl *VD = LVR->getDecl();
3748 if (VD->hasAttr<CleanupAttr>()) {
3753 // If our store can represent the binding and we aren't storing to something
3754 // that doesn't have local storage then just return and have the simulation
3755 // state continue as is.
3759 // Otherwise, find all symbols referenced by 'val' that we are tracking
3760 // and stop tracking them.
3761 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
3762 C.addTransition(state);
3765 ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
3767 bool Assumption) const {
3768 // FIXME: We may add to the interface of evalAssume the list of symbols
3769 // whose assumptions have changed. For now we just iterate through the
3770 // bindings and check if any of the tracked symbols are NULL. This isn't
3771 // too bad since the number of symbols we will track in practice are
3772 // probably small and evalAssume is only called at branches and a few
3774 RefBindingsTy B = state->get<RefBindings>();
3779 bool changed = false;
3780 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
3782 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3783 // Check if the symbol is null stop tracking the symbol.
3784 ConstraintManager &CMgr = state->getConstraintManager();
3785 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3786 if (AllocFailed.isConstrainedTrue()) {
3788 B = RefBFactory.remove(B, I.getKey());
3793 state = state->set<RefBindings>(B);
3799 RetainCountChecker::checkRegionChanges(ProgramStateRef state,
3800 const InvalidatedSymbols *invalidated,
3801 ArrayRef<const MemRegion *> ExplicitRegions,
3802 ArrayRef<const MemRegion *> Regions,
3803 const LocationContext *LCtx,
3804 const CallEvent *Call) const {
3808 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3809 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3810 E = ExplicitRegions.end(); I != E; ++I) {
3811 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3812 WhitelistedSymbols.insert(SR->getSymbol());
3815 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
3816 E = invalidated->end(); I!=E; ++I) {
3818 if (WhitelistedSymbols.count(sym))
3820 // Remove any existing reference-count binding.
3821 state = removeRefBinding(state, sym);
3826 //===----------------------------------------------------------------------===//
3827 // Handle dead symbols and end-of-path.
3828 //===----------------------------------------------------------------------===//
3831 RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
3833 const ProgramPointTag *Tag,
3834 CheckerContext &Ctx,
3835 SymbolRef Sym, RefVal V) const {
3836 unsigned ACnt = V.getAutoreleaseCount();
3838 // No autorelease counts? Nothing to be done.
3842 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
3843 unsigned Cnt = V.getCount();
3845 // FIXME: Handle sending 'autorelease' to already released object.
3847 if (V.getKind() == RefVal::ReturnedOwned)
3850 // If we would over-release here, but we know the value came from an ivar,
3851 // assume it was a strong ivar that's just been relinquished.
3853 V.getIvarAccessHistory() == RefVal::IvarAccessHistory::AccessedDirectly) {
3854 V = V.releaseViaIvar();
3861 if (V.getKind() == RefVal::ReturnedOwned)
3862 V = V ^ RefVal::ReturnedNotOwned;
3864 V = V ^ RefVal::NotOwned;
3866 V.setCount(V.getCount() - ACnt);
3867 V.setAutoreleaseCount(0);
3869 return setRefBinding(state, Sym, V);
3872 // HACK: Ignore retain-count issues on values accessed through ivars,
3873 // because of cases like this:
3874 // [_contentView retain];
3875 // [_contentView removeFromSuperview];
3876 // [self addSubview:_contentView]; // invalidates 'self'
3877 // [_contentView release];
3878 if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3881 // Woah! More autorelease counts then retain counts left.
3883 V = V ^ RefVal::ErrorOverAutorelease;
3884 state = setRefBinding(state, Sym, V);
3886 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
3888 SmallString<128> sbuf;
3889 llvm::raw_svector_ostream os(sbuf);
3890 os << "Object was autoreleased ";
3891 if (V.getAutoreleaseCount() > 1)
3892 os << V.getAutoreleaseCount() << " times but the object ";
3895 os << "has a +" << V.getCount() << " retain count";
3897 if (!overAutorelease)
3898 overAutorelease.reset(new OverAutorelease(this));
3900 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3901 Ctx.emitReport(std::unique_ptr<BugReport>(
3902 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3903 SummaryLog, N, Sym, os.str())));
3910 RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
3911 SymbolRef sid, RefVal V,
3912 SmallVectorImpl<SymbolRef> &Leaked) const {
3915 // HACK: Ignore retain-count issues on values accessed through ivars,
3916 // because of cases like this:
3917 // [_contentView retain];
3918 // [_contentView removeFromSuperview];
3919 // [self addSubview:_contentView]; // invalidates 'self'
3920 // [_contentView release];
3921 if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3923 else if (V.isOwned())
3925 else if (V.isNotOwned() || V.isReturnedOwned())
3926 hasLeak = (V.getCount() > 0);
3931 return removeRefBinding(state, sid);
3933 Leaked.push_back(sid);
3934 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
3938 RetainCountChecker::processLeaks(ProgramStateRef state,
3939 SmallVectorImpl<SymbolRef> &Leaked,
3940 CheckerContext &Ctx,
3941 ExplodedNode *Pred) const {
3942 // Generate an intermediate node representing the leak point.
3943 ExplodedNode *N = Ctx.addTransition(state, Pred);
3946 for (SmallVectorImpl<SymbolRef>::iterator
3947 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3949 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3950 bool GCEnabled = Ctx.isObjCGCEnabled();
3951 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3952 : getLeakAtReturnBug(LOpts, GCEnabled);
3953 assert(BT && "BugType not initialized.");
3955 Ctx.emitReport(std::unique_ptr<BugReport>(
3956 new CFRefLeakReport(*BT, LOpts, GCEnabled, SummaryLog, N, *I, Ctx,
3957 IncludeAllocationLine)));
3964 void RetainCountChecker::checkBeginFunction(CheckerContext &Ctx) const {
3965 if (!Ctx.inTopFrame())
3968 const LocationContext *LCtx = Ctx.getLocationContext();
3969 const FunctionDecl *FD = dyn_cast<FunctionDecl>(LCtx->getDecl());
3971 if (!FD || isTrustedReferenceCountImplementation(FD))
3974 ProgramStateRef state = Ctx.getState();
3976 const RetainSummary *FunctionSummary = getSummaryManager(Ctx).getFunctionSummary(FD);
3977 ArgEffects CalleeSideArgEffects = FunctionSummary->getArgEffects();
3979 for (unsigned idx = 0, e = FD->getNumParams(); idx != e; ++idx) {
3980 const ParmVarDecl *Param = FD->getParamDecl(idx);
3981 SymbolRef Sym = state->getSVal(state->getRegion(Param, LCtx)).getAsSymbol();
3983 QualType Ty = Param->getType();
3984 const ArgEffect *AE = CalleeSideArgEffects.lookup(idx);
3985 if (AE && *AE == DecRef && isGeneralizedObjectRef(Ty))
3986 state = setRefBinding(state, Sym, RefVal::makeOwned(RetEffect::ObjKind::Generalized, Ty));
3987 else if (isGeneralizedObjectRef(Ty))
3988 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RetEffect::ObjKind::Generalized, Ty));
3991 Ctx.addTransition(state);
3994 void RetainCountChecker::checkEndFunction(const ReturnStmt *RS,
3995 CheckerContext &Ctx) const {
3996 ProgramStateRef state = Ctx.getState();
3997 RefBindingsTy B = state->get<RefBindings>();
3998 ExplodedNode *Pred = Ctx.getPredecessor();
4000 // Don't process anything within synthesized bodies.
4001 const LocationContext *LCtx = Pred->getLocationContext();
4002 if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
4003 assert(!LCtx->inTopFrame());
4007 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
4008 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/nullptr, Ctx,
4009 I->first, I->second);
4014 // If the current LocationContext has a parent, don't check for leaks.
4015 // We will do that later.
4016 // FIXME: we should instead check for imbalances of the retain/releases,
4017 // and suggest annotations.
4018 if (LCtx->getParent())
4021 B = state->get<RefBindings>();
4022 SmallVector<SymbolRef, 10> Leaked;
4024 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
4025 state = handleSymbolDeath(state, I->first, I->second, Leaked);
4027 processLeaks(state, Leaked, Ctx, Pred);
4030 const ProgramPointTag *
4031 RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
4032 const CheckerProgramPointTag *&tag = DeadSymbolTags[sym];
4034 SmallString<64> buf;
4035 llvm::raw_svector_ostream out(buf);
4036 out << "Dead Symbol : ";
4037 sym->dumpToStream(out);
4038 tag = new CheckerProgramPointTag(this, out.str());
4043 void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
4044 CheckerContext &C) const {
4045 ExplodedNode *Pred = C.getPredecessor();
4047 ProgramStateRef state = C.getState();
4048 RefBindingsTy B = state->get<RefBindings>();
4049 SmallVector<SymbolRef, 10> Leaked;
4051 // Update counts from autorelease pools
4052 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
4053 E = SymReaper.dead_end(); I != E; ++I) {
4055 if (const RefVal *T = B.lookup(Sym)){
4056 // Use the symbol as the tag.
4057 // FIXME: This might not be as unique as we would like.
4058 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
4059 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
4063 // Fetch the new reference count from the state, and use it to handle
4065 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
4069 if (Leaked.empty()) {
4070 C.addTransition(state);
4074 Pred = processLeaks(state, Leaked, C, Pred);
4076 // Did we cache out?
4080 // Now generate a new node that nukes the old bindings.
4081 // The only bindings left at this point are the leaked symbols.
4082 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
4083 B = state->get<RefBindings>();
4085 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
4088 B = F.remove(B, *I);
4090 state = state->set<RefBindings>(B);
4091 C.addTransition(state, Pred);
4094 void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
4095 const char *NL, const char *Sep) const {
4097 RefBindingsTy B = State->get<RefBindings>();
4104 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
4105 Out << I->first << " : ";
4106 I->second.print(Out);
4111 //===----------------------------------------------------------------------===//
4112 // Checker registration.
4113 //===----------------------------------------------------------------------===//
4115 void ento::registerRetainCountChecker(CheckerManager &Mgr) {
4116 Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
4119 //===----------------------------------------------------------------------===//
4120 // Implementation of the CallEffects API.
4121 //===----------------------------------------------------------------------===//
4125 namespace objc_retain {
4127 // This is a bit gross, but it allows us to populate CallEffects without
4128 // creating a bunch of accessors. This kind is very localized, so the
4129 // damage of this macro is limited.
4130 #define createCallEffect(D, KIND)\
4131 ASTContext &Ctx = D->getASTContext();\
4132 LangOptions L = Ctx.getLangOpts();\
4133 RetainSummaryManager M(Ctx, L.GCOnly, L.ObjCAutoRefCount);\
4134 const RetainSummary *S = M.get ## KIND ## Summary(D);\
4135 CallEffects CE(S->getRetEffect());\
4136 CE.Receiver = S->getReceiverEffect();\
4137 unsigned N = D->param_size();\
4138 for (unsigned i = 0; i < N; ++i) {\
4139 CE.Args.push_back(S->getArg(i));\
4142 CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) {
4143 createCallEffect(MD, Method);
4147 CallEffects CallEffects::getEffect(const FunctionDecl *FD) {
4148 createCallEffect(FD, Function);
4152 #undef createCallEffect
4154 } // end namespace objc_retain
4155 } // end namespace ento
4156 } // end namespace clang