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