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