1 //==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- C++ -*--//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the methods for RetainCountChecker, which implements
11 //  a reference count checker for Core Foundation and Cocoa on (Mac OS X).
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ClangSACheckers.h"
16 #include "AllocationDiagnostics.h"
17 #include "SelectorExtras.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/ParentMap.h"
22 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
23 #include "clang/Basic/LangOptions.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
26 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
27 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
28 #include "clang/StaticAnalyzer/Core/Checker.h"
29 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
30 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
31 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
32 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
33 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/FoldingSet.h"
36 #include "llvm/ADT/ImmutableList.h"
37 #include "llvm/ADT/ImmutableMap.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SmallString.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include <cstdarg>
42 
43 using namespace clang;
44 using namespace ento;
45 using namespace objc_retain;
46 using llvm::StrInStrNoCase;
47 
48 //===----------------------------------------------------------------------===//
49 // Adapters for FoldingSet.
50 //===----------------------------------------------------------------------===//
51 
52 namespace llvm {
53 template <> struct FoldingSetTrait<ArgEffect> {
Profilellvm::FoldingSetTrait54 static inline void Profile(const ArgEffect X, FoldingSetNodeID &ID) {
55   ID.AddInteger((unsigned) X);
56 }
57 };
58 template <> struct FoldingSetTrait<RetEffect> {
Profilellvm::FoldingSetTrait59   static inline void Profile(const RetEffect &X, FoldingSetNodeID &ID) {
60     ID.AddInteger((unsigned) X.getKind());
61     ID.AddInteger((unsigned) X.getObjKind());
62 }
63 };
64 } // end llvm namespace
65 
66 //===----------------------------------------------------------------------===//
67 // Reference-counting logic (typestate + counts).
68 //===----------------------------------------------------------------------===//
69 
70 /// ArgEffects summarizes the effects of a function/method call on all of
71 /// its arguments.
72 typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
73 
74 namespace {
75 class RefVal {
76 public:
77   enum Kind {
78     Owned = 0, // Owning reference.
79     NotOwned,  // Reference is not owned by still valid (not freed).
80     Released,  // Object has been released.
81     ReturnedOwned, // Returned object passes ownership to caller.
82     ReturnedNotOwned, // Return object does not pass ownership to caller.
83     ERROR_START,
84     ErrorDeallocNotOwned, // -dealloc called on non-owned object.
85     ErrorDeallocGC, // Calling -dealloc with GC enabled.
86     ErrorUseAfterRelease, // Object used after released.
87     ErrorReleaseNotOwned, // Release of an object that was not owned.
88     ERROR_LEAK_START,
89     ErrorLeak,  // A memory leak due to excessive reference counts.
90     ErrorLeakReturned, // A memory leak due to the returning method not having
91                        // the correct naming conventions.
92     ErrorGCLeakReturned,
93     ErrorOverAutorelease,
94     ErrorReturnedNotOwned
95   };
96 
97 private:
98   /// The number of outstanding retains.
99   unsigned Cnt;
100   /// The number of outstanding autoreleases.
101   unsigned ACnt;
102   /// The (static) type of the object at the time we started tracking it.
103   QualType T;
104 
105   /// The current state of the object.
106   ///
107   /// See the RefVal::Kind enum for possible values.
108   unsigned RawKind : 5;
109 
110   /// The kind of object being tracked (CF or ObjC), if known.
111   ///
112   /// See the RetEffect::ObjKind enum for possible values.
113   unsigned RawObjectKind : 2;
114 
115   /// True if the current state and/or retain count may turn out to not be the
116   /// best possible approximation of the reference counting state.
117   ///
118   /// If true, the checker may decide to throw away ("override") this state
119   /// in favor of something else when it sees the object being used in new ways.
120   ///
121   /// This setting should not be propagated to state derived from this state.
122   /// Once we start deriving new states, it would be inconsistent to override
123   /// them.
124   unsigned IsOverridable : 1;
125 
RefVal(Kind k,RetEffect::ObjKind o,unsigned cnt,unsigned acnt,QualType t,bool Overridable=false)126   RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t,
127          bool Overridable = false)
128     : Cnt(cnt), ACnt(acnt), T(t), RawKind(static_cast<unsigned>(k)),
129       RawObjectKind(static_cast<unsigned>(o)), IsOverridable(Overridable) {
130     assert(getKind() == k && "not enough bits for the kind");
131     assert(getObjKind() == o && "not enough bits for the object kind");
132   }
133 
134 public:
getKind() const135   Kind getKind() const { return static_cast<Kind>(RawKind); }
136 
getObjKind() const137   RetEffect::ObjKind getObjKind() const {
138     return static_cast<RetEffect::ObjKind>(RawObjectKind);
139   }
140 
getCount() const141   unsigned getCount() const { return Cnt; }
getAutoreleaseCount() const142   unsigned getAutoreleaseCount() const { return ACnt; }
getCombinedCounts() const143   unsigned getCombinedCounts() const { return Cnt + ACnt; }
clearCounts()144   void clearCounts() {
145     Cnt = 0;
146     ACnt = 0;
147     IsOverridable = false;
148   }
setCount(unsigned i)149   void setCount(unsigned i) {
150     Cnt = i;
151     IsOverridable = false;
152   }
setAutoreleaseCount(unsigned i)153   void setAutoreleaseCount(unsigned i) {
154     ACnt = i;
155     IsOverridable = false;
156   }
157 
getType() const158   QualType getType() const { return T; }
159 
isOverridable() const160   bool isOverridable() const { return IsOverridable; }
161 
isOwned() const162   bool isOwned() const {
163     return getKind() == Owned;
164   }
165 
isNotOwned() const166   bool isNotOwned() const {
167     return getKind() == NotOwned;
168   }
169 
isReturnedOwned() const170   bool isReturnedOwned() const {
171     return getKind() == ReturnedOwned;
172   }
173 
isReturnedNotOwned() const174   bool isReturnedNotOwned() const {
175     return getKind() == ReturnedNotOwned;
176   }
177 
178   /// Create a state for an object whose lifetime is the responsibility of the
179   /// current function, at least partially.
180   ///
181   /// Most commonly, this is an owned object with a retain count of +1.
makeOwned(RetEffect::ObjKind o,QualType t,unsigned Count=1)182   static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
183                           unsigned Count = 1) {
184     return RefVal(Owned, o, Count, 0, t);
185   }
186 
187   /// Create a state for an object whose lifetime is not the responsibility of
188   /// the current function.
189   ///
190   /// Most commonly, this is an unowned object with a retain count of +0.
makeNotOwned(RetEffect::ObjKind o,QualType t,unsigned Count=0)191   static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
192                              unsigned Count = 0) {
193     return RefVal(NotOwned, o, Count, 0, t);
194   }
195 
196   /// Create an "overridable" state for an unowned object at +0.
197   ///
198   /// An overridable state is one that provides a good approximation of the
199   /// reference counting state now, but which may be discarded later if the
200   /// checker sees the object being used in new ways.
makeOverridableNotOwned(RetEffect::ObjKind o,QualType t)201   static RefVal makeOverridableNotOwned(RetEffect::ObjKind o, QualType t) {
202     return RefVal(NotOwned, o, 0, 0, t, /*Overridable=*/true);
203   }
204 
operator -(size_t i) const205   RefVal operator-(size_t i) const {
206     return RefVal(getKind(), getObjKind(), getCount() - i,
207                   getAutoreleaseCount(), getType());
208   }
209 
operator +(size_t i) const210   RefVal operator+(size_t i) const {
211     return RefVal(getKind(), getObjKind(), getCount() + i,
212                   getAutoreleaseCount(), getType());
213   }
214 
operator ^(Kind k) const215   RefVal operator^(Kind k) const {
216     return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
217                   getType());
218   }
219 
autorelease() const220   RefVal autorelease() const {
221     return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
222                   getType());
223   }
224 
225   // Comparison, profiling, and pretty-printing.
226 
hasSameState(const RefVal & X) const227   bool hasSameState(const RefVal &X) const {
228     return getKind() == X.getKind() && Cnt == X.Cnt && ACnt == X.ACnt;
229   }
230 
operator ==(const RefVal & X) const231   bool operator==(const RefVal& X) const {
232     return T == X.T && hasSameState(X) && getObjKind() == X.getObjKind() &&
233            IsOverridable == X.IsOverridable;
234   }
235 
Profile(llvm::FoldingSetNodeID & ID) const236   void Profile(llvm::FoldingSetNodeID& ID) const {
237     ID.Add(T);
238     ID.AddInteger(RawKind);
239     ID.AddInteger(Cnt);
240     ID.AddInteger(ACnt);
241     ID.AddInteger(RawObjectKind);
242     ID.AddBoolean(IsOverridable);
243   }
244 
245   void print(raw_ostream &Out) const;
246 };
247 
print(raw_ostream & Out) const248 void RefVal::print(raw_ostream &Out) const {
249   if (!T.isNull())
250     Out << "Tracked " << T.getAsString() << '/';
251 
252   if (isOverridable())
253     Out << "(overridable) ";
254 
255   switch (getKind()) {
256     default: llvm_unreachable("Invalid RefVal kind");
257     case Owned: {
258       Out << "Owned";
259       unsigned cnt = getCount();
260       if (cnt) Out << " (+ " << cnt << ")";
261       break;
262     }
263 
264     case NotOwned: {
265       Out << "NotOwned";
266       unsigned cnt = getCount();
267       if (cnt) Out << " (+ " << cnt << ")";
268       break;
269     }
270 
271     case ReturnedOwned: {
272       Out << "ReturnedOwned";
273       unsigned cnt = getCount();
274       if (cnt) Out << " (+ " << cnt << ")";
275       break;
276     }
277 
278     case ReturnedNotOwned: {
279       Out << "ReturnedNotOwned";
280       unsigned cnt = getCount();
281       if (cnt) Out << " (+ " << cnt << ")";
282       break;
283     }
284 
285     case Released:
286       Out << "Released";
287       break;
288 
289     case ErrorDeallocGC:
290       Out << "-dealloc (GC)";
291       break;
292 
293     case ErrorDeallocNotOwned:
294       Out << "-dealloc (not-owned)";
295       break;
296 
297     case ErrorLeak:
298       Out << "Leaked";
299       break;
300 
301     case ErrorLeakReturned:
302       Out << "Leaked (Bad naming)";
303       break;
304 
305     case ErrorGCLeakReturned:
306       Out << "Leaked (GC-ed at return)";
307       break;
308 
309     case ErrorUseAfterRelease:
310       Out << "Use-After-Release [ERROR]";
311       break;
312 
313     case ErrorReleaseNotOwned:
314       Out << "Release of Not-Owned [ERROR]";
315       break;
316 
317     case RefVal::ErrorOverAutorelease:
318       Out << "Over-autoreleased";
319       break;
320 
321     case RefVal::ErrorReturnedNotOwned:
322       Out << "Non-owned object returned instead of owned";
323       break;
324   }
325 
326   if (ACnt) {
327     Out << " [ARC +" << ACnt << ']';
328   }
329 }
330 } //end anonymous namespace
331 
332 //===----------------------------------------------------------------------===//
333 // RefBindings - State used to track object reference counts.
334 //===----------------------------------------------------------------------===//
335 
REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings,SymbolRef,RefVal) const336 REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
337 
338 static inline const RefVal *getRefBinding(ProgramStateRef State,
339                                           SymbolRef Sym) {
340   return State->get<RefBindings>(Sym);
341 }
342 
setRefBinding(ProgramStateRef State,SymbolRef Sym,RefVal Val)343 static inline ProgramStateRef setRefBinding(ProgramStateRef State,
344                                             SymbolRef Sym, RefVal Val) {
345   return State->set<RefBindings>(Sym, Val);
346 }
347 
removeRefBinding(ProgramStateRef State,SymbolRef Sym)348 static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
349   return State->remove<RefBindings>(Sym);
350 }
351 
352 //===----------------------------------------------------------------------===//
353 // Function/Method behavior summaries.
354 //===----------------------------------------------------------------------===//
355 
356 namespace {
357 class RetainSummary {
358   /// Args - a map of (index, ArgEffect) pairs, where index
359   ///  specifies the argument (starting from 0).  This can be sparsely
360   ///  populated; arguments with no entry in Args use 'DefaultArgEffect'.
361   ArgEffects Args;
362 
363   /// DefaultArgEffect - The default ArgEffect to apply to arguments that
364   ///  do not have an entry in Args.
365   ArgEffect DefaultArgEffect;
366 
367   /// Receiver - If this summary applies to an Objective-C message expression,
368   ///  this is the effect applied to the state of the receiver.
369   ArgEffect Receiver;
370 
371   /// Ret - The effect on the return value.  Used to indicate if the
372   ///  function/method call returns a new tracked symbol.
373   RetEffect Ret;
374 
375 public:
RetainSummary(ArgEffects A,RetEffect R,ArgEffect defaultEff,ArgEffect ReceiverEff)376   RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
377                 ArgEffect ReceiverEff)
378     : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
379 
380   /// getArg - Return the argument effect on the argument specified by
381   ///  idx (starting from 0).
getArg(unsigned idx) const382   ArgEffect getArg(unsigned idx) const {
383     if (const ArgEffect *AE = Args.lookup(idx))
384       return *AE;
385 
386     return DefaultArgEffect;
387   }
388 
addArg(ArgEffects::Factory & af,unsigned idx,ArgEffect e)389   void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
390     Args = af.add(Args, idx, e);
391   }
392 
393   /// setDefaultArgEffect - Set the default argument effect.
setDefaultArgEffect(ArgEffect E)394   void setDefaultArgEffect(ArgEffect E) {
395     DefaultArgEffect = E;
396   }
397 
398   /// getRetEffect - Returns the effect on the return value of the call.
getRetEffect() const399   RetEffect getRetEffect() const { return Ret; }
400 
401   /// setRetEffect - Set the effect of the return value of the call.
setRetEffect(RetEffect E)402   void setRetEffect(RetEffect E) { Ret = E; }
403 
404 
405   /// Sets the effect on the receiver of the message.
setReceiverEffect(ArgEffect e)406   void setReceiverEffect(ArgEffect e) { Receiver = e; }
407 
408   /// getReceiverEffect - Returns the effect on the receiver of the call.
409   ///  This is only meaningful if the summary applies to an ObjCMessageExpr*.
getReceiverEffect() const410   ArgEffect getReceiverEffect() const { return Receiver; }
411 
412   /// Test if two retain summaries are identical. Note that merely equivalent
413   /// summaries are not necessarily identical (for example, if an explicit
414   /// argument effect matches the default effect).
operator ==(const RetainSummary & Other) const415   bool operator==(const RetainSummary &Other) const {
416     return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
417            Receiver == Other.Receiver && Ret == Other.Ret;
418   }
419 
420   /// Profile this summary for inclusion in a FoldingSet.
Profile(llvm::FoldingSetNodeID & ID) const421   void Profile(llvm::FoldingSetNodeID& ID) const {
422     ID.Add(Args);
423     ID.Add(DefaultArgEffect);
424     ID.Add(Receiver);
425     ID.Add(Ret);
426   }
427 
428   /// A retain summary is simple if it has no ArgEffects other than the default.
isSimple() const429   bool isSimple() const {
430     return Args.isEmpty();
431   }
432 
433 private:
getArgEffects() const434   ArgEffects getArgEffects() const { return Args; }
getDefaultArgEffect() const435   ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
436 
437   friend class RetainSummaryManager;
438 };
439 } // end anonymous namespace
440 
441 //===----------------------------------------------------------------------===//
442 // Data structures for constructing summaries.
443 //===----------------------------------------------------------------------===//
444 
445 namespace {
446 class ObjCSummaryKey {
447   IdentifierInfo* II;
448   Selector S;
449 public:
ObjCSummaryKey(IdentifierInfo * ii,Selector s)450   ObjCSummaryKey(IdentifierInfo* ii, Selector s)
451     : II(ii), S(s) {}
452 
ObjCSummaryKey(const ObjCInterfaceDecl * d,Selector s)453   ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
454     : II(d ? d->getIdentifier() : nullptr), S(s) {}
455 
ObjCSummaryKey(Selector s)456   ObjCSummaryKey(Selector s)
457     : II(nullptr), S(s) {}
458 
getIdentifier() const459   IdentifierInfo *getIdentifier() const { return II; }
getSelector() const460   Selector getSelector() const { return S; }
461 };
462 }
463 
464 namespace llvm {
465 template <> struct DenseMapInfo<ObjCSummaryKey> {
getEmptyKeyllvm::DenseMapInfo466   static inline ObjCSummaryKey getEmptyKey() {
467     return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
468                           DenseMapInfo<Selector>::getEmptyKey());
469   }
470 
getTombstoneKeyllvm::DenseMapInfo471   static inline ObjCSummaryKey getTombstoneKey() {
472     return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
473                           DenseMapInfo<Selector>::getTombstoneKey());
474   }
475 
getHashValuellvm::DenseMapInfo476   static unsigned getHashValue(const ObjCSummaryKey &V) {
477     typedef std::pair<IdentifierInfo*, Selector> PairTy;
478     return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
479                                                      V.getSelector()));
480   }
481 
isEqualllvm::DenseMapInfo482   static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
483     return LHS.getIdentifier() == RHS.getIdentifier() &&
484            LHS.getSelector() == RHS.getSelector();
485   }
486 
487 };
488 } // end llvm namespace
489 
490 namespace {
491 class ObjCSummaryCache {
492   typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
493   MapTy M;
494 public:
ObjCSummaryCache()495   ObjCSummaryCache() {}
496 
find(const ObjCInterfaceDecl * D,Selector S)497   const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
498     // Do a lookup with the (D,S) pair.  If we find a match return
499     // the iterator.
500     ObjCSummaryKey K(D, S);
501     MapTy::iterator I = M.find(K);
502 
503     if (I != M.end())
504       return I->second;
505     if (!D)
506       return nullptr;
507 
508     // Walk the super chain.  If we find a hit with a parent, we'll end
509     // up returning that summary.  We actually allow that key (null,S), as
510     // we cache summaries for the null ObjCInterfaceDecl* to allow us to
511     // generate initial summaries without having to worry about NSObject
512     // being declared.
513     // FIXME: We may change this at some point.
514     for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
515       if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
516         break;
517 
518       if (!C)
519         return nullptr;
520     }
521 
522     // Cache the summary with original key to make the next lookup faster
523     // and return the iterator.
524     const RetainSummary *Summ = I->second;
525     M[K] = Summ;
526     return Summ;
527   }
528 
find(IdentifierInfo * II,Selector S)529   const RetainSummary *find(IdentifierInfo* II, Selector S) {
530     // FIXME: Class method lookup.  Right now we dont' have a good way
531     // of going between IdentifierInfo* and the class hierarchy.
532     MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
533 
534     if (I == M.end())
535       I = M.find(ObjCSummaryKey(S));
536 
537     return I == M.end() ? nullptr : I->second;
538   }
539 
operator [](ObjCSummaryKey K)540   const RetainSummary *& operator[](ObjCSummaryKey K) {
541     return M[K];
542   }
543 
operator [](Selector S)544   const RetainSummary *& operator[](Selector S) {
545     return M[ ObjCSummaryKey(S) ];
546   }
547 };
548 } // end anonymous namespace
549 
550 //===----------------------------------------------------------------------===//
551 // Data structures for managing collections of summaries.
552 //===----------------------------------------------------------------------===//
553 
554 namespace {
555 class RetainSummaryManager {
556 
557   //==-----------------------------------------------------------------==//
558   //  Typedefs.
559   //==-----------------------------------------------------------------==//
560 
561   typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
562           FuncSummariesTy;
563 
564   typedef ObjCSummaryCache ObjCMethodSummariesTy;
565 
566   typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
567 
568   //==-----------------------------------------------------------------==//
569   //  Data.
570   //==-----------------------------------------------------------------==//
571 
572   /// Ctx - The ASTContext object for the analyzed ASTs.
573   ASTContext &Ctx;
574 
575   /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
576   const bool GCEnabled;
577 
578   /// Records whether or not the analyzed code runs in ARC mode.
579   const bool ARCEnabled;
580 
581   /// FuncSummaries - A map from FunctionDecls to summaries.
582   FuncSummariesTy FuncSummaries;
583 
584   /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
585   ///  to summaries.
586   ObjCMethodSummariesTy ObjCClassMethodSummaries;
587 
588   /// ObjCMethodSummaries - A map from selectors to summaries.
589   ObjCMethodSummariesTy ObjCMethodSummaries;
590 
591   /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
592   ///  and all other data used by the checker.
593   llvm::BumpPtrAllocator BPAlloc;
594 
595   /// AF - A factory for ArgEffects objects.
596   ArgEffects::Factory AF;
597 
598   /// ScratchArgs - A holding buffer for construct ArgEffects.
599   ArgEffects ScratchArgs;
600 
601   /// ObjCAllocRetE - Default return effect for methods returning Objective-C
602   ///  objects.
603   RetEffect ObjCAllocRetE;
604 
605   /// ObjCInitRetE - Default return effect for init methods returning
606   ///   Objective-C objects.
607   RetEffect ObjCInitRetE;
608 
609   /// SimpleSummaries - Used for uniquing summaries that don't have special
610   /// effects.
611   llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
612 
613   //==-----------------------------------------------------------------==//
614   //  Methods.
615   //==-----------------------------------------------------------------==//
616 
617   /// getArgEffects - Returns a persistent ArgEffects object based on the
618   ///  data in ScratchArgs.
619   ArgEffects getArgEffects();
620 
621   enum UnaryFuncKind { cfretain, cfrelease, cfautorelease, cfmakecollectable };
622 
623   const RetainSummary *getUnarySummary(const FunctionType* FT,
624                                        UnaryFuncKind func);
625 
626   const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
627   const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
628   const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
629 
630   const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
631 
getPersistentSummary(RetEffect RetEff,ArgEffect ReceiverEff=DoNothing,ArgEffect DefaultEff=MayEscape)632   const RetainSummary *getPersistentSummary(RetEffect RetEff,
633                                             ArgEffect ReceiverEff = DoNothing,
634                                             ArgEffect DefaultEff = MayEscape) {
635     RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
636     return getPersistentSummary(Summ);
637   }
638 
getDoNothingSummary()639   const RetainSummary *getDoNothingSummary() {
640     return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
641   }
642 
getDefaultSummary()643   const RetainSummary *getDefaultSummary() {
644     return getPersistentSummary(RetEffect::MakeNoRet(),
645                                 DoNothing, MayEscape);
646   }
647 
getPersistentStopSummary()648   const RetainSummary *getPersistentStopSummary() {
649     return getPersistentSummary(RetEffect::MakeNoRet(),
650                                 StopTracking, StopTracking);
651   }
652 
653   void InitializeClassMethodSummaries();
654   void InitializeMethodSummaries();
655 private:
addNSObjectClsMethSummary(Selector S,const RetainSummary * Summ)656   void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
657     ObjCClassMethodSummaries[S] = Summ;
658   }
659 
addNSObjectMethSummary(Selector S,const RetainSummary * Summ)660   void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
661     ObjCMethodSummaries[S] = Summ;
662   }
663 
addClassMethSummary(const char * Cls,const char * name,const RetainSummary * Summ,bool isNullary=true)664   void addClassMethSummary(const char* Cls, const char* name,
665                            const RetainSummary *Summ, bool isNullary = true) {
666     IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
667     Selector S = isNullary ? GetNullarySelector(name, Ctx)
668                            : GetUnarySelector(name, Ctx);
669     ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)]  = Summ;
670   }
671 
addInstMethSummary(const char * Cls,const char * nullaryName,const RetainSummary * Summ)672   void addInstMethSummary(const char* Cls, const char* nullaryName,
673                           const RetainSummary *Summ) {
674     IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
675     Selector S = GetNullarySelector(nullaryName, Ctx);
676     ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)]  = Summ;
677   }
678 
addMethodSummary(IdentifierInfo * ClsII,ObjCMethodSummariesTy & Summaries,const RetainSummary * Summ,va_list argp)679   void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy &Summaries,
680                         const RetainSummary *Summ, va_list argp) {
681     Selector S = getKeywordSelector(Ctx, argp);
682     Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
683   }
684 
addInstMethSummary(const char * Cls,const RetainSummary * Summ,...)685   void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
686     va_list argp;
687     va_start(argp, Summ);
688     addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
689     va_end(argp);
690   }
691 
addClsMethSummary(const char * Cls,const RetainSummary * Summ,...)692   void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
693     va_list argp;
694     va_start(argp, Summ);
695     addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
696     va_end(argp);
697   }
698 
addClsMethSummary(IdentifierInfo * II,const RetainSummary * Summ,...)699   void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
700     va_list argp;
701     va_start(argp, Summ);
702     addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
703     va_end(argp);
704   }
705 
706 public:
707 
RetainSummaryManager(ASTContext & ctx,bool gcenabled,bool usesARC)708   RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
709    : Ctx(ctx),
710      GCEnabled(gcenabled),
711      ARCEnabled(usesARC),
712      AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
713      ObjCAllocRetE(gcenabled
714                     ? RetEffect::MakeGCNotOwned()
715                     : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC)
716                                : RetEffect::MakeOwned(RetEffect::ObjC, true))),
717      ObjCInitRetE(gcenabled
718                     ? RetEffect::MakeGCNotOwned()
719                     : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC)
720                                : RetEffect::MakeOwnedWhenTrackedReceiver())) {
721     InitializeClassMethodSummaries();
722     InitializeMethodSummaries();
723   }
724 
725   const RetainSummary *getSummary(const CallEvent &Call,
726                                   ProgramStateRef State = nullptr);
727 
728   const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
729 
730   const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
731                                         const ObjCMethodDecl *MD,
732                                         QualType RetTy,
733                                         ObjCMethodSummariesTy &CachedSummaries);
734 
735   const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
736                                                 ProgramStateRef State);
737 
getClassMethodSummary(const ObjCMethodCall & M)738   const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
739     assert(!M.isInstanceMessage());
740     const ObjCInterfaceDecl *Class = M.getReceiverInterface();
741 
742     return getMethodSummary(M.getSelector(), Class, M.getDecl(),
743                             M.getResultType(), ObjCClassMethodSummaries);
744   }
745 
746   /// getMethodSummary - This version of getMethodSummary is used to query
747   ///  the summary for the current method being analyzed.
getMethodSummary(const ObjCMethodDecl * MD)748   const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
749     const ObjCInterfaceDecl *ID = MD->getClassInterface();
750     Selector S = MD->getSelector();
751     QualType ResultTy = MD->getReturnType();
752 
753     ObjCMethodSummariesTy *CachedSummaries;
754     if (MD->isInstanceMethod())
755       CachedSummaries = &ObjCMethodSummaries;
756     else
757       CachedSummaries = &ObjCClassMethodSummaries;
758 
759     return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
760   }
761 
762   const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
763                                                 Selector S, QualType RetTy);
764 
765   /// Determine if there is a special return effect for this function or method.
766   Optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy,
767                                                   const Decl *D);
768 
769   void updateSummaryFromAnnotations(const RetainSummary *&Summ,
770                                     const ObjCMethodDecl *MD);
771 
772   void updateSummaryFromAnnotations(const RetainSummary *&Summ,
773                                     const FunctionDecl *FD);
774 
775   void updateSummaryForCall(const RetainSummary *&Summ,
776                             const CallEvent &Call);
777 
isGCEnabled() const778   bool isGCEnabled() const { return GCEnabled; }
779 
isARCEnabled() const780   bool isARCEnabled() const { return ARCEnabled; }
781 
isARCorGCEnabled() const782   bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
783 
getObjAllocRetEffect() const784   RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
785 
786   friend class RetainSummaryTemplate;
787 };
788 
789 // Used to avoid allocating long-term (BPAlloc'd) memory for default retain
790 // summaries. If a function or method looks like it has a default summary, but
791 // it has annotations, the annotations are added to the stack-based template
792 // and then copied into managed memory.
793 class RetainSummaryTemplate {
794   RetainSummaryManager &Manager;
795   const RetainSummary *&RealSummary;
796   RetainSummary ScratchSummary;
797   bool Accessed;
798 public:
RetainSummaryTemplate(const RetainSummary * & real,RetainSummaryManager & mgr)799   RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
800     : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
801 
~RetainSummaryTemplate()802   ~RetainSummaryTemplate() {
803     if (Accessed)
804       RealSummary = Manager.getPersistentSummary(ScratchSummary);
805   }
806 
operator *()807   RetainSummary &operator*() {
808     Accessed = true;
809     return ScratchSummary;
810   }
811 
operator ->()812   RetainSummary *operator->() {
813     Accessed = true;
814     return &ScratchSummary;
815   }
816 };
817 
818 } // end anonymous namespace
819 
820 //===----------------------------------------------------------------------===//
821 // Implementation of checker data structures.
822 //===----------------------------------------------------------------------===//
823 
getArgEffects()824 ArgEffects RetainSummaryManager::getArgEffects() {
825   ArgEffects AE = ScratchArgs;
826   ScratchArgs = AF.getEmptyMap();
827   return AE;
828 }
829 
830 const RetainSummary *
getPersistentSummary(const RetainSummary & OldSumm)831 RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
832   // Unique "simple" summaries -- those without ArgEffects.
833   if (OldSumm.isSimple()) {
834     llvm::FoldingSetNodeID ID;
835     OldSumm.Profile(ID);
836 
837     void *Pos;
838     CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
839 
840     if (!N) {
841       N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
842       new (N) CachedSummaryNode(OldSumm);
843       SimpleSummaries.InsertNode(N, Pos);
844     }
845 
846     return &N->getValue();
847   }
848 
849   RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
850   new (Summ) RetainSummary(OldSumm);
851   return Summ;
852 }
853 
854 //===----------------------------------------------------------------------===//
855 // Summary creation for functions (largely uses of Core Foundation).
856 //===----------------------------------------------------------------------===//
857 
isRetain(const FunctionDecl * FD,StringRef FName)858 static bool isRetain(const FunctionDecl *FD, StringRef FName) {
859   return FName.endswith("Retain");
860 }
861 
isRelease(const FunctionDecl * FD,StringRef FName)862 static bool isRelease(const FunctionDecl *FD, StringRef FName) {
863   return FName.endswith("Release");
864 }
865 
isAutorelease(const FunctionDecl * FD,StringRef FName)866 static bool isAutorelease(const FunctionDecl *FD, StringRef FName) {
867   return FName.endswith("Autorelease");
868 }
869 
isMakeCollectable(const FunctionDecl * FD,StringRef FName)870 static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
871   // FIXME: Remove FunctionDecl parameter.
872   // FIXME: Is it really okay if MakeCollectable isn't a suffix?
873   return FName.find("MakeCollectable") != StringRef::npos;
874 }
875 
getStopTrackingHardEquivalent(ArgEffect E)876 static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
877   switch (E) {
878   case DoNothing:
879   case Autorelease:
880   case DecRefBridgedTransferred:
881   case IncRef:
882   case IncRefMsg:
883   case MakeCollectable:
884   case MayEscape:
885   case StopTracking:
886   case StopTrackingHard:
887     return StopTrackingHard;
888   case DecRef:
889   case DecRefAndStopTrackingHard:
890     return DecRefAndStopTrackingHard;
891   case DecRefMsg:
892   case DecRefMsgAndStopTrackingHard:
893     return DecRefMsgAndStopTrackingHard;
894   case Dealloc:
895     return Dealloc;
896   }
897 
898   llvm_unreachable("Unknown ArgEffect kind");
899 }
900 
updateSummaryForCall(const RetainSummary * & S,const CallEvent & Call)901 void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
902                                                 const CallEvent &Call) {
903   if (Call.hasNonZeroCallbackArg()) {
904     ArgEffect RecEffect =
905       getStopTrackingHardEquivalent(S->getReceiverEffect());
906     ArgEffect DefEffect =
907       getStopTrackingHardEquivalent(S->getDefaultArgEffect());
908 
909     ArgEffects CustomArgEffects = S->getArgEffects();
910     for (ArgEffects::iterator I = CustomArgEffects.begin(),
911                               E = CustomArgEffects.end();
912          I != E; ++I) {
913       ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
914       if (Translated != DefEffect)
915         ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
916     }
917 
918     RetEffect RE = RetEffect::MakeNoRetHard();
919 
920     // Special cases where the callback argument CANNOT free the return value.
921     // This can generally only happen if we know that the callback will only be
922     // called when the return value is already being deallocated.
923     if (const SimpleFunctionCall *FC = dyn_cast<SimpleFunctionCall>(&Call)) {
924       if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
925         // When the CGBitmapContext is deallocated, the callback here will free
926         // the associated data buffer.
927         if (Name->isStr("CGBitmapContextCreateWithData"))
928           RE = S->getRetEffect();
929       }
930     }
931 
932     S = getPersistentSummary(RE, RecEffect, DefEffect);
933   }
934 
935   // Special case '[super init];' and '[self init];'
936   //
937   // Even though calling '[super init]' without assigning the result to self
938   // and checking if the parent returns 'nil' is a bad pattern, it is common.
939   // Additionally, our Self Init checker already warns about it. To avoid
940   // overwhelming the user with messages from both checkers, we model the case
941   // of '[super init]' in cases when it is not consumed by another expression
942   // as if the call preserves the value of 'self'; essentially, assuming it can
943   // never fail and return 'nil'.
944   // Note, we don't want to just stop tracking the value since we want the
945   // RetainCount checker to report leaks and use-after-free if SelfInit checker
946   // is turned off.
947   if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
948     if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
949 
950       // Check if the message is not consumed, we know it will not be used in
951       // an assignment, ex: "self = [super init]".
952       const Expr *ME = MC->getOriginExpr();
953       const LocationContext *LCtx = MC->getLocationContext();
954       ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
955       if (!PM.isConsumedExpr(ME)) {
956         RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
957         ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
958         ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
959       }
960     }
961 
962   }
963 }
964 
965 const RetainSummary *
getSummary(const CallEvent & Call,ProgramStateRef State)966 RetainSummaryManager::getSummary(const CallEvent &Call,
967                                  ProgramStateRef State) {
968   const RetainSummary *Summ;
969   switch (Call.getKind()) {
970   case CE_Function:
971     Summ = getFunctionSummary(cast<SimpleFunctionCall>(Call).getDecl());
972     break;
973   case CE_CXXMember:
974   case CE_CXXMemberOperator:
975   case CE_Block:
976   case CE_CXXConstructor:
977   case CE_CXXDestructor:
978   case CE_CXXAllocator:
979     // FIXME: These calls are currently unsupported.
980     return getPersistentStopSummary();
981   case CE_ObjCMessage: {
982     const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
983     if (Msg.isInstanceMessage())
984       Summ = getInstanceMethodSummary(Msg, State);
985     else
986       Summ = getClassMethodSummary(Msg);
987     break;
988   }
989   }
990 
991   updateSummaryForCall(Summ, Call);
992 
993   assert(Summ && "Unknown call type?");
994   return Summ;
995 }
996 
997 const RetainSummary *
getFunctionSummary(const FunctionDecl * FD)998 RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
999   // If we don't know what function we're calling, use our default summary.
1000   if (!FD)
1001     return getDefaultSummary();
1002 
1003   // Look up a summary in our cache of FunctionDecls -> Summaries.
1004   FuncSummariesTy::iterator I = FuncSummaries.find(FD);
1005   if (I != FuncSummaries.end())
1006     return I->second;
1007 
1008   // No summary?  Generate one.
1009   const RetainSummary *S = nullptr;
1010   bool AllowAnnotations = true;
1011 
1012   do {
1013     // We generate "stop" summaries for implicitly defined functions.
1014     if (FD->isImplicit()) {
1015       S = getPersistentStopSummary();
1016       break;
1017     }
1018 
1019     // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
1020     // function's type.
1021     const FunctionType* FT = FD->getType()->getAs<FunctionType>();
1022     const IdentifierInfo *II = FD->getIdentifier();
1023     if (!II)
1024       break;
1025 
1026     StringRef FName = II->getName();
1027 
1028     // Strip away preceding '_'.  Doing this here will effect all the checks
1029     // down below.
1030     FName = FName.substr(FName.find_first_not_of('_'));
1031 
1032     // Inspect the result type.
1033     QualType RetTy = FT->getReturnType();
1034 
1035     // FIXME: This should all be refactored into a chain of "summary lookup"
1036     //  filters.
1037     assert(ScratchArgs.isEmpty());
1038 
1039     if (FName == "pthread_create" || FName == "pthread_setspecific") {
1040       // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1041       // This will be addressed better with IPA.
1042       S = getPersistentStopSummary();
1043     } else if (FName == "NSMakeCollectable") {
1044       // Handle: id NSMakeCollectable(CFTypeRef)
1045       S = (RetTy->isObjCIdType())
1046           ? getUnarySummary(FT, cfmakecollectable)
1047           : getPersistentStopSummary();
1048       // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1049       // but we can fully model NSMakeCollectable ourselves.
1050       AllowAnnotations = false;
1051     } else if (FName == "CFPlugInInstanceCreate") {
1052       S = getPersistentSummary(RetEffect::MakeNoRet());
1053     } else if (FName == "IOBSDNameMatching" ||
1054                FName == "IOServiceMatching" ||
1055                FName == "IOServiceNameMatching" ||
1056                FName == "IORegistryEntrySearchCFProperty" ||
1057                FName == "IORegistryEntryIDMatching" ||
1058                FName == "IOOpenFirmwarePathMatching") {
1059       // Part of <rdar://problem/6961230>. (IOKit)
1060       // This should be addressed using a API table.
1061       S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1062                                DoNothing, DoNothing);
1063     } else if (FName == "IOServiceGetMatchingService" ||
1064                FName == "IOServiceGetMatchingServices") {
1065       // FIXES: <rdar://problem/6326900>
1066       // This should be addressed using a API table.  This strcmp is also
1067       // a little gross, but there is no need to super optimize here.
1068       ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
1069       S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1070     } else if (FName == "IOServiceAddNotification" ||
1071                FName == "IOServiceAddMatchingNotification") {
1072       // Part of <rdar://problem/6961230>. (IOKit)
1073       // This should be addressed using a API table.
1074       ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
1075       S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1076     } else if (FName == "CVPixelBufferCreateWithBytes") {
1077       // FIXES: <rdar://problem/7283567>
1078       // Eventually this can be improved by recognizing that the pixel
1079       // buffer passed to CVPixelBufferCreateWithBytes is released via
1080       // a callback and doing full IPA to make sure this is done correctly.
1081       // FIXME: This function has an out parameter that returns an
1082       // allocated object.
1083       ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
1084       S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1085     } else if (FName == "CGBitmapContextCreateWithData") {
1086       // FIXES: <rdar://problem/7358899>
1087       // Eventually this can be improved by recognizing that 'releaseInfo'
1088       // passed to CGBitmapContextCreateWithData is released via
1089       // a callback and doing full IPA to make sure this is done correctly.
1090       ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
1091       S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1092                                DoNothing, DoNothing);
1093     } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1094       // FIXES: <rdar://problem/7283567>
1095       // Eventually this can be improved by recognizing that the pixel
1096       // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1097       // via a callback and doing full IPA to make sure this is done
1098       // correctly.
1099       ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
1100       S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1101     } else if (FName == "dispatch_set_context" ||
1102                FName == "xpc_connection_set_context") {
1103       // <rdar://problem/11059275> - The analyzer currently doesn't have
1104       // a good way to reason about the finalizer function for libdispatch.
1105       // If we pass a context object that is memory managed, stop tracking it.
1106       // <rdar://problem/13783514> - Same problem, but for XPC.
1107       // FIXME: this hack should possibly go away once we can handle
1108       // libdispatch and XPC finalizers.
1109       ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1110       S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1111     } else if (FName.startswith("NSLog")) {
1112       S = getDoNothingSummary();
1113     } else if (FName.startswith("NS") &&
1114                 (FName.find("Insert") != StringRef::npos)) {
1115       // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1116       // be deallocated by NSMapRemove. (radar://11152419)
1117       ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1118       ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1119       S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1120     }
1121 
1122     // Did we get a summary?
1123     if (S)
1124       break;
1125 
1126     if (RetTy->isPointerType()) {
1127       // For CoreFoundation ('CF') types.
1128       if (cocoa::isRefType(RetTy, "CF", FName)) {
1129         if (isRetain(FD, FName)) {
1130           S = getUnarySummary(FT, cfretain);
1131         } else if (isAutorelease(FD, FName)) {
1132           S = getUnarySummary(FT, cfautorelease);
1133           // The headers use cf_consumed, but we can fully model CFAutorelease
1134           // ourselves.
1135           AllowAnnotations = false;
1136         } else if (isMakeCollectable(FD, FName)) {
1137           S = getUnarySummary(FT, cfmakecollectable);
1138           AllowAnnotations = false;
1139         } else {
1140           S = getCFCreateGetRuleSummary(FD);
1141         }
1142 
1143         break;
1144       }
1145 
1146       // For CoreGraphics ('CG') types.
1147       if (cocoa::isRefType(RetTy, "CG", FName)) {
1148         if (isRetain(FD, FName))
1149           S = getUnarySummary(FT, cfretain);
1150         else
1151           S = getCFCreateGetRuleSummary(FD);
1152 
1153         break;
1154       }
1155 
1156       // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1157       if (cocoa::isRefType(RetTy, "DADisk") ||
1158           cocoa::isRefType(RetTy, "DADissenter") ||
1159           cocoa::isRefType(RetTy, "DASessionRef")) {
1160         S = getCFCreateGetRuleSummary(FD);
1161         break;
1162       }
1163 
1164       if (FD->hasAttr<CFAuditedTransferAttr>()) {
1165         S = getCFCreateGetRuleSummary(FD);
1166         break;
1167       }
1168 
1169       break;
1170     }
1171 
1172     // Check for release functions, the only kind of functions that we care
1173     // about that don't return a pointer type.
1174     if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
1175       // Test for 'CGCF'.
1176       FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
1177 
1178       if (isRelease(FD, FName))
1179         S = getUnarySummary(FT, cfrelease);
1180       else {
1181         assert (ScratchArgs.isEmpty());
1182         // Remaining CoreFoundation and CoreGraphics functions.
1183         // We use to assume that they all strictly followed the ownership idiom
1184         // and that ownership cannot be transferred.  While this is technically
1185         // correct, many methods allow a tracked object to escape.  For example:
1186         //
1187         //   CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1188         //   CFDictionaryAddValue(y, key, x);
1189         //   CFRelease(x);
1190         //   ... it is okay to use 'x' since 'y' has a reference to it
1191         //
1192         // We handle this and similar cases with the follow heuristic.  If the
1193         // function name contains "InsertValue", "SetValue", "AddValue",
1194         // "AppendValue", or "SetAttribute", then we assume that arguments may
1195         // "escape."  This means that something else holds on to the object,
1196         // allowing it be used even after its local retain count drops to 0.
1197         ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1198                        StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1199                        StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1200                        StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
1201                        StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
1202                       ? MayEscape : DoNothing;
1203 
1204         S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
1205       }
1206     }
1207   }
1208   while (0);
1209 
1210   // If we got all the way here without any luck, use a default summary.
1211   if (!S)
1212     S = getDefaultSummary();
1213 
1214   // Annotations override defaults.
1215   if (AllowAnnotations)
1216     updateSummaryFromAnnotations(S, FD);
1217 
1218   FuncSummaries[FD] = S;
1219   return S;
1220 }
1221 
1222 const RetainSummary *
getCFCreateGetRuleSummary(const FunctionDecl * FD)1223 RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1224   if (coreFoundation::followsCreateRule(FD))
1225     return getCFSummaryCreateRule(FD);
1226 
1227   return getCFSummaryGetRule(FD);
1228 }
1229 
1230 const RetainSummary *
getUnarySummary(const FunctionType * FT,UnaryFuncKind func)1231 RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1232                                       UnaryFuncKind func) {
1233 
1234   // Sanity check that this is *really* a unary function.  This can
1235   // happen if people do weird things.
1236   const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
1237   if (!FTP || FTP->getNumParams() != 1)
1238     return getPersistentStopSummary();
1239 
1240   assert (ScratchArgs.isEmpty());
1241 
1242   ArgEffect Effect;
1243   switch (func) {
1244   case cfretain: Effect = IncRef; break;
1245   case cfrelease: Effect = DecRef; break;
1246   case cfautorelease: Effect = Autorelease; break;
1247   case cfmakecollectable: Effect = MakeCollectable; break;
1248   }
1249 
1250   ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1251   return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1252 }
1253 
1254 const RetainSummary *
getCFSummaryCreateRule(const FunctionDecl * FD)1255 RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
1256   assert (ScratchArgs.isEmpty());
1257 
1258   return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
1259 }
1260 
1261 const RetainSummary *
getCFSummaryGetRule(const FunctionDecl * FD)1262 RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
1263   assert (ScratchArgs.isEmpty());
1264   return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1265                               DoNothing, DoNothing);
1266 }
1267 
1268 //===----------------------------------------------------------------------===//
1269 // Summary creation for Selectors.
1270 //===----------------------------------------------------------------------===//
1271 
1272 Optional<RetEffect>
getRetEffectFromAnnotations(QualType RetTy,const Decl * D)1273 RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
1274                                                   const Decl *D) {
1275   if (cocoa::isCocoaObjectRef(RetTy)) {
1276     if (D->hasAttr<NSReturnsRetainedAttr>())
1277       return ObjCAllocRetE;
1278 
1279     if (D->hasAttr<NSReturnsNotRetainedAttr>() ||
1280         D->hasAttr<NSReturnsAutoreleasedAttr>())
1281       return RetEffect::MakeNotOwned(RetEffect::ObjC);
1282 
1283   } else if (!RetTy->isPointerType()) {
1284     return None;
1285   }
1286 
1287   if (D->hasAttr<CFReturnsRetainedAttr>())
1288     return RetEffect::MakeOwned(RetEffect::CF, true);
1289 
1290   if (D->hasAttr<CFReturnsNotRetainedAttr>())
1291     return RetEffect::MakeNotOwned(RetEffect::CF);
1292 
1293   return None;
1294 }
1295 
1296 void
updateSummaryFromAnnotations(const RetainSummary * & Summ,const FunctionDecl * FD)1297 RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1298                                                    const FunctionDecl *FD) {
1299   if (!FD)
1300     return;
1301 
1302   assert(Summ && "Must have a summary to add annotations to.");
1303   RetainSummaryTemplate Template(Summ, *this);
1304 
1305   // Effects on the parameters.
1306   unsigned parm_idx = 0;
1307   for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
1308          pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
1309     const ParmVarDecl *pd = *pi;
1310     if (pd->hasAttr<NSConsumedAttr>())
1311       Template->addArg(AF, parm_idx, DecRefMsg);
1312     else if (pd->hasAttr<CFConsumedAttr>())
1313       Template->addArg(AF, parm_idx, DecRef);
1314   }
1315 
1316   QualType RetTy = FD->getReturnType();
1317   if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
1318     Template->setRetEffect(*RetE);
1319 }
1320 
1321 void
updateSummaryFromAnnotations(const RetainSummary * & Summ,const ObjCMethodDecl * MD)1322 RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1323                                                    const ObjCMethodDecl *MD) {
1324   if (!MD)
1325     return;
1326 
1327   assert(Summ && "Must have a valid summary to add annotations to");
1328   RetainSummaryTemplate Template(Summ, *this);
1329 
1330   // Effects on the receiver.
1331   if (MD->hasAttr<NSConsumesSelfAttr>())
1332     Template->setReceiverEffect(DecRefMsg);
1333 
1334   // Effects on the parameters.
1335   unsigned parm_idx = 0;
1336   for (ObjCMethodDecl::param_const_iterator
1337          pi=MD->param_begin(), pe=MD->param_end();
1338        pi != pe; ++pi, ++parm_idx) {
1339     const ParmVarDecl *pd = *pi;
1340     if (pd->hasAttr<NSConsumedAttr>())
1341       Template->addArg(AF, parm_idx, DecRefMsg);
1342     else if (pd->hasAttr<CFConsumedAttr>()) {
1343       Template->addArg(AF, parm_idx, DecRef);
1344     }
1345   }
1346 
1347   QualType RetTy = MD->getReturnType();
1348   if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1349     Template->setRetEffect(*RetE);
1350 }
1351 
1352 const RetainSummary *
getStandardMethodSummary(const ObjCMethodDecl * MD,Selector S,QualType RetTy)1353 RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1354                                                Selector S, QualType RetTy) {
1355   // Any special effects?
1356   ArgEffect ReceiverEff = DoNothing;
1357   RetEffect ResultEff = RetEffect::MakeNoRet();
1358 
1359   // Check the method family, and apply any default annotations.
1360   switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1361     case OMF_None:
1362     case OMF_initialize:
1363     case OMF_performSelector:
1364       // Assume all Objective-C methods follow Cocoa Memory Management rules.
1365       // FIXME: Does the non-threaded performSelector family really belong here?
1366       // The selector could be, say, @selector(copy).
1367       if (cocoa::isCocoaObjectRef(RetTy))
1368         ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1369       else if (coreFoundation::isCFObjectRef(RetTy)) {
1370         // ObjCMethodDecl currently doesn't consider CF objects as valid return
1371         // values for alloc, new, copy, or mutableCopy, so we have to
1372         // double-check with the selector. This is ugly, but there aren't that
1373         // many Objective-C methods that return CF objects, right?
1374         if (MD) {
1375           switch (S.getMethodFamily()) {
1376           case OMF_alloc:
1377           case OMF_new:
1378           case OMF_copy:
1379           case OMF_mutableCopy:
1380             ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1381             break;
1382           default:
1383             ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1384             break;
1385           }
1386         } else {
1387           ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1388         }
1389       }
1390       break;
1391     case OMF_init:
1392       ResultEff = ObjCInitRetE;
1393       ReceiverEff = DecRefMsg;
1394       break;
1395     case OMF_alloc:
1396     case OMF_new:
1397     case OMF_copy:
1398     case OMF_mutableCopy:
1399       if (cocoa::isCocoaObjectRef(RetTy))
1400         ResultEff = ObjCAllocRetE;
1401       else if (coreFoundation::isCFObjectRef(RetTy))
1402         ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1403       break;
1404     case OMF_autorelease:
1405       ReceiverEff = Autorelease;
1406       break;
1407     case OMF_retain:
1408       ReceiverEff = IncRefMsg;
1409       break;
1410     case OMF_release:
1411       ReceiverEff = DecRefMsg;
1412       break;
1413     case OMF_dealloc:
1414       ReceiverEff = Dealloc;
1415       break;
1416     case OMF_self:
1417       // -self is handled specially by the ExprEngine to propagate the receiver.
1418       break;
1419     case OMF_retainCount:
1420     case OMF_finalize:
1421       // These methods don't return objects.
1422       break;
1423   }
1424 
1425   // If one of the arguments in the selector has the keyword 'delegate' we
1426   // should stop tracking the reference count for the receiver.  This is
1427   // because the reference count is quite possibly handled by a delegate
1428   // method.
1429   if (S.isKeywordSelector()) {
1430     for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1431       StringRef Slot = S.getNameForSlot(i);
1432       if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1433         if (ResultEff == ObjCInitRetE)
1434           ResultEff = RetEffect::MakeNoRetHard();
1435         else
1436           ReceiverEff = StopTrackingHard;
1437       }
1438     }
1439   }
1440 
1441   if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1442       ResultEff.getKind() == RetEffect::NoRet)
1443     return getDefaultSummary();
1444 
1445   return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
1446 }
1447 
1448 const RetainSummary *
getInstanceMethodSummary(const ObjCMethodCall & Msg,ProgramStateRef State)1449 RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
1450                                                ProgramStateRef State) {
1451   const ObjCInterfaceDecl *ReceiverClass = nullptr;
1452 
1453   // We do better tracking of the type of the object than the core ExprEngine.
1454   // See if we have its type in our private state.
1455   // FIXME: Eventually replace the use of state->get<RefBindings> with
1456   // a generic API for reasoning about the Objective-C types of symbolic
1457   // objects.
1458   SVal ReceiverV = Msg.getReceiverSVal();
1459   if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
1460     if (const RefVal *T = getRefBinding(State, Sym))
1461       if (const ObjCObjectPointerType *PT =
1462             T->getType()->getAs<ObjCObjectPointerType>())
1463         ReceiverClass = PT->getInterfaceDecl();
1464 
1465   // If we don't know what kind of object this is, fall back to its static type.
1466   if (!ReceiverClass)
1467     ReceiverClass = Msg.getReceiverInterface();
1468 
1469   // FIXME: The receiver could be a reference to a class, meaning that
1470   //  we should use the class method.
1471   // id x = [NSObject class];
1472   // [x performSelector:... withObject:... afterDelay:...];
1473   Selector S = Msg.getSelector();
1474   const ObjCMethodDecl *Method = Msg.getDecl();
1475   if (!Method && ReceiverClass)
1476     Method = ReceiverClass->getInstanceMethod(S);
1477 
1478   return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1479                           ObjCMethodSummaries);
1480 }
1481 
1482 const RetainSummary *
getMethodSummary(Selector S,const ObjCInterfaceDecl * ID,const ObjCMethodDecl * MD,QualType RetTy,ObjCMethodSummariesTy & CachedSummaries)1483 RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
1484                                        const ObjCMethodDecl *MD, QualType RetTy,
1485                                        ObjCMethodSummariesTy &CachedSummaries) {
1486 
1487   // Look up a summary in our summary cache.
1488   const RetainSummary *Summ = CachedSummaries.find(ID, S);
1489 
1490   if (!Summ) {
1491     Summ = getStandardMethodSummary(MD, S, RetTy);
1492 
1493     // Annotations override defaults.
1494     updateSummaryFromAnnotations(Summ, MD);
1495 
1496     // Memoize the summary.
1497     CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
1498   }
1499 
1500   return Summ;
1501 }
1502 
InitializeClassMethodSummaries()1503 void RetainSummaryManager::InitializeClassMethodSummaries() {
1504   assert(ScratchArgs.isEmpty());
1505   // Create the [NSAssertionHandler currentHander] summary.
1506   addClassMethSummary("NSAssertionHandler", "currentHandler",
1507                 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
1508 
1509   // Create the [NSAutoreleasePool addObject:] summary.
1510   ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
1511   addClassMethSummary("NSAutoreleasePool", "addObject",
1512                       getPersistentSummary(RetEffect::MakeNoRet(),
1513                                            DoNothing, Autorelease));
1514 }
1515 
InitializeMethodSummaries()1516 void RetainSummaryManager::InitializeMethodSummaries() {
1517 
1518   assert (ScratchArgs.isEmpty());
1519 
1520   // Create the "init" selector.  It just acts as a pass-through for the
1521   // receiver.
1522   const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
1523   addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1524 
1525   // awakeAfterUsingCoder: behaves basically like an 'init' method.  It
1526   // claims the receiver and returns a retained object.
1527   addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1528                          InitSumm);
1529 
1530   // The next methods are allocators.
1531   const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1532   const RetainSummary *CFAllocSumm =
1533     getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
1534 
1535   // Create the "retain" selector.
1536   RetEffect NoRet = RetEffect::MakeNoRet();
1537   const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
1538   addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
1539 
1540   // Create the "release" selector.
1541   Summ = getPersistentSummary(NoRet, DecRefMsg);
1542   addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
1543 
1544   // Create the -dealloc summary.
1545   Summ = getPersistentSummary(NoRet, Dealloc);
1546   addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
1547 
1548   // Create the "autorelease" selector.
1549   Summ = getPersistentSummary(NoRet, Autorelease);
1550   addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
1551 
1552   // For NSWindow, allocated objects are (initially) self-owned.
1553   // FIXME: For now we opt for false negatives with NSWindow, as these objects
1554   //  self-own themselves.  However, they only do this once they are displayed.
1555   //  Thus, we need to track an NSWindow's display status.
1556   //  This is tracked in <rdar://problem/6062711>.
1557   //  See also http://llvm.org/bugs/show_bug.cgi?id=3714.
1558   const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1559                                                    StopTracking,
1560                                                    StopTracking);
1561 
1562   addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1563 
1564   // For NSPanel (which subclasses NSWindow), allocated objects are not
1565   //  self-owned.
1566   // FIXME: For now we don't track NSPanels. object for the same reason
1567   //   as for NSWindow objects.
1568   addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1569 
1570   // For NSNull, objects returned by +null are singletons that ignore
1571   // retain/release semantics.  Just don't track them.
1572   // <rdar://problem/12858915>
1573   addClassMethSummary("NSNull", "null", NoTrackYet);
1574 
1575   // Don't track allocated autorelease pools, as it is okay to prematurely
1576   // exit a method.
1577   addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
1578   addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
1579   addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
1580 
1581   // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1582   addInstMethSummary("QCRenderer", AllocSumm,
1583                      "createSnapshotImageOfType", nullptr);
1584   addInstMethSummary("QCView", AllocSumm,
1585                      "createSnapshotImageOfType", nullptr);
1586 
1587   // Create summaries for CIContext, 'createCGImage' and
1588   // 'createCGLayerWithSize'.  These objects are CF objects, and are not
1589   // automatically garbage collected.
1590   addInstMethSummary("CIContext", CFAllocSumm,
1591                      "createCGImage", "fromRect", nullptr);
1592   addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect",
1593                      "format", "colorSpace", nullptr);
1594   addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info",
1595                      nullptr);
1596 }
1597 
1598 //===----------------------------------------------------------------------===//
1599 // Error reporting.
1600 //===----------------------------------------------------------------------===//
1601 namespace {
1602   typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1603     SummaryLogTy;
1604 
1605   //===-------------===//
1606   // Bug Descriptions. //
1607   //===-------------===//
1608 
1609   class CFRefBug : public BugType {
1610   protected:
CFRefBug(const CheckerBase * checker,StringRef name)1611     CFRefBug(const CheckerBase *checker, StringRef name)
1612         : BugType(checker, name, categories::MemoryCoreFoundationObjectiveC) {}
1613 
1614   public:
1615 
1616     // FIXME: Eventually remove.
1617     virtual const char *getDescription() const = 0;
1618 
isLeak() const1619     virtual bool isLeak() const { return false; }
1620   };
1621 
1622   class UseAfterRelease : public CFRefBug {
1623   public:
UseAfterRelease(const CheckerBase * checker)1624     UseAfterRelease(const CheckerBase *checker)
1625         : CFRefBug(checker, "Use-after-release") {}
1626 
getDescription() const1627     const char *getDescription() const override {
1628       return "Reference-counted object is used after it is released";
1629     }
1630   };
1631 
1632   class BadRelease : public CFRefBug {
1633   public:
BadRelease(const CheckerBase * checker)1634     BadRelease(const CheckerBase *checker) : CFRefBug(checker, "Bad release") {}
1635 
getDescription() const1636     const char *getDescription() const override {
1637       return "Incorrect decrement of the reference count of an object that is "
1638              "not owned at this point by the caller";
1639     }
1640   };
1641 
1642   class DeallocGC : public CFRefBug {
1643   public:
DeallocGC(const CheckerBase * checker)1644     DeallocGC(const CheckerBase *checker)
1645         : CFRefBug(checker, "-dealloc called while using garbage collection") {}
1646 
getDescription() const1647     const char *getDescription() const override {
1648       return "-dealloc called while using garbage collection";
1649     }
1650   };
1651 
1652   class DeallocNotOwned : public CFRefBug {
1653   public:
DeallocNotOwned(const CheckerBase * checker)1654     DeallocNotOwned(const CheckerBase *checker)
1655         : CFRefBug(checker, "-dealloc sent to non-exclusively owned object") {}
1656 
getDescription() const1657     const char *getDescription() const override {
1658       return "-dealloc sent to object that may be referenced elsewhere";
1659     }
1660   };
1661 
1662   class OverAutorelease : public CFRefBug {
1663   public:
OverAutorelease(const CheckerBase * checker)1664     OverAutorelease(const CheckerBase *checker)
1665         : CFRefBug(checker, "Object autoreleased too many times") {}
1666 
getDescription() const1667     const char *getDescription() const override {
1668       return "Object autoreleased too many times";
1669     }
1670   };
1671 
1672   class ReturnedNotOwnedForOwned : public CFRefBug {
1673   public:
ReturnedNotOwnedForOwned(const CheckerBase * checker)1674     ReturnedNotOwnedForOwned(const CheckerBase *checker)
1675         : CFRefBug(checker, "Method should return an owned object") {}
1676 
getDescription() const1677     const char *getDescription() const override {
1678       return "Object with a +0 retain count returned to caller where a +1 "
1679              "(owning) retain count is expected";
1680     }
1681   };
1682 
1683   class Leak : public CFRefBug {
1684   public:
Leak(const CheckerBase * checker,StringRef name)1685     Leak(const CheckerBase *checker, StringRef name) : CFRefBug(checker, name) {
1686       // Leaks should not be reported if they are post-dominated by a sink.
1687       setSuppressOnSink(true);
1688     }
1689 
getDescription() const1690     const char *getDescription() const override { return ""; }
1691 
isLeak() const1692     bool isLeak() const override { return true; }
1693   };
1694 
1695   //===---------===//
1696   // Bug Reports.  //
1697   //===---------===//
1698 
1699   class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
1700   protected:
1701     SymbolRef Sym;
1702     const SummaryLogTy &SummaryLog;
1703     bool GCEnabled;
1704 
1705   public:
CFRefReportVisitor(SymbolRef sym,bool gcEnabled,const SummaryLogTy & log)1706     CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1707        : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
1708 
Profile(llvm::FoldingSetNodeID & ID) const1709     void Profile(llvm::FoldingSetNodeID &ID) const override {
1710       static int x = 0;
1711       ID.AddPointer(&x);
1712       ID.AddPointer(Sym);
1713     }
1714 
1715     PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1716                                    const ExplodedNode *PrevN,
1717                                    BugReporterContext &BRC,
1718                                    BugReport &BR) override;
1719 
1720     std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
1721                                                     const ExplodedNode *N,
1722                                                     BugReport &BR) override;
1723   };
1724 
1725   class CFRefLeakReportVisitor : public CFRefReportVisitor {
1726   public:
CFRefLeakReportVisitor(SymbolRef sym,bool GCEnabled,const SummaryLogTy & log)1727     CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
1728                            const SummaryLogTy &log)
1729        : CFRefReportVisitor(sym, GCEnabled, log) {}
1730 
1731     std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
1732                                                     const ExplodedNode *N,
1733                                                     BugReport &BR) override;
1734 
clone() const1735     std::unique_ptr<BugReporterVisitor> clone() const override {
1736       // The curiously-recurring template pattern only works for one level of
1737       // subclassing. Rather than make a new template base for
1738       // CFRefReportVisitor, we simply override clone() to do the right thing.
1739       // This could be trouble someday if BugReporterVisitorImpl is ever
1740       // used for something else besides a convenient implementation of clone().
1741       return llvm::make_unique<CFRefLeakReportVisitor>(*this);
1742     }
1743   };
1744 
1745   class CFRefReport : public BugReport {
1746     void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
1747 
1748   public:
CFRefReport(CFRefBug & D,const LangOptions & LOpts,bool GCEnabled,const SummaryLogTy & Log,ExplodedNode * n,SymbolRef sym,bool registerVisitor=true)1749     CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1750                 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1751                 bool registerVisitor = true)
1752       : BugReport(D, D.getDescription(), n) {
1753       if (registerVisitor)
1754         addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log));
1755       addGCModeDescription(LOpts, GCEnabled);
1756     }
1757 
CFRefReport(CFRefBug & D,const LangOptions & LOpts,bool GCEnabled,const SummaryLogTy & Log,ExplodedNode * n,SymbolRef sym,StringRef endText)1758     CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1759                 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1760                 StringRef endText)
1761       : BugReport(D, D.getDescription(), endText, n) {
1762       addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log));
1763       addGCModeDescription(LOpts, GCEnabled);
1764     }
1765 
getRanges()1766     std::pair<ranges_iterator, ranges_iterator> getRanges() override {
1767       const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1768       if (!BugTy.isLeak())
1769         return BugReport::getRanges();
1770       else
1771         return std::make_pair(ranges_iterator(), ranges_iterator());
1772     }
1773   };
1774 
1775   class CFRefLeakReport : public CFRefReport {
1776     const MemRegion* AllocBinding;
1777   public:
1778     CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1779                     const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1780                     CheckerContext &Ctx,
1781                     bool IncludeAllocationLine);
1782 
getLocation(const SourceManager & SM) const1783     PathDiagnosticLocation getLocation(const SourceManager &SM) const override {
1784       assert(Location.isValid());
1785       return Location;
1786     }
1787   };
1788 } // end anonymous namespace
1789 
addGCModeDescription(const LangOptions & LOpts,bool GCEnabled)1790 void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1791                                        bool GCEnabled) {
1792   const char *GCModeDescription = nullptr;
1793 
1794   switch (LOpts.getGC()) {
1795   case LangOptions::GCOnly:
1796     assert(GCEnabled);
1797     GCModeDescription = "Code is compiled to only use garbage collection";
1798     break;
1799 
1800   case LangOptions::NonGC:
1801     assert(!GCEnabled);
1802     GCModeDescription = "Code is compiled to use reference counts";
1803     break;
1804 
1805   case LangOptions::HybridGC:
1806     if (GCEnabled) {
1807       GCModeDescription = "Code is compiled to use either garbage collection "
1808                           "(GC) or reference counts (non-GC).  The bug occurs "
1809                           "with GC enabled";
1810       break;
1811     } else {
1812       GCModeDescription = "Code is compiled to use either garbage collection "
1813                           "(GC) or reference counts (non-GC).  The bug occurs "
1814                           "in non-GC mode";
1815       break;
1816     }
1817   }
1818 
1819   assert(GCModeDescription && "invalid/unknown GC mode");
1820   addExtraText(GCModeDescription);
1821 }
1822 
isNumericLiteralExpression(const Expr * E)1823 static bool isNumericLiteralExpression(const Expr *E) {
1824   // FIXME: This set of cases was copied from SemaExprObjC.
1825   return isa<IntegerLiteral>(E) ||
1826          isa<CharacterLiteral>(E) ||
1827          isa<FloatingLiteral>(E) ||
1828          isa<ObjCBoolLiteralExpr>(E) ||
1829          isa<CXXBoolLiteralExpr>(E);
1830 }
1831 
VisitNode(const ExplodedNode * N,const ExplodedNode * PrevN,BugReporterContext & BRC,BugReport & BR)1832 PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1833                                                    const ExplodedNode *PrevN,
1834                                                    BugReporterContext &BRC,
1835                                                    BugReport &BR) {
1836   // FIXME: We will eventually need to handle non-statement-based events
1837   // (__attribute__((cleanup))).
1838   if (!N->getLocation().getAs<StmtPoint>())
1839     return nullptr;
1840 
1841   // Check if the type state has changed.
1842   ProgramStateRef PrevSt = PrevN->getState();
1843   ProgramStateRef CurrSt = N->getState();
1844   const LocationContext *LCtx = N->getLocationContext();
1845 
1846   const RefVal* CurrT = getRefBinding(CurrSt, Sym);
1847   if (!CurrT) return nullptr;
1848 
1849   const RefVal &CurrV = *CurrT;
1850   const RefVal *PrevT = getRefBinding(PrevSt, Sym);
1851 
1852   // Create a string buffer to constain all the useful things we want
1853   // to tell the user.
1854   std::string sbuf;
1855   llvm::raw_string_ostream os(sbuf);
1856 
1857   // This is the allocation site since the previous node had no bindings
1858   // for this symbol.
1859   if (!PrevT) {
1860     const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
1861 
1862     if (isa<ObjCArrayLiteral>(S)) {
1863       os << "NSArray literal is an object with a +0 retain count";
1864     }
1865     else if (isa<ObjCDictionaryLiteral>(S)) {
1866       os << "NSDictionary literal is an object with a +0 retain count";
1867     }
1868     else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1869       if (isNumericLiteralExpression(BL->getSubExpr()))
1870         os << "NSNumber literal is an object with a +0 retain count";
1871       else {
1872         const ObjCInterfaceDecl *BoxClass = nullptr;
1873         if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1874           BoxClass = Method->getClassInterface();
1875 
1876         // We should always be able to find the boxing class interface,
1877         // but consider this future-proofing.
1878         if (BoxClass)
1879           os << *BoxClass << " b";
1880         else
1881           os << "B";
1882 
1883         os << "oxed expression produces an object with a +0 retain count";
1884       }
1885     }
1886     else {
1887       if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1888         // Get the name of the callee (if it is available).
1889         SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1890         if (const FunctionDecl *FD = X.getAsFunctionDecl())
1891           os << "Call to function '" << *FD << '\'';
1892         else
1893           os << "function call";
1894       }
1895       else {
1896         assert(isa<ObjCMessageExpr>(S));
1897         CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1898         CallEventRef<ObjCMethodCall> Call
1899           = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1900 
1901         switch (Call->getMessageKind()) {
1902         case OCM_Message:
1903           os << "Method";
1904           break;
1905         case OCM_PropertyAccess:
1906           os << "Property";
1907           break;
1908         case OCM_Subscript:
1909           os << "Subscript";
1910           break;
1911         }
1912       }
1913 
1914       if (CurrV.getObjKind() == RetEffect::CF) {
1915         os << " returns a Core Foundation object with a ";
1916       }
1917       else {
1918         assert (CurrV.getObjKind() == RetEffect::ObjC);
1919         os << " returns an Objective-C object with a ";
1920       }
1921 
1922       if (CurrV.isOwned()) {
1923         os << "+1 retain count";
1924 
1925         if (GCEnabled) {
1926           assert(CurrV.getObjKind() == RetEffect::CF);
1927           os << ".  "
1928           "Core Foundation objects are not automatically garbage collected.";
1929         }
1930       }
1931       else {
1932         assert (CurrV.isNotOwned());
1933         os << "+0 retain count";
1934       }
1935     }
1936 
1937     PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1938                                   N->getLocationContext());
1939     return new PathDiagnosticEventPiece(Pos, os.str());
1940   }
1941 
1942   // Gather up the effects that were performed on the object at this
1943   // program point
1944   SmallVector<ArgEffect, 2> AEffects;
1945 
1946   const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1947   if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
1948     // We only have summaries attached to nodes after evaluating CallExpr and
1949     // ObjCMessageExprs.
1950     const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
1951 
1952     if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1953       // Iterate through the parameter expressions and see if the symbol
1954       // was ever passed as an argument.
1955       unsigned i = 0;
1956 
1957       for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
1958            AI!=AE; ++AI, ++i) {
1959 
1960         // Retrieve the value of the argument.  Is it the symbol
1961         // we are interested in?
1962         if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
1963           continue;
1964 
1965         // We have an argument.  Get the effect!
1966         AEffects.push_back(Summ->getArg(i));
1967       }
1968     }
1969     else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
1970       if (const Expr *receiver = ME->getInstanceReceiver())
1971         if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
1972               .getAsLocSymbol() == Sym) {
1973           // The symbol we are tracking is the receiver.
1974           AEffects.push_back(Summ->getReceiverEffect());
1975         }
1976     }
1977   }
1978 
1979   do {
1980     // Get the previous type state.
1981     RefVal PrevV = *PrevT;
1982 
1983     // Specially handle -dealloc.
1984     if (!GCEnabled && std::find(AEffects.begin(), AEffects.end(), Dealloc) !=
1985                           AEffects.end()) {
1986       // Determine if the object's reference count was pushed to zero.
1987       assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
1988       // We may not have transitioned to 'release' if we hit an error.
1989       // This case is handled elsewhere.
1990       if (CurrV.getKind() == RefVal::Released) {
1991         assert(CurrV.getCombinedCounts() == 0);
1992         os << "Object released by directly sending the '-dealloc' message";
1993         break;
1994       }
1995     }
1996 
1997     // Specially handle CFMakeCollectable and friends.
1998     if (std::find(AEffects.begin(), AEffects.end(), MakeCollectable) !=
1999         AEffects.end()) {
2000       // Get the name of the function.
2001       const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
2002       SVal X =
2003         CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
2004       const FunctionDecl *FD = X.getAsFunctionDecl();
2005 
2006       if (GCEnabled) {
2007         // Determine if the object's reference count was pushed to zero.
2008         assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
2009 
2010         os << "In GC mode a call to '" << *FD
2011         <<  "' decrements an object's retain count and registers the "
2012         "object with the garbage collector. ";
2013 
2014         if (CurrV.getKind() == RefVal::Released) {
2015           assert(CurrV.getCount() == 0);
2016           os << "Since it now has a 0 retain count the object can be "
2017           "automatically collected by the garbage collector.";
2018         }
2019         else
2020           os << "An object must have a 0 retain count to be garbage collected. "
2021           "After this call its retain count is +" << CurrV.getCount()
2022           << '.';
2023       }
2024       else
2025         os << "When GC is not enabled a call to '" << *FD
2026         << "' has no effect on its argument.";
2027 
2028       // Nothing more to say.
2029       break;
2030     }
2031 
2032     // Determine if the typestate has changed.
2033     if (!PrevV.hasSameState(CurrV))
2034       switch (CurrV.getKind()) {
2035         case RefVal::Owned:
2036         case RefVal::NotOwned:
2037 
2038           if (PrevV.getCount() == CurrV.getCount()) {
2039             // Did an autorelease message get sent?
2040             if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2041               return nullptr;
2042 
2043             assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
2044             os << "Object autoreleased";
2045             break;
2046           }
2047 
2048           if (PrevV.getCount() > CurrV.getCount())
2049             os << "Reference count decremented.";
2050           else
2051             os << "Reference count incremented.";
2052 
2053           if (unsigned Count = CurrV.getCount())
2054             os << " The object now has a +" << Count << " retain count.";
2055 
2056           if (PrevV.getKind() == RefVal::Released) {
2057             assert(GCEnabled && CurrV.getCount() > 0);
2058             os << " The object is not eligible for garbage collection until "
2059                   "the retain count reaches 0 again.";
2060           }
2061 
2062           break;
2063 
2064         case RefVal::Released:
2065           os << "Object released.";
2066           break;
2067 
2068         case RefVal::ReturnedOwned:
2069           // Autoreleases can be applied after marking a node ReturnedOwned.
2070           if (CurrV.getAutoreleaseCount())
2071             return nullptr;
2072 
2073           os << "Object returned to caller as an owning reference (single "
2074                 "retain count transferred to caller)";
2075           break;
2076 
2077         case RefVal::ReturnedNotOwned:
2078           os << "Object returned to caller with a +0 retain count";
2079           break;
2080 
2081         default:
2082           return nullptr;
2083       }
2084 
2085     // Emit any remaining diagnostics for the argument effects (if any).
2086     for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2087          E=AEffects.end(); I != E; ++I) {
2088 
2089       // A bunch of things have alternate behavior under GC.
2090       if (GCEnabled)
2091         switch (*I) {
2092           default: break;
2093           case Autorelease:
2094             os << "In GC mode an 'autorelease' has no effect.";
2095             continue;
2096           case IncRefMsg:
2097             os << "In GC mode the 'retain' message has no effect.";
2098             continue;
2099           case DecRefMsg:
2100             os << "In GC mode the 'release' message has no effect.";
2101             continue;
2102         }
2103     }
2104   } while (0);
2105 
2106   if (os.str().empty())
2107     return nullptr; // We have nothing to say!
2108 
2109   const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
2110   PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2111                                 N->getLocationContext());
2112   PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
2113 
2114   // Add the range by scanning the children of the statement for any bindings
2115   // to Sym.
2116   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
2117        I!=E; ++I)
2118     if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
2119       if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
2120         P->addRange(Exp->getSourceRange());
2121         break;
2122       }
2123 
2124   return P;
2125 }
2126 
2127 // Find the first node in the current function context that referred to the
2128 // tracked symbol and the memory location that value was stored to. Note, the
2129 // value is only reported if the allocation occurred in the same function as
2130 // the leak. The function can also return a location context, which should be
2131 // treated as interesting.
2132 struct AllocationInfo {
2133   const ExplodedNode* N;
2134   const MemRegion *R;
2135   const LocationContext *InterestingMethodContext;
AllocationInfoAllocationInfo2136   AllocationInfo(const ExplodedNode *InN,
2137                  const MemRegion *InR,
2138                  const LocationContext *InInterestingMethodContext) :
2139     N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
2140 };
2141 
2142 static AllocationInfo
GetAllocationSite(ProgramStateManager & StateMgr,const ExplodedNode * N,SymbolRef Sym)2143 GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
2144                   SymbolRef Sym) {
2145   const ExplodedNode *AllocationNode = N;
2146   const ExplodedNode *AllocationNodeInCurrentContext = N;
2147   const MemRegion *FirstBinding = nullptr;
2148   const LocationContext *LeakContext = N->getLocationContext();
2149 
2150   // The location context of the init method called on the leaked object, if
2151   // available.
2152   const LocationContext *InitMethodContext = nullptr;
2153 
2154   while (N) {
2155     ProgramStateRef St = N->getState();
2156     const LocationContext *NContext = N->getLocationContext();
2157 
2158     if (!getRefBinding(St, Sym))
2159       break;
2160 
2161     StoreManager::FindUniqueBinding FB(Sym);
2162     StateMgr.iterBindings(St, FB);
2163 
2164     if (FB) {
2165       const MemRegion *R = FB.getRegion();
2166       const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>();
2167       // Do not show local variables belonging to a function other than
2168       // where the error is reported.
2169       if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame())
2170         FirstBinding = R;
2171     }
2172 
2173     // AllocationNode is the last node in which the symbol was tracked.
2174     AllocationNode = N;
2175 
2176     // AllocationNodeInCurrentContext, is the last node in the current context
2177     // in which the symbol was tracked.
2178     if (NContext == LeakContext)
2179       AllocationNodeInCurrentContext = N;
2180 
2181     // Find the last init that was called on the given symbol and store the
2182     // init method's location context.
2183     if (!InitMethodContext)
2184       if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) {
2185         const Stmt *CE = CEP->getCallExpr();
2186         if (const ObjCMessageExpr *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
2187           const Stmt *RecExpr = ME->getInstanceReceiver();
2188           if (RecExpr) {
2189             SVal RecV = St->getSVal(RecExpr, NContext);
2190             if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
2191               InitMethodContext = CEP->getCalleeContext();
2192           }
2193         }
2194       }
2195 
2196     N = N->pred_empty() ? nullptr : *(N->pred_begin());
2197   }
2198 
2199   // If we are reporting a leak of the object that was allocated with alloc,
2200   // mark its init method as interesting.
2201   const LocationContext *InterestingMethodContext = nullptr;
2202   if (InitMethodContext) {
2203     const ProgramPoint AllocPP = AllocationNode->getLocation();
2204     if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
2205       if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
2206         if (ME->getMethodFamily() == OMF_alloc)
2207           InterestingMethodContext = InitMethodContext;
2208   }
2209 
2210   // If allocation happened in a function different from the leak node context,
2211   // do not report the binding.
2212   assert(N && "Could not find allocation node");
2213   if (N->getLocationContext() != LeakContext) {
2214     FirstBinding = nullptr;
2215   }
2216 
2217   return AllocationInfo(AllocationNodeInCurrentContext,
2218                         FirstBinding,
2219                         InterestingMethodContext);
2220 }
2221 
2222 std::unique_ptr<PathDiagnosticPiece>
getEndPath(BugReporterContext & BRC,const ExplodedNode * EndN,BugReport & BR)2223 CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2224                                const ExplodedNode *EndN, BugReport &BR) {
2225   BR.markInteresting(Sym);
2226   return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
2227 }
2228 
2229 std::unique_ptr<PathDiagnosticPiece>
getEndPath(BugReporterContext & BRC,const ExplodedNode * EndN,BugReport & BR)2230 CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2231                                    const ExplodedNode *EndN, BugReport &BR) {
2232 
2233   // Tell the BugReporterContext to report cases when the tracked symbol is
2234   // assigned to different variables, etc.
2235   BR.markInteresting(Sym);
2236 
2237   // We are reporting a leak.  Walk up the graph to get to the first node where
2238   // the symbol appeared, and also get the first VarDecl that tracked object
2239   // is stored to.
2240   AllocationInfo AllocI =
2241     GetAllocationSite(BRC.getStateManager(), EndN, Sym);
2242 
2243   const MemRegion* FirstBinding = AllocI.R;
2244   BR.markInteresting(AllocI.InterestingMethodContext);
2245 
2246   SourceManager& SM = BRC.getSourceManager();
2247 
2248   // Compute an actual location for the leak.  Sometimes a leak doesn't
2249   // occur at an actual statement (e.g., transition between blocks; end
2250   // of function) so we need to walk the graph and compute a real location.
2251   const ExplodedNode *LeakN = EndN;
2252   PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
2253 
2254   std::string sbuf;
2255   llvm::raw_string_ostream os(sbuf);
2256 
2257   os << "Object leaked: ";
2258 
2259   if (FirstBinding) {
2260     os << "object allocated and stored into '"
2261        << FirstBinding->getString() << '\'';
2262   }
2263   else
2264     os << "allocated object";
2265 
2266   // Get the retain count.
2267   const RefVal* RV = getRefBinding(EndN->getState(), Sym);
2268   assert(RV);
2269 
2270   if (RV->getKind() == RefVal::ErrorLeakReturned) {
2271     // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2272     // objects.  Only "copy", "alloc", "retain" and "new" transfer ownership
2273     // to the caller for NS objects.
2274     const Decl *D = &EndN->getCodeDecl();
2275 
2276     os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2277                                   : " is returned from a function ");
2278 
2279     if (D->hasAttr<CFReturnsNotRetainedAttr>())
2280       os << "that is annotated as CF_RETURNS_NOT_RETAINED";
2281     else if (D->hasAttr<NSReturnsNotRetainedAttr>())
2282       os << "that is annotated as NS_RETURNS_NOT_RETAINED";
2283     else {
2284       if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2285         os << "whose name ('" << MD->getSelector().getAsString()
2286            << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2287               "  This violates the naming convention rules"
2288               " given in the Memory Management Guide for Cocoa";
2289       }
2290       else {
2291         const FunctionDecl *FD = cast<FunctionDecl>(D);
2292         os << "whose name ('" << *FD
2293            << "') does not contain 'Copy' or 'Create'.  This violates the naming"
2294               " convention rules given in the Memory Management Guide for Core"
2295               " Foundation";
2296       }
2297     }
2298   }
2299   else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2300     const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
2301     os << " and returned from method '" << MD.getSelector().getAsString()
2302        << "' is potentially leaked when using garbage collection.  Callers "
2303           "of this method do not expect a returned object with a +1 retain "
2304           "count since they expect the object to be managed by the garbage "
2305           "collector";
2306   }
2307   else
2308     os << " is not referenced later in this execution path and has a retain "
2309           "count of +" << RV->getCount();
2310 
2311   return llvm::make_unique<PathDiagnosticEventPiece>(L, os.str());
2312 }
2313 
CFRefLeakReport(CFRefBug & D,const LangOptions & LOpts,bool GCEnabled,const SummaryLogTy & Log,ExplodedNode * n,SymbolRef sym,CheckerContext & Ctx,bool IncludeAllocationLine)2314 CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2315                                  bool GCEnabled, const SummaryLogTy &Log,
2316                                  ExplodedNode *n, SymbolRef sym,
2317                                  CheckerContext &Ctx,
2318                                  bool IncludeAllocationLine)
2319   : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
2320 
2321   // Most bug reports are cached at the location where they occurred.
2322   // With leaks, we want to unique them by the location where they were
2323   // allocated, and only report a single path.  To do this, we need to find
2324   // the allocation site of a piece of tracked memory, which we do via a
2325   // call to GetAllocationSite.  This will walk the ExplodedGraph backwards.
2326   // Note that this is *not* the trimmed graph; we are guaranteed, however,
2327   // that all ancestor nodes that represent the allocation site have the
2328   // same SourceLocation.
2329   const ExplodedNode *AllocNode = nullptr;
2330 
2331   const SourceManager& SMgr = Ctx.getSourceManager();
2332 
2333   AllocationInfo AllocI =
2334     GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
2335 
2336   AllocNode = AllocI.N;
2337   AllocBinding = AllocI.R;
2338   markInteresting(AllocI.InterestingMethodContext);
2339 
2340   // Get the SourceLocation for the allocation site.
2341   // FIXME: This will crash the analyzer if an allocation comes from an
2342   // implicit call (ex: a destructor call).
2343   // (Currently there are no such allocations in Cocoa, though.)
2344   const Stmt *AllocStmt = 0;
2345   ProgramPoint P = AllocNode->getLocation();
2346   if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
2347     AllocStmt = Exit->getCalleeContext()->getCallSite();
2348   else {
2349     // We are going to get a BlockEdge when the leak and allocation happen in
2350     // different, non-nested frames (contexts). For example, the case where an
2351     // allocation happens in a block that captures a reference to it and
2352     // that reference is overwritten/dropped by another call to the block.
2353     if (Optional<BlockEdge> Edge = P.getAs<BlockEdge>()) {
2354       if (Optional<CFGStmt> St = Edge->getDst()->front().getAs<CFGStmt>()) {
2355         AllocStmt = St->getStmt();
2356       }
2357     }
2358     else {
2359       AllocStmt = P.castAs<PostStmt>().getStmt();
2360     }
2361   }
2362   assert(AllocStmt && "Cannot find allocation statement");
2363 
2364   PathDiagnosticLocation AllocLocation =
2365     PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2366                                         AllocNode->getLocationContext());
2367   Location = AllocLocation;
2368 
2369   // Set uniqieing info, which will be used for unique the bug reports. The
2370   // leaks should be uniqued on the allocation site.
2371   UniqueingLocation = AllocLocation;
2372   UniqueingDecl = AllocNode->getLocationContext()->getDecl();
2373 
2374   // Fill in the description of the bug.
2375   Description.clear();
2376   llvm::raw_string_ostream os(Description);
2377   os << "Potential leak ";
2378   if (GCEnabled)
2379     os << "(when using garbage collection) ";
2380   os << "of an object";
2381 
2382   if (AllocBinding) {
2383     os << " stored into '" << AllocBinding->getString() << '\'';
2384     if (IncludeAllocationLine) {
2385       FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager());
2386       os << " (allocated on line " << SL.getSpellingLineNumber() << ")";
2387     }
2388   }
2389 
2390   addVisitor(llvm::make_unique<CFRefLeakReportVisitor>(sym, GCEnabled, Log));
2391 }
2392 
2393 //===----------------------------------------------------------------------===//
2394 // Main checker logic.
2395 //===----------------------------------------------------------------------===//
2396 
2397 namespace {
2398 class RetainCountChecker
2399   : public Checker< check::Bind,
2400                     check::DeadSymbols,
2401                     check::EndAnalysis,
2402                     check::EndFunction,
2403                     check::PostStmt<BlockExpr>,
2404                     check::PostStmt<CastExpr>,
2405                     check::PostStmt<ObjCArrayLiteral>,
2406                     check::PostStmt<ObjCDictionaryLiteral>,
2407                     check::PostStmt<ObjCBoxedExpr>,
2408                     check::PostStmt<ObjCIvarRefExpr>,
2409                     check::PostCall,
2410                     check::PreStmt<ReturnStmt>,
2411                     check::RegionChanges,
2412                     eval::Assume,
2413                     eval::Call > {
2414   mutable std::unique_ptr<CFRefBug> useAfterRelease, releaseNotOwned;
2415   mutable std::unique_ptr<CFRefBug> deallocGC, deallocNotOwned;
2416   mutable std::unique_ptr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2417   mutable std::unique_ptr<CFRefBug> leakWithinFunction, leakAtReturn;
2418   mutable std::unique_ptr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
2419 
2420   typedef llvm::DenseMap<SymbolRef, const CheckerProgramPointTag *> SymbolTagMap;
2421 
2422   // This map is only used to ensure proper deletion of any allocated tags.
2423   mutable SymbolTagMap DeadSymbolTags;
2424 
2425   mutable std::unique_ptr<RetainSummaryManager> Summaries;
2426   mutable std::unique_ptr<RetainSummaryManager> SummariesGC;
2427   mutable SummaryLogTy SummaryLog;
2428   mutable bool ShouldResetSummaryLog;
2429 
2430   /// Optional setting to indicate if leak reports should include
2431   /// the allocation line.
2432   mutable bool IncludeAllocationLine;
2433 
2434 public:
RetainCountChecker(AnalyzerOptions & AO)2435   RetainCountChecker(AnalyzerOptions &AO)
2436     : ShouldResetSummaryLog(false),
2437       IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {}
2438 
~RetainCountChecker()2439   virtual ~RetainCountChecker() {
2440     DeleteContainerSeconds(DeadSymbolTags);
2441   }
2442 
checkEndAnalysis(ExplodedGraph & G,BugReporter & BR,ExprEngine & Eng) const2443   void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2444                         ExprEngine &Eng) const {
2445     // FIXME: This is a hack to make sure the summary log gets cleared between
2446     // analyses of different code bodies.
2447     //
2448     // Why is this necessary? Because a checker's lifetime is tied to a
2449     // translation unit, but an ExplodedGraph's lifetime is just a code body.
2450     // Once in a blue moon, a new ExplodedNode will have the same address as an
2451     // old one with an associated summary, and the bug report visitor gets very
2452     // confused. (To make things worse, the summary lifetime is currently also
2453     // tied to a code body, so we get a crash instead of incorrect results.)
2454     //
2455     // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2456     // changes, things will start going wrong again. Really the lifetime of this
2457     // log needs to be tied to either the specific nodes in it or the entire
2458     // ExplodedGraph, not to a specific part of the code being analyzed.
2459     //
2460     // (Also, having stateful local data means that the same checker can't be
2461     // used from multiple threads, but a lot of checkers have incorrect
2462     // assumptions about that anyway. So that wasn't a priority at the time of
2463     // this fix.)
2464     //
2465     // This happens at the end of analysis, but bug reports are emitted /after/
2466     // this point. So we can't just clear the summary log now. Instead, we mark
2467     // that the next time we access the summary log, it should be cleared.
2468 
2469     // If we never reset the summary log during /this/ code body analysis,
2470     // there were no new summaries. There might still have been summaries from
2471     // the /last/ analysis, so clear them out to make sure the bug report
2472     // visitors don't get confused.
2473     if (ShouldResetSummaryLog)
2474       SummaryLog.clear();
2475 
2476     ShouldResetSummaryLog = !SummaryLog.empty();
2477   }
2478 
getLeakWithinFunctionBug(const LangOptions & LOpts,bool GCEnabled) const2479   CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2480                                      bool GCEnabled) const {
2481     if (GCEnabled) {
2482       if (!leakWithinFunctionGC)
2483         leakWithinFunctionGC.reset(new Leak(this, "Leak of object when using "
2484                                                   "garbage collection"));
2485       return leakWithinFunctionGC.get();
2486     } else {
2487       if (!leakWithinFunction) {
2488         if (LOpts.getGC() == LangOptions::HybridGC) {
2489           leakWithinFunction.reset(new Leak(this,
2490                                             "Leak of object when not using "
2491                                             "garbage collection (GC) in "
2492                                             "dual GC/non-GC code"));
2493         } else {
2494           leakWithinFunction.reset(new Leak(this, "Leak"));
2495         }
2496       }
2497       return leakWithinFunction.get();
2498     }
2499   }
2500 
getLeakAtReturnBug(const LangOptions & LOpts,bool GCEnabled) const2501   CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2502     if (GCEnabled) {
2503       if (!leakAtReturnGC)
2504         leakAtReturnGC.reset(new Leak(this,
2505                                       "Leak of returned object when using "
2506                                       "garbage collection"));
2507       return leakAtReturnGC.get();
2508     } else {
2509       if (!leakAtReturn) {
2510         if (LOpts.getGC() == LangOptions::HybridGC) {
2511           leakAtReturn.reset(new Leak(this,
2512                                       "Leak of returned object when not using "
2513                                       "garbage collection (GC) in dual "
2514                                       "GC/non-GC code"));
2515         } else {
2516           leakAtReturn.reset(new Leak(this, "Leak of returned object"));
2517         }
2518       }
2519       return leakAtReturn.get();
2520     }
2521   }
2522 
getSummaryManager(ASTContext & Ctx,bool GCEnabled) const2523   RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2524                                           bool GCEnabled) const {
2525     // FIXME: We don't support ARC being turned on and off during one analysis.
2526     // (nor, for that matter, do we support changing ASTContexts)
2527     bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
2528     if (GCEnabled) {
2529       if (!SummariesGC)
2530         SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
2531       else
2532         assert(SummariesGC->isARCEnabled() == ARCEnabled);
2533       return *SummariesGC;
2534     } else {
2535       if (!Summaries)
2536         Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
2537       else
2538         assert(Summaries->isARCEnabled() == ARCEnabled);
2539       return *Summaries;
2540     }
2541   }
2542 
getSummaryManager(CheckerContext & C) const2543   RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2544     return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2545   }
2546 
2547   void printState(raw_ostream &Out, ProgramStateRef State,
2548                   const char *NL, const char *Sep) const override;
2549 
2550   void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
2551   void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2552   void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
2553 
2554   void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2555   void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
2556   void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2557 
2558   void checkPostStmt(const ObjCIvarRefExpr *IRE, CheckerContext &C) const;
2559 
2560   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
2561 
2562   void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
2563                     CheckerContext &C) const;
2564 
2565   void processSummaryOfInlined(const RetainSummary &Summ,
2566                                const CallEvent &Call,
2567                                CheckerContext &C) const;
2568 
2569   bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2570 
2571   ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
2572                                  bool Assumption) const;
2573 
2574   ProgramStateRef
2575   checkRegionChanges(ProgramStateRef state,
2576                      const InvalidatedSymbols *invalidated,
2577                      ArrayRef<const MemRegion *> ExplicitRegions,
2578                      ArrayRef<const MemRegion *> Regions,
2579                      const CallEvent *Call) const;
2580 
wantsRegionChangeUpdate(ProgramStateRef state) const2581   bool wantsRegionChangeUpdate(ProgramStateRef state) const {
2582     return true;
2583   }
2584 
2585   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2586   void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2587                                 ExplodedNode *Pred, RetEffect RE, RefVal X,
2588                                 SymbolRef Sym, ProgramStateRef state) const;
2589 
2590   void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
2591   void checkEndFunction(CheckerContext &C) const;
2592 
2593   ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
2594                                RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2595                                CheckerContext &C) const;
2596 
2597   void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
2598                            RefVal::Kind ErrorKind, SymbolRef Sym,
2599                            CheckerContext &C) const;
2600 
2601   void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
2602 
2603   const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2604 
2605   ProgramStateRef handleSymbolDeath(ProgramStateRef state,
2606                                     SymbolRef sid, RefVal V,
2607                                     SmallVectorImpl<SymbolRef> &Leaked) const;
2608 
2609   ProgramStateRef
2610   handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2611                           const ProgramPointTag *Tag, CheckerContext &Ctx,
2612                           SymbolRef Sym, RefVal V) const;
2613 
2614   ExplodedNode *processLeaks(ProgramStateRef state,
2615                              SmallVectorImpl<SymbolRef> &Leaked,
2616                              CheckerContext &Ctx,
2617                              ExplodedNode *Pred = nullptr) const;
2618 };
2619 } // end anonymous namespace
2620 
2621 namespace {
2622 class StopTrackingCallback : public SymbolVisitor {
2623   ProgramStateRef state;
2624 public:
StopTrackingCallback(ProgramStateRef st)2625   StopTrackingCallback(ProgramStateRef st) : state(st) {}
getState() const2626   ProgramStateRef getState() const { return state; }
2627 
VisitSymbol(SymbolRef sym)2628   bool VisitSymbol(SymbolRef sym) override {
2629     state = state->remove<RefBindings>(sym);
2630     return true;
2631   }
2632 };
2633 } // end anonymous namespace
2634 
2635 //===----------------------------------------------------------------------===//
2636 // Handle statements that may have an effect on refcounts.
2637 //===----------------------------------------------------------------------===//
2638 
checkPostStmt(const BlockExpr * BE,CheckerContext & C) const2639 void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2640                                        CheckerContext &C) const {
2641 
2642   // Scan the BlockDecRefExprs for any object the retain count checker
2643   // may be tracking.
2644   if (!BE->getBlockDecl()->hasCaptures())
2645     return;
2646 
2647   ProgramStateRef state = C.getState();
2648   const BlockDataRegion *R =
2649     cast<BlockDataRegion>(state->getSVal(BE,
2650                                          C.getLocationContext()).getAsRegion());
2651 
2652   BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2653                                             E = R->referenced_vars_end();
2654 
2655   if (I == E)
2656     return;
2657 
2658   // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2659   // via captured variables, even though captured variables result in a copy
2660   // and in implicit increment/decrement of a retain count.
2661   SmallVector<const MemRegion*, 10> Regions;
2662   const LocationContext *LC = C.getLocationContext();
2663   MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2664 
2665   for ( ; I != E; ++I) {
2666     const VarRegion *VR = I.getCapturedRegion();
2667     if (VR->getSuperRegion() == R) {
2668       VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2669     }
2670     Regions.push_back(VR);
2671   }
2672 
2673   state =
2674     state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2675                                     Regions.data() + Regions.size()).getState();
2676   C.addTransition(state);
2677 }
2678 
checkPostStmt(const CastExpr * CE,CheckerContext & C) const2679 void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2680                                        CheckerContext &C) const {
2681   const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2682   if (!BE)
2683     return;
2684 
2685   ArgEffect AE = IncRef;
2686 
2687   switch (BE->getBridgeKind()) {
2688     case clang::OBC_Bridge:
2689       // Do nothing.
2690       return;
2691     case clang::OBC_BridgeRetained:
2692       AE = IncRef;
2693       break;
2694     case clang::OBC_BridgeTransfer:
2695       AE = DecRefBridgedTransferred;
2696       break;
2697   }
2698 
2699   ProgramStateRef state = C.getState();
2700   SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
2701   if (!Sym)
2702     return;
2703   const RefVal* T = getRefBinding(state, Sym);
2704   if (!T)
2705     return;
2706 
2707   RefVal::Kind hasErr = (RefVal::Kind) 0;
2708   state = updateSymbol(state, Sym, *T, AE, hasErr, C);
2709 
2710   if (hasErr) {
2711     // FIXME: If we get an error during a bridge cast, should we report it?
2712     // Should we assert that there is no error?
2713     return;
2714   }
2715 
2716   C.addTransition(state);
2717 }
2718 
processObjCLiterals(CheckerContext & C,const Expr * Ex) const2719 void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2720                                              const Expr *Ex) const {
2721   ProgramStateRef state = C.getState();
2722   const ExplodedNode *pred = C.getPredecessor();
2723   for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2724        it != et ; ++it) {
2725     const Stmt *child = *it;
2726     SVal V = state->getSVal(child, pred->getLocationContext());
2727     if (SymbolRef sym = V.getAsSymbol())
2728       if (const RefVal* T = getRefBinding(state, sym)) {
2729         RefVal::Kind hasErr = (RefVal::Kind) 0;
2730         state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2731         if (hasErr) {
2732           processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2733           return;
2734         }
2735       }
2736   }
2737 
2738   // Return the object as autoreleased.
2739   //  RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2740   if (SymbolRef sym =
2741         state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2742     QualType ResultTy = Ex->getType();
2743     state = setRefBinding(state, sym,
2744                           RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
2745   }
2746 
2747   C.addTransition(state);
2748 }
2749 
checkPostStmt(const ObjCArrayLiteral * AL,CheckerContext & C) const2750 void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2751                                        CheckerContext &C) const {
2752   // Apply the 'MayEscape' to all values.
2753   processObjCLiterals(C, AL);
2754 }
2755 
checkPostStmt(const ObjCDictionaryLiteral * DL,CheckerContext & C) const2756 void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2757                                        CheckerContext &C) const {
2758   // Apply the 'MayEscape' to all keys and values.
2759   processObjCLiterals(C, DL);
2760 }
2761 
checkPostStmt(const ObjCBoxedExpr * Ex,CheckerContext & C) const2762 void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2763                                        CheckerContext &C) const {
2764   const ExplodedNode *Pred = C.getPredecessor();
2765   const LocationContext *LCtx = Pred->getLocationContext();
2766   ProgramStateRef State = Pred->getState();
2767 
2768   if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2769     QualType ResultTy = Ex->getType();
2770     State = setRefBinding(State, Sym,
2771                           RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
2772   }
2773 
2774   C.addTransition(State);
2775 }
2776 
checkPostStmt(const ObjCIvarRefExpr * IRE,CheckerContext & C) const2777 void RetainCountChecker::checkPostStmt(const ObjCIvarRefExpr *IRE,
2778                                        CheckerContext &C) const {
2779   ProgramStateRef State = C.getState();
2780   // If an instance variable was previously accessed through a property,
2781   // it may have a synthesized refcount of +0. Override right now that we're
2782   // doing direct access.
2783   if (Optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>())
2784     if (SymbolRef Sym = State->getSVal(*IVarLoc).getAsSymbol())
2785       if (const RefVal *RV = getRefBinding(State, Sym))
2786         if (RV->isOverridable())
2787           State = removeRefBinding(State, Sym);
2788   C.addTransition(State);
2789 }
2790 
checkPostCall(const CallEvent & Call,CheckerContext & C) const2791 void RetainCountChecker::checkPostCall(const CallEvent &Call,
2792                                        CheckerContext &C) const {
2793   RetainSummaryManager &Summaries = getSummaryManager(C);
2794   const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
2795 
2796   if (C.wasInlined) {
2797     processSummaryOfInlined(*Summ, Call, C);
2798     return;
2799   }
2800   checkSummary(*Summ, Call, C);
2801 }
2802 
2803 /// GetReturnType - Used to get the return type of a message expression or
2804 ///  function call with the intention of affixing that type to a tracked symbol.
2805 ///  While the return type can be queried directly from RetEx, when
2806 ///  invoking class methods we augment to the return type to be that of
2807 ///  a pointer to the class (as opposed it just being id).
2808 // FIXME: We may be able to do this with related result types instead.
2809 // This function is probably overestimating.
GetReturnType(const Expr * RetE,ASTContext & Ctx)2810 static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2811   QualType RetTy = RetE->getType();
2812   // If RetE is not a message expression just return its type.
2813   // If RetE is a message expression, return its types if it is something
2814   /// more specific than id.
2815   if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2816     if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2817       if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2818           PT->isObjCClassType()) {
2819         // At this point we know the return type of the message expression is
2820         // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2821         // is a call to a class method whose type we can resolve.  In such
2822         // cases, promote the return type to XXX* (where XXX is the class).
2823         const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2824         return !D ? RetTy :
2825                     Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2826       }
2827 
2828   return RetTy;
2829 }
2830 
wasSynthesizedProperty(const ObjCMethodCall * Call,ExplodedNode * N)2831 static bool wasSynthesizedProperty(const ObjCMethodCall *Call,
2832                                    ExplodedNode *N) {
2833   if (!Call || !Call->getDecl()->isPropertyAccessor())
2834     return false;
2835 
2836   CallExitEnd PP = N->getLocation().castAs<CallExitEnd>();
2837   const StackFrameContext *Frame = PP.getCalleeContext();
2838   return Frame->getAnalysisDeclContext()->isBodyAutosynthesized();
2839 }
2840 
2841 // We don't always get the exact modeling of the function with regards to the
2842 // retain count checker even when the function is inlined. For example, we need
2843 // to stop tracking the symbols which were marked with StopTrackingHard.
processSummaryOfInlined(const RetainSummary & Summ,const CallEvent & CallOrMsg,CheckerContext & C) const2844 void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2845                                                  const CallEvent &CallOrMsg,
2846                                                  CheckerContext &C) const {
2847   ProgramStateRef state = C.getState();
2848 
2849   // Evaluate the effect of the arguments.
2850   for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2851     if (Summ.getArg(idx) == StopTrackingHard) {
2852       SVal V = CallOrMsg.getArgSVal(idx);
2853       if (SymbolRef Sym = V.getAsLocSymbol()) {
2854         state = removeRefBinding(state, Sym);
2855       }
2856     }
2857   }
2858 
2859   // Evaluate the effect on the message receiver.
2860   const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2861   if (MsgInvocation) {
2862     if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2863       if (Summ.getReceiverEffect() == StopTrackingHard) {
2864         state = removeRefBinding(state, Sym);
2865       }
2866     }
2867   }
2868 
2869   // Consult the summary for the return value.
2870   RetEffect RE = Summ.getRetEffect();
2871   if (RE.getKind() == RetEffect::NoRetHard) {
2872     SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
2873     if (Sym)
2874       state = removeRefBinding(state, Sym);
2875   } else if (RE.getKind() == RetEffect::NotOwnedSymbol) {
2876     if (wasSynthesizedProperty(MsgInvocation, C.getPredecessor())) {
2877       // Believe the summary if we synthesized the body of a property getter
2878       // and the return value is currently untracked. If the corresponding
2879       // instance variable is later accessed directly, however, we're going to
2880       // want to override this state, so that the owning object can perform
2881       // reference counting operations on its own ivars.
2882       SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
2883       if (Sym && !getRefBinding(state, Sym))
2884         state = setRefBinding(state, Sym,
2885                               RefVal::makeOverridableNotOwned(RE.getObjKind(),
2886                                                               Sym->getType()));
2887     }
2888   }
2889 
2890   C.addTransition(state);
2891 }
2892 
checkSummary(const RetainSummary & Summ,const CallEvent & CallOrMsg,CheckerContext & C) const2893 void RetainCountChecker::checkSummary(const RetainSummary &Summ,
2894                                       const CallEvent &CallOrMsg,
2895                                       CheckerContext &C) const {
2896   ProgramStateRef state = C.getState();
2897 
2898   // Evaluate the effect of the arguments.
2899   RefVal::Kind hasErr = (RefVal::Kind) 0;
2900   SourceRange ErrorRange;
2901   SymbolRef ErrorSym = nullptr;
2902 
2903   for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2904     SVal V = CallOrMsg.getArgSVal(idx);
2905 
2906     if (SymbolRef Sym = V.getAsLocSymbol()) {
2907       if (const RefVal *T = getRefBinding(state, Sym)) {
2908         state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
2909         if (hasErr) {
2910           ErrorRange = CallOrMsg.getArgSourceRange(idx);
2911           ErrorSym = Sym;
2912           break;
2913         }
2914       }
2915     }
2916   }
2917 
2918   // Evaluate the effect on the message receiver.
2919   bool ReceiverIsTracked = false;
2920   if (!hasErr) {
2921     const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2922     if (MsgInvocation) {
2923       if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2924         if (const RefVal *T = getRefBinding(state, Sym)) {
2925           ReceiverIsTracked = true;
2926           state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
2927                                  hasErr, C);
2928           if (hasErr) {
2929             ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
2930             ErrorSym = Sym;
2931           }
2932         }
2933       }
2934     }
2935   }
2936 
2937   // Process any errors.
2938   if (hasErr) {
2939     processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2940     return;
2941   }
2942 
2943   // Consult the summary for the return value.
2944   RetEffect RE = Summ.getRetEffect();
2945 
2946   if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2947     if (ReceiverIsTracked)
2948       RE = getSummaryManager(C).getObjAllocRetEffect();
2949     else
2950       RE = RetEffect::MakeNoRet();
2951   }
2952 
2953   switch (RE.getKind()) {
2954     default:
2955       llvm_unreachable("Unhandled RetEffect.");
2956 
2957     case RetEffect::NoRet:
2958     case RetEffect::NoRetHard:
2959       // No work necessary.
2960       break;
2961 
2962     case RetEffect::OwnedAllocatedSymbol:
2963     case RetEffect::OwnedSymbol: {
2964       SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
2965       if (!Sym)
2966         break;
2967 
2968       // Use the result type from the CallEvent as it automatically adjusts
2969       // for methods/functions that return references.
2970       QualType ResultTy = CallOrMsg.getResultType();
2971       state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2972                                                           ResultTy));
2973 
2974       // FIXME: Add a flag to the checker where allocations are assumed to
2975       // *not* fail.
2976       break;
2977     }
2978 
2979     case RetEffect::GCNotOwnedSymbol:
2980     case RetEffect::NotOwnedSymbol: {
2981       const Expr *Ex = CallOrMsg.getOriginExpr();
2982       SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
2983       if (!Sym)
2984         break;
2985       assert(Ex);
2986       // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2987       QualType ResultTy = GetReturnType(Ex, C.getASTContext());
2988       state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2989                                                              ResultTy));
2990       break;
2991     }
2992   }
2993 
2994   // This check is actually necessary; otherwise the statement builder thinks
2995   // we've hit a previously-found path.
2996   // Normally addTransition takes care of this, but we want the node pointer.
2997   ExplodedNode *NewNode;
2998   if (state == C.getState()) {
2999     NewNode = C.getPredecessor();
3000   } else {
3001     NewNode = C.addTransition(state);
3002   }
3003 
3004   // Annotate the node with summary we used.
3005   if (NewNode) {
3006     // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
3007     if (ShouldResetSummaryLog) {
3008       SummaryLog.clear();
3009       ShouldResetSummaryLog = false;
3010     }
3011     SummaryLog[NewNode] = &Summ;
3012   }
3013 }
3014 
3015 
3016 ProgramStateRef
updateSymbol(ProgramStateRef state,SymbolRef sym,RefVal V,ArgEffect E,RefVal::Kind & hasErr,CheckerContext & C) const3017 RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
3018                                  RefVal V, ArgEffect E, RefVal::Kind &hasErr,
3019                                  CheckerContext &C) const {
3020   // In GC mode [... release] and [... retain] do nothing.
3021   // In ARC mode they shouldn't exist at all, but we just ignore them.
3022   bool IgnoreRetainMsg = C.isObjCGCEnabled();
3023   if (!IgnoreRetainMsg)
3024     IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
3025 
3026   switch (E) {
3027   default:
3028     break;
3029   case IncRefMsg:
3030     E = IgnoreRetainMsg ? DoNothing : IncRef;
3031     break;
3032   case DecRefMsg:
3033     E = IgnoreRetainMsg ? DoNothing : DecRef;
3034     break;
3035   case DecRefMsgAndStopTrackingHard:
3036     E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
3037     break;
3038   case MakeCollectable:
3039     E = C.isObjCGCEnabled() ? DecRef : DoNothing;
3040     break;
3041   }
3042 
3043   // Handle all use-after-releases.
3044   if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
3045     V = V ^ RefVal::ErrorUseAfterRelease;
3046     hasErr = V.getKind();
3047     return setRefBinding(state, sym, V);
3048   }
3049 
3050   switch (E) {
3051     case DecRefMsg:
3052     case IncRefMsg:
3053     case MakeCollectable:
3054     case DecRefMsgAndStopTrackingHard:
3055       llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
3056 
3057     case Dealloc:
3058       // Any use of -dealloc in GC is *bad*.
3059       if (C.isObjCGCEnabled()) {
3060         V = V ^ RefVal::ErrorDeallocGC;
3061         hasErr = V.getKind();
3062         break;
3063       }
3064 
3065       switch (V.getKind()) {
3066         default:
3067           llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
3068         case RefVal::Owned:
3069           // The object immediately transitions to the released state.
3070           V = V ^ RefVal::Released;
3071           V.clearCounts();
3072           return setRefBinding(state, sym, V);
3073         case RefVal::NotOwned:
3074           V = V ^ RefVal::ErrorDeallocNotOwned;
3075           hasErr = V.getKind();
3076           break;
3077       }
3078       break;
3079 
3080     case MayEscape:
3081       if (V.getKind() == RefVal::Owned) {
3082         V = V ^ RefVal::NotOwned;
3083         break;
3084       }
3085 
3086       // Fall-through.
3087 
3088     case DoNothing:
3089       return state;
3090 
3091     case Autorelease:
3092       if (C.isObjCGCEnabled())
3093         return state;
3094       // Update the autorelease counts.
3095       V = V.autorelease();
3096       break;
3097 
3098     case StopTracking:
3099     case StopTrackingHard:
3100       return removeRefBinding(state, sym);
3101 
3102     case IncRef:
3103       switch (V.getKind()) {
3104         default:
3105           llvm_unreachable("Invalid RefVal state for a retain.");
3106         case RefVal::Owned:
3107         case RefVal::NotOwned:
3108           V = V + 1;
3109           break;
3110         case RefVal::Released:
3111           // Non-GC cases are handled above.
3112           assert(C.isObjCGCEnabled());
3113           V = (V ^ RefVal::Owned) + 1;
3114           break;
3115       }
3116       break;
3117 
3118     case DecRef:
3119     case DecRefBridgedTransferred:
3120     case DecRefAndStopTrackingHard:
3121       switch (V.getKind()) {
3122         default:
3123           // case 'RefVal::Released' handled above.
3124           llvm_unreachable("Invalid RefVal state for a release.");
3125 
3126         case RefVal::Owned:
3127           assert(V.getCount() > 0);
3128           if (V.getCount() == 1)
3129             V = V ^ (E == DecRefBridgedTransferred ? RefVal::NotOwned
3130                                                    : RefVal::Released);
3131           else if (E == DecRefAndStopTrackingHard)
3132             return removeRefBinding(state, sym);
3133 
3134           V = V - 1;
3135           break;
3136 
3137         case RefVal::NotOwned:
3138           if (V.getCount() > 0) {
3139             if (E == DecRefAndStopTrackingHard)
3140               return removeRefBinding(state, sym);
3141             V = V - 1;
3142           } else {
3143             V = V ^ RefVal::ErrorReleaseNotOwned;
3144             hasErr = V.getKind();
3145           }
3146           break;
3147 
3148         case RefVal::Released:
3149           // Non-GC cases are handled above.
3150           assert(C.isObjCGCEnabled());
3151           V = V ^ RefVal::ErrorUseAfterRelease;
3152           hasErr = V.getKind();
3153           break;
3154       }
3155       break;
3156   }
3157   return setRefBinding(state, sym, V);
3158 }
3159 
processNonLeakError(ProgramStateRef St,SourceRange ErrorRange,RefVal::Kind ErrorKind,SymbolRef Sym,CheckerContext & C) const3160 void RetainCountChecker::processNonLeakError(ProgramStateRef St,
3161                                              SourceRange ErrorRange,
3162                                              RefVal::Kind ErrorKind,
3163                                              SymbolRef Sym,
3164                                              CheckerContext &C) const {
3165   ExplodedNode *N = C.generateSink(St);
3166   if (!N)
3167     return;
3168 
3169   CFRefBug *BT;
3170   switch (ErrorKind) {
3171     default:
3172       llvm_unreachable("Unhandled error.");
3173     case RefVal::ErrorUseAfterRelease:
3174       if (!useAfterRelease)
3175         useAfterRelease.reset(new UseAfterRelease(this));
3176       BT = &*useAfterRelease;
3177       break;
3178     case RefVal::ErrorReleaseNotOwned:
3179       if (!releaseNotOwned)
3180         releaseNotOwned.reset(new BadRelease(this));
3181       BT = &*releaseNotOwned;
3182       break;
3183     case RefVal::ErrorDeallocGC:
3184       if (!deallocGC)
3185         deallocGC.reset(new DeallocGC(this));
3186       BT = &*deallocGC;
3187       break;
3188     case RefVal::ErrorDeallocNotOwned:
3189       if (!deallocNotOwned)
3190         deallocNotOwned.reset(new DeallocNotOwned(this));
3191       BT = &*deallocNotOwned;
3192       break;
3193   }
3194 
3195   assert(BT);
3196   CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
3197                                         C.isObjCGCEnabled(), SummaryLog,
3198                                         N, Sym);
3199   report->addRange(ErrorRange);
3200   C.emitReport(report);
3201 }
3202 
3203 //===----------------------------------------------------------------------===//
3204 // Handle the return values of retain-count-related functions.
3205 //===----------------------------------------------------------------------===//
3206 
evalCall(const CallExpr * CE,CheckerContext & C) const3207 bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
3208   // Get the callee. We're only interested in simple C functions.
3209   ProgramStateRef state = C.getState();
3210   const FunctionDecl *FD = C.getCalleeDecl(CE);
3211   if (!FD)
3212     return false;
3213 
3214   IdentifierInfo *II = FD->getIdentifier();
3215   if (!II)
3216     return false;
3217 
3218   // For now, we're only handling the functions that return aliases of their
3219   // arguments: CFRetain and CFMakeCollectable (and their families).
3220   // Eventually we should add other functions we can model entirely,
3221   // such as CFRelease, which don't invalidate their arguments or globals.
3222   if (CE->getNumArgs() != 1)
3223     return false;
3224 
3225   // Get the name of the function.
3226   StringRef FName = II->getName();
3227   FName = FName.substr(FName.find_first_not_of('_'));
3228 
3229   // See if it's one of the specific functions we know how to eval.
3230   bool canEval = false;
3231 
3232   QualType ResultTy = CE->getCallReturnType();
3233   if (ResultTy->isObjCIdType()) {
3234     // Handle: id NSMakeCollectable(CFTypeRef)
3235     canEval = II->isStr("NSMakeCollectable");
3236   } else if (ResultTy->isPointerType()) {
3237     // Handle: (CF|CG)Retain
3238     //         CFAutorelease
3239     //         CFMakeCollectable
3240     // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3241     if (cocoa::isRefType(ResultTy, "CF", FName) ||
3242         cocoa::isRefType(ResultTy, "CG", FName)) {
3243       canEval = isRetain(FD, FName) || isAutorelease(FD, FName) ||
3244                 isMakeCollectable(FD, FName);
3245     }
3246   }
3247 
3248   if (!canEval)
3249     return false;
3250 
3251   // Bind the return value.
3252   const LocationContext *LCtx = C.getLocationContext();
3253   SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
3254   if (RetVal.isUnknown()) {
3255     // If the receiver is unknown, conjure a return value.
3256     SValBuilder &SVB = C.getSValBuilder();
3257     RetVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, ResultTy, C.blockCount());
3258   }
3259   state = state->BindExpr(CE, LCtx, RetVal, false);
3260 
3261   // FIXME: This should not be necessary, but otherwise the argument seems to be
3262   // considered alive during the next statement.
3263   if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3264     // Save the refcount status of the argument.
3265     SymbolRef Sym = RetVal.getAsLocSymbol();
3266     const RefVal *Binding = nullptr;
3267     if (Sym)
3268       Binding = getRefBinding(state, Sym);
3269 
3270     // Invalidate the argument region.
3271     state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
3272                                      /*CausesPointerEscape*/ false);
3273 
3274     // Restore the refcount status of the argument.
3275     if (Binding)
3276       state = setRefBinding(state, Sym, *Binding);
3277   }
3278 
3279   C.addTransition(state);
3280   return true;
3281 }
3282 
3283 //===----------------------------------------------------------------------===//
3284 // Handle return statements.
3285 //===----------------------------------------------------------------------===//
3286 
checkPreStmt(const ReturnStmt * S,CheckerContext & C) const3287 void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3288                                       CheckerContext &C) const {
3289 
3290   // Only adjust the reference count if this is the top-level call frame,
3291   // and not the result of inlining.  In the future, we should do
3292   // better checking even for inlined calls, and see if they match
3293   // with their expected semantics (e.g., the method should return a retained
3294   // object, etc.).
3295   if (!C.inTopFrame())
3296     return;
3297 
3298   const Expr *RetE = S->getRetValue();
3299   if (!RetE)
3300     return;
3301 
3302   ProgramStateRef state = C.getState();
3303   SymbolRef Sym =
3304     state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
3305   if (!Sym)
3306     return;
3307 
3308   // Get the reference count binding (if any).
3309   const RefVal *T = getRefBinding(state, Sym);
3310   if (!T)
3311     return;
3312 
3313   // Change the reference count.
3314   RefVal X = *T;
3315 
3316   switch (X.getKind()) {
3317     case RefVal::Owned: {
3318       unsigned cnt = X.getCount();
3319       assert(cnt > 0);
3320       X.setCount(cnt - 1);
3321       X = X ^ RefVal::ReturnedOwned;
3322       break;
3323     }
3324 
3325     case RefVal::NotOwned: {
3326       unsigned cnt = X.getCount();
3327       if (cnt) {
3328         X.setCount(cnt - 1);
3329         X = X ^ RefVal::ReturnedOwned;
3330       }
3331       else {
3332         X = X ^ RefVal::ReturnedNotOwned;
3333       }
3334       break;
3335     }
3336 
3337     default:
3338       return;
3339   }
3340 
3341   // Update the binding.
3342   state = setRefBinding(state, Sym, X);
3343   ExplodedNode *Pred = C.addTransition(state);
3344 
3345   // At this point we have updated the state properly.
3346   // Everything after this is merely checking to see if the return value has
3347   // been over- or under-retained.
3348 
3349   // Did we cache out?
3350   if (!Pred)
3351     return;
3352 
3353   // Update the autorelease counts.
3354   static CheckerProgramPointTag AutoreleaseTag(this, "Autorelease");
3355   state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
3356 
3357   // Did we cache out?
3358   if (!state)
3359     return;
3360 
3361   // Get the updated binding.
3362   T = getRefBinding(state, Sym);
3363   assert(T);
3364   X = *T;
3365 
3366   // Consult the summary of the enclosing method.
3367   RetainSummaryManager &Summaries = getSummaryManager(C);
3368   const Decl *CD = &Pred->getCodeDecl();
3369   RetEffect RE = RetEffect::MakeNoRet();
3370 
3371   // FIXME: What is the convention for blocks? Is there one?
3372   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
3373     const RetainSummary *Summ = Summaries.getMethodSummary(MD);
3374     RE = Summ->getRetEffect();
3375   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3376     if (!isa<CXXMethodDecl>(FD)) {
3377       const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3378       RE = Summ->getRetEffect();
3379     }
3380   }
3381 
3382   checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
3383 }
3384 
checkReturnWithRetEffect(const ReturnStmt * S,CheckerContext & C,ExplodedNode * Pred,RetEffect RE,RefVal X,SymbolRef Sym,ProgramStateRef state) const3385 void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3386                                                   CheckerContext &C,
3387                                                   ExplodedNode *Pred,
3388                                                   RetEffect RE, RefVal X,
3389                                                   SymbolRef Sym,
3390                                               ProgramStateRef state) const {
3391   // Any leaks or other errors?
3392   if (X.isReturnedOwned() && X.getCount() == 0) {
3393     if (RE.getKind() != RetEffect::NoRet) {
3394       bool hasError = false;
3395       if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3396         // Things are more complicated with garbage collection.  If the
3397         // returned object is suppose to be an Objective-C object, we have
3398         // a leak (as the caller expects a GC'ed object) because no
3399         // method should return ownership unless it returns a CF object.
3400         hasError = true;
3401         X = X ^ RefVal::ErrorGCLeakReturned;
3402       }
3403       else if (!RE.isOwned()) {
3404         // Either we are using GC and the returned object is a CF type
3405         // or we aren't using GC.  In either case, we expect that the
3406         // enclosing method is expected to return ownership.
3407         hasError = true;
3408         X = X ^ RefVal::ErrorLeakReturned;
3409       }
3410 
3411       if (hasError) {
3412         // Generate an error node.
3413         state = setRefBinding(state, Sym, X);
3414 
3415         static CheckerProgramPointTag ReturnOwnLeakTag(this, "ReturnsOwnLeak");
3416         ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
3417         if (N) {
3418           const LangOptions &LOpts = C.getASTContext().getLangOpts();
3419           bool GCEnabled = C.isObjCGCEnabled();
3420           CFRefReport *report =
3421             new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3422                                 LOpts, GCEnabled, SummaryLog,
3423                                 N, Sym, C, IncludeAllocationLine);
3424 
3425           C.emitReport(report);
3426         }
3427       }
3428     }
3429   } else if (X.isReturnedNotOwned()) {
3430     if (RE.isOwned()) {
3431       // Trying to return a not owned object to a caller expecting an
3432       // owned object.
3433       state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
3434 
3435       static CheckerProgramPointTag ReturnNotOwnedTag(this,
3436                                                       "ReturnNotOwnedForOwned");
3437       ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
3438       if (N) {
3439         if (!returnNotOwnedForOwned)
3440           returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned(this));
3441 
3442         CFRefReport *report =
3443             new CFRefReport(*returnNotOwnedForOwned,
3444                             C.getASTContext().getLangOpts(),
3445                             C.isObjCGCEnabled(), SummaryLog, N, Sym);
3446         C.emitReport(report);
3447       }
3448     }
3449   }
3450 }
3451 
3452 //===----------------------------------------------------------------------===//
3453 // Check various ways a symbol can be invalidated.
3454 //===----------------------------------------------------------------------===//
3455 
checkBind(SVal loc,SVal val,const Stmt * S,CheckerContext & C) const3456 void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
3457                                    CheckerContext &C) const {
3458   // Are we storing to something that causes the value to "escape"?
3459   bool escapes = true;
3460 
3461   // A value escapes in three possible cases (this may change):
3462   //
3463   // (1) we are binding to something that is not a memory region.
3464   // (2) we are binding to a memregion that does not have stack storage
3465   // (3) we are binding to a memregion with stack storage that the store
3466   //     does not understand.
3467   ProgramStateRef state = C.getState();
3468 
3469   if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
3470     escapes = !regionLoc->getRegion()->hasStackStorage();
3471 
3472     if (!escapes) {
3473       // To test (3), generate a new state with the binding added.  If it is
3474       // the same state, then it escapes (since the store cannot represent
3475       // the binding).
3476       // Do this only if we know that the store is not supposed to generate the
3477       // same state.
3478       SVal StoredVal = state->getSVal(regionLoc->getRegion());
3479       if (StoredVal != val)
3480         escapes = (state == (state->bindLoc(*regionLoc, val)));
3481     }
3482     if (!escapes) {
3483       // Case 4: We do not currently model what happens when a symbol is
3484       // assigned to a struct field, so be conservative here and let the symbol
3485       // go. TODO: This could definitely be improved upon.
3486       escapes = !isa<VarRegion>(regionLoc->getRegion());
3487     }
3488   }
3489 
3490   // If we are storing the value into an auto function scope variable annotated
3491   // with (__attribute__((cleanup))), stop tracking the value to avoid leak
3492   // false positives.
3493   if (const VarRegion *LVR = dyn_cast_or_null<VarRegion>(loc.getAsRegion())) {
3494     const VarDecl *VD = LVR->getDecl();
3495     if (VD->hasAttr<CleanupAttr>()) {
3496       escapes = true;
3497     }
3498   }
3499 
3500   // If our store can represent the binding and we aren't storing to something
3501   // that doesn't have local storage then just return and have the simulation
3502   // state continue as is.
3503   if (!escapes)
3504       return;
3505 
3506   // Otherwise, find all symbols referenced by 'val' that we are tracking
3507   // and stop tracking them.
3508   state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
3509   C.addTransition(state);
3510 }
3511 
evalAssume(ProgramStateRef state,SVal Cond,bool Assumption) const3512 ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
3513                                                    SVal Cond,
3514                                                    bool Assumption) const {
3515 
3516   // FIXME: We may add to the interface of evalAssume the list of symbols
3517   //  whose assumptions have changed.  For now we just iterate through the
3518   //  bindings and check if any of the tracked symbols are NULL.  This isn't
3519   //  too bad since the number of symbols we will track in practice are
3520   //  probably small and evalAssume is only called at branches and a few
3521   //  other places.
3522   RefBindingsTy B = state->get<RefBindings>();
3523 
3524   if (B.isEmpty())
3525     return state;
3526 
3527   bool changed = false;
3528   RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
3529 
3530   for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3531     // Check if the symbol is null stop tracking the symbol.
3532     ConstraintManager &CMgr = state->getConstraintManager();
3533     ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3534     if (AllocFailed.isConstrainedTrue()) {
3535       changed = true;
3536       B = RefBFactory.remove(B, I.getKey());
3537     }
3538   }
3539 
3540   if (changed)
3541     state = state->set<RefBindings>(B);
3542 
3543   return state;
3544 }
3545 
3546 ProgramStateRef
checkRegionChanges(ProgramStateRef state,const InvalidatedSymbols * invalidated,ArrayRef<const MemRegion * > ExplicitRegions,ArrayRef<const MemRegion * > Regions,const CallEvent * Call) const3547 RetainCountChecker::checkRegionChanges(ProgramStateRef state,
3548                                     const InvalidatedSymbols *invalidated,
3549                                     ArrayRef<const MemRegion *> ExplicitRegions,
3550                                     ArrayRef<const MemRegion *> Regions,
3551                                     const CallEvent *Call) const {
3552   if (!invalidated)
3553     return state;
3554 
3555   llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3556   for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3557        E = ExplicitRegions.end(); I != E; ++I) {
3558     if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3559       WhitelistedSymbols.insert(SR->getSymbol());
3560   }
3561 
3562   for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
3563        E = invalidated->end(); I!=E; ++I) {
3564     SymbolRef sym = *I;
3565     if (WhitelistedSymbols.count(sym))
3566       continue;
3567     // Remove any existing reference-count binding.
3568     state = removeRefBinding(state, sym);
3569   }
3570   return state;
3571 }
3572 
3573 //===----------------------------------------------------------------------===//
3574 // Handle dead symbols and end-of-path.
3575 //===----------------------------------------------------------------------===//
3576 
3577 ProgramStateRef
handleAutoreleaseCounts(ProgramStateRef state,ExplodedNode * Pred,const ProgramPointTag * Tag,CheckerContext & Ctx,SymbolRef Sym,RefVal V) const3578 RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
3579                                             ExplodedNode *Pred,
3580                                             const ProgramPointTag *Tag,
3581                                             CheckerContext &Ctx,
3582                                             SymbolRef Sym, RefVal V) const {
3583   unsigned ACnt = V.getAutoreleaseCount();
3584 
3585   // No autorelease counts?  Nothing to be done.
3586   if (!ACnt)
3587     return state;
3588 
3589   assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
3590   unsigned Cnt = V.getCount();
3591 
3592   // FIXME: Handle sending 'autorelease' to already released object.
3593 
3594   if (V.getKind() == RefVal::ReturnedOwned)
3595     ++Cnt;
3596 
3597   if (ACnt <= Cnt) {
3598     if (ACnt == Cnt) {
3599       V.clearCounts();
3600       if (V.getKind() == RefVal::ReturnedOwned)
3601         V = V ^ RefVal::ReturnedNotOwned;
3602       else
3603         V = V ^ RefVal::NotOwned;
3604     } else {
3605       V.setCount(V.getCount() - ACnt);
3606       V.setAutoreleaseCount(0);
3607     }
3608     return setRefBinding(state, Sym, V);
3609   }
3610 
3611   // Woah!  More autorelease counts then retain counts left.
3612   // Emit hard error.
3613   V = V ^ RefVal::ErrorOverAutorelease;
3614   state = setRefBinding(state, Sym, V);
3615 
3616   ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
3617   if (N) {
3618     SmallString<128> sbuf;
3619     llvm::raw_svector_ostream os(sbuf);
3620     os << "Object was autoreleased ";
3621     if (V.getAutoreleaseCount() > 1)
3622       os << V.getAutoreleaseCount() << " times but the object ";
3623     else
3624       os << "but ";
3625     os << "has a +" << V.getCount() << " retain count";
3626 
3627     if (!overAutorelease)
3628       overAutorelease.reset(new OverAutorelease(this));
3629 
3630     const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3631     CFRefReport *report =
3632       new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3633                       SummaryLog, N, Sym, os.str());
3634     Ctx.emitReport(report);
3635   }
3636 
3637   return nullptr;
3638 }
3639 
3640 ProgramStateRef
handleSymbolDeath(ProgramStateRef state,SymbolRef sid,RefVal V,SmallVectorImpl<SymbolRef> & Leaked) const3641 RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
3642                                       SymbolRef sid, RefVal V,
3643                                     SmallVectorImpl<SymbolRef> &Leaked) const {
3644   bool hasLeak = false;
3645   if (V.isOwned())
3646     hasLeak = true;
3647   else if (V.isNotOwned() || V.isReturnedOwned())
3648     hasLeak = (V.getCount() > 0);
3649 
3650   if (!hasLeak)
3651     return removeRefBinding(state, sid);
3652 
3653   Leaked.push_back(sid);
3654   return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
3655 }
3656 
3657 ExplodedNode *
processLeaks(ProgramStateRef state,SmallVectorImpl<SymbolRef> & Leaked,CheckerContext & Ctx,ExplodedNode * Pred) const3658 RetainCountChecker::processLeaks(ProgramStateRef state,
3659                                  SmallVectorImpl<SymbolRef> &Leaked,
3660                                  CheckerContext &Ctx,
3661                                  ExplodedNode *Pred) const {
3662   // Generate an intermediate node representing the leak point.
3663   ExplodedNode *N = Ctx.addTransition(state, Pred);
3664 
3665   if (N) {
3666     for (SmallVectorImpl<SymbolRef>::iterator
3667          I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3668 
3669       const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3670       bool GCEnabled = Ctx.isObjCGCEnabled();
3671       CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3672                           : getLeakAtReturnBug(LOpts, GCEnabled);
3673       assert(BT && "BugType not initialized.");
3674 
3675       CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
3676                                                     SummaryLog, N, *I, Ctx,
3677                                                     IncludeAllocationLine);
3678       Ctx.emitReport(report);
3679     }
3680   }
3681 
3682   return N;
3683 }
3684 
checkEndFunction(CheckerContext & Ctx) const3685 void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
3686   ProgramStateRef state = Ctx.getState();
3687   RefBindingsTy B = state->get<RefBindings>();
3688   ExplodedNode *Pred = Ctx.getPredecessor();
3689 
3690   // Don't process anything within synthesized bodies.
3691   const LocationContext *LCtx = Pred->getLocationContext();
3692   if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
3693     assert(LCtx->getParent());
3694     return;
3695   }
3696 
3697   for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3698     state = handleAutoreleaseCounts(state, Pred, /*Tag=*/nullptr, Ctx,
3699                                     I->first, I->second);
3700     if (!state)
3701       return;
3702   }
3703 
3704   // If the current LocationContext has a parent, don't check for leaks.
3705   // We will do that later.
3706   // FIXME: we should instead check for imbalances of the retain/releases,
3707   // and suggest annotations.
3708   if (LCtx->getParent())
3709     return;
3710 
3711   B = state->get<RefBindings>();
3712   SmallVector<SymbolRef, 10> Leaked;
3713 
3714   for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
3715     state = handleSymbolDeath(state, I->first, I->second, Leaked);
3716 
3717   processLeaks(state, Leaked, Ctx, Pred);
3718 }
3719 
3720 const ProgramPointTag *
getDeadSymbolTag(SymbolRef sym) const3721 RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
3722   const CheckerProgramPointTag *&tag = DeadSymbolTags[sym];
3723   if (!tag) {
3724     SmallString<64> buf;
3725     llvm::raw_svector_ostream out(buf);
3726     out << "Dead Symbol : ";
3727     sym->dumpToStream(out);
3728     tag = new CheckerProgramPointTag(this, out.str());
3729   }
3730   return tag;
3731 }
3732 
checkDeadSymbols(SymbolReaper & SymReaper,CheckerContext & C) const3733 void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3734                                           CheckerContext &C) const {
3735   ExplodedNode *Pred = C.getPredecessor();
3736 
3737   ProgramStateRef state = C.getState();
3738   RefBindingsTy B = state->get<RefBindings>();
3739   SmallVector<SymbolRef, 10> Leaked;
3740 
3741   // Update counts from autorelease pools
3742   for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3743        E = SymReaper.dead_end(); I != E; ++I) {
3744     SymbolRef Sym = *I;
3745     if (const RefVal *T = B.lookup(Sym)){
3746       // Use the symbol as the tag.
3747       // FIXME: This might not be as unique as we would like.
3748       const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
3749       state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
3750       if (!state)
3751         return;
3752 
3753       // Fetch the new reference count from the state, and use it to handle
3754       // this symbol.
3755       state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
3756     }
3757   }
3758 
3759   if (Leaked.empty()) {
3760     C.addTransition(state);
3761     return;
3762   }
3763 
3764   Pred = processLeaks(state, Leaked, C, Pred);
3765 
3766   // Did we cache out?
3767   if (!Pred)
3768     return;
3769 
3770   // Now generate a new node that nukes the old bindings.
3771   // The only bindings left at this point are the leaked symbols.
3772   RefBindingsTy::Factory &F = state->get_context<RefBindings>();
3773   B = state->get<RefBindings>();
3774 
3775   for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3776                                             E = Leaked.end();
3777        I != E; ++I)
3778     B = F.remove(B, *I);
3779 
3780   state = state->set<RefBindings>(B);
3781   C.addTransition(state, Pred);
3782 }
3783 
printState(raw_ostream & Out,ProgramStateRef State,const char * NL,const char * Sep) const3784 void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
3785                                     const char *NL, const char *Sep) const {
3786 
3787   RefBindingsTy B = State->get<RefBindings>();
3788 
3789   if (B.isEmpty())
3790     return;
3791 
3792   Out << Sep << NL;
3793 
3794   for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3795     Out << I->first << " : ";
3796     I->second.print(Out);
3797     Out << NL;
3798   }
3799 }
3800 
3801 //===----------------------------------------------------------------------===//
3802 // Checker registration.
3803 //===----------------------------------------------------------------------===//
3804 
registerRetainCountChecker(CheckerManager & Mgr)3805 void ento::registerRetainCountChecker(CheckerManager &Mgr) {
3806   Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
3807 }
3808 
3809 //===----------------------------------------------------------------------===//
3810 // Implementation of the CallEffects API.
3811 //===----------------------------------------------------------------------===//
3812 
3813 namespace clang { namespace ento { namespace objc_retain {
3814 
3815 // This is a bit gross, but it allows us to populate CallEffects without
3816 // creating a bunch of accessors.  This kind is very localized, so the
3817 // damage of this macro is limited.
3818 #define createCallEffect(D, KIND)\
3819   ASTContext &Ctx = D->getASTContext();\
3820   LangOptions L = Ctx.getLangOpts();\
3821   RetainSummaryManager M(Ctx, L.GCOnly, L.ObjCAutoRefCount);\
3822   const RetainSummary *S = M.get ## KIND ## Summary(D);\
3823   CallEffects CE(S->getRetEffect());\
3824   CE.Receiver = S->getReceiverEffect();\
3825   unsigned N = D->param_size();\
3826   for (unsigned i = 0; i < N; ++i) {\
3827     CE.Args.push_back(S->getArg(i));\
3828   }
3829 
getEffect(const ObjCMethodDecl * MD)3830 CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) {
3831   createCallEffect(MD, Method);
3832   return CE;
3833 }
3834 
getEffect(const FunctionDecl * FD)3835 CallEffects CallEffects::getEffect(const FunctionDecl *FD) {
3836   createCallEffect(FD, Function);
3837   return CE;
3838 }
3839 
3840 #undef createCallEffect
3841 
3842 }}}
3843