clang  6.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 
1066  // FIXME: This should all be refactored into a chain of "summary lookup"
1067  // filters.
1068  assert(ScratchArgs.isEmpty());
1069 
1070  if (FName == "pthread_create" || FName == "pthread_setspecific") {
1071  // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1072  // This will be addressed better with IPA.
1073  S = getPersistentStopSummary();
1074  } else if (FName == "NSMakeCollectable") {
1075  // Handle: id NSMakeCollectable(CFTypeRef)
1076  S = (RetTy->isObjCIdType())
1077  ? getUnarySummary(FT, cfmakecollectable)
1078  : getPersistentStopSummary();
1079  // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1080  // but we can fully model NSMakeCollectable ourselves.
1081  AllowAnnotations = false;
1082  } else if (FName == "CFPlugInInstanceCreate") {
1083  S = getPersistentSummary(RetEffect::MakeNoRet());
1084  } else if (FName == "IOBSDNameMatching" ||
1085  FName == "IOServiceMatching" ||
1086  FName == "IOServiceNameMatching" ||
1087  FName == "IORegistryEntrySearchCFProperty" ||
1088  FName == "IORegistryEntryIDMatching" ||
1089  FName == "IOOpenFirmwarePathMatching") {
1090  // Part of <rdar://problem/6961230>. (IOKit)
1091  // This should be addressed using a API table.
1092  S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF),
1093  DoNothing, DoNothing);
1094  } else if (FName == "IOServiceGetMatchingService" ||
1095  FName == "IOServiceGetMatchingServices") {
1096  // FIXES: <rdar://problem/6326900>
1097  // This should be addressed using a API table. This strcmp is also
1098  // a little gross, but there is no need to super optimize here.
1099  ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
1100  S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1101  } else if (FName == "IOServiceAddNotification" ||
1102  FName == "IOServiceAddMatchingNotification") {
1103  // Part of <rdar://problem/6961230>. (IOKit)
1104  // This should be addressed using a API table.
1105  ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
1106  S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1107  } else if (FName == "CVPixelBufferCreateWithBytes") {
1108  // FIXES: <rdar://problem/7283567>
1109  // Eventually this can be improved by recognizing that the pixel
1110  // buffer passed to CVPixelBufferCreateWithBytes is released via
1111  // a callback and doing full IPA to make sure this is done correctly.
1112  // FIXME: This function has an out parameter that returns an
1113  // allocated object.
1114  ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
1115  S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1116  } else if (FName == "CGBitmapContextCreateWithData") {
1117  // FIXES: <rdar://problem/7358899>
1118  // Eventually this can be improved by recognizing that 'releaseInfo'
1119  // passed to CGBitmapContextCreateWithData is released via
1120  // a callback and doing full IPA to make sure this is done correctly.
1121  ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
1122  S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF),
1123  DoNothing, DoNothing);
1124  } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1125  // FIXES: <rdar://problem/7283567>
1126  // Eventually this can be improved by recognizing that the pixel
1127  // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1128  // via a callback and doing full IPA to make sure this is done
1129  // correctly.
1130  ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
1131  S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1132  } else if (FName == "VTCompressionSessionEncodeFrame") {
1133  // The context argument passed to VTCompressionSessionEncodeFrame()
1134  // is passed to the callback specified when creating the session
1135  // (e.g. with VTCompressionSessionCreate()) which can release it.
1136  // To account for this possibility, conservatively stop tracking
1137  // the context.
1138  ScratchArgs = AF.add(ScratchArgs, 5, StopTracking);
1139  S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1140  } else if (FName == "dispatch_set_context" ||
1141  FName == "xpc_connection_set_context") {
1142  // <rdar://problem/11059275> - The analyzer currently doesn't have
1143  // a good way to reason about the finalizer function for libdispatch.
1144  // If we pass a context object that is memory managed, stop tracking it.
1145  // <rdar://problem/13783514> - Same problem, but for XPC.
1146  // FIXME: this hack should possibly go away once we can handle
1147  // libdispatch and XPC finalizers.
1148  ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1149  S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1150  } else if (FName.startswith("NSLog")) {
1151  S = getDoNothingSummary();
1152  } else if (FName.startswith("NS") &&
1153  (FName.find("Insert") != StringRef::npos)) {
1154  // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1155  // be deallocated by NSMapRemove. (radar://11152419)
1156  ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1157  ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1158  S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1159  }
1160 
1161  // Did we get a summary?
1162  if (S)
1163  break;
1164 
1165  if (RetTy->isPointerType()) {
1166  // For CoreFoundation ('CF') types.
1167  if (cocoa::isRefType(RetTy, "CF", FName)) {
1168  if (isRetain(FD, FName)) {
1169  S = getUnarySummary(FT, cfretain);
1170  } else if (isAutorelease(FD, FName)) {
1171  S = getUnarySummary(FT, cfautorelease);
1172  // The headers use cf_consumed, but we can fully model CFAutorelease
1173  // ourselves.
1174  AllowAnnotations = false;
1175  } else if (isMakeCollectable(FD, FName)) {
1176  S = getUnarySummary(FT, cfmakecollectable);
1177  AllowAnnotations = false;
1178  } else {
1179  S = getCFCreateGetRuleSummary(FD);
1180  }
1181 
1182  break;
1183  }
1184 
1185  // For CoreGraphics ('CG') and CoreVideo ('CV') types.
1186  if (cocoa::isRefType(RetTy, "CG", FName) ||
1187  cocoa::isRefType(RetTy, "CV", FName)) {
1188  if (isRetain(FD, FName))
1189  S = getUnarySummary(FT, cfretain);
1190  else
1191  S = getCFCreateGetRuleSummary(FD);
1192 
1193  break;
1194  }
1195 
1196  // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1197  if (cocoa::isRefType(RetTy, "DADisk") ||
1198  cocoa::isRefType(RetTy, "DADissenter") ||
1199  cocoa::isRefType(RetTy, "DASessionRef")) {
1200  S = getCFCreateGetRuleSummary(FD);
1201  break;
1202  }
1203 
1204  if (FD->hasAttr<CFAuditedTransferAttr>()) {
1205  S = getCFCreateGetRuleSummary(FD);
1206  break;
1207  }
1208 
1209  break;
1210  }
1211 
1212  // Check for release functions, the only kind of functions that we care
1213  // about that don't return a pointer type.
1214  if (FName.size() >= 2 &&
1215  FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
1216  // Test for 'CGCF'.
1217  FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
1218 
1219  if (isRelease(FD, FName))
1220  S = getUnarySummary(FT, cfrelease);
1221  else {
1222  assert (ScratchArgs.isEmpty());
1223  // Remaining CoreFoundation and CoreGraphics functions.
1224  // We use to assume that they all strictly followed the ownership idiom
1225  // and that ownership cannot be transferred. While this is technically
1226  // correct, many methods allow a tracked object to escape. For example:
1227  //
1228  // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1229  // CFDictionaryAddValue(y, key, x);
1230  // CFRelease(x);
1231  // ... it is okay to use 'x' since 'y' has a reference to it
1232  //
1233  // We handle this and similar cases with the follow heuristic. If the
1234  // function name contains "InsertValue", "SetValue", "AddValue",
1235  // "AppendValue", or "SetAttribute", then we assume that arguments may
1236  // "escape." This means that something else holds on to the object,
1237  // allowing it be used even after its local retain count drops to 0.
1238  ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1239  StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1240  StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1241  StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
1242  StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
1243  ? MayEscape : DoNothing;
1244 
1245  S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
1246  }
1247  }
1248  }
1249  while (0);
1250 
1251  // If we got all the way here without any luck, use a default summary.
1252  if (!S)
1253  S = getDefaultSummary();
1254 
1255  // Annotations override defaults.
1256  if (AllowAnnotations)
1257  updateSummaryFromAnnotations(S, FD);
1258 
1259  FuncSummaries[FD] = S;
1260  return S;
1261 }
1262 
1263 const RetainSummary *
1264 RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1266  return getCFSummaryCreateRule(FD);
1267 
1268  return getCFSummaryGetRule(FD);
1269 }
1270 
1271 const RetainSummary *
1272 RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1273  UnaryFuncKind func) {
1274 
1275  // Sanity check that this is *really* a unary function. This can
1276  // happen if people do weird things.
1277  const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
1278  if (!FTP || FTP->getNumParams() != 1)
1279  return getPersistentStopSummary();
1280 
1281  assert (ScratchArgs.isEmpty());
1282 
1283  ArgEffect Effect;
1284  switch (func) {
1285  case cfretain: Effect = IncRef; break;
1286  case cfrelease: Effect = DecRef; break;
1287  case cfautorelease: Effect = Autorelease; break;
1288  case cfmakecollectable: Effect = MakeCollectable; break;
1289  }
1290 
1291  ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1292  return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1293 }
1294 
1295 const RetainSummary *
1296 RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
1297  assert (ScratchArgs.isEmpty());
1298 
1299  return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF));
1300 }
1301 
1302 const RetainSummary *
1303 RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
1304  assert (ScratchArgs.isEmpty());
1305  return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1306  DoNothing, DoNothing);
1307 }
1308 
1309 /// Returns true if the declaration 'D' is annotated with 'rcAnnotation'.
1310 static bool hasRCAnnotation(const Decl *D, StringRef rcAnnotation) {
1311  for (const auto *Ann : D->specific_attrs<AnnotateAttr>()) {
1312  if (Ann->getAnnotation() == rcAnnotation)
1313  return true;
1314  }
1315  return false;
1316 }
1317 
1318 /// Returns true if the function declaration 'FD' contains
1319 /// 'rc_ownership_trusted_implementation' annotate attribute.
1321  return hasRCAnnotation(FD, "rc_ownership_trusted_implementation");
1322 }
1323 
1325  if (Ty.getAsString().substr(0, 4) == "isl_")
1326  return true;
1327  else
1328  return false;
1329 }
1330 
1331 //===----------------------------------------------------------------------===//
1332 // Summary creation for Selectors.
1333 //===----------------------------------------------------------------------===//
1334 
1336 RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
1337  const Decl *D) {
1338  if (cocoa::isCocoaObjectRef(RetTy)) {
1339  if (D->hasAttr<NSReturnsRetainedAttr>())
1340  return ObjCAllocRetE;
1341 
1342  if (D->hasAttr<NSReturnsNotRetainedAttr>() ||
1343  D->hasAttr<NSReturnsAutoreleasedAttr>())
1345 
1346  } else if (!RetTy->isPointerType()) {
1347  return None;
1348  }
1349 
1350  if (D->hasAttr<CFReturnsRetainedAttr>())
1352  else if (hasRCAnnotation(D, "rc_ownership_returns_retained"))
1354 
1355  if (D->hasAttr<CFReturnsNotRetainedAttr>())
1357 
1358  return None;
1359 }
1360 
1361 void
1362 RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1363  const FunctionDecl *FD) {
1364  if (!FD)
1365  return;
1366 
1367  assert(Summ && "Must have a summary to add annotations to.");
1368  RetainSummaryTemplate Template(Summ, *this);
1369 
1370  // Effects on the parameters.
1371  unsigned parm_idx = 0;
1373  pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
1374  const ParmVarDecl *pd = *pi;
1375  if (pd->hasAttr<NSConsumedAttr>())
1376  Template->addArg(AF, parm_idx, DecRefMsg);
1377  else if (pd->hasAttr<CFConsumedAttr>() ||
1378  hasRCAnnotation(pd, "rc_ownership_consumed"))
1379  Template->addArg(AF, parm_idx, DecRef);
1380  else if (pd->hasAttr<CFReturnsRetainedAttr>() ||
1381  hasRCAnnotation(pd, "rc_ownership_returns_retained")) {
1382  QualType PointeeTy = pd->getType()->getPointeeType();
1383  if (!PointeeTy.isNull())
1384  if (coreFoundation::isCFObjectRef(PointeeTy))
1385  Template->addArg(AF, parm_idx, RetainedOutParameter);
1386  } else if (pd->hasAttr<CFReturnsNotRetainedAttr>()) {
1387  QualType PointeeTy = pd->getType()->getPointeeType();
1388  if (!PointeeTy.isNull())
1389  if (coreFoundation::isCFObjectRef(PointeeTy))
1390  Template->addArg(AF, parm_idx, UnretainedOutParameter);
1391  }
1392  }
1393 
1394  QualType RetTy = FD->getReturnType();
1395  if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
1396  Template->setRetEffect(*RetE);
1397 }
1398 
1399 void
1400 RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1401  const ObjCMethodDecl *MD) {
1402  if (!MD)
1403  return;
1404 
1405  assert(Summ && "Must have a valid summary to add annotations to");
1406  RetainSummaryTemplate Template(Summ, *this);
1407 
1408  // Effects on the receiver.
1409  if (MD->hasAttr<NSConsumesSelfAttr>())
1410  Template->setReceiverEffect(DecRefMsg);
1411 
1412  // Effects on the parameters.
1413  unsigned parm_idx = 0;
1415  pi=MD->param_begin(), pe=MD->param_end();
1416  pi != pe; ++pi, ++parm_idx) {
1417  const ParmVarDecl *pd = *pi;
1418  if (pd->hasAttr<NSConsumedAttr>())
1419  Template->addArg(AF, parm_idx, DecRefMsg);
1420  else if (pd->hasAttr<CFConsumedAttr>()) {
1421  Template->addArg(AF, parm_idx, DecRef);
1422  } else if (pd->hasAttr<CFReturnsRetainedAttr>()) {
1423  QualType PointeeTy = pd->getType()->getPointeeType();
1424  if (!PointeeTy.isNull())
1425  if (coreFoundation::isCFObjectRef(PointeeTy))
1426  Template->addArg(AF, parm_idx, RetainedOutParameter);
1427  } else if (pd->hasAttr<CFReturnsNotRetainedAttr>()) {
1428  QualType PointeeTy = pd->getType()->getPointeeType();
1429  if (!PointeeTy.isNull())
1430  if (coreFoundation::isCFObjectRef(PointeeTy))
1431  Template->addArg(AF, parm_idx, UnretainedOutParameter);
1432  }
1433  }
1434 
1435  QualType RetTy = MD->getReturnType();
1436  if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1437  Template->setRetEffect(*RetE);
1438 }
1439 
1440 const RetainSummary *
1441 RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1442  Selector S, QualType RetTy) {
1443  // Any special effects?
1444  ArgEffect ReceiverEff = DoNothing;
1445  RetEffect ResultEff = RetEffect::MakeNoRet();
1446 
1447  // Check the method family, and apply any default annotations.
1448  switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1449  case OMF_None:
1450  case OMF_initialize:
1451  case OMF_performSelector:
1452  // Assume all Objective-C methods follow Cocoa Memory Management rules.
1453  // FIXME: Does the non-threaded performSelector family really belong here?
1454  // The selector could be, say, @selector(copy).
1455  if (cocoa::isCocoaObjectRef(RetTy))
1457  else if (coreFoundation::isCFObjectRef(RetTy)) {
1458  // ObjCMethodDecl currently doesn't consider CF objects as valid return
1459  // values for alloc, new, copy, or mutableCopy, so we have to
1460  // double-check with the selector. This is ugly, but there aren't that
1461  // many Objective-C methods that return CF objects, right?
1462  if (MD) {
1463  switch (S.getMethodFamily()) {
1464  case OMF_alloc:
1465  case OMF_new:
1466  case OMF_copy:
1467  case OMF_mutableCopy:
1468  ResultEff = RetEffect::MakeOwned(RetEffect::CF);
1469  break;
1470  default:
1472  break;
1473  }
1474  } else {
1476  }
1477  }
1478  break;
1479  case OMF_init:
1480  ResultEff = ObjCInitRetE;
1481  ReceiverEff = DecRefMsg;
1482  break;
1483  case OMF_alloc:
1484  case OMF_new:
1485  case OMF_copy:
1486  case OMF_mutableCopy:
1487  if (cocoa::isCocoaObjectRef(RetTy))
1488  ResultEff = ObjCAllocRetE;
1489  else if (coreFoundation::isCFObjectRef(RetTy))
1490  ResultEff = RetEffect::MakeOwned(RetEffect::CF);
1491  break;
1492  case OMF_autorelease:
1493  ReceiverEff = Autorelease;
1494  break;
1495  case OMF_retain:
1496  ReceiverEff = IncRefMsg;
1497  break;
1498  case OMF_release:
1499  ReceiverEff = DecRefMsg;
1500  break;
1501  case OMF_dealloc:
1502  ReceiverEff = Dealloc;
1503  break;
1504  case OMF_self:
1505  // -self is handled specially by the ExprEngine to propagate the receiver.
1506  break;
1507  case OMF_retainCount:
1508  case OMF_finalize:
1509  // These methods don't return objects.
1510  break;
1511  }
1512 
1513  // If one of the arguments in the selector has the keyword 'delegate' we
1514  // should stop tracking the reference count for the receiver. This is
1515  // because the reference count is quite possibly handled by a delegate
1516  // method.
1517  if (S.isKeywordSelector()) {
1518  for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1519  StringRef Slot = S.getNameForSlot(i);
1520  if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1521  if (ResultEff == ObjCInitRetE)
1522  ResultEff = RetEffect::MakeNoRetHard();
1523  else
1524  ReceiverEff = StopTrackingHard;
1525  }
1526  }
1527  }
1528 
1529  if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1530  ResultEff.getKind() == RetEffect::NoRet)
1531  return getDefaultSummary();
1532 
1533  return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
1534 }
1535 
1536 const RetainSummary *
1537 RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
1538  ProgramStateRef State) {
1539  const ObjCInterfaceDecl *ReceiverClass = nullptr;
1540 
1541  // We do better tracking of the type of the object than the core ExprEngine.
1542  // See if we have its type in our private state.
1543  // FIXME: Eventually replace the use of state->get<RefBindings> with
1544  // a generic API for reasoning about the Objective-C types of symbolic
1545  // objects.
1546  SVal ReceiverV = Msg.getReceiverSVal();
1547  if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
1548  if (const RefVal *T = getRefBinding(State, Sym))
1549  if (const ObjCObjectPointerType *PT =
1550  T->getType()->getAs<ObjCObjectPointerType>())
1551  ReceiverClass = PT->getInterfaceDecl();
1552 
1553  // If we don't know what kind of object this is, fall back to its static type.
1554  if (!ReceiverClass)
1555  ReceiverClass = Msg.getReceiverInterface();
1556 
1557  // FIXME: The receiver could be a reference to a class, meaning that
1558  // we should use the class method.
1559  // id x = [NSObject class];
1560  // [x performSelector:... withObject:... afterDelay:...];
1561  Selector S = Msg.getSelector();
1562  const ObjCMethodDecl *Method = Msg.getDecl();
1563  if (!Method && ReceiverClass)
1564  Method = ReceiverClass->getInstanceMethod(S);
1565 
1566  return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1567  ObjCMethodSummaries);
1568 }
1569 
1570 const RetainSummary *
1571 RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
1572  const ObjCMethodDecl *MD, QualType RetTy,
1573  ObjCMethodSummariesTy &CachedSummaries) {
1574 
1575  // Look up a summary in our summary cache.
1576  const RetainSummary *Summ = CachedSummaries.find(ID, S);
1577 
1578  if (!Summ) {
1579  Summ = getStandardMethodSummary(MD, S, RetTy);
1580 
1581  // Annotations override defaults.
1582  updateSummaryFromAnnotations(Summ, MD);
1583 
1584  // Memoize the summary.
1585  CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
1586  }
1587 
1588  return Summ;
1589 }
1590 
1591 void RetainSummaryManager::InitializeClassMethodSummaries() {
1592  assert(ScratchArgs.isEmpty());
1593  // Create the [NSAssertionHandler currentHander] summary.
1594  addClassMethSummary("NSAssertionHandler", "currentHandler",
1595  getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
1596 
1597  // Create the [NSAutoreleasePool addObject:] summary.
1598  ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
1599  addClassMethSummary("NSAutoreleasePool", "addObject",
1600  getPersistentSummary(RetEffect::MakeNoRet(),
1602 }
1603 
1604 void RetainSummaryManager::InitializeMethodSummaries() {
1605 
1606  assert (ScratchArgs.isEmpty());
1607 
1608  // Create the "init" selector. It just acts as a pass-through for the
1609  // receiver.
1610  const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
1611  addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1612 
1613  // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1614  // claims the receiver and returns a retained object.
1615  addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1616  InitSumm);
1617 
1618  // The next methods are allocators.
1619  const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1620  const RetainSummary *CFAllocSumm =
1621  getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF));
1622 
1623  // Create the "retain" selector.
1624  RetEffect NoRet = RetEffect::MakeNoRet();
1625  const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
1626  addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
1627 
1628  // Create the "release" selector.
1629  Summ = getPersistentSummary(NoRet, DecRefMsg);
1630  addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
1631 
1632  // Create the -dealloc summary.
1633  Summ = getPersistentSummary(NoRet, Dealloc);
1634  addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
1635 
1636  // Create the "autorelease" selector.
1637  Summ = getPersistentSummary(NoRet, Autorelease);
1638  addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
1639 
1640  // For NSWindow, allocated objects are (initially) self-owned.
1641  // FIXME: For now we opt for false negatives with NSWindow, as these objects
1642  // self-own themselves. However, they only do this once they are displayed.
1643  // Thus, we need to track an NSWindow's display status.
1644  // This is tracked in <rdar://problem/6062711>.
1645  // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
1646  const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1647  StopTracking,
1648  StopTracking);
1649 
1650  addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1651 
1652  // For NSPanel (which subclasses NSWindow), allocated objects are not
1653  // self-owned.
1654  // FIXME: For now we don't track NSPanels. object for the same reason
1655  // as for NSWindow objects.
1656  addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1657 
1658  // For NSNull, objects returned by +null are singletons that ignore
1659  // retain/release semantics. Just don't track them.
1660  // <rdar://problem/12858915>
1661  addClassMethSummary("NSNull", "null", NoTrackYet);
1662 
1663  // Don't track allocated autorelease pools, as it is okay to prematurely
1664  // exit a method.
1665  addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
1666  addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
1667  addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
1668 
1669  // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1670  addInstMethSummary("QCRenderer", AllocSumm, "createSnapshotImageOfType");
1671  addInstMethSummary("QCView", AllocSumm, "createSnapshotImageOfType");
1672 
1673  // Create summaries for CIContext, 'createCGImage' and
1674  // 'createCGLayerWithSize'. These objects are CF objects, and are not
1675  // automatically garbage collected.
1676  addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect");
1677  addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect",
1678  "format", "colorSpace");
1679  addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info");
1680 }
1681 
1682 //===----------------------------------------------------------------------===//
1683 // Error reporting.
1684 //===----------------------------------------------------------------------===//
1685 namespace {
1686  typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1687  SummaryLogTy;
1688 
1689  //===-------------===//
1690  // Bug Descriptions. //
1691  //===-------------===//
1692 
1693  class CFRefBug : public BugType {
1694  protected:
1695  CFRefBug(const CheckerBase *checker, StringRef name)
1697 
1698  public:
1699 
1700  // FIXME: Eventually remove.
1701  virtual const char *getDescription() const = 0;
1702 
1703  virtual bool isLeak() const { return false; }
1704  };
1705 
1706  class UseAfterRelease : public CFRefBug {
1707  public:
1708  UseAfterRelease(const CheckerBase *checker)
1709  : CFRefBug(checker, "Use-after-release") {}
1710 
1711  const char *getDescription() const override {
1712  return "Reference-counted object is used after it is released";
1713  }
1714  };
1715 
1716  class BadRelease : public CFRefBug {
1717  public:
1718  BadRelease(const CheckerBase *checker) : CFRefBug(checker, "Bad release") {}
1719 
1720  const char *getDescription() const override {
1721  return "Incorrect decrement of the reference count of an object that is "
1722  "not owned at this point by the caller";
1723  }
1724  };
1725 
1726  class DeallocGC : public CFRefBug {
1727  public:
1728  DeallocGC(const CheckerBase *checker)
1729  : CFRefBug(checker, "-dealloc called while using garbage collection") {}
1730 
1731  const char *getDescription() const override {
1732  return "-dealloc called while using garbage collection";
1733  }
1734  };
1735 
1736  class DeallocNotOwned : public CFRefBug {
1737  public:
1738  DeallocNotOwned(const CheckerBase *checker)
1739  : CFRefBug(checker, "-dealloc sent to non-exclusively owned object") {}
1740 
1741  const char *getDescription() const override {
1742  return "-dealloc sent to object that may be referenced elsewhere";
1743  }
1744  };
1745 
1746  class OverAutorelease : public CFRefBug {
1747  public:
1748  OverAutorelease(const CheckerBase *checker)
1749  : CFRefBug(checker, "Object autoreleased too many times") {}
1750 
1751  const char *getDescription() const override {
1752  return "Object autoreleased too many times";
1753  }
1754  };
1755 
1756  class ReturnedNotOwnedForOwned : public CFRefBug {
1757  public:
1758  ReturnedNotOwnedForOwned(const CheckerBase *checker)
1759  : CFRefBug(checker, "Method should return an owned object") {}
1760 
1761  const char *getDescription() const override {
1762  return "Object with a +0 retain count returned to caller where a +1 "
1763  "(owning) retain count is expected";
1764  }
1765  };
1766 
1767  class Leak : public CFRefBug {
1768  public:
1769  Leak(const CheckerBase *checker, StringRef name) : CFRefBug(checker, name) {
1770  // Leaks should not be reported if they are post-dominated by a sink.
1771  setSuppressOnSink(true);
1772  }
1773 
1774  const char *getDescription() const override { return ""; }
1775 
1776  bool isLeak() const override { return true; }
1777  };
1778 
1779  //===---------===//
1780  // Bug Reports. //
1781  //===---------===//
1782 
1783  class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
1784  protected:
1785  SymbolRef Sym;
1786  const SummaryLogTy &SummaryLog;
1787  bool GCEnabled;
1788 
1789  public:
1790  CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1791  : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
1792 
1793  void Profile(llvm::FoldingSetNodeID &ID) const override {
1794  static int x = 0;
1795  ID.AddPointer(&x);
1796  ID.AddPointer(Sym);
1797  }
1798 
1799  std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
1800  const ExplodedNode *PrevN,
1801  BugReporterContext &BRC,
1802  BugReport &BR) override;
1803 
1804  std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
1805  const ExplodedNode *N,
1806  BugReport &BR) override;
1807  };
1808 
1809  class CFRefLeakReportVisitor : public CFRefReportVisitor {
1810  public:
1811  CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
1812  const SummaryLogTy &log)
1813  : CFRefReportVisitor(sym, GCEnabled, log) {}
1814 
1815  std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
1816  const ExplodedNode *N,
1817  BugReport &BR) override;
1818 
1819  std::unique_ptr<BugReporterVisitor> clone() const override {
1820  // The curiously-recurring template pattern only works for one level of
1821  // subclassing. Rather than make a new template base for
1822  // CFRefReportVisitor, we simply override clone() to do the right thing.
1823  // This could be trouble someday if BugReporterVisitorImpl is ever
1824  // used for something else besides a convenient implementation of clone().
1825  return llvm::make_unique<CFRefLeakReportVisitor>(*this);
1826  }
1827  };
1828 
1829  class CFRefReport : public BugReport {
1830  void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
1831 
1832  public:
1833  CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1834  const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1835  bool registerVisitor = true)
1836  : BugReport(D, D.getDescription(), n) {
1837  if (registerVisitor)
1838  addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log));
1839  addGCModeDescription(LOpts, GCEnabled);
1840  }
1841 
1842  CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1843  const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1844  StringRef endText)
1845  : BugReport(D, D.getDescription(), endText, n) {
1846  addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log));
1847  addGCModeDescription(LOpts, GCEnabled);
1848  }
1849 
1850  llvm::iterator_range<ranges_iterator> getRanges() override {
1851  const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1852  if (!BugTy.isLeak())
1853  return BugReport::getRanges();
1854  return llvm::make_range(ranges_iterator(), ranges_iterator());
1855  }
1856  };
1857 
1858  class CFRefLeakReport : public CFRefReport {
1859  const MemRegion* AllocBinding;
1860  const Stmt *AllocStmt;
1861 
1862  // Finds the function declaration where a leak warning for the parameter 'sym' should be raised.
1863  void deriveParamLocation(CheckerContext &Ctx, SymbolRef sym);
1864  // Finds the location where a leak warning for 'sym' should be raised.
1865  void deriveAllocLocation(CheckerContext &Ctx, SymbolRef sym);
1866  // Produces description of a leak warning which is printed on the console.
1867  void createDescription(CheckerContext &Ctx, bool GCEnabled, bool IncludeAllocationLine);
1868 
1869  public:
1870  CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1871  const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1872  CheckerContext &Ctx,
1873  bool IncludeAllocationLine);
1874 
1875  PathDiagnosticLocation getLocation(const SourceManager &SM) const override {
1876  assert(Location.isValid());
1877  return Location;
1878  }
1879  };
1880 } // end anonymous namespace
1881 
1882 void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1883  bool GCEnabled) {
1884  const char *GCModeDescription = nullptr;
1885 
1886  switch (LOpts.getGC()) {
1887  case LangOptions::GCOnly:
1888  assert(GCEnabled);
1889  GCModeDescription = "Code is compiled to only use garbage collection";
1890  break;
1891 
1892  case LangOptions::NonGC:
1893  assert(!GCEnabled);
1894  GCModeDescription = "Code is compiled to use reference counts";
1895  break;
1896 
1897  case LangOptions::HybridGC:
1898  if (GCEnabled) {
1899  GCModeDescription = "Code is compiled to use either garbage collection "
1900  "(GC) or reference counts (non-GC). The bug occurs "
1901  "with GC enabled";
1902  break;
1903  } else {
1904  GCModeDescription = "Code is compiled to use either garbage collection "
1905  "(GC) or reference counts (non-GC). The bug occurs "
1906  "in non-GC mode";
1907  break;
1908  }
1909  }
1910 
1911  assert(GCModeDescription && "invalid/unknown GC mode");
1912  addExtraText(GCModeDescription);
1913 }
1914 
1915 static bool isNumericLiteralExpression(const Expr *E) {
1916  // FIXME: This set of cases was copied from SemaExprObjC.
1917  return isa<IntegerLiteral>(E) ||
1918  isa<CharacterLiteral>(E) ||
1919  isa<FloatingLiteral>(E) ||
1920  isa<ObjCBoolLiteralExpr>(E) ||
1921  isa<CXXBoolLiteralExpr>(E);
1922 }
1923 
1924 /// Returns true if this stack frame is for an Objective-C method that is a
1925 /// property getter or setter whose body has been synthesized by the analyzer.
1926 static bool isSynthesizedAccessor(const StackFrameContext *SFC) {
1927  auto Method = dyn_cast_or_null<ObjCMethodDecl>(SFC->getDecl());
1928  if (!Method || !Method->isPropertyAccessor())
1929  return false;
1930 
1932 }
1933 
1934 std::shared_ptr<PathDiagnosticPiece>
1935 CFRefReportVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *PrevN,
1936  BugReporterContext &BRC, BugReport &BR) {
1937  // FIXME: We will eventually need to handle non-statement-based events
1938  // (__attribute__((cleanup))).
1939  if (!N->getLocation().getAs<StmtPoint>())
1940  return nullptr;
1941 
1942  // Check if the type state has changed.
1943  ProgramStateRef PrevSt = PrevN->getState();
1944  ProgramStateRef CurrSt = N->getState();
1945  const LocationContext *LCtx = N->getLocationContext();
1946 
1947  const RefVal* CurrT = getRefBinding(CurrSt, Sym);
1948  if (!CurrT) return nullptr;
1949 
1950  const RefVal &CurrV = *CurrT;
1951  const RefVal *PrevT = getRefBinding(PrevSt, Sym);
1952 
1953  // Create a string buffer to constain all the useful things we want
1954  // to tell the user.
1955  std::string sbuf;
1956  llvm::raw_string_ostream os(sbuf);
1957 
1958  // This is the allocation site since the previous node had no bindings
1959  // for this symbol.
1960  if (!PrevT) {
1961  const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
1962 
1963  if (isa<ObjCIvarRefExpr>(S) &&
1965  S = LCtx->getCurrentStackFrame()->getCallSite();
1966  }
1967 
1968  if (isa<ObjCArrayLiteral>(S)) {
1969  os << "NSArray literal is an object with a +0 retain count";
1970  }
1971  else if (isa<ObjCDictionaryLiteral>(S)) {
1972  os << "NSDictionary literal is an object with a +0 retain count";
1973  }
1974  else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1975  if (isNumericLiteralExpression(BL->getSubExpr()))
1976  os << "NSNumber literal is an object with a +0 retain count";
1977  else {
1978  const ObjCInterfaceDecl *BoxClass = nullptr;
1979  if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1980  BoxClass = Method->getClassInterface();
1981 
1982  // We should always be able to find the boxing class interface,
1983  // but consider this future-proofing.
1984  if (BoxClass)
1985  os << *BoxClass << " b";
1986  else
1987  os << "B";
1988 
1989  os << "oxed expression produces an object with a +0 retain count";
1990  }
1991  }
1992  else if (isa<ObjCIvarRefExpr>(S)) {
1993  os << "Object loaded from instance variable";
1994  }
1995  else {
1996  if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1997  // Get the name of the callee (if it is available).
1998  SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1999  if (const FunctionDecl *FD = X.getAsFunctionDecl())
2000  os << "Call to function '" << *FD << '\'';
2001  else
2002  os << "function call";
2003  }
2004  else {
2005  assert(isa<ObjCMessageExpr>(S));
2006  CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
2008  = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
2009 
2010  switch (Call->getMessageKind()) {
2011  case OCM_Message:
2012  os << "Method";
2013  break;
2014  case OCM_PropertyAccess:
2015  os << "Property";
2016  break;
2017  case OCM_Subscript:
2018  os << "Subscript";
2019  break;
2020  }
2021  }
2022 
2023  if (CurrV.getObjKind() == RetEffect::CF) {
2024  os << " returns a Core Foundation object of type "
2025  << Sym->getType().getAsString() << " with a ";
2026  } else if (CurrV.getObjKind() == RetEffect::Generalized) {
2027  os << " returns an object of type " << Sym->getType().getAsString()
2028  << " with a ";
2029  } else {
2030  assert (CurrV.getObjKind() == RetEffect::ObjC);
2031  QualType T = Sym->getType();
2032  if (!isa<ObjCObjectPointerType>(T)) {
2033  os << " returns an Objective-C object with a ";
2034  } else {
2035  const ObjCObjectPointerType *PT = cast<ObjCObjectPointerType>(T);
2036  os << " returns an instance of "
2037  << PT->getPointeeType().getAsString() << " with a ";
2038  }
2039  }
2040 
2041  if (CurrV.isOwned()) {
2042  os << "+1 retain count";
2043 
2044  if (GCEnabled) {
2045  assert(CurrV.getObjKind() == RetEffect::CF);
2046  os << ". "
2047  "Core Foundation objects are not automatically garbage collected.";
2048  }
2049  }
2050  else {
2051  assert (CurrV.isNotOwned());
2052  os << "+0 retain count";
2053  }
2054  }
2055 
2057  N->getLocationContext());
2058  return std::make_shared<PathDiagnosticEventPiece>(Pos, os.str());
2059  }
2060 
2061  // Gather up the effects that were performed on the object at this
2062  // program point
2063  SmallVector<ArgEffect, 2> AEffects;
2064 
2065  const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
2066  if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
2067  // We only have summaries attached to nodes after evaluating CallExpr and
2068  // ObjCMessageExprs.
2069  const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
2070 
2071  if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
2072  // Iterate through the parameter expressions and see if the symbol
2073  // was ever passed as an argument.
2074  unsigned i = 0;
2075 
2076  for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2077  AI!=AE; ++AI, ++i) {
2078 
2079  // Retrieve the value of the argument. Is it the symbol
2080  // we are interested in?
2081  if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
2082  continue;
2083 
2084  // We have an argument. Get the effect!
2085  AEffects.push_back(Summ->getArg(i));
2086  }
2087  }
2088  else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2089  if (const Expr *receiver = ME->getInstanceReceiver())
2090  if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2091  .getAsLocSymbol() == Sym) {
2092  // The symbol we are tracking is the receiver.
2093  AEffects.push_back(Summ->getReceiverEffect());
2094  }
2095  }
2096  }
2097 
2098  do {
2099  // Get the previous type state.
2100  RefVal PrevV = *PrevT;
2101 
2102  // Specially handle -dealloc.
2103  if (!GCEnabled && std::find(AEffects.begin(), AEffects.end(), Dealloc) !=
2104  AEffects.end()) {
2105  // Determine if the object's reference count was pushed to zero.
2106  assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
2107  // We may not have transitioned to 'release' if we hit an error.
2108  // This case is handled elsewhere.
2109  if (CurrV.getKind() == RefVal::Released) {
2110  assert(CurrV.getCombinedCounts() == 0);
2111  os << "Object released by directly sending the '-dealloc' message";
2112  break;
2113  }
2114  }
2115 
2116  // Specially handle CFMakeCollectable and friends.
2117  if (std::find(AEffects.begin(), AEffects.end(), MakeCollectable) !=
2118  AEffects.end()) {
2119  // Get the name of the function.
2120  const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
2121  SVal X =
2122  CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
2123  const FunctionDecl *FD = X.getAsFunctionDecl();
2124 
2125  if (GCEnabled) {
2126  // Determine if the object's reference count was pushed to zero.
2127  assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
2128 
2129  os << "In GC mode a call to '" << *FD
2130  << "' decrements an object's retain count and registers the "
2131  "object with the garbage collector. ";
2132 
2133  if (CurrV.getKind() == RefVal::Released) {
2134  assert(CurrV.getCount() == 0);
2135  os << "Since it now has a 0 retain count the object can be "
2136  "automatically collected by the garbage collector.";
2137  }
2138  else
2139  os << "An object must have a 0 retain count to be garbage collected. "
2140  "After this call its retain count is +" << CurrV.getCount()
2141  << '.';
2142  }
2143  else
2144  os << "When GC is not enabled a call to '" << *FD
2145  << "' has no effect on its argument.";
2146 
2147  // Nothing more to say.
2148  break;
2149  }
2150 
2151  // Determine if the typestate has changed.
2152  if (!PrevV.hasSameState(CurrV))
2153  switch (CurrV.getKind()) {
2154  case RefVal::Owned:
2155  case RefVal::NotOwned:
2156  if (PrevV.getCount() == CurrV.getCount()) {
2157  // Did an autorelease message get sent?
2158  if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2159  return nullptr;
2160 
2161  assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
2162  os << "Object autoreleased";
2163  break;
2164  }
2165 
2166  if (PrevV.getCount() > CurrV.getCount())
2167  os << "Reference count decremented.";
2168  else
2169  os << "Reference count incremented.";
2170 
2171  if (unsigned Count = CurrV.getCount())
2172  os << " The object now has a +" << Count << " retain count.";
2173 
2174  if (PrevV.getKind() == RefVal::Released) {
2175  assert(GCEnabled && CurrV.getCount() > 0);
2176  os << " The object is not eligible for garbage collection until "
2177  "the retain count reaches 0 again.";
2178  }
2179 
2180  break;
2181 
2182  case RefVal::Released:
2183  if (CurrV.getIvarAccessHistory() ==
2184  RefVal::IvarAccessHistory::ReleasedAfterDirectAccess &&
2185  CurrV.getIvarAccessHistory() != PrevV.getIvarAccessHistory()) {
2186  os << "Strong instance variable relinquished. ";
2187  }
2188  os << "Object released.";
2189  break;
2190 
2191  case RefVal::ReturnedOwned:
2192  // Autoreleases can be applied after marking a node ReturnedOwned.
2193  if (CurrV.getAutoreleaseCount())
2194  return nullptr;
2195 
2196  os << "Object returned to caller as an owning reference (single "
2197  "retain count transferred to caller)";
2198  break;
2199 
2200  case RefVal::ReturnedNotOwned:
2201  os << "Object returned to caller with a +0 retain count";
2202  break;
2203 
2204  default:
2205  return nullptr;
2206  }
2207 
2208  // Emit any remaining diagnostics for the argument effects (if any).
2209  for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2210  E=AEffects.end(); I != E; ++I) {
2211 
2212  // A bunch of things have alternate behavior under GC.
2213  if (GCEnabled)
2214  switch (*I) {
2215  default: break;
2216  case Autorelease:
2217  os << "In GC mode an 'autorelease' has no effect.";
2218  continue;
2219  case IncRefMsg:
2220  os << "In GC mode the 'retain' message has no effect.";
2221  continue;
2222  case DecRefMsg:
2223  os << "In GC mode the 'release' message has no effect.";
2224  continue;
2225  }
2226  }
2227  } while (0);
2228 
2229  if (os.str().empty())
2230  return nullptr; // We have nothing to say!
2231 
2232  const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
2234  N->getLocationContext());
2235  auto P = std::make_shared<PathDiagnosticEventPiece>(Pos, os.str());
2236 
2237  // Add the range by scanning the children of the statement for any bindings
2238  // to Sym.
2239  for (const Stmt *Child : S->children())
2240  if (const Expr *Exp = dyn_cast_or_null<Expr>(Child))
2241  if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
2242  P->addRange(Exp->getSourceRange());
2243  break;
2244  }
2245 
2246  return std::move(P);
2247 }
2248 
2249 namespace {
2250 // Find the first node in the current function context that referred to the
2251 // tracked symbol and the memory location that value was stored to. Note, the
2252 // value is only reported if the allocation occurred in the same function as
2253 // the leak. The function can also return a location context, which should be
2254 // treated as interesting.
2255 struct AllocationInfo {
2256  const ExplodedNode* N;
2257  const MemRegion *R;
2258  const LocationContext *InterestingMethodContext;
2259  AllocationInfo(const ExplodedNode *InN,
2260  const MemRegion *InR,
2261  const LocationContext *InInterestingMethodContext) :
2262  N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
2263 };
2264 } // end anonymous namespace
2265 
2266 static AllocationInfo
2268  SymbolRef Sym) {
2269  const ExplodedNode *AllocationNode = N;
2270  const ExplodedNode *AllocationNodeInCurrentOrParentContext = N;
2271  const MemRegion *FirstBinding = nullptr;
2272  const LocationContext *LeakContext = N->getLocationContext();
2273 
2274  // The location context of the init method called on the leaked object, if
2275  // available.
2276  const LocationContext *InitMethodContext = nullptr;
2277 
2278  while (N) {
2279  ProgramStateRef St = N->getState();
2280  const LocationContext *NContext = N->getLocationContext();
2281 
2282  if (!getRefBinding(St, Sym))
2283  break;
2284 
2286  StateMgr.iterBindings(St, FB);
2287 
2288  if (FB) {
2289  const MemRegion *R = FB.getRegion();
2290  const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>();
2291  // Do not show local variables belonging to a function other than
2292  // where the error is reported.
2293  if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame())
2294  FirstBinding = R;
2295  }
2296 
2297  // AllocationNode is the last node in which the symbol was tracked.
2298  AllocationNode = N;
2299 
2300  // AllocationNodeInCurrentContext, is the last node in the current or
2301  // parent context in which the symbol was tracked.
2302  //
2303  // Note that the allocation site might be in the parent conext. For example,
2304  // the case where an allocation happens in a block that captures a reference
2305  // to it and that reference is overwritten/dropped by another call to
2306  // the block.
2307  if (NContext == LeakContext || NContext->isParentOf(LeakContext))
2308  AllocationNodeInCurrentOrParentContext = N;
2309 
2310  // Find the last init that was called on the given symbol and store the
2311  // init method's location context.
2312  if (!InitMethodContext)
2313  if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) {
2314  const Stmt *CE = CEP->getCallExpr();
2315  if (const ObjCMessageExpr *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
2316  const Stmt *RecExpr = ME->getInstanceReceiver();
2317  if (RecExpr) {
2318  SVal RecV = St->getSVal(RecExpr, NContext);
2319  if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
2320  InitMethodContext = CEP->getCalleeContext();
2321  }
2322  }
2323  }
2324 
2325  N = N->pred_empty() ? nullptr : *(N->pred_begin());
2326  }
2327 
2328  // If we are reporting a leak of the object that was allocated with alloc,
2329  // mark its init method as interesting.
2330  const LocationContext *InterestingMethodContext = nullptr;
2331  if (InitMethodContext) {
2332  const ProgramPoint AllocPP = AllocationNode->getLocation();
2333  if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
2334  if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
2335  if (ME->getMethodFamily() == OMF_alloc)
2336  InterestingMethodContext = InitMethodContext;
2337  }
2338 
2339  // If allocation happened in a function different from the leak node context,
2340  // do not report the binding.
2341  assert(N && "Could not find allocation node");
2342  if (N->getLocationContext() != LeakContext) {
2343  FirstBinding = nullptr;
2344  }
2345 
2346  return AllocationInfo(AllocationNodeInCurrentOrParentContext,
2347  FirstBinding,
2348  InterestingMethodContext);
2349 }
2350 
2351 std::unique_ptr<PathDiagnosticPiece>
2352 CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2353  const ExplodedNode *EndN, BugReport &BR) {
2354  BR.markInteresting(Sym);
2355  return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
2356 }
2357 
2358 std::unique_ptr<PathDiagnosticPiece>
2359 CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2360  const ExplodedNode *EndN, BugReport &BR) {
2361 
2362  // Tell the BugReporterContext to report cases when the tracked symbol is
2363  // assigned to different variables, etc.
2364  BR.markInteresting(Sym);
2365 
2366  // We are reporting a leak. Walk up the graph to get to the first node where
2367  // the symbol appeared, and also get the first VarDecl that tracked object
2368  // is stored to.
2369  AllocationInfo AllocI =
2370  GetAllocationSite(BRC.getStateManager(), EndN, Sym);
2371 
2372  const MemRegion* FirstBinding = AllocI.R;
2373  BR.markInteresting(AllocI.InterestingMethodContext);
2374 
2376 
2377  // Compute an actual location for the leak. Sometimes a leak doesn't
2378  // occur at an actual statement (e.g., transition between blocks; end
2379  // of function) so we need to walk the graph and compute a real location.
2380  const ExplodedNode *LeakN = EndN;
2382 
2383  std::string sbuf;
2384  llvm::raw_string_ostream os(sbuf);
2385 
2386  os << "Object leaked: ";
2387 
2388  if (FirstBinding) {
2389  os << "object allocated and stored into '"
2390  << FirstBinding->getString() << '\'';
2391  }
2392  else
2393  os << "allocated object";
2394 
2395  // Get the retain count.
2396  const RefVal* RV = getRefBinding(EndN->getState(), Sym);
2397  assert(RV);
2398 
2399  if (RV->getKind() == RefVal::ErrorLeakReturned) {
2400  // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2401  // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
2402  // to the caller for NS objects.
2403  const Decl *D = &EndN->getCodeDecl();
2404 
2405  os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2406  : " is returned from a function ");
2407 
2408  if (D->hasAttr<CFReturnsNotRetainedAttr>())
2409  os << "that is annotated as CF_RETURNS_NOT_RETAINED";
2410  else if (D->hasAttr<NSReturnsNotRetainedAttr>())
2411  os << "that is annotated as NS_RETURNS_NOT_RETAINED";
2412  else {
2413  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2414  if (BRC.getASTContext().getLangOpts().ObjCAutoRefCount) {
2415  os << "managed by Automatic Reference Counting";
2416  } else {
2417  os << "whose name ('" << MD->getSelector().getAsString()
2418  << "') does not start with "
2419  "'copy', 'mutableCopy', 'alloc' or 'new'."
2420  " This violates the naming convention rules"
2421  " given in the Memory Management Guide for Cocoa";
2422  }
2423  }
2424  else {
2425  const FunctionDecl *FD = cast<FunctionDecl>(D);
2426  os << "whose name ('" << *FD
2427  << "') does not contain 'Copy' or 'Create'. This violates the naming"
2428  " convention rules given in the Memory Management Guide for Core"
2429  " Foundation";
2430  }
2431  }
2432  }
2433  else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2434  const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
2435  os << " and returned from method '" << MD.getSelector().getAsString()
2436  << "' is potentially leaked when using garbage collection. Callers "
2437  "of this method do not expect a returned object with a +1 retain "
2438  "count since they expect the object to be managed by the garbage "
2439  "collector";
2440  }
2441  else
2442  os << " is not referenced later in this execution path and has a retain "
2443  "count of +" << RV->getCount();
2444 
2445  return llvm::make_unique<PathDiagnosticEventPiece>(L, os.str());
2446 }
2447 
2448 void CFRefLeakReport::deriveParamLocation(CheckerContext &Ctx, SymbolRef sym) {
2449  const SourceManager& SMgr = Ctx.getSourceManager();
2450 
2451  if (!sym->getOriginRegion())
2452  return;
2453 
2454  auto *Region = dyn_cast<DeclRegion>(sym->getOriginRegion());
2455  if (Region) {
2456  const Decl *PDecl = Region->getDecl();
2457  if (PDecl && isa<ParmVarDecl>(PDecl)) {
2458  PathDiagnosticLocation ParamLocation = PathDiagnosticLocation::create(PDecl, SMgr);
2459  Location = ParamLocation;
2460  UniqueingLocation = ParamLocation;
2461  UniqueingDecl = Ctx.getLocationContext()->getDecl();
2462  }
2463  }
2464 }
2465 
2466 void CFRefLeakReport::deriveAllocLocation(CheckerContext &Ctx,SymbolRef sym) {
2467  // Most bug reports are cached at the location where they occurred.
2468  // With leaks, we want to unique them by the location where they were
2469  // allocated, and only report a single path. To do this, we need to find
2470  // the allocation site of a piece of tracked memory, which we do via a
2471  // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2472  // Note that this is *not* the trimmed graph; we are guaranteed, however,
2473  // that all ancestor nodes that represent the allocation site have the
2474  // same SourceLocation.
2475  const ExplodedNode *AllocNode = nullptr;
2476 
2477  const SourceManager& SMgr = Ctx.getSourceManager();
2478 
2479  AllocationInfo AllocI =
2480  GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
2481 
2482  AllocNode = AllocI.N;
2483  AllocBinding = AllocI.R;
2484  markInteresting(AllocI.InterestingMethodContext);
2485 
2486  // Get the SourceLocation for the allocation site.
2487  // FIXME: This will crash the analyzer if an allocation comes from an
2488  // implicit call (ex: a destructor call).
2489  // (Currently there are no such allocations in Cocoa, though.)
2490  AllocStmt = PathDiagnosticLocation::getStmt(AllocNode);
2491 
2492  if (!AllocStmt) {
2493  AllocBinding = nullptr;
2494  return;
2495  }
2496 
2497  PathDiagnosticLocation AllocLocation =
2498  PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2499  AllocNode->getLocationContext());
2500  Location = AllocLocation;
2501 
2502  // Set uniqieing info, which will be used for unique the bug reports. The
2503  // leaks should be uniqued on the allocation site.
2504  UniqueingLocation = AllocLocation;
2505  UniqueingDecl = AllocNode->getLocationContext()->getDecl();
2506 }
2507 
2508 void CFRefLeakReport::createDescription(CheckerContext &Ctx, bool GCEnabled, bool IncludeAllocationLine) {
2509  assert(Location.isValid() && UniqueingDecl && UniqueingLocation.isValid());
2510  Description.clear();
2511  llvm::raw_string_ostream os(Description);
2512  os << "Potential leak ";
2513  if (GCEnabled)
2514  os << "(when using garbage collection) ";
2515  os << "of an object";
2516 
2517  if (AllocBinding) {
2518  os << " stored into '" << AllocBinding->getString() << '\'';
2519  if (IncludeAllocationLine) {
2520  FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager());
2521  os << " (allocated on line " << SL.getSpellingLineNumber() << ")";
2522  }
2523  }
2524 }
2525 
2526 CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2527  bool GCEnabled, const SummaryLogTy &Log,
2528  ExplodedNode *n, SymbolRef sym,
2529  CheckerContext &Ctx,
2530  bool IncludeAllocationLine)
2531  : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
2532 
2533  deriveAllocLocation(Ctx, sym);
2534  if (!AllocBinding)
2535  deriveParamLocation(Ctx, sym);
2536 
2537  createDescription(Ctx, GCEnabled, IncludeAllocationLine);
2538 
2539  addVisitor(llvm::make_unique<CFRefLeakReportVisitor>(sym, GCEnabled, Log));
2540 }
2541 
2542 //===----------------------------------------------------------------------===//
2543 // Main checker logic.
2544 //===----------------------------------------------------------------------===//
2545 
2546 namespace {
2547 class RetainCountChecker
2548  : public Checker< check::Bind,
2549  check::DeadSymbols,
2550  check::EndAnalysis,
2551  check::BeginFunction,
2552  check::EndFunction,
2553  check::PostStmt<BlockExpr>,
2554  check::PostStmt<CastExpr>,
2555  check::PostStmt<ObjCArrayLiteral>,
2556  check::PostStmt<ObjCDictionaryLiteral>,
2557  check::PostStmt<ObjCBoxedExpr>,
2558  check::PostStmt<ObjCIvarRefExpr>,
2559  check::PostCall,
2560  check::PreStmt<ReturnStmt>,
2561  check::RegionChanges,
2562  eval::Assume,
2563  eval::Call > {
2564  mutable std::unique_ptr<CFRefBug> useAfterRelease, releaseNotOwned;
2565  mutable std::unique_ptr<CFRefBug> deallocGC, deallocNotOwned;
2566  mutable std::unique_ptr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2567  mutable std::unique_ptr<CFRefBug> leakWithinFunction, leakAtReturn;
2568  mutable std::unique_ptr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
2569 
2570  typedef llvm::DenseMap<SymbolRef, const CheckerProgramPointTag *> SymbolTagMap;
2571 
2572  // This map is only used to ensure proper deletion of any allocated tags.
2573  mutable SymbolTagMap DeadSymbolTags;
2574 
2575  mutable std::unique_ptr<RetainSummaryManager> Summaries;
2576  mutable std::unique_ptr<RetainSummaryManager> SummariesGC;
2577  mutable SummaryLogTy SummaryLog;
2578  mutable bool ShouldResetSummaryLog;
2579 
2580  /// Optional setting to indicate if leak reports should include
2581  /// the allocation line.
2582  mutable bool IncludeAllocationLine;
2583 
2584 public:
2585  RetainCountChecker(AnalyzerOptions &AO)
2586  : ShouldResetSummaryLog(false),
2587  IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {}
2588 
2589  ~RetainCountChecker() override { DeleteContainerSeconds(DeadSymbolTags); }
2590 
2591  void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2592  ExprEngine &Eng) const {
2593  // FIXME: This is a hack to make sure the summary log gets cleared between
2594  // analyses of different code bodies.
2595  //
2596  // Why is this necessary? Because a checker's lifetime is tied to a
2597  // translation unit, but an ExplodedGraph's lifetime is just a code body.
2598  // Once in a blue moon, a new ExplodedNode will have the same address as an
2599  // old one with an associated summary, and the bug report visitor gets very
2600  // confused. (To make things worse, the summary lifetime is currently also
2601  // tied to a code body, so we get a crash instead of incorrect results.)
2602  //
2603  // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2604  // changes, things will start going wrong again. Really the lifetime of this
2605  // log needs to be tied to either the specific nodes in it or the entire
2606  // ExplodedGraph, not to a specific part of the code being analyzed.
2607  //
2608  // (Also, having stateful local data means that the same checker can't be
2609  // used from multiple threads, but a lot of checkers have incorrect
2610  // assumptions about that anyway. So that wasn't a priority at the time of
2611  // this fix.)
2612  //
2613  // This happens at the end of analysis, but bug reports are emitted /after/
2614  // this point. So we can't just clear the summary log now. Instead, we mark
2615  // that the next time we access the summary log, it should be cleared.
2616 
2617  // If we never reset the summary log during /this/ code body analysis,
2618  // there were no new summaries. There might still have been summaries from
2619  // the /last/ analysis, so clear them out to make sure the bug report
2620  // visitors don't get confused.
2621  if (ShouldResetSummaryLog)
2622  SummaryLog.clear();
2623 
2624  ShouldResetSummaryLog = !SummaryLog.empty();
2625  }
2626 
2627  CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2628  bool GCEnabled) const {
2629  if (GCEnabled) {
2630  if (!leakWithinFunctionGC)
2631  leakWithinFunctionGC.reset(new Leak(this, "Leak of object when using "
2632  "garbage collection"));
2633  return leakWithinFunctionGC.get();
2634  } else {
2635  if (!leakWithinFunction) {
2636  if (LOpts.getGC() == LangOptions::HybridGC) {
2637  leakWithinFunction.reset(new Leak(this,
2638  "Leak of object when not using "
2639  "garbage collection (GC) in "
2640  "dual GC/non-GC code"));
2641  } else {
2642  leakWithinFunction.reset(new Leak(this, "Leak"));
2643  }
2644  }
2645  return leakWithinFunction.get();
2646  }
2647  }
2648 
2649  CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2650  if (GCEnabled) {
2651  if (!leakAtReturnGC)
2652  leakAtReturnGC.reset(new Leak(this,
2653  "Leak of returned object when using "
2654  "garbage collection"));
2655  return leakAtReturnGC.get();
2656  } else {
2657  if (!leakAtReturn) {
2658  if (LOpts.getGC() == LangOptions::HybridGC) {
2659  leakAtReturn.reset(new Leak(this,
2660  "Leak of returned object when not using "
2661  "garbage collection (GC) in dual "
2662  "GC/non-GC code"));
2663  } else {
2664  leakAtReturn.reset(new Leak(this, "Leak of returned object"));
2665  }
2666  }
2667  return leakAtReturn.get();
2668  }
2669  }
2670 
2671  RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2672  bool GCEnabled) const {
2673  // FIXME: We don't support ARC being turned on and off during one analysis.
2674  // (nor, for that matter, do we support changing ASTContexts)
2675  bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
2676  if (GCEnabled) {
2677  if (!SummariesGC)
2678  SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
2679  else
2680  assert(SummariesGC->isARCEnabled() == ARCEnabled);
2681  return *SummariesGC;
2682  } else {
2683  if (!Summaries)
2684  Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
2685  else
2686  assert(Summaries->isARCEnabled() == ARCEnabled);
2687  return *Summaries;
2688  }
2689  }
2690 
2691  RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2692  return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2693  }
2694 
2695  void printState(raw_ostream &Out, ProgramStateRef State,
2696  const char *NL, const char *Sep) const override;
2697 
2698  void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
2699  void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2700  void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
2701 
2702  void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2703  void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
2704  void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2705 
2706  void checkPostStmt(const ObjCIvarRefExpr *IRE, CheckerContext &C) const;
2707 
2708  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
2709 
2710  void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
2711  CheckerContext &C) const;
2712 
2713  void processSummaryOfInlined(const RetainSummary &Summ,
2714  const CallEvent &Call,
2715  CheckerContext &C) const;
2716 
2717  bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2718 
2719  ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
2720  bool Assumption) const;
2721 
2723  checkRegionChanges(ProgramStateRef state,
2724  const InvalidatedSymbols *invalidated,
2725  ArrayRef<const MemRegion *> ExplicitRegions,
2727  const LocationContext* LCtx,
2728  const CallEvent *Call) const;
2729 
2730  void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2731  void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2732  ExplodedNode *Pred, RetEffect RE, RefVal X,
2733  SymbolRef Sym, ProgramStateRef state) const;
2734 
2735  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
2736  void checkBeginFunction(CheckerContext &C) const;
2737  void checkEndFunction(CheckerContext &C) const;
2738 
2739  ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
2740  RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2741  CheckerContext &C) const;
2742 
2743  void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
2744  RefVal::Kind ErrorKind, SymbolRef Sym,
2745  CheckerContext &C) const;
2746 
2747  void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
2748 
2749  const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2750 
2751  ProgramStateRef handleSymbolDeath(ProgramStateRef state,
2752  SymbolRef sid, RefVal V,
2753  SmallVectorImpl<SymbolRef> &Leaked) const;
2754 
2756  handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2757  const ProgramPointTag *Tag, CheckerContext &Ctx,
2758  SymbolRef Sym, RefVal V) const;
2759 
2760  ExplodedNode *processLeaks(ProgramStateRef state,
2762  CheckerContext &Ctx,
2763  ExplodedNode *Pred = nullptr) const;
2764 };
2765 } // end anonymous namespace
2766 
2767 namespace {
2768 class StopTrackingCallback final : public SymbolVisitor {
2770 public:
2771  StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
2772  ProgramStateRef getState() const { return state; }
2773 
2774  bool VisitSymbol(SymbolRef sym) override {
2775  state = state->remove<RefBindings>(sym);
2776  return true;
2777  }
2778 };
2779 } // end anonymous namespace
2780 
2781 //===----------------------------------------------------------------------===//
2782 // Handle statements that may have an effect on refcounts.
2783 //===----------------------------------------------------------------------===//
2784 
2785 void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2786  CheckerContext &C) const {
2787 
2788  // Scan the BlockDecRefExprs for any object the retain count checker
2789  // may be tracking.
2790  if (!BE->getBlockDecl()->hasCaptures())
2791  return;
2792 
2794  const BlockDataRegion *R =
2795  cast<BlockDataRegion>(state->getSVal(BE,
2796  C.getLocationContext()).getAsRegion());
2797 
2799  E = R->referenced_vars_end();
2800 
2801  if (I == E)
2802  return;
2803 
2804  // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2805  // via captured variables, even though captured variables result in a copy
2806  // and in implicit increment/decrement of a retain count.
2808  const LocationContext *LC = C.getLocationContext();
2810 
2811  for ( ; I != E; ++I) {
2812  const VarRegion *VR = I.getCapturedRegion();
2813  if (VR->getSuperRegion() == R) {
2814  VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2815  }
2816  Regions.push_back(VR);
2817  }
2818 
2819  state =
2820  state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2821  Regions.data() + Regions.size()).getState();
2822  C.addTransition(state);
2823 }
2824 
2825 void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2826  CheckerContext &C) const {
2827  const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2828  if (!BE)
2829  return;
2830 
2831  ArgEffect AE = IncRef;
2832 
2833  switch (BE->getBridgeKind()) {
2834  case clang::OBC_Bridge:
2835  // Do nothing.
2836  return;
2838  AE = IncRef;
2839  break;
2842  break;
2843  }
2844 
2846  SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
2847  if (!Sym)
2848  return;
2849  const RefVal* T = getRefBinding(state, Sym);
2850  if (!T)
2851  return;
2852 
2853  RefVal::Kind hasErr = (RefVal::Kind) 0;
2854  state = updateSymbol(state, Sym, *T, AE, hasErr, C);
2855 
2856  if (hasErr) {
2857  // FIXME: If we get an error during a bridge cast, should we report it?
2858  return;
2859  }
2860 
2861  C.addTransition(state);
2862 }
2863 
2864 void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2865  const Expr *Ex) const {
2867  const ExplodedNode *pred = C.getPredecessor();
2868  for (const Stmt *Child : Ex->children()) {
2869  SVal V = state->getSVal(Child, pred->getLocationContext());
2870  if (SymbolRef sym = V.getAsSymbol())
2871  if (const RefVal* T = getRefBinding(state, sym)) {
2872  RefVal::Kind hasErr = (RefVal::Kind) 0;
2873  state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2874  if (hasErr) {
2875  processNonLeakError(state, Child->getSourceRange(), hasErr, sym, C);
2876  return;
2877  }
2878  }
2879  }
2880 
2881  // Return the object as autoreleased.
2882  // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2883  if (SymbolRef sym =
2884  state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2885  QualType ResultTy = Ex->getType();
2886  state = setRefBinding(state, sym,
2887  RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
2888  }
2889 
2890  C.addTransition(state);
2891 }
2892 
2893 void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2894  CheckerContext &C) const {
2895  // Apply the 'MayEscape' to all values.
2896  processObjCLiterals(C, AL);
2897 }
2898 
2899 void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2900  CheckerContext &C) const {
2901  // Apply the 'MayEscape' to all keys and values.
2902  processObjCLiterals(C, DL);
2903 }
2904 
2905 void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2906  CheckerContext &C) const {
2907  const ExplodedNode *Pred = C.getPredecessor();
2908  const LocationContext *LCtx = Pred->getLocationContext();
2909  ProgramStateRef State = Pred->getState();
2910 
2911  if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2912  QualType ResultTy = Ex->getType();
2913  State = setRefBinding(State, Sym,
2914  RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
2915  }
2916 
2917  C.addTransition(State);
2918 }
2919 
2920 void RetainCountChecker::checkPostStmt(const ObjCIvarRefExpr *IRE,
2921  CheckerContext &C) const {
2922  Optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>();
2923  if (!IVarLoc)
2924  return;
2925 
2926  ProgramStateRef State = C.getState();
2927  SymbolRef Sym = State->getSVal(*IVarLoc).getAsSymbol();
2928  if (!Sym || !dyn_cast_or_null<ObjCIvarRegion>(Sym->getOriginRegion()))
2929  return;
2930 
2931  // Accessing an ivar directly is unusual. If we've done that, be more
2932  // forgiving about what the surrounding code is allowed to do.
2933 
2934  QualType Ty = Sym->getType();
2936  if (Ty->isObjCRetainableType())
2937  Kind = RetEffect::ObjC;
2938  else if (coreFoundation::isCFObjectRef(Ty))
2939  Kind = RetEffect::CF;
2940  else
2941  return;
2942 
2943  // If the value is already known to be nil, don't bother tracking it.
2944  ConstraintManager &CMgr = State->getConstraintManager();
2945  if (CMgr.isNull(State, Sym).isConstrainedTrue())
2946  return;
2947 
2948  if (const RefVal *RV = getRefBinding(State, Sym)) {
2949  // If we've seen this symbol before, or we're only seeing it now because
2950  // of something the analyzer has synthesized, don't do anything.
2951  if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None ||
2953  return;
2954  }
2955 
2956  // Note that this value has been loaded from an ivar.
2957  C.addTransition(setRefBinding(State, Sym, RV->withIvarAccess()));
2958  return;
2959  }
2960 
2961  RefVal PlusZero = RefVal::makeNotOwned(Kind, Ty);
2962 
2963  // In a synthesized accessor, the effective retain count is +0.
2965  C.addTransition(setRefBinding(State, Sym, PlusZero));
2966  return;
2967  }
2968 
2969  State = setRefBinding(State, Sym, PlusZero.withIvarAccess());
2970  C.addTransition(State);
2971 }
2972 
2973 void RetainCountChecker::checkPostCall(const CallEvent &Call,
2974  CheckerContext &C) const {
2975  RetainSummaryManager &Summaries = getSummaryManager(C);
2976  const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
2977 
2978  if (C.wasInlined) {
2979  processSummaryOfInlined(*Summ, Call, C);
2980  return;
2981  }
2982  checkSummary(*Summ, Call, C);
2983 }
2984 
2985 /// GetReturnType - Used to get the return type of a message expression or
2986 /// function call with the intention of affixing that type to a tracked symbol.
2987 /// While the return type can be queried directly from RetEx, when
2988 /// invoking class methods we augment to the return type to be that of
2989 /// a pointer to the class (as opposed it just being id).
2990 // FIXME: We may be able to do this with related result types instead.
2991 // This function is probably overestimating.
2992 static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2993  QualType RetTy = RetE->getType();
2994  // If RetE is not a message expression just return its type.
2995  // If RetE is a message expression, return its types if it is something
2996  /// more specific than id.
2997  if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2998  if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2999  if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
3000  PT->isObjCClassType()) {
3001  // At this point we know the return type of the message expression is
3002  // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
3003  // is a call to a class method whose type we can resolve. In such
3004  // cases, promote the return type to XXX* (where XXX is the class).
3005  const ObjCInterfaceDecl *D = ME->getReceiverInterface();
3006  return !D ? RetTy :
3008  }
3009 
3010  return RetTy;
3011 }
3012 
3013 // We don't always get the exact modeling of the function with regards to the
3014 // retain count checker even when the function is inlined. For example, we need
3015 // to stop tracking the symbols which were marked with StopTrackingHard.
3016 void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
3017  const CallEvent &CallOrMsg,
3018  CheckerContext &C) const {
3020 
3021  // Evaluate the effect of the arguments.
3022  for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
3023  if (Summ.getArg(idx) == StopTrackingHard) {
3024  SVal V = CallOrMsg.getArgSVal(idx);
3025  if (SymbolRef Sym = V.getAsLocSymbol()) {
3026  state = removeRefBinding(state, Sym);
3027  }
3028  }
3029  }
3030 
3031  // Evaluate the effect on the message receiver.
3032  const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
3033  if (MsgInvocation) {
3034  if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
3035  if (Summ.getReceiverEffect() == StopTrackingHard) {
3036  state = removeRefBinding(state, Sym);
3037  }
3038  }
3039  }
3040 
3041  // Consult the summary for the return value.
3042  RetEffect RE = Summ.getRetEffect();
3043  if (RE.getKind() == RetEffect::NoRetHard) {
3044  SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
3045  if (Sym)
3046  state = removeRefBinding(state, Sym);
3047  }
3048 
3049  C.addTransition(state);
3050 }
3051 
3053  SVal ArgVal,
3054  ArgEffect Effect) {
3055  auto *ArgRegion = dyn_cast_or_null<TypedValueRegion>(ArgVal.getAsRegion());
3056  if (!ArgRegion)
3057  return State;
3058 
3059  QualType PointeeTy = ArgRegion->getValueType();
3060  if (!coreFoundation::isCFObjectRef(PointeeTy))
3061  return State;
3062 
3063  SVal PointeeVal = State->getSVal(ArgRegion);
3064  SymbolRef Pointee = PointeeVal.getAsLocSymbol();
3065  if (!Pointee)
3066  return State;
3067 
3068  switch (Effect) {
3070  State = setRefBinding(State, Pointee,
3071  RefVal::makeNotOwned(RetEffect::CF, PointeeTy));
3072  break;
3073  case RetainedOutParameter:
3074  // Do nothing. Retained out parameters will either point to a +1 reference
3075  // or NULL, but the way you check for failure differs depending on the API.
3076  // Consequently, we don't have a good way to track them yet.
3077  break;
3078 
3079  default:
3080  llvm_unreachable("only for out parameters");
3081  }
3082 
3083  return State;
3084 }
3085 
3086 void RetainCountChecker::checkSummary(const RetainSummary &Summ,
3087  const CallEvent &CallOrMsg,
3088  CheckerContext &C) const {
3090 
3091  // Evaluate the effect of the arguments.
3092  RefVal::Kind hasErr = (RefVal::Kind) 0;
3093  SourceRange ErrorRange;
3094  SymbolRef ErrorSym = nullptr;
3095 
3096  for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
3097  SVal V = CallOrMsg.getArgSVal(idx);
3098 
3099  ArgEffect Effect = Summ.getArg(idx);
3100  if (Effect == RetainedOutParameter || Effect == UnretainedOutParameter) {
3101  state = updateOutParameter(state, V, Effect);
3102  } else if (SymbolRef Sym = V.getAsLocSymbol()) {
3103  if (const RefVal *T = getRefBinding(state, Sym)) {
3104  state = updateSymbol(state, Sym, *T, Effect, hasErr, C);
3105  if (hasErr) {
3106  ErrorRange = CallOrMsg.getArgSourceRange(idx);
3107  ErrorSym = Sym;
3108  break;
3109  }
3110  }
3111  }
3112  }
3113 
3114  // Evaluate the effect on the message receiver.
3115  bool ReceiverIsTracked = false;
3116  if (!hasErr) {
3117  const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
3118  if (MsgInvocation) {
3119  if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
3120  if (const RefVal *T = getRefBinding(state, Sym)) {
3121  ReceiverIsTracked = true;
3122  state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
3123  hasErr, C);
3124  if (hasErr) {
3125  ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
3126  ErrorSym = Sym;
3127  }
3128  }
3129  }
3130  }
3131  }
3132 
3133  // Process any errors.
3134  if (hasErr) {
3135  processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
3136  return;
3137  }
3138 
3139  // Consult the summary for the return value.
3140  RetEffect RE = Summ.getRetEffect();
3141 
3143  if (ReceiverIsTracked)
3144  RE = getSummaryManager(C).getObjAllocRetEffect();
3145  else
3146  RE = RetEffect::MakeNoRet();
3147  }
3148 
3149  switch (RE.getKind()) {
3150  default:
3151  llvm_unreachable("Unhandled RetEffect.");
3152 
3153  case RetEffect::NoRet:
3154  case RetEffect::NoRetHard:
3155  // No work necessary.
3156  break;
3157 
3158  case RetEffect::OwnedSymbol: {
3159  SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
3160  if (!Sym)
3161  break;
3162 
3163  // Use the result type from the CallEvent as it automatically adjusts
3164  // for methods/functions that return references.
3165  QualType ResultTy = CallOrMsg.getResultType();
3166  state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
3167  ResultTy));
3168 
3169  // FIXME: Add a flag to the checker where allocations are assumed to
3170  // *not* fail.
3171  break;
3172  }
3173 
3176  const Expr *Ex = CallOrMsg.getOriginExpr();
3177  SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
3178  if (!Sym)
3179  break;
3180  assert(Ex);
3181  // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
3182  QualType ResultTy = GetReturnType(Ex, C.getASTContext());
3183  state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
3184  ResultTy));
3185  break;
3186  }
3187  }
3188 
3189  // This check is actually necessary; otherwise the statement builder thinks
3190  // we've hit a previously-found path.
3191  // Normally addTransition takes care of this, but we want the node pointer.
3192  ExplodedNode *NewNode;
3193  if (state == C.getState()) {
3194  NewNode = C.getPredecessor();
3195  } else {
3196  NewNode = C.addTransition(state);
3197  }
3198 
3199  // Annotate the node with summary we used.
3200  if (NewNode) {
3201  // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
3202  if (ShouldResetSummaryLog) {
3203  SummaryLog.clear();
3204  ShouldResetSummaryLog = false;
3205  }
3206  SummaryLog[NewNode] = &Summ;
3207  }
3208 }
3209 
3211 RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
3212  RefVal V, ArgEffect E, RefVal::Kind &hasErr,
3213  CheckerContext &C) const {
3214  // In GC mode [... release] and [... retain] do nothing.
3215  // In ARC mode they shouldn't exist at all, but we just ignore them.
3216  bool IgnoreRetainMsg = C.isObjCGCEnabled();
3217  if (!IgnoreRetainMsg)
3218  IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
3219 
3220  switch (E) {
3221  default:
3222  break;
3223  case IncRefMsg:
3224  E = IgnoreRetainMsg ? DoNothing : IncRef;
3225  break;
3226  case DecRefMsg:
3227  E = IgnoreRetainMsg ? DoNothing : DecRef;
3228  break;
3230  E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
3231  break;
3232  case MakeCollectable:
3233  E = C.isObjCGCEnabled() ? DecRef : DoNothing;
3234  break;
3235  }
3236 
3237  // Handle all use-after-releases.
3238  if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
3239  V = V ^ RefVal::ErrorUseAfterRelease;
3240  hasErr = V.getKind();
3241  return setRefBinding(state, sym, V);
3242  }
3243 
3244  switch (E) {
3245  case DecRefMsg:
3246  case IncRefMsg:
3247  case MakeCollectable:
3249  llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
3250 
3252  case RetainedOutParameter:
3253  llvm_unreachable("Applies to pointer-to-pointer parameters, which should "
3254  "not have ref state.");
3255 
3256  case Dealloc:
3257  // Any use of -dealloc in GC is *bad*.
3258  if (C.isObjCGCEnabled()) {
3259  V = V ^ RefVal::ErrorDeallocGC;
3260  hasErr = V.getKind();
3261  break;
3262  }
3263 
3264  switch (V.getKind()) {
3265  default:
3266  llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
3267  case RefVal::Owned:
3268  // The object immediately transitions to the released state.
3269  V = V ^ RefVal::Released;
3270  V.clearCounts();
3271  return setRefBinding(state, sym, V);
3272  case RefVal::NotOwned:
3273  V = V ^ RefVal::ErrorDeallocNotOwned;
3274  hasErr = V.getKind();
3275  break;
3276  }
3277  break;
3278 
3279  case MayEscape:
3280  if (V.getKind() == RefVal::Owned) {
3281  V = V ^ RefVal::NotOwned;
3282  break;
3283  }
3284 
3285  // Fall-through.
3286 
3287  case DoNothing:
3288  return state;
3289 
3290  case Autorelease:
3291  if (C.isObjCGCEnabled())
3292  return state;
3293  // Update the autorelease counts.
3294  V = V.autorelease();
3295  break;
3296 
3297  case StopTracking:
3298  case StopTrackingHard:
3299  return removeRefBinding(state, sym);
3300 
3301  case IncRef:
3302  switch (V.getKind()) {
3303  default:
3304  llvm_unreachable("Invalid RefVal state for a retain.");
3305  case RefVal::Owned:
3306  case RefVal::NotOwned:
3307  V = V + 1;
3308  break;
3309  case RefVal::Released:
3310  // Non-GC cases are handled above.
3311  assert(C.isObjCGCEnabled());
3312  V = (V ^ RefVal::Owned) + 1;
3313  break;
3314  }
3315  break;
3316 
3317  case DecRef:
3320  switch (V.getKind()) {
3321  default:
3322  // case 'RefVal::Released' handled above.
3323  llvm_unreachable("Invalid RefVal state for a release.");
3324 
3325  case RefVal::Owned:
3326  assert(V.getCount() > 0);
3327  if (V.getCount() == 1) {
3328  if (E == DecRefBridgedTransferred ||
3329  V.getIvarAccessHistory() ==
3330  RefVal::IvarAccessHistory::AccessedDirectly)
3331  V = V ^ RefVal::NotOwned;
3332  else
3333  V = V ^ RefVal::Released;
3334  } else if (E == DecRefAndStopTrackingHard) {
3335  return removeRefBinding(state, sym);
3336  }
3337 
3338  V = V - 1;
3339  break;
3340 
3341  case RefVal::NotOwned:
3342  if (V.getCount() > 0) {
3343  if (E == DecRefAndStopTrackingHard)
3344  return removeRefBinding(state, sym);
3345  V = V - 1;
3346  } else if (V.getIvarAccessHistory() ==
3347  RefVal::IvarAccessHistory::AccessedDirectly) {
3348  // Assume that the instance variable was holding on the object at
3349  // +1, and we just didn't know.
3350  if (E == DecRefAndStopTrackingHard)
3351  return removeRefBinding(state, sym);
3352  V = V.releaseViaIvar() ^ RefVal::Released;
3353  } else {
3354  V = V ^ RefVal::ErrorReleaseNotOwned;
3355  hasErr = V.getKind();
3356  }
3357  break;
3358 
3359  case RefVal::Released:
3360  // Non-GC cases are handled above.
3361  assert(C.isObjCGCEnabled());
3362  V = V ^ RefVal::ErrorUseAfterRelease;
3363  hasErr = V.getKind();
3364  break;
3365  }
3366  break;
3367  }
3368  return setRefBinding(state, sym, V);
3369 }
3370 
3371 void RetainCountChecker::processNonLeakError(ProgramStateRef St,
3372  SourceRange ErrorRange,
3373  RefVal::Kind ErrorKind,
3374  SymbolRef Sym,
3375  CheckerContext &C) const {
3376  // HACK: Ignore retain-count issues on values accessed through ivars,
3377  // because of cases like this:
3378  // [_contentView retain];
3379  // [_contentView removeFromSuperview];
3380  // [self addSubview:_contentView]; // invalidates 'self'
3381  // [_contentView release];
3382  if (const RefVal *RV = getRefBinding(St, Sym))
3383  if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3384  return;
3385 
3386  ExplodedNode *N = C.generateErrorNode(St);
3387  if (!N)
3388  return;
3389 
3390  CFRefBug *BT;
3391  switch (ErrorKind) {
3392  default:
3393  llvm_unreachable("Unhandled error.");
3394  case RefVal::ErrorUseAfterRelease:
3395  if (!useAfterRelease)
3396  useAfterRelease.reset(new UseAfterRelease(this));
3397  BT = useAfterRelease.get();
3398  break;
3399  case RefVal::ErrorReleaseNotOwned:
3400  if (!releaseNotOwned)
3401  releaseNotOwned.reset(new BadRelease(this));
3402  BT = releaseNotOwned.get();
3403  break;
3404  case RefVal::ErrorDeallocGC:
3405  if (!deallocGC)
3406  deallocGC.reset(new DeallocGC(this));
3407  BT = deallocGC.get();
3408  break;
3409  case RefVal::ErrorDeallocNotOwned:
3410  if (!deallocNotOwned)
3411  deallocNotOwned.reset(new DeallocNotOwned(this));
3412  BT = deallocNotOwned.get();
3413  break;
3414  }
3415 
3416  assert(BT);
3417  auto report = std::unique_ptr<BugReport>(
3418  new CFRefReport(*BT, C.getASTContext().getLangOpts(), C.isObjCGCEnabled(),
3419  SummaryLog, N, Sym));
3420  report->addRange(ErrorRange);
3421  C.emitReport(std::move(report));
3422 }
3423 
3424 //===----------------------------------------------------------------------===//
3425 // Handle the return values of retain-count-related functions.
3426 //===----------------------------------------------------------------------===//
3427 
3428 bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
3429  // Get the callee. We're only interested in simple C functions.
3430  ProgramStateRef state = C.getState();
3431  const FunctionDecl *FD = C.getCalleeDecl(CE);
3432  if (!FD)
3433  return false;
3434 
3435  IdentifierInfo *II = FD->getIdentifier();
3436  if (!II)
3437  return false;
3438 
3439  // For now, we're only handling the functions that return aliases of their
3440  // arguments: CFRetain and CFMakeCollectable (and their families).
3441  // Eventually we should add other functions we can model entirely,
3442  // such as CFRelease, which don't invalidate their arguments or globals.
3443  if (CE->getNumArgs() != 1)
3444  return false;
3445 
3446  // Get the name of the function.
3447  StringRef FName = II->getName();
3448  FName = FName.substr(FName.find_first_not_of('_'));
3449 
3450  // See if it's one of the specific functions we know how to eval.
3451  bool canEval = false;
3452  // See if the function has 'rc_ownership_trusted_implementation'
3453  // annotate attribute. If it does, we will not inline it.
3454  bool hasTrustedImplementationAnnotation = false;
3455 
3456  QualType ResultTy = CE->getCallReturnType(C.getASTContext());
3457  if (ResultTy->isObjCIdType()) {
3458  // Handle: id NSMakeCollectable(CFTypeRef)
3459  canEval = II->isStr("NSMakeCollectable");
3460  } else if (ResultTy->isPointerType()) {
3461  // Handle: (CF|CG|CV)Retain
3462  // CFAutorelease
3463  // CFMakeCollectable
3464  // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3465  if (cocoa::isRefType(ResultTy, "CF", FName) ||
3466  cocoa::isRefType(ResultTy, "CG", FName) ||
3467  cocoa::isRefType(ResultTy, "CV", FName)) {
3468  canEval = isRetain(FD, FName) || isAutorelease(FD, FName) ||
3469  isMakeCollectable(FD, FName);
3470  } else {
3471  if (FD->getDefinition()) {
3473  hasTrustedImplementationAnnotation = canEval;
3474  }
3475  }
3476  }
3477 
3478  if (!canEval)
3479  return false;
3480 
3481  // Bind the return value.
3482  const LocationContext *LCtx = C.getLocationContext();
3483  SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
3484  if (RetVal.isUnknown() ||
3485  (hasTrustedImplementationAnnotation && !ResultTy.isNull())) {
3486  // If the receiver is unknown or the function has
3487  // 'rc_ownership_trusted_implementation' annotate attribute, conjure a
3488  // return value.
3489  SValBuilder &SVB = C.getSValBuilder();
3490  RetVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, ResultTy, C.blockCount());
3491  }
3492  state = state->BindExpr(CE, LCtx, RetVal, false);
3493 
3494  // FIXME: This should not be necessary, but otherwise the argument seems to be
3495  // considered alive during the next statement.
3496  if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3497  // Save the refcount status of the argument.
3498  SymbolRef Sym = RetVal.getAsLocSymbol();
3499  const RefVal *Binding = nullptr;
3500  if (Sym)
3501  Binding = getRefBinding(state, Sym);
3502 
3503  // Invalidate the argument region.
3504  state = state->invalidateRegions(
3505  ArgRegion, CE, C.blockCount(), LCtx,
3506  /*CausesPointerEscape*/ hasTrustedImplementationAnnotation);
3507 
3508  // Restore the refcount status of the argument.
3509  if (Binding)
3510  state = setRefBinding(state, Sym, *Binding);
3511  }
3512 
3513  C.addTransition(state);
3514  return true;
3515 }
3516 
3517 //===----------------------------------------------------------------------===//
3518 // Handle return statements.
3519 //===----------------------------------------------------------------------===//
3520 
3521 void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3522  CheckerContext &C) const {
3523 
3524  // Only adjust the reference count if this is the top-level call frame,
3525  // and not the result of inlining. In the future, we should do
3526  // better checking even for inlined calls, and see if they match
3527  // with their expected semantics (e.g., the method should return a retained
3528  // object, etc.).
3529  if (!C.inTopFrame())
3530  return;
3531 
3532  const Expr *RetE = S->getRetValue();
3533  if (!RetE)
3534  return;
3535 
3536  ProgramStateRef state = C.getState();
3537  SymbolRef Sym =
3538  state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
3539  if (!Sym)
3540  return;
3541 
3542  // Get the reference count binding (if any).
3543  const RefVal *T = getRefBinding(state, Sym);
3544  if (!T)
3545  return;
3546 
3547  // Change the reference count.
3548  RefVal X = *T;
3549 
3550  switch (X.getKind()) {
3551  case RefVal::Owned: {
3552  unsigned cnt = X.getCount();
3553  assert(cnt > 0);
3554  X.setCount(cnt - 1);
3555  X = X ^ RefVal::ReturnedOwned;
3556  break;
3557  }
3558 
3559  case RefVal::NotOwned: {
3560  unsigned cnt = X.getCount();
3561  if (cnt) {
3562  X.setCount(cnt - 1);
3563  X = X ^ RefVal::ReturnedOwned;
3564  }
3565  else {
3566  X = X ^ RefVal::ReturnedNotOwned;
3567  }
3568  break;
3569  }
3570 
3571  default:
3572  return;
3573  }
3574 
3575  // Update the binding.
3576  state = setRefBinding(state, Sym, X);
3577  ExplodedNode *Pred = C.addTransition(state);
3578 
3579  // At this point we have updated the state properly.
3580  // Everything after this is merely checking to see if the return value has
3581  // been over- or under-retained.
3582 
3583  // Did we cache out?
3584  if (!Pred)
3585  return;
3586 
3587  // Update the autorelease counts.
3588  static CheckerProgramPointTag AutoreleaseTag(this, "Autorelease");
3589  state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
3590 
3591  // Did we cache out?
3592  if (!state)
3593  return;
3594 
3595  // Get the updated binding.
3596  T = getRefBinding(state, Sym);
3597  assert(T);
3598  X = *T;
3599 
3600  // Consult the summary of the enclosing method.
3601  RetainSummaryManager &Summaries = getSummaryManager(C);
3602  const Decl *CD = &Pred->getCodeDecl();
3604 
3605  // FIXME: What is the convention for blocks? Is there one?
3606  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
3607  const RetainSummary *Summ = Summaries.getMethodSummary(MD);
3608  RE = Summ->getRetEffect();
3609  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3610  if (!isa<CXXMethodDecl>(FD)) {
3611  const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3612  RE = Summ->getRetEffect();
3613  }
3614  }
3615 
3616  checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
3617 }
3618 
3619 void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3620  CheckerContext &C,
3621  ExplodedNode *Pred,
3622  RetEffect RE, RefVal X,
3623  SymbolRef Sym,
3624  ProgramStateRef state) const {
3625  // HACK: Ignore retain-count issues on values accessed through ivars,
3626  // because of cases like this:
3627  // [_contentView retain];
3628  // [_contentView removeFromSuperview];
3629  // [self addSubview:_contentView]; // invalidates 'self'
3630  // [_contentView release];
3631  if (X.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3632  return;
3633 
3634  // Any leaks or other errors?
3635  if (X.isReturnedOwned() && X.getCount() == 0) {
3636  if (RE.getKind() != RetEffect::NoRet) {
3637  bool hasError = false;
3638  if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3639  // Things are more complicated with garbage collection. If the
3640  // returned object is suppose to be an Objective-C object, we have
3641  // a leak (as the caller expects a GC'ed object) because no
3642  // method should return ownership unless it returns a CF object.
3643  hasError = true;
3644  X = X ^ RefVal::ErrorGCLeakReturned;
3645  }
3646  else if (!RE.isOwned()) {
3647  // Either we are using GC and the returned object is a CF type
3648  // or we aren't using GC. In either case, we expect that the
3649  // enclosing method is expected to return ownership.
3650  hasError = true;
3651  X = X ^ RefVal::ErrorLeakReturned;
3652  }
3653 
3654  if (hasError) {
3655  // Generate an error node.
3656  state = setRefBinding(state, Sym, X);
3657 
3658  static CheckerProgramPointTag ReturnOwnLeakTag(this, "ReturnsOwnLeak");
3659  ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
3660  if (N) {
3661  const LangOptions &LOpts = C.getASTContext().getLangOpts();
3662  bool GCEnabled = C.isObjCGCEnabled();
3663  C.emitReport(std::unique_ptr<BugReport>(new CFRefLeakReport(
3664  *getLeakAtReturnBug(LOpts, GCEnabled), LOpts, GCEnabled,
3665  SummaryLog, N, Sym, C, IncludeAllocationLine)));
3666  }
3667  }
3668  }
3669  } else if (X.isReturnedNotOwned()) {
3670  if (RE.isOwned()) {
3671  if (X.getIvarAccessHistory() ==
3672  RefVal::IvarAccessHistory::AccessedDirectly) {
3673  // Assume the method was trying to transfer a +1 reference from a
3674  // strong ivar to the caller.
3675  state = setRefBinding(state, Sym,
3676  X.releaseViaIvar() ^ RefVal::ReturnedOwned);
3677  } else {
3678  // Trying to return a not owned object to a caller expecting an
3679  // owned object.
3680  state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
3681 
3682  static CheckerProgramPointTag
3683  ReturnNotOwnedTag(this, "ReturnNotOwnedForOwned");
3684 
3685  ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
3686  if (N) {
3687  if (!returnNotOwnedForOwned)
3688  returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned(this));
3689 
3690  C.emitReport(std::unique_ptr<BugReport>(new CFRefReport(
3691  *returnNotOwnedForOwned, C.getASTContext().getLangOpts(),
3692  C.isObjCGCEnabled(), SummaryLog, N, Sym)));
3693  }
3694  }
3695  }
3696  }
3697 }
3698 
3699 //===----------------------------------------------------------------------===//
3700 // Check various ways a symbol can be invalidated.
3701 //===----------------------------------------------------------------------===//
3702 
3703 void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
3704  CheckerContext &C) const {
3705  // Are we storing to something that causes the value to "escape"?
3706  bool escapes = true;
3707 
3708  // A value escapes in three possible cases (this may change):
3709  //
3710  // (1) we are binding to something that is not a memory region.
3711  // (2) we are binding to a memregion that does not have stack storage
3712  // (3) we are binding to a memregion with stack storage that the store
3713  // does not understand.
3714  ProgramStateRef state = C.getState();
3715 
3716  if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
3717  escapes = !regionLoc->getRegion()->hasStackStorage();
3718 
3719  if (!escapes) {
3720  // To test (3), generate a new state with the binding added. If it is
3721  // the same state, then it escapes (since the store cannot represent
3722  // the binding).
3723  // Do this only if we know that the store is not supposed to generate the
3724  // same state.
3725  SVal StoredVal = state->getSVal(regionLoc->getRegion());
3726  if (StoredVal != val)
3727  escapes = (state == (state->bindLoc(*regionLoc, val, C.getLocationContext())));
3728  }
3729  if (!escapes) {
3730  // Case 4: We do not currently model what happens when a symbol is
3731  // assigned to a struct field, so be conservative here and let the symbol
3732  // go. TODO: This could definitely be improved upon.
3733  escapes = !isa<VarRegion>(regionLoc->getRegion());
3734  }
3735  }
3736 
3737  // If we are storing the value into an auto function scope variable annotated
3738  // with (__attribute__((cleanup))), stop tracking the value to avoid leak
3739  // false positives.
3740  if (const VarRegion *LVR = dyn_cast_or_null<VarRegion>(loc.getAsRegion())) {
3741  const VarDecl *VD = LVR->getDecl();
3742  if (VD->hasAttr<CleanupAttr>()) {
3743  escapes = true;
3744  }
3745  }
3746 
3747  // If our store can represent the binding and we aren't storing to something
3748  // that doesn't have local storage then just return and have the simulation
3749  // state continue as is.
3750  if (!escapes)
3751  return;
3752 
3753  // Otherwise, find all symbols referenced by 'val' that we are tracking
3754  // and stop tracking them.
3755  state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
3756  C.addTransition(state);
3757 }
3758 
3759 ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
3760  SVal Cond,
3761  bool Assumption) const {
3762  // FIXME: We may add to the interface of evalAssume the list of symbols
3763  // whose assumptions have changed. For now we just iterate through the
3764  // bindings and check if any of the tracked symbols are NULL. This isn't
3765  // too bad since the number of symbols we will track in practice are
3766  // probably small and evalAssume is only called at branches and a few
3767  // other places.
3768  RefBindingsTy B = state->get<RefBindings>();
3769 
3770  if (B.isEmpty())
3771  return state;
3772 
3773  bool changed = false;
3774  RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
3775 
3776  for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3777  // Check if the symbol is null stop tracking the symbol.
3778  ConstraintManager &CMgr = state->getConstraintManager();
3779  ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3780  if (AllocFailed.isConstrainedTrue()) {
3781  changed = true;
3782  B = RefBFactory.remove(B, I.getKey());
3783  }
3784  }
3785 
3786  if (changed)
3787  state = state->set<RefBindings>(B);
3788 
3789  return state;
3790 }
3791 
3793 RetainCountChecker::checkRegionChanges(ProgramStateRef state,
3794  const InvalidatedSymbols *invalidated,
3795  ArrayRef<const MemRegion *> ExplicitRegions,
3797  const LocationContext *LCtx,
3798  const CallEvent *Call) const {
3799  if (!invalidated)
3800  return state;
3801 
3802  llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3803  for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3804  E = ExplicitRegions.end(); I != E; ++I) {
3805  if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3806  WhitelistedSymbols.insert(SR->getSymbol());
3807  }
3808 
3809  for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
3810  E = invalidated->end(); I!=E; ++I) {
3811  SymbolRef sym = *I;
3812  if (WhitelistedSymbols.count(sym))
3813  continue;
3814  // Remove any existing reference-count binding.
3815  state = removeRefBinding(state, sym);
3816  }
3817  return state;
3818 }
3819 
3820 //===----------------------------------------------------------------------===//
3821 // Handle dead symbols and end-of-path.
3822 //===----------------------------------------------------------------------===//
3823 
3825 RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
3826  ExplodedNode *Pred,
3827  const ProgramPointTag *Tag,
3828  CheckerContext &Ctx,
3829  SymbolRef Sym, RefVal V) const {
3830  unsigned ACnt = V.getAutoreleaseCount();
3831 
3832  // No autorelease counts? Nothing to be done.
3833  if (!ACnt)
3834  return state;
3835 
3836  assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
3837  unsigned Cnt = V.getCount();
3838 
3839  // FIXME: Handle sending 'autorelease' to already released object.
3840 
3841  if (V.getKind() == RefVal::ReturnedOwned)
3842  ++Cnt;
3843 
3844  // If we would over-release here, but we know the value came from an ivar,
3845  // assume it was a strong ivar that's just been relinquished.
3846  if (ACnt > Cnt &&
3847  V.getIvarAccessHistory() == RefVal::IvarAccessHistory::AccessedDirectly) {
3848  V = V.releaseViaIvar();
3849  --ACnt;
3850  }
3851 
3852  if (ACnt <= Cnt) {
3853  if (ACnt == Cnt) {
3854  V.clearCounts();
3855  if (V.getKind() == RefVal::ReturnedOwned)
3856  V = V ^ RefVal::ReturnedNotOwned;
3857  else
3858  V = V ^ RefVal::NotOwned;
3859  } else {
3860  V.setCount(V.getCount() - ACnt);
3861  V.setAutoreleaseCount(0);
3862  }
3863  return setRefBinding(state, Sym, V);
3864  }
3865 
3866  // HACK: Ignore retain-count issues on values accessed through ivars,
3867  // because of cases like this:
3868  // [_contentView retain];
3869  // [_contentView removeFromSuperview];
3870  // [self addSubview:_contentView]; // invalidates 'self'
3871  // [_contentView release];
3872  if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3873  return state;
3874 
3875  // Woah! More autorelease counts then retain counts left.
3876  // Emit hard error.
3877  V = V ^ RefVal::ErrorOverAutorelease;
3878  state = setRefBinding(state, Sym, V);
3879 
3880  ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
3881  if (N) {
3882  SmallString<128> sbuf;
3883  llvm::raw_svector_ostream os(sbuf);
3884  os << "Object was autoreleased ";
3885  if (V.getAutoreleaseCount() > 1)
3886  os << V.getAutoreleaseCount() << " times but the object ";
3887  else
3888  os << "but ";
3889  os << "has a +" << V.getCount() << " retain count";
3890 
3891  if (!overAutorelease)
3892  overAutorelease.reset(new OverAutorelease(this));
3893 
3894  const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3895  Ctx.emitReport(std::unique_ptr<BugReport>(
3896  new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3897  SummaryLog, N, Sym, os.str())));
3898  }
3899 
3900  return nullptr;
3901 }
3902 
3904 RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
3905  SymbolRef sid, RefVal V,
3906  SmallVectorImpl<SymbolRef> &Leaked) const {
3907  bool hasLeak;
3908 
3909  // HACK: Ignore retain-count issues on values accessed through ivars,
3910  // because of cases like this:
3911  // [_contentView retain];
3912  // [_contentView removeFromSuperview];
3913  // [self addSubview:_contentView]; // invalidates 'self'
3914  // [_contentView release];
3915  if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3916  hasLeak = false;
3917  else if (V.isOwned())
3918  hasLeak = true;
3919  else if (V.isNotOwned() || V.isReturnedOwned())
3920  hasLeak = (V.getCount() > 0);
3921  else
3922  hasLeak = false;
3923 
3924  if (!hasLeak)
3925  return removeRefBinding(state, sid);
3926 
3927  Leaked.push_back(sid);
3928  return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
3929 }
3930 
3931 ExplodedNode *
3932 RetainCountChecker::processLeaks(ProgramStateRef state,
3934  CheckerContext &Ctx,
3935  ExplodedNode *Pred) const {
3936  // Generate an intermediate node representing the leak point.
3937  ExplodedNode *N = Ctx.addTransition(state, Pred);
3938 
3939  if (N) {
3941  I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3942 
3943  const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3944  bool GCEnabled = Ctx.isObjCGCEnabled();
3945  CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3946  : getLeakAtReturnBug(LOpts, GCEnabled);
3947  assert(BT && "BugType not initialized.");
3948 
3949  Ctx.emitReport(std::unique_ptr<BugReport>(
3950  new CFRefLeakReport(*BT, LOpts, GCEnabled, SummaryLog, N, *I, Ctx,
3951  IncludeAllocationLine)));
3952  }
3953  }
3954 
3955  return N;
3956 }
3957 
3958 void RetainCountChecker::checkBeginFunction(CheckerContext &Ctx) const {
3959  if (!Ctx.inTopFrame())
3960  return;
3961 
3962  const LocationContext *LCtx = Ctx.getLocationContext();
3963  const FunctionDecl *FD = dyn_cast<FunctionDecl>(LCtx->getDecl());
3964 
3966  return;
3967 
3968  ProgramStateRef state = Ctx.getState();
3969 
3970  const RetainSummary *FunctionSummary = getSummaryManager(Ctx).getFunctionSummary(FD);
3971  ArgEffects CalleeSideArgEffects = FunctionSummary->getArgEffects();
3972 
3973  for (unsigned idx = 0, e = FD->getNumParams(); idx != e; ++idx) {
3974  const ParmVarDecl *Param = FD->getParamDecl(idx);
3975  SymbolRef Sym = state->getSVal(state->getRegion(Param, LCtx)).getAsSymbol();
3976 
3977  QualType Ty = Param->getType();
3978  const ArgEffect *AE = CalleeSideArgEffects.lookup(idx);
3979  if (AE && *AE == DecRef && isGeneralizedObjectRef(Ty))
3980  state = setRefBinding(state, Sym, RefVal::makeOwned(RetEffect::ObjKind::Generalized, Ty));
3981  else if (isGeneralizedObjectRef(Ty))
3982  state = setRefBinding(state, Sym, RefVal::makeNotOwned(RetEffect::ObjKind::Generalized, Ty));
3983  }
3984 
3985  Ctx.addTransition(state);
3986 }
3987 
3988 void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
3989  ProgramStateRef state = Ctx.getState();
3990  RefBindingsTy B = state->get<RefBindings>();
3991  ExplodedNode *Pred = Ctx.getPredecessor();
3992 
3993  // Don't process anything within synthesized bodies.
3994  const LocationContext *LCtx = Pred->getLocationContext();
3996  assert(!LCtx->inTopFrame());
3997  return;
3998  }
3999 
4000  for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
4001  state = handleAutoreleaseCounts(state, Pred, /*Tag=*/nullptr, Ctx,
4002  I->first, I->second);
4003  if (!state)
4004  return;
4005  }
4006 
4007  // If the current LocationContext has a parent, don't check for leaks.
4008  // We will do that later.
4009  // FIXME: we should instead check for imbalances of the retain/releases,
4010  // and suggest annotations.
4011  if (LCtx->getParent())
4012  return;
4013 
4014  B = state->get<RefBindings>();
4016 
4017  for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
4018  state = handleSymbolDeath(state, I->first, I->second, Leaked);
4019 
4020  processLeaks(state, Leaked, Ctx, Pred);
4021 }
4022 
4023 const ProgramPointTag *
4024 RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
4025  const CheckerProgramPointTag *&tag = DeadSymbolTags[sym];
4026  if (!tag) {
4027  SmallString<64> buf;
4028  llvm::raw_svector_ostream out(buf);
4029  out << "Dead Symbol : ";
4030  sym->dumpToStream(out);
4031  tag = new CheckerProgramPointTag(this, out.str());
4032  }
4033  return tag;
4034 }
4035 
4036 void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
4037  CheckerContext &C) const {
4038  ExplodedNode *Pred = C.getPredecessor();
4039 
4040  ProgramStateRef state = C.getState();
4041  RefBindingsTy B = state->get<RefBindings>();
4043 
4044  // Update counts from autorelease pools
4045  for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
4046  E = SymReaper.dead_end(); I != E; ++I) {
4047  SymbolRef Sym = *I;
4048  if (const RefVal *T = B.lookup(Sym)){
4049  // Use the symbol as the tag.
4050  // FIXME: This might not be as unique as we would like.
4051  const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
4052  state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
4053  if (!state)
4054  return;
4055 
4056  // Fetch the new reference count from the state, and use it to handle
4057  // this symbol.
4058  state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
4059  }
4060  }
4061 
4062  if (Leaked.empty()) {
4063  C.addTransition(state);
4064  return;
4065  }
4066 
4067  Pred = processLeaks(state, Leaked, C, Pred);
4068 
4069  // Did we cache out?
4070  if (!Pred)
4071  return;
4072 
4073  // Now generate a new node that nukes the old bindings.
4074  // The only bindings left at this point are the leaked symbols.
4075  RefBindingsTy::Factory &F = state->get_context<RefBindings>();
4076  B = state->get<RefBindings>();
4077 
4078  for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
4079  E = Leaked.end();
4080  I != E; ++I)
4081  B = F.remove(B, *I);
4082 
4083  state = state->set<RefBindings>(B);
4084  C.addTransition(state, Pred);
4085 }
4086 
4087 void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
4088  const char *NL, const char *Sep) const {
4089 
4090  RefBindingsTy B = State->get<RefBindings>();
4091 
4092  if (B.isEmpty())
4093  return;
4094 
4095  Out << Sep << NL;
4096 
4097  for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
4098  Out << I->first << " : ";
4099  I->second.print(Out);
4100  Out << NL;
4101  }
4102 }
4103 
4104 //===----------------------------------------------------------------------===//
4105 // Checker registration.
4106 //===----------------------------------------------------------------------===//
4107 
4108 void ento::registerRetainCountChecker(CheckerManager &Mgr) {
4109  Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
4110 }
4111 
4112 //===----------------------------------------------------------------------===//
4113 // Implementation of the CallEffects API.
4114 //===----------------------------------------------------------------------===//
4115 
4116 namespace clang {
4117 namespace ento {
4118 namespace objc_retain {
4119 
4120 // This is a bit gross, but it allows us to populate CallEffects without
4121 // creating a bunch of accessors. This kind is very localized, so the
4122 // damage of this macro is limited.
4123 #define createCallEffect(D, KIND)\
4124  ASTContext &Ctx = D->getASTContext();\
4125  LangOptions L = Ctx.getLangOpts();\
4126  RetainSummaryManager M(Ctx, L.GCOnly, L.ObjCAutoRefCount);\
4127  const RetainSummary *S = M.get ## KIND ## Summary(D);\
4128  CallEffects CE(S->getRetEffect());\
4129  CE.Receiver = S->getReceiverEffect();\
4130  unsigned N = D->param_size();\
4131  for (unsigned i = 0; i < N; ++i) {\
4132  CE.Args.push_back(S->getArg(i));\
4133  }
4134 
4136  createCallEffect(MD, Method);
4137  return CE;
4138 }
4139 
4141  createCallEffect(FD, Function);
4142  return CE;
4143 }
4144 
4145 #undef createCallEffect
4146 
4147 } // end namespace objc_retain
4148 } // end namespace ento
4149 } // end namespace clang
const BlockDecl * getBlockDecl() const
Definition: Expr.h:4853
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:1855
SVal getReceiverSVal() const
Returns the value of the receiver at the time of this call.
Definition: CallEvent.cpp:746
static Selector GetNullarySelector(StringRef name, ASTContext &Ctx)
Utility function for constructing a nullary selector.
Definition: ASTContext.h:2764
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1629
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:614
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:2278
bool hasCaptures() const
hasCaptures - True if this block (or its nested blocks) captures anything of local storage from its e...
Definition: Decl.h:3699
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1089
static Selector GetUnarySelector(StringRef name, ASTContext &Ctx)
Utility function for constructing an unary selector.
Definition: ASTContext.h:2770
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:60
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2266
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:2920
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:415
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:81
Represents a point when we begin processing an inlined call.
Definition: ProgramPoint.h:585
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
param_const_iterator param_end() const
Definition: DeclObjC.h:357
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
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:769
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:2117
unsigned getNumParams() const
Definition: Type.h:3349
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6052
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:113
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.
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1445
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
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:232
const MemRegion * getSuperRegion() const
Definition: MemRegion.h:430
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:150
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:128
static Selector getKeywordSelector(ASTContext &Ctx, IdentifierInfos *... IIs)
LineState State
bool isObjCIdType() const
Definition: Type.h:5818
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:905
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:48
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp, [NSNumber numberWithInt:42]];.
Definition: ExprObjC.h:144
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:513
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:931
bool followsCreateRule(const FunctionDecl *FD)
BlockDataRegion - A region that represents a block instance.
Definition: MemRegion.h:656
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:208
const LocationContext * getLocationContext() const
virtual bool inTopFrame() const
Return true if the current LocationContext has no caller context.
const LocationContext * getParent() const
bool isUnknown() const
Definition: SVals.h:128
std::string getAsString() const
Definition: Type.h:940
SVal getReturnValue() const
Returns the return value of the call.
Definition: CallEvent.cpp:240
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:2704
referenced_vars_iterator referenced_vars_end() const
Definition: MemRegion.cpp:1458
Represents an ObjC class declaration.
Definition: DeclObjC.h:1108
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:330
virtual BugReport::NodeResolver & getNodeResolver()=0
virtual QualType getType() const =0
param_iterator param_begin()
Definition: Decl.h:2088
SymbolRef getAsSymbol(bool IncludeBaseRegions=false) const
If this SVal wraps a symbol return that SymbolRef.
Definition: SVals.cpp:116
ArrayRef< ParmVarDecl * >::const_iterator param_const_iterator
Definition: Decl.h:2086
bool hasAttr() const
Definition: DeclBase.h:521
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:329
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:349
Indicates that the returned value is an owned (+1) symbol.
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3126
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.
ID
Defines the address space values used by the address space qualifier of QualType. ...
Definition: AddressSpaces.h:26
const RegionTy * getAs() const
Definition: MemRegion.h:1174
SymbolicRegion - A special, "non-concrete" region.
Definition: MemRegion.h:742
Expr - This represents one expression.
Definition: Expr.h:106
Defines the clang::LangOptions interface.
Indicates that the tracked object is a CF object.
Indicates that the object is not owned and controlled by the Garbage collector.
bool isObjCRetainableType() const
Definition: Type.cpp:3768
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:4839
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:537
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:257
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:314
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:1392
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:860
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:416
unsigned getNumArgs() const
void markInteresting(SymbolRef sym)
Selector getSelector() const
Definition: DeclObjC.h:328
ObjCBridgeCastKind getBridgeKind() const
Determine which kind of bridge is being performed via this cast.
Definition: ExprObjC.h:1546
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:681
Represents a C function or static C++ member function call.
Definition: CallEvent.h:457
const SourceManager & SM
Definition: Format.cpp:1307
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:935
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:1117
#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:3062
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:140
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:2099
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.
referenced_vars_iterator referenced_vars_begin() const
Definition: MemRegion.cpp:1441
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:94
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:1519
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:233
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:781
Performs the combined functionality of DecRef and StopTrackingHard.
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:2089
static ArgEffect getStopTrackingHardEquivalent(ArgEffect E)
SourceRange getReceiverRange() const
Source range of the receiver.
Definition: ExprObjC.cpp:290
Represents a pointer to an Objective C object.
Definition: Type.h:5230
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:553
param_const_iterator param_begin() const
Definition: DeclObjC.h:354
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:479
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:505
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:13065
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.
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:1091
SValBuilder & getSValBuilder()
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2209
A SourceLocation and its associated SourceManager.
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:897
virtual const ExplodedNode * getOriginalNode(const ExplodedNode *N)=0
bool isPointerType() const
Definition: Type.h:5722
All typestate tracking of the object ceases.
void iterBindings(ProgramStateRef state, StoreManager::BindingsHandler &F)
Definition: ProgramState.h:549
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:226
QualType getType() const
Definition: Decl.h:600
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:493
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:151
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:1025
AnalysisDeclContext * getAnalysisDeclContext() const
const LocationContext * getLocationContext() const
unsigned getNumParams() const
getNumParams - Return the number of parameters this function must have based on its FunctionType...
Definition: Decl.cpp:2851
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:659
This class handles loading and caching of source files into memory.
SourceManager & getSourceManager()
Definition: BugReporter.h:565
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:5245