clang  9.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 "RetainCountChecker.h"
16 
17 using namespace clang;
18 using namespace ento;
19 using namespace retaincountchecker;
20 using llvm::StrInStrNoCase;
21 
22 REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
23 
24 namespace clang {
25 namespace ento {
26 namespace retaincountchecker {
27 
29  return State->get<RefBindings>(Sym);
30 }
31 
33  RefVal Val) {
34  assert(Sym != nullptr);
35  return State->set<RefBindings>(Sym, Val);
36 }
37 
39  return State->remove<RefBindings>(Sym);
40 }
41 
42 class UseAfterRelease : public RefCountBug {
43 public:
44  UseAfterRelease(const CheckerBase *checker)
45  : RefCountBug(checker, "Use-after-release") {}
46 
47  const char *getDescription() const override {
48  return "Reference-counted object is used after it is released";
49  }
50 };
51 
52 class BadRelease : public RefCountBug {
53 public:
54  BadRelease(const CheckerBase *checker) : RefCountBug(checker, "Bad release") {}
55 
56  const char *getDescription() const override {
57  return "Incorrect decrement of the reference count of an object that is "
58  "not owned at this point by the caller";
59  }
60 };
61 
62 class DeallocNotOwned : public RefCountBug {
63 public:
64  DeallocNotOwned(const CheckerBase *checker)
65  : RefCountBug(checker, "-dealloc sent to non-exclusively owned object") {}
66 
67  const char *getDescription() const override {
68  return "-dealloc sent to object that may be referenced elsewhere";
69  }
70 };
71 
72 class OverAutorelease : public RefCountBug {
73 public:
74  OverAutorelease(const CheckerBase *checker)
75  : RefCountBug(checker, "Object autoreleased too many times") {}
76 
77  const char *getDescription() const override {
78  return "Object autoreleased too many times";
79  }
80 };
81 
83 public:
85  : RefCountBug(checker, "Method should return an owned object") {}
86 
87  const char *getDescription() const override {
88  return "Object with a +0 retain count returned to caller where a +1 "
89  "(owning) retain count is expected";
90  }
91 };
92 
93 class Leak : public RefCountBug {
94 public:
95  Leak(const CheckerBase *checker, StringRef name) : RefCountBug(checker, name) {
96  // Leaks should not be reported if they are post-dominated by a sink.
97  setSuppressOnSink(true);
98  }
99 
100  const char *getDescription() const override { return ""; }
101 
102  bool isLeak() const override { return true; }
103 };
104 
105 } // end namespace retaincountchecker
106 } // end namespace ento
107 } // end namespace clang
108 
109 void RefVal::print(raw_ostream &Out) const {
110  if (!T.isNull())
111  Out << "Tracked " << T.getAsString() << " | ";
112 
113  switch (getKind()) {
114  default: llvm_unreachable("Invalid RefVal kind");
115  case Owned: {
116  Out << "Owned";
117  unsigned cnt = getCount();
118  if (cnt) Out << " (+ " << cnt << ")";
119  break;
120  }
121 
122  case NotOwned: {
123  Out << "NotOwned";
124  unsigned cnt = getCount();
125  if (cnt) Out << " (+ " << cnt << ")";
126  break;
127  }
128 
129  case ReturnedOwned: {
130  Out << "ReturnedOwned";
131  unsigned cnt = getCount();
132  if (cnt) Out << " (+ " << cnt << ")";
133  break;
134  }
135 
136  case ReturnedNotOwned: {
137  Out << "ReturnedNotOwned";
138  unsigned cnt = getCount();
139  if (cnt) Out << " (+ " << cnt << ")";
140  break;
141  }
142 
143  case Released:
144  Out << "Released";
145  break;
146 
147  case ErrorDeallocNotOwned:
148  Out << "-dealloc (not-owned)";
149  break;
150 
151  case ErrorLeak:
152  Out << "Leaked";
153  break;
154 
155  case ErrorLeakReturned:
156  Out << "Leaked (Bad naming)";
157  break;
158 
159  case ErrorUseAfterRelease:
160  Out << "Use-After-Release [ERROR]";
161  break;
162 
163  case ErrorReleaseNotOwned:
164  Out << "Release of Not-Owned [ERROR]";
165  break;
166 
168  Out << "Over-autoreleased";
169  break;
170 
172  Out << "Non-owned object returned instead of owned";
173  break;
174  }
175 
176  switch (getIvarAccessHistory()) {
178  break;
179  case IvarAccessHistory::AccessedDirectly:
180  Out << " [direct ivar access]";
181  break;
182  case IvarAccessHistory::ReleasedAfterDirectAccess:
183  Out << " [released after direct ivar access]";
184  }
185 
186  if (ACnt) {
187  Out << " [autorelease -" << ACnt << ']';
188  }
189 }
190 
191 namespace {
192 class StopTrackingCallback final : public SymbolVisitor {
194 public:
195  StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
196  ProgramStateRef getState() const { return state; }
197 
198  bool VisitSymbol(SymbolRef sym) override {
199  state = removeRefBinding(state, sym);
200  return true;
201  }
202 };
203 } // end anonymous namespace
204 
205 //===----------------------------------------------------------------------===//
206 // Handle statements that may have an effect on refcounts.
207 //===----------------------------------------------------------------------===//
208 
210  CheckerContext &C) const {
211 
212  // Scan the BlockDecRefExprs for any object the retain count checker
213  // may be tracking.
214  if (!BE->getBlockDecl()->hasCaptures())
215  return;
216 
218  auto *R = cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
219 
220  BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
221  E = R->referenced_vars_end();
222 
223  if (I == E)
224  return;
225 
226  // FIXME: For now we invalidate the tracking of all symbols passed to blocks
227  // via captured variables, even though captured variables result in a copy
228  // and in implicit increment/decrement of a retain count.
230  const LocationContext *LC = C.getLocationContext();
232 
233  for ( ; I != E; ++I) {
234  const VarRegion *VR = I.getCapturedRegion();
235  if (VR->getSuperRegion() == R) {
236  VR = MemMgr.getVarRegion(VR->getDecl(), LC);
237  }
238  Regions.push_back(VR);
239  }
240 
241  state = state->scanReachableSymbols<StopTrackingCallback>(Regions).getState();
242  C.addTransition(state);
243 }
244 
246  CheckerContext &C) const {
247  const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
248  if (!BE)
249  return;
250 
252 
253  switch (BE->getBridgeKind()) {
254  case OBC_Bridge:
255  // Do nothing.
256  return;
257  case OBC_BridgeRetained:
258  AE = AE.withKind(IncRef);
259  break;
260  case OBC_BridgeTransfer:
262  break;
263  }
264 
266  SymbolRef Sym = C.getSVal(CE).getAsLocSymbol();
267  if (!Sym)
268  return;
269  const RefVal* T = getRefBinding(state, Sym);
270  if (!T)
271  return;
272 
273  RefVal::Kind hasErr = (RefVal::Kind) 0;
274  state = updateSymbol(state, Sym, *T, AE, hasErr, C);
275 
276  if (hasErr) {
277  // FIXME: If we get an error during a bridge cast, should we report it?
278  return;
279  }
280 
281  C.addTransition(state);
282 }
283 
285  const Expr *Ex) const {
287  const ExplodedNode *pred = C.getPredecessor();
288  for (const Stmt *Child : Ex->children()) {
289  SVal V = pred->getSVal(Child);
290  if (SymbolRef sym = V.getAsSymbol())
291  if (const RefVal* T = getRefBinding(state, sym)) {
292  RefVal::Kind hasErr = (RefVal::Kind) 0;
293  state = updateSymbol(state, sym, *T,
294  ArgEffect(MayEscape, ObjKind::ObjC), hasErr, C);
295  if (hasErr) {
296  processNonLeakError(state, Child->getSourceRange(), hasErr, sym, C);
297  return;
298  }
299  }
300  }
301 
302  // Return the object as autoreleased.
303  // RetEffect RE = RetEffect::MakeNotOwned(ObjKind::ObjC);
304  if (SymbolRef sym =
305  state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
306  QualType ResultTy = Ex->getType();
307  state = setRefBinding(state, sym,
309  }
310 
311  C.addTransition(state);
312 }
313 
315  CheckerContext &C) const {
316  // Apply the 'MayEscape' to all values.
317  processObjCLiterals(C, AL);
318 }
319 
321  CheckerContext &C) const {
322  // Apply the 'MayEscape' to all keys and values.
323  processObjCLiterals(C, DL);
324 }
325 
327  CheckerContext &C) const {
328  const ExplodedNode *Pred = C.getPredecessor();
329  ProgramStateRef State = Pred->getState();
330 
331  if (SymbolRef Sym = Pred->getSVal(Ex).getAsSymbol()) {
332  QualType ResultTy = Ex->getType();
333  State = setRefBinding(State, Sym,
335  }
336 
337  C.addTransition(State);
338 }
339 
341  CheckerContext &C) const {
342  Optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>();
343  if (!IVarLoc)
344  return;
345 
347  SymbolRef Sym = State->getSVal(*IVarLoc).getAsSymbol();
348  if (!Sym || !dyn_cast_or_null<ObjCIvarRegion>(Sym->getOriginRegion()))
349  return;
350 
351  // Accessing an ivar directly is unusual. If we've done that, be more
352  // forgiving about what the surrounding code is allowed to do.
353 
354  QualType Ty = Sym->getType();
355  ObjKind Kind;
356  if (Ty->isObjCRetainableType())
357  Kind = ObjKind::ObjC;
358  else if (coreFoundation::isCFObjectRef(Ty))
359  Kind = ObjKind::CF;
360  else
361  return;
362 
363  // If the value is already known to be nil, don't bother tracking it.
364  ConstraintManager &CMgr = State->getConstraintManager();
365  if (CMgr.isNull(State, Sym).isConstrainedTrue())
366  return;
367 
368  if (const RefVal *RV = getRefBinding(State, Sym)) {
369  // If we've seen this symbol before, or we're only seeing it now because
370  // of something the analyzer has synthesized, don't do anything.
371  if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None ||
373  return;
374  }
375 
376  // Note that this value has been loaded from an ivar.
377  C.addTransition(setRefBinding(State, Sym, RV->withIvarAccess()));
378  return;
379  }
380 
381  RefVal PlusZero = RefVal::makeNotOwned(Kind, Ty);
382 
383  // In a synthesized accessor, the effective retain count is +0.
385  C.addTransition(setRefBinding(State, Sym, PlusZero));
386  return;
387  }
388 
389  State = setRefBinding(State, Sym, PlusZero.withIvarAccess());
390  C.addTransition(State);
391 }
392 
394  CheckerContext &C) const {
395  RetainSummaryManager &Summaries = getSummaryManager(C);
396 
397  // Leave null if no receiver.
398  QualType ReceiverType;
399  if (const auto *MC = dyn_cast<ObjCMethodCall>(&Call)) {
400  if (MC->isInstanceMessage()) {
401  SVal ReceiverV = MC->getReceiverSVal();
402  if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
403  if (const RefVal *T = getRefBinding(C.getState(), Sym))
404  ReceiverType = T->getType();
405  }
406  }
407 
408  const RetainSummary *Summ = Summaries.getSummary(Call, ReceiverType);
409 
410  if (C.wasInlined) {
411  processSummaryOfInlined(*Summ, Call, C);
412  return;
413  }
414  checkSummary(*Summ, Call, C);
415 }
416 
417 RefCountBug *
419  if (!leakWithinFunction)
420  leakWithinFunction.reset(new Leak(this, "Leak"));
421  return leakWithinFunction.get();
422 }
423 
424 RefCountBug *
426  if (!leakAtReturn)
427  leakAtReturn.reset(new Leak(this, "Leak of returned object"));
428  return leakAtReturn.get();
429 }
430 
431 /// GetReturnType - Used to get the return type of a message expression or
432 /// function call with the intention of affixing that type to a tracked symbol.
433 /// While the return type can be queried directly from RetEx, when
434 /// invoking class methods we augment to the return type to be that of
435 /// a pointer to the class (as opposed it just being id).
436 // FIXME: We may be able to do this with related result types instead.
437 // This function is probably overestimating.
438 static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
439  QualType RetTy = RetE->getType();
440  // If RetE is not a message expression just return its type.
441  // If RetE is a message expression, return its types if it is something
442  /// more specific than id.
443  if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
444  if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
445  if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
446  PT->isObjCClassType()) {
447  // At this point we know the return type of the message expression is
448  // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
449  // is a call to a class method whose type we can resolve. In such
450  // cases, promote the return type to XXX* (where XXX is the class).
451  const ObjCInterfaceDecl *D = ME->getReceiverInterface();
452  return !D ? RetTy :
454  }
455 
456  return RetTy;
457 }
458 
460  QualType ResultTy) {
461  if (RE.isOwned()) {
462  return RefVal::makeOwned(RE.getObjKind(), ResultTy);
463  } else if (RE.notOwned()) {
464  return RefVal::makeNotOwned(RE.getObjKind(), ResultTy);
465  }
466 
467  return None;
468 }
469 
470 static bool isPointerToObject(QualType QT) {
471  QualType PT = QT->getPointeeType();
472  if (!PT.isNull())
473  if (PT->getAsCXXRecordDecl())
474  return true;
475  return false;
476 }
477 
478 /// Whether the tracked value should be escaped on a given call.
479 /// OSObjects are escaped when passed to void * / etc.
480 static bool shouldEscapeOSArgumentOnCall(const CallEvent &CE, unsigned ArgIdx,
481  const RefVal *TrackedValue) {
482  if (TrackedValue->getObjKind() != ObjKind::OS)
483  return false;
484  if (ArgIdx >= CE.parameters().size())
485  return false;
486  return !isPointerToObject(CE.parameters()[ArgIdx]->getType());
487 }
488 
489 // We don't always get the exact modeling of the function with regards to the
490 // retain count checker even when the function is inlined. For example, we need
491 // to stop tracking the symbols which were marked with StopTrackingHard.
492 void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
493  const CallEvent &CallOrMsg,
494  CheckerContext &C) const {
496 
497  // Evaluate the effect of the arguments.
498  for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
499  SVal V = CallOrMsg.getArgSVal(idx);
500 
501  if (SymbolRef Sym = V.getAsLocSymbol()) {
502  bool ShouldRemoveBinding = Summ.getArg(idx).getKind() == StopTrackingHard;
503  if (const RefVal *T = getRefBinding(state, Sym))
504  if (shouldEscapeOSArgumentOnCall(CallOrMsg, idx, T))
505  ShouldRemoveBinding = true;
506 
507  if (ShouldRemoveBinding)
508  state = removeRefBinding(state, Sym);
509  }
510  }
511 
512  // Evaluate the effect on the message receiver.
513  if (const auto *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg)) {
514  if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
515  if (Summ.getReceiverEffect().getKind() == StopTrackingHard) {
516  state = removeRefBinding(state, Sym);
517  }
518  }
519  }
520 
521  // Consult the summary for the return value.
522  RetEffect RE = Summ.getRetEffect();
523 
524  if (SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol()) {
525  if (RE.getKind() == RetEffect::NoRetHard)
526  state = removeRefBinding(state, Sym);
527  }
528 
529  C.addTransition(state);
530 }
531 
532 /// A value escapes in these possible cases:
533 ///
534 /// - binding to something that is not a memory region.
535 /// - binding to a memregion that does not have stack storage
536 /// - binding to a variable that has a destructor attached using CleanupAttr
537 ///
538 /// We do not currently model what happens when a symbol is
539 /// assigned to a struct field, so be conservative here and let the symbol go.
540 /// FIXME: This could definitely be improved upon.
541 static bool shouldEscapeRegion(const MemRegion *R) {
542  const auto *VR = dyn_cast<VarRegion>(R);
543  if (!R->hasStackStorage() || !VR)
544  return true;
545 
546  const VarDecl *VD = VR->getDecl();
547  if (!VD->hasAttr<CleanupAttr>())
548  return false; // CleanupAttr attaches destructors, which cause escaping.
549  return true;
550 }
551 
553 updateOutParameters(ProgramStateRef State, const RetainSummary &Summ,
554  const CallEvent &CE) {
555 
556  SVal L = CE.getReturnValue();
557 
558  // Splitting is required to support out parameters,
559  // as out parameters might be created only on the "success" branch.
560  // We want to avoid eagerly splitting unless out parameters are actually
561  // needed.
562  bool SplitNecessary = false;
563  for (auto &P : Summ.getArgEffects())
564  if (P.second.getKind() == RetainedOutParameterOnNonZero ||
565  P.second.getKind() == RetainedOutParameterOnZero)
566  SplitNecessary = true;
567 
568  ProgramStateRef AssumeNonZeroReturn = State;
569  ProgramStateRef AssumeZeroReturn = State;
570 
571  if (SplitNecessary) {
572  if (auto DL = L.getAs<DefinedOrUnknownSVal>()) {
573  AssumeNonZeroReturn = AssumeNonZeroReturn->assume(*DL, true);
574  AssumeZeroReturn = AssumeZeroReturn->assume(*DL, false);
575  }
576  }
577 
578  for (unsigned idx = 0, e = CE.getNumArgs(); idx != e; ++idx) {
579  SVal ArgVal = CE.getArgSVal(idx);
580  ArgEffect AE = Summ.getArg(idx);
581 
582  auto *ArgRegion = dyn_cast_or_null<TypedValueRegion>(ArgVal.getAsRegion());
583  if (!ArgRegion)
584  continue;
585 
586  QualType PointeeTy = ArgRegion->getValueType();
587  SVal PointeeVal = State->getSVal(ArgRegion);
588  SymbolRef Pointee = PointeeVal.getAsLocSymbol();
589  if (!Pointee)
590  continue;
591 
592  if (shouldEscapeRegion(ArgRegion))
593  continue;
594 
595  auto makeNotOwnedParameter = [&](ProgramStateRef St) {
596  return setRefBinding(St, Pointee,
597  RefVal::makeNotOwned(AE.getObjKind(), PointeeTy));
598  };
599  auto makeOwnedParameter = [&](ProgramStateRef St) {
600  return setRefBinding(St, Pointee,
601  RefVal::makeOwned(ObjKind::OS, PointeeTy));
602  };
603 
604  switch (AE.getKind()) {
606  AssumeNonZeroReturn = makeNotOwnedParameter(AssumeNonZeroReturn);
607  AssumeZeroReturn = makeNotOwnedParameter(AssumeZeroReturn);
608  break;
610  AssumeNonZeroReturn = makeOwnedParameter(AssumeNonZeroReturn);
611  AssumeZeroReturn = makeOwnedParameter(AssumeZeroReturn);
612  break;
614  AssumeNonZeroReturn = makeOwnedParameter(AssumeNonZeroReturn);
615  break;
617  AssumeZeroReturn = makeOwnedParameter(AssumeZeroReturn);
618  break;
619  default:
620  break;
621  }
622  }
623 
624  if (SplitNecessary) {
625  return {AssumeNonZeroReturn, AssumeZeroReturn};
626  } else {
627  assert(AssumeZeroReturn == AssumeNonZeroReturn);
628  return {AssumeZeroReturn};
629  }
630 }
631 
632 void RetainCountChecker::checkSummary(const RetainSummary &Summ,
633  const CallEvent &CallOrMsg,
634  CheckerContext &C) const {
636 
637  // Evaluate the effect of the arguments.
638  RefVal::Kind hasErr = (RefVal::Kind) 0;
639  SourceRange ErrorRange;
640  SymbolRef ErrorSym = nullptr;
641 
642  // Helper tag for providing diagnostics: indicate whether dealloc was sent
643  // at this location.
644  static CheckerProgramPointTag DeallocSentTag(this, DeallocTagDescription);
645  bool DeallocSent = false;
646 
647  for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
648  SVal V = CallOrMsg.getArgSVal(idx);
649 
650  ArgEffect Effect = Summ.getArg(idx);
651  if (SymbolRef Sym = V.getAsLocSymbol()) {
652  if (const RefVal *T = getRefBinding(state, Sym)) {
653 
654  if (shouldEscapeOSArgumentOnCall(CallOrMsg, idx, T))
656 
657  state = updateSymbol(state, Sym, *T, Effect, hasErr, C);
658  if (hasErr) {
659  ErrorRange = CallOrMsg.getArgSourceRange(idx);
660  ErrorSym = Sym;
661  break;
662  } else if (Effect.getKind() == Dealloc) {
663  DeallocSent = true;
664  }
665  }
666  }
667  }
668 
669  // Evaluate the effect on the message receiver / `this` argument.
670  bool ReceiverIsTracked = false;
671  if (!hasErr) {
672  if (const auto *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg)) {
673  if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
674  if (const RefVal *T = getRefBinding(state, Sym)) {
675  ReceiverIsTracked = true;
676  state = updateSymbol(state, Sym, *T,
677  Summ.getReceiverEffect(), hasErr, C);
678  if (hasErr) {
679  ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
680  ErrorSym = Sym;
681  } else if (Summ.getReceiverEffect().getKind() == Dealloc) {
682  DeallocSent = true;
683  }
684  }
685  }
686  } else if (const auto *MCall = dyn_cast<CXXMemberCall>(&CallOrMsg)) {
687  if (SymbolRef Sym = MCall->getCXXThisVal().getAsLocSymbol()) {
688  if (const RefVal *T = getRefBinding(state, Sym)) {
689  state = updateSymbol(state, Sym, *T, Summ.getThisEffect(),
690  hasErr, C);
691  if (hasErr) {
692  ErrorRange = MCall->getOriginExpr()->getSourceRange();
693  ErrorSym = Sym;
694  }
695  }
696  }
697  }
698  }
699 
700  // Process any errors.
701  if (hasErr) {
702  processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
703  return;
704  }
705 
706  // Consult the summary for the return value.
707  RetEffect RE = Summ.getRetEffect();
708 
710  if (ReceiverIsTracked)
711  RE = getSummaryManager(C).getObjAllocRetEffect();
712  else
713  RE = RetEffect::MakeNoRet();
714  }
715 
716  if (SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol()) {
717  QualType ResultTy = CallOrMsg.getResultType();
718  if (RE.notOwned()) {
719  const Expr *Ex = CallOrMsg.getOriginExpr();
720  assert(Ex);
721  ResultTy = GetReturnType(Ex, C.getASTContext());
722  }
723  if (Optional<RefVal> updatedRefVal = refValFromRetEffect(RE, ResultTy))
724  state = setRefBinding(state, Sym, *updatedRefVal);
725  }
726 
728  updateOutParameters(state, Summ, CallOrMsg);
729 
730  for (ProgramStateRef St : Out) {
731  if (DeallocSent) {
732  C.addTransition(St, C.getPredecessor(), &DeallocSentTag);
733  } else {
734  C.addTransition(St);
735  }
736  }
737 }
738 
740  SymbolRef sym, RefVal V,
741  ArgEffect AE,
742  RefVal::Kind &hasErr,
743  CheckerContext &C) const {
744  bool IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
745  if (AE.getObjKind() == ObjKind::ObjC && IgnoreRetainMsg) {
746  switch (AE.getKind()) {
747  default:
748  break;
749  case IncRef:
750  AE = AE.withKind(DoNothing);
751  break;
752  case DecRef:
753  AE = AE.withKind(DoNothing);
754  break;
756  AE = AE.withKind(StopTracking);
757  break;
758  }
759  }
760 
761  // Handle all use-after-releases.
762  if (V.getKind() == RefVal::Released) {
764  hasErr = V.getKind();
765  return setRefBinding(state, sym, V);
766  }
767 
768  switch (AE.getKind()) {
773  llvm_unreachable("Applies to pointer-to-pointer parameters, which should "
774  "not have ref state.");
775 
776  case Dealloc: // NB. we only need to add a note in a non-error case.
777  switch (V.getKind()) {
778  default:
779  llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
780  case RefVal::Owned:
781  // The object immediately transitions to the released state.
782  V = V ^ RefVal::Released;
783  V.clearCounts();
784  return setRefBinding(state, sym, V);
785  case RefVal::NotOwned:
787  hasErr = V.getKind();
788  break;
789  }
790  break;
791 
792  case MayEscape:
793  if (V.getKind() == RefVal::Owned) {
794  V = V ^ RefVal::NotOwned;
795  break;
796  }
797 
798  LLVM_FALLTHROUGH;
799 
800  case DoNothing:
801  return state;
802 
803  case Autorelease:
804  // Update the autorelease counts.
805  V = V.autorelease();
806  break;
807 
808  case StopTracking:
809  case StopTrackingHard:
810  return removeRefBinding(state, sym);
811 
812  case IncRef:
813  switch (V.getKind()) {
814  default:
815  llvm_unreachable("Invalid RefVal state for a retain.");
816  case RefVal::Owned:
817  case RefVal::NotOwned:
818  V = V + 1;
819  break;
820  }
821  break;
822 
823  case DecRef:
826  switch (V.getKind()) {
827  default:
828  // case 'RefVal::Released' handled above.
829  llvm_unreachable("Invalid RefVal state for a release.");
830 
831  case RefVal::Owned:
832  assert(V.getCount() > 0);
833  if (V.getCount() == 1) {
834  if (AE.getKind() == DecRefBridgedTransferred ||
835  V.getIvarAccessHistory() ==
837  V = V ^ RefVal::NotOwned;
838  else
839  V = V ^ RefVal::Released;
840  } else if (AE.getKind() == DecRefAndStopTrackingHard) {
841  return removeRefBinding(state, sym);
842  }
843 
844  V = V - 1;
845  break;
846 
847  case RefVal::NotOwned:
848  if (V.getCount() > 0) {
850  return removeRefBinding(state, sym);
851  V = V - 1;
852  } else if (V.getIvarAccessHistory() ==
854  // Assume that the instance variable was holding on the object at
855  // +1, and we just didn't know.
857  return removeRefBinding(state, sym);
859  } else {
861  hasErr = V.getKind();
862  }
863  break;
864  }
865  break;
866  }
867  return setRefBinding(state, sym, V);
868 }
869 
871  SourceRange ErrorRange,
873  SymbolRef Sym,
874  CheckerContext &C) const {
875  // HACK: Ignore retain-count issues on values accessed through ivars,
876  // because of cases like this:
877  // [_contentView retain];
878  // [_contentView removeFromSuperview];
879  // [self addSubview:_contentView]; // invalidates 'self'
880  // [_contentView release];
881  if (const RefVal *RV = getRefBinding(St, Sym))
882  if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
883  return;
884 
885  ExplodedNode *N = C.generateErrorNode(St);
886  if (!N)
887  return;
888 
889  RefCountBug *BT;
890  switch (ErrorKind) {
891  default:
892  llvm_unreachable("Unhandled error.");
894  if (!useAfterRelease)
895  useAfterRelease.reset(new UseAfterRelease(this));
896  BT = useAfterRelease.get();
897  break;
899  if (!releaseNotOwned)
900  releaseNotOwned.reset(new BadRelease(this));
901  BT = releaseNotOwned.get();
902  break;
904  if (!deallocNotOwned)
905  deallocNotOwned.reset(new DeallocNotOwned(this));
906  BT = deallocNotOwned.get();
907  break;
908  }
909 
910  assert(BT);
911  auto report = llvm::make_unique<RefCountReport>(
912  *BT, C.getASTContext().getLangOpts(), N, Sym);
913  report->addRange(ErrorRange);
914  C.emitReport(std::move(report));
915 }
916 
917 //===----------------------------------------------------------------------===//
918 // Handle the return values of retain-count-related functions.
919 //===----------------------------------------------------------------------===//
920 
922  // Get the callee. We're only interested in simple C functions.
924  const FunctionDecl *FD = C.getCalleeDecl(CE);
925  if (!FD)
926  return false;
927 
928  RetainSummaryManager &SmrMgr = getSummaryManager(C);
929  QualType ResultTy = CE->getCallReturnType(C.getASTContext());
930 
931  // See if the function has 'rc_ownership_trusted_implementation'
932  // annotate attribute. If it does, we will not inline it.
933  bool hasTrustedImplementationAnnotation = false;
934 
935  const LocationContext *LCtx = C.getLocationContext();
936 
937  using BehaviorSummary = RetainSummaryManager::BehaviorSummary;
939  SmrMgr.canEval(CE, FD, hasTrustedImplementationAnnotation);
940 
941  // See if it's one of the specific functions we know how to eval.
942  if (!BSmr)
943  return false;
944 
945  // Bind the return value.
946  if (BSmr == BehaviorSummary::Identity ||
947  BSmr == BehaviorSummary::IdentityOrZero) {
948  SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
949 
950  // If the receiver is unknown or the function has
951  // 'rc_ownership_trusted_implementation' annotate attribute, conjure a
952  // return value.
953  if (RetVal.isUnknown() ||
954  (hasTrustedImplementationAnnotation && !ResultTy.isNull())) {
955  SValBuilder &SVB = C.getSValBuilder();
956  RetVal =
957  SVB.conjureSymbolVal(nullptr, CE, LCtx, ResultTy, C.blockCount());
958  }
959  state = state->BindExpr(CE, LCtx, RetVal, /*Invalidate=*/false);
960 
961  if (BSmr == BehaviorSummary::IdentityOrZero) {
962  // Add a branch where the output is zero.
963  ProgramStateRef NullOutputState = C.getState();
964 
965  // Assume that output is zero on the other branch.
966  NullOutputState = NullOutputState->BindExpr(
967  CE, LCtx, C.getSValBuilder().makeNull(), /*Invalidate=*/false);
968 
969  C.addTransition(NullOutputState);
970 
971  // And on the original branch assume that both input and
972  // output are non-zero.
973  if (auto L = RetVal.getAs<DefinedOrUnknownSVal>())
974  state = state->assume(*L, /*Assumption=*/true);
975 
976  }
977  }
978 
979  C.addTransition(state);
980  return true;
981 }
982 
983 ExplodedNode * RetainCountChecker::processReturn(const ReturnStmt *S,
984  CheckerContext &C) const {
985  ExplodedNode *Pred = C.getPredecessor();
986 
987  // Only adjust the reference count if this is the top-level call frame,
988  // and not the result of inlining. In the future, we should do
989  // better checking even for inlined calls, and see if they match
990  // with their expected semantics (e.g., the method should return a retained
991  // object, etc.).
992  if (!C.inTopFrame())
993  return Pred;
994 
995  if (!S)
996  return Pred;
997 
998  const Expr *RetE = S->getRetValue();
999  if (!RetE)
1000  return Pred;
1001 
1003  SymbolRef Sym =
1004  state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
1005  if (!Sym)
1006  return Pred;
1007 
1008  // Get the reference count binding (if any).
1009  const RefVal *T = getRefBinding(state, Sym);
1010  if (!T)
1011  return Pred;
1012 
1013  // Change the reference count.
1014  RefVal X = *T;
1015 
1016  switch (X.getKind()) {
1017  case RefVal::Owned: {
1018  unsigned cnt = X.getCount();
1019  assert(cnt > 0);
1020  X.setCount(cnt - 1);
1021  X = X ^ RefVal::ReturnedOwned;
1022  break;
1023  }
1024 
1025  case RefVal::NotOwned: {
1026  unsigned cnt = X.getCount();
1027  if (cnt) {
1028  X.setCount(cnt - 1);
1029  X = X ^ RefVal::ReturnedOwned;
1030  } else {
1031  X = X ^ RefVal::ReturnedNotOwned;
1032  }
1033  break;
1034  }
1035 
1036  default:
1037  return Pred;
1038  }
1039 
1040  // Update the binding.
1041  state = setRefBinding(state, Sym, X);
1042  Pred = C.addTransition(state);
1043 
1044  // At this point we have updated the state properly.
1045  // Everything after this is merely checking to see if the return value has
1046  // been over- or under-retained.
1047 
1048  // Did we cache out?
1049  if (!Pred)
1050  return nullptr;
1051 
1052  // Update the autorelease counts.
1053  static CheckerProgramPointTag AutoreleaseTag(this, "Autorelease");
1054  state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X, S);
1055 
1056  // Have we generated a sink node?
1057  if (!state)
1058  return nullptr;
1059 
1060  // Get the updated binding.
1061  T = getRefBinding(state, Sym);
1062  assert(T);
1063  X = *T;
1064 
1065  // Consult the summary of the enclosing method.
1066  RetainSummaryManager &Summaries = getSummaryManager(C);
1067  const Decl *CD = &Pred->getCodeDecl();
1069 
1070  // FIXME: What is the convention for blocks? Is there one?
1071  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
1072  const RetainSummary *Summ = Summaries.getMethodSummary(MD);
1073  RE = Summ->getRetEffect();
1074  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
1075  if (!isa<CXXMethodDecl>(FD)) {
1076  const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
1077  RE = Summ->getRetEffect();
1078  }
1079  }
1080 
1081  return checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
1082 }
1083 
1085  CheckerContext &C,
1086  ExplodedNode *Pred,
1087  RetEffect RE, RefVal X,
1088  SymbolRef Sym,
1089  ProgramStateRef state) const {
1090  // HACK: Ignore retain-count issues on values accessed through ivars,
1091  // because of cases like this:
1092  // [_contentView retain];
1093  // [_contentView removeFromSuperview];
1094  // [self addSubview:_contentView]; // invalidates 'self'
1095  // [_contentView release];
1097  return Pred;
1098 
1099  // Any leaks or other errors?
1100  if (X.isReturnedOwned() && X.getCount() == 0) {
1101  if (RE.getKind() != RetEffect::NoRet) {
1102  if (!RE.isOwned()) {
1103 
1104  // The returning type is a CF, we expect the enclosing method should
1105  // return ownership.
1106  X = X ^ RefVal::ErrorLeakReturned;
1107 
1108  // Generate an error node.
1109  state = setRefBinding(state, Sym, X);
1110 
1111  static CheckerProgramPointTag ReturnOwnLeakTag(this, "ReturnsOwnLeak");
1112  ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
1113  if (N) {
1114  const LangOptions &LOpts = C.getASTContext().getLangOpts();
1115  auto R = llvm::make_unique<RefLeakReport>(
1116  *getLeakAtReturnBug(LOpts), LOpts, N, Sym, C);
1117  C.emitReport(std::move(R));
1118  }
1119  return N;
1120  }
1121  }
1122  } else if (X.isReturnedNotOwned()) {
1123  if (RE.isOwned()) {
1124  if (X.getIvarAccessHistory() ==
1126  // Assume the method was trying to transfer a +1 reference from a
1127  // strong ivar to the caller.
1128  state = setRefBinding(state, Sym,
1130  } else {
1131  // Trying to return a not owned object to a caller expecting an
1132  // owned object.
1133  state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
1134 
1135  static CheckerProgramPointTag
1136  ReturnNotOwnedTag(this, "ReturnNotOwnedForOwned");
1137 
1138  ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
1139  if (N) {
1140  if (!returnNotOwnedForOwned)
1141  returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned(this));
1142 
1143  auto R = llvm::make_unique<RefCountReport>(
1144  *returnNotOwnedForOwned, C.getASTContext().getLangOpts(), N, Sym);
1145  C.emitReport(std::move(R));
1146  }
1147  return N;
1148  }
1149  }
1150  }
1151  return Pred;
1152 }
1153 
1154 //===----------------------------------------------------------------------===//
1155 // Check various ways a symbol can be invalidated.
1156 //===----------------------------------------------------------------------===//
1157 
1159  CheckerContext &C) const {
1161  const MemRegion *MR = loc.getAsRegion();
1162 
1163  // Find all symbols referenced by 'val' that we are tracking
1164  // and stop tracking them.
1165  if (MR && shouldEscapeRegion(MR)) {
1166  state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1167  C.addTransition(state);
1168  }
1169 }
1170 
1172  SVal Cond,
1173  bool Assumption) const {
1174  // FIXME: We may add to the interface of evalAssume the list of symbols
1175  // whose assumptions have changed. For now we just iterate through the
1176  // bindings and check if any of the tracked symbols are NULL. This isn't
1177  // too bad since the number of symbols we will track in practice are
1178  // probably small and evalAssume is only called at branches and a few
1179  // other places.
1180  RefBindingsTy B = state->get<RefBindings>();
1181 
1182  if (B.isEmpty())
1183  return state;
1184 
1185  bool changed = false;
1186  RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
1187  ConstraintManager &CMgr = state->getConstraintManager();
1188 
1189  for (auto &I : B) {
1190  // Check if the symbol is null stop tracking the symbol.
1191  ConditionTruthVal AllocFailed = CMgr.isNull(state, I.first);
1192  if (AllocFailed.isConstrainedTrue()) {
1193  changed = true;
1194  B = RefBFactory.remove(B, I.first);
1195  }
1196  }
1197 
1198  if (changed)
1199  state = state->set<RefBindings>(B);
1200 
1201  return state;
1202 }
1203 
1205  ProgramStateRef state, const InvalidatedSymbols *invalidated,
1206  ArrayRef<const MemRegion *> ExplicitRegions,
1207  ArrayRef<const MemRegion *> Regions, const LocationContext *LCtx,
1208  const CallEvent *Call) const {
1209  if (!invalidated)
1210  return state;
1211 
1212  llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
1213 
1214  for (const MemRegion *I : ExplicitRegions)
1215  if (const SymbolicRegion *SR = I->StripCasts()->getAs<SymbolicRegion>())
1216  WhitelistedSymbols.insert(SR->getSymbol());
1217 
1218  for (SymbolRef sym : *invalidated) {
1219  if (WhitelistedSymbols.count(sym))
1220  continue;
1221  // Remove any existing reference-count binding.
1222  state = removeRefBinding(state, sym);
1223  }
1224  return state;
1225 }
1226 
1229  ExplodedNode *Pred,
1230  const ProgramPointTag *Tag,
1231  CheckerContext &Ctx,
1232  SymbolRef Sym,
1233  RefVal V,
1234  const ReturnStmt *S) const {
1235  unsigned ACnt = V.getAutoreleaseCount();
1236 
1237  // No autorelease counts? Nothing to be done.
1238  if (!ACnt)
1239  return state;
1240 
1241  unsigned Cnt = V.getCount();
1242 
1243  // FIXME: Handle sending 'autorelease' to already released object.
1244 
1245  if (V.getKind() == RefVal::ReturnedOwned)
1246  ++Cnt;
1247 
1248  // If we would over-release here, but we know the value came from an ivar,
1249  // assume it was a strong ivar that's just been relinquished.
1250  if (ACnt > Cnt &&
1252  V = V.releaseViaIvar();
1253  --ACnt;
1254  }
1255 
1256  if (ACnt <= Cnt) {
1257  if (ACnt == Cnt) {
1258  V.clearCounts();
1259  if (V.getKind() == RefVal::ReturnedOwned) {
1260  V = V ^ RefVal::ReturnedNotOwned;
1261  } else {
1262  V = V ^ RefVal::NotOwned;
1263  }
1264  } else {
1265  V.setCount(V.getCount() - ACnt);
1266  V.setAutoreleaseCount(0);
1267  }
1268  return setRefBinding(state, Sym, V);
1269  }
1270 
1271  // HACK: Ignore retain-count issues on values accessed through ivars,
1272  // because of cases like this:
1273  // [_contentView retain];
1274  // [_contentView removeFromSuperview];
1275  // [self addSubview:_contentView]; // invalidates 'self'
1276  // [_contentView release];
1278  return state;
1279 
1280  // Woah! More autorelease counts then retain counts left.
1281  // Emit hard error.
1283  state = setRefBinding(state, Sym, V);
1284 
1285  ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
1286  if (N) {
1287  SmallString<128> sbuf;
1288  llvm::raw_svector_ostream os(sbuf);
1289  os << "Object was autoreleased ";
1290  if (V.getAutoreleaseCount() > 1)
1291  os << V.getAutoreleaseCount() << " times but the object ";
1292  else
1293  os << "but ";
1294  os << "has a +" << V.getCount() << " retain count";
1295 
1296  if (!overAutorelease)
1297  overAutorelease.reset(new OverAutorelease(this));
1298 
1299  const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
1300  auto R = llvm::make_unique<RefCountReport>(*overAutorelease, LOpts, N, Sym,
1301  os.str());
1302  Ctx.emitReport(std::move(R));
1303  }
1304 
1305  return nullptr;
1306 }
1307 
1310  SymbolRef sid, RefVal V,
1311  SmallVectorImpl<SymbolRef> &Leaked) const {
1312  bool hasLeak;
1313 
1314  // HACK: Ignore retain-count issues on values accessed through ivars,
1315  // because of cases like this:
1316  // [_contentView retain];
1317  // [_contentView removeFromSuperview];
1318  // [self addSubview:_contentView]; // invalidates 'self'
1319  // [_contentView release];
1321  hasLeak = false;
1322  else if (V.isOwned())
1323  hasLeak = true;
1324  else if (V.isNotOwned() || V.isReturnedOwned())
1325  hasLeak = (V.getCount() > 0);
1326  else
1327  hasLeak = false;
1328 
1329  if (!hasLeak)
1330  return removeRefBinding(state, sid);
1331 
1332  Leaked.push_back(sid);
1333  return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
1334 }
1335 
1336 ExplodedNode *
1339  CheckerContext &Ctx,
1340  ExplodedNode *Pred) const {
1341  // Generate an intermediate node representing the leak point.
1342  ExplodedNode *N = Ctx.addTransition(state, Pred);
1343  const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
1344 
1345  if (N) {
1346  for (SymbolRef L : Leaked) {
1347  RefCountBug *BT = Pred ? getLeakWithinFunctionBug(LOpts)
1348  : getLeakAtReturnBug(LOpts);
1349  assert(BT && "BugType not initialized.");
1350 
1351  Ctx.emitReport(llvm::make_unique<RefLeakReport>(*BT, LOpts, N, L, Ctx));
1352  }
1353  }
1354 
1355  return N;
1356 }
1357 
1358 static bool isISLObjectRef(QualType Ty) {
1359  return StringRef(Ty.getAsString()).startswith("isl_");
1360 }
1361 
1363  if (!Ctx.inTopFrame())
1364  return;
1365 
1366  RetainSummaryManager &SmrMgr = getSummaryManager(Ctx);
1367  const LocationContext *LCtx = Ctx.getLocationContext();
1368  const FunctionDecl *FD = dyn_cast<FunctionDecl>(LCtx->getDecl());
1369 
1370  if (!FD || SmrMgr.isTrustedReferenceCountImplementation(FD))
1371  return;
1372 
1373  ProgramStateRef state = Ctx.getState();
1374  const RetainSummary *FunctionSummary = SmrMgr.getFunctionSummary(FD);
1375  ArgEffects CalleeSideArgEffects = FunctionSummary->getArgEffects();
1376 
1377  for (unsigned idx = 0, e = FD->getNumParams(); idx != e; ++idx) {
1378  const ParmVarDecl *Param = FD->getParamDecl(idx);
1379  SymbolRef Sym = state->getSVal(state->getRegion(Param, LCtx)).getAsSymbol();
1380 
1381  QualType Ty = Param->getType();
1382  const ArgEffect *AE = CalleeSideArgEffects.lookup(idx);
1383  if (AE && AE->getKind() == DecRef && isISLObjectRef(Ty)) {
1384  state = setRefBinding(
1385  state, Sym, RefVal::makeOwned(ObjKind::Generalized, Ty));
1386  } else if (isISLObjectRef(Ty)) {
1387  state = setRefBinding(
1388  state, Sym,
1390  }
1391  }
1392 
1393  Ctx.addTransition(state);
1394 }
1395 
1397  CheckerContext &Ctx) const {
1398  ExplodedNode *Pred = processReturn(RS, Ctx);
1399 
1400  // Created state cached out.
1401  if (!Pred) {
1402  return;
1403  }
1404 
1405  ProgramStateRef state = Pred->getState();
1406  RefBindingsTy B = state->get<RefBindings>();
1407 
1408  // Don't process anything within synthesized bodies.
1409  const LocationContext *LCtx = Pred->getLocationContext();
1410  if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
1411  assert(!LCtx->inTopFrame());
1412  return;
1413  }
1414 
1415  for (auto &I : B) {
1416  state = handleAutoreleaseCounts(state, Pred, /*Tag=*/nullptr, Ctx,
1417  I.first, I.second);
1418  if (!state)
1419  return;
1420  }
1421 
1422  // If the current LocationContext has a parent, don't check for leaks.
1423  // We will do that later.
1424  // FIXME: we should instead check for imbalances of the retain/releases,
1425  // and suggest annotations.
1426  if (LCtx->getParent())
1427  return;
1428 
1429  B = state->get<RefBindings>();
1431 
1432  for (auto &I : B)
1433  state = handleSymbolDeath(state, I.first, I.second, Leaked);
1434 
1435  processLeaks(state, Leaked, Ctx, Pred);
1436 }
1437 
1439  CheckerContext &C) const {
1440  ExplodedNode *Pred = C.getPredecessor();
1441 
1444 
1445  // Update counts from autorelease pools
1446  for (const auto &I: state->get<RefBindings>()) {
1447  SymbolRef Sym = I.first;
1448  if (SymReaper.isDead(Sym)) {
1449  static CheckerProgramPointTag Tag(this, "DeadSymbolAutorelease");
1450  const RefVal &V = I.second;
1451  state = handleAutoreleaseCounts(state, Pred, &Tag, C, Sym, V);
1452  if (!state)
1453  return;
1454 
1455  // Fetch the new reference count from the state, and use it to handle
1456  // this symbol.
1457  state = handleSymbolDeath(state, Sym, *getRefBinding(state, Sym), Leaked);
1458  }
1459  }
1460 
1461  if (Leaked.empty()) {
1462  C.addTransition(state);
1463  return;
1464  }
1465 
1466  Pred = processLeaks(state, Leaked, C, Pred);
1467 
1468  // Did we cache out?
1469  if (!Pred)
1470  return;
1471 
1472  // Now generate a new node that nukes the old bindings.
1473  // The only bindings left at this point are the leaked symbols.
1474  RefBindingsTy::Factory &F = state->get_context<RefBindings>();
1475  RefBindingsTy B = state->get<RefBindings>();
1476 
1477  for (SymbolRef L : Leaked)
1478  B = F.remove(B, L);
1479 
1480  state = state->set<RefBindings>(B);
1481  C.addTransition(state, Pred);
1482 }
1483 
1485  const char *NL, const char *Sep) const {
1486 
1487  RefBindingsTy B = State->get<RefBindings>();
1488 
1489  if (B.isEmpty())
1490  return;
1491 
1492  Out << Sep << NL;
1493 
1494  for (auto &I : B) {
1495  Out << I.first << " : ";
1496  I.second.print(Out);
1497  Out << NL;
1498  }
1499 }
1500 
1501 //===----------------------------------------------------------------------===//
1502 // Checker registration.
1503 //===----------------------------------------------------------------------===//
1504 
1505 void ento::registerRetainCountChecker(CheckerManager &Mgr) {
1506  auto *Chk = Mgr.registerChecker<RetainCountChecker>();
1507  Chk->TrackObjCAndCFObjects = true;
1508 }
1509 
1510 // FIXME: remove this, hack for backwards compatibility:
1511 // it should be possible to enable the NS/CF retain count checker as
1512 // osx.cocoa.RetainCount, and it should be possible to disable
1513 // osx.OSObjectRetainCount using osx.cocoa.RetainCount:CheckOSObject=false.
1515  auto I = Options.Config.find("osx.cocoa.RetainCount:CheckOSObject");
1516  if (I != Options.Config.end())
1517  return I->getValue() == "false";
1518  return false;
1519 }
1520 
1521 void ento::registerOSObjectRetainCountChecker(CheckerManager &Mgr) {
1522  auto *Chk = Mgr.registerChecker<RetainCountChecker>();
1524  Chk->TrackOSObjects = true;
1525 }
Indicates that the tracked object is a generalized object.
Indicates that the tracked object is a CF object.
const BlockDecl * getBlockDecl() const
Definition: Expr.h:5191
ProgramStateRef handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred, const ProgramPointTag *Tag, CheckerContext &Ctx, SymbolRef Sym, RefVal V, const ReturnStmt *S=nullptr) const
Represents a function declaration or definition.
Definition: Decl.h:1738
There is no effect.
ObjKind
Determines the object kind of a tracked object.
A (possibly-)qualified type.
Definition: Type.h:638
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:95
ExplodedNode * generateErrorNode(ProgramStateRef State=nullptr, const ProgramPointTag *Tag=nullptr)
Generate a transition to a node that will be used to report an error.
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2553
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition: Decl.h:3977
ProgramStateRef handleSymbolDeath(ProgramStateRef state, SymbolRef sid, RefVal V, SmallVectorImpl< SymbolRef > &Leaked) const
bool isDead(SymbolRef sym)
Returns whether or not a symbol has been confirmed dead.
The argument has its reference count decreased by 1 to model a transferred bridge cast under ARC...
bool evalCall(const CallExpr *CE, CheckerContext &C) const
Stmt - This represents one statement.
Definition: Stmt.h:66
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:505
Bridging via __bridge, which does nothing but reinterpret the bits.
All typestate tracking of the object ceases.
static ProgramStateRef setRefBinding(ProgramStateRef State, SymbolRef Sym, RefVal Val)
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:87
The argument has its reference count increased by 1.
StringRef P
static SmallVector< ProgramStateRef, 2 > updateOutParameters(ProgramStateRef State, const RetainSummary &Summ, const CallEvent &CE)
void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const
The argument is treated as if an -autorelease message had been sent to the referenced object...
const ProgramStateRef & getState() const
Indicates that no retain count information is tracked for the return value.
static bool isPointerToObject(QualType QT)
RefCountBug * getLeakAtReturnBug(const LangOptions &LOpts) const
const Expr * getOriginExpr() const
Returns the expression whose value will be the result of this call.
Definition: CallEvent.h:255
static RetEffect MakeNoRet()
Represents a variable declaration or definition.
Definition: Decl.h:813
SymbolRef getAsLocSymbol(bool IncludeBaseRegions=false) const
If this SVal is a location and wraps a symbol, return that SymbolRef.
Definition: SVals.cpp:85
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6755
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:102
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:1550
const bool wasInlined
If we are post visiting a call, this flag will be set if the call was inlined.
RefCountBug * getLeakWithinFunctionBug(const LangOptions &LOpts) const
Symbolic value.
Definition: SymExpr.h:30
const MemRegion * getSuperRegion() const
Definition: MemRegion.h:448
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...
MemRegionManager & getRegionManager()
Definition: SValBuilder.h:175
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:155
LineState State
void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange, RefVal::Kind ErrorKind, SymbolRef Sym, CheckerContext &C) const
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
The argument has its reference count decreased by 1.
The argument is a pointer to a retain-counted object; on exit, the new value of the pointer is a +0 v...
void checkPostCall(const CallEvent &Call, CheckerContext &C) const
Indicates that the return value is an owned object when the receiver is also a tracked object...
child_range children()
Definition: Stmt.cpp:237
const LocationContext * getLocationContext() const
The argument is a pointer to a retain-counted object; on exit, the new value of the pointer is a +1 v...
bool isUnknown() const
Definition: SVals.h:137
SVal getReturnValue() const
Returns the return value of the call.
Definition: CallEvent.cpp:415
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2998
const char * getDescription() const override
static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym)
Represents an ObjC class declaration.
Definition: DeclObjC.h:1172
Bridging via __bridge_transfer, which transfers ownership of an Objective-C pointer into ARC...
static bool shouldEscapeOSArgumentOnCall(const CallEvent &CE, unsigned ArgIdx, const RefVal *TrackedValue)
Whether the tracked value should be escaped on a given call.
virtual QualType getType() const =0
virtual ArrayRef< ParmVarDecl * > parameters() const =0
Return call&#39;s formal parameters.
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:531
bool isConstrainedTrue() const
Return true if the constraint is perfectly constrained to &#39;true&#39;.
void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1613
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...
IvarAccessHistory getIvarAccessHistory() const
Returns what the analyzer knows about direct accesses to a particular instance variable.
const RegionTy * getAs() const
Definition: MemRegion.h:1231
SymbolicRegion - A special, "non-concrete" region.
Definition: MemRegion.h:764
The argument is treated as potentially escaping, meaning that even when its reference count hits 0 it...
void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const
This represents one expression.
Definition: Expr.h:106
static bool shouldEscapeRegion(const MemRegion *R)
A value escapes in these possible cases:
bool TrackObjCAndCFObjects
Track Objective-C and CoreFoundation objects.
bool isObjCRetainableType() const
Definition: Type.cpp:3921
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:5177
#define bool
Definition: stdbool.h:31
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition: ExprObjC.h:288
void printState(raw_ostream &Out, ProgramStateRef State, const char *NL, const char *Sep) const override
See CheckerManager::runCheckersForPrintState.
QualType getType() const
Definition: Expr.h:128
The argument is treated as if the referenced object was deallocated.
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
Definition: Stmt.h:2443
ExplodedNode * checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C, ExplodedNode *Pred, RetEffect RE, RefVal X, SymbolRef Sym, ProgramStateRef state) const
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:904
void processObjCLiterals(CheckerContext &C, const Expr *Ex) const
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl...
ObjCBridgeCastKind getBridgeKind() const
Determine which kind of bridge is being performed via this cast.
Definition: ExprObjC.h:1602
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:703
ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym, RefVal V, ArgEffect E, RefVal::Kind &hasErr, CheckerContext &C) const
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:953
void emitReport(std::unique_ptr< BugReport > R)
Emit the diagnostics report.
static bool isISLObjectRef(QualType Ty)
Kind
ArgEffectKind getKind() const
DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag, const Expr *expr, const LocationContext *LCtx, unsigned count)
Create a new symbol with a unique &#39;name&#39;.
CHECKER * registerChecker(AT &&... Args)
Used to register checkers.
Expr * getRetValue()
Definition: Stmt.h:2476
ExplodedNode * generateSink(ProgramStateRef State, ExplodedNode *Pred, const ProgramPointTag *Tag=nullptr)
Generate a sink node.
Leak(const CheckerBase *checker, StringRef name)
#define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value)
Declares an immutable map of type NameTy, suitable for placement into the ProgramState.
ProgramPoints can be "tagged" as representing points specific to a given analysis entity...
Definition: ProgramPoint.h:40
Indicates that the tracked object is an Objective-C object.
const MemRegion * getAsRegion() const
Definition: SVals.cpp:151
ConfigTable Config
A key-value table of use-specified configuration values.
ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond, bool Assumption) const
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2285
SVal - This represents a symbolic expression, which can be either an L-value or an R-value...
Definition: SVals.h:76
Performs the combined functionality of DecRef and StopTrackingHard.
A class responsible for cleaning up unused symbols.
SVal getSVal(const Stmt *S) const
Get the value of an arbitrary expression at this node.
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:117
static bool hasPrevCheckOSObjectOptionDisabled(AnalyzerOptions &Options)
unsigned blockCount() const
Returns the number of times the current block has been visited along the analyzed path...
An Objective-C "bridged" cast expression, which casts between Objective-C pointers and C pointers...
Definition: ExprObjC.h:1575
Dataflow Directional Tag Classes.
virtual SourceRange getArgSourceRange(unsigned Index) const
Returns the source range for errors associated with this argument.
Definition: CallEvent.cpp:408
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:846
static Optional< RefVal > refValFromRetEffect(RetEffect RE, QualType ResultTy)
ProgramStateRef checkRegionChanges(ProgramStateRef state, const InvalidatedSymbols *invalidated, ArrayRef< const MemRegion *> ExplicitRegions, ArrayRef< const MemRegion *> Regions, const LocationContext *LCtx, const CallEvent *Call) const
ExplodedNode * processLeaks(ProgramStateRef state, SmallVectorImpl< SymbolRef > &Leaked, CheckerContext &Ctx, ExplodedNode *Pred=nullptr) const
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:971
const MemRegion * StripCasts(bool StripBaseAndDerivedCasts=true) const
Definition: MemRegion.cpp:1194
static RefVal makeOwned(ObjKind o, QualType t)
Create a state for an object whose lifetime is the responsibility of the current function, at least partially.
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition: Expr.cpp:1396
Represents an abstract call to a function or method along a particular path.
Definition: CallEvent.h:171
Bridging via __bridge_retain, which makes an ARC object available as a +1 C pointer.
AnalyzerOptions & getAnalyzerOptions()
const Decl * getDecl() const
Represents a pointer to an Objective C object.
Definition: Type.h:5797
const StackFrameContext * getStackFrame() const
Indicates that the tracking object is a descendant of a referenced-counted OSObject, used in the Darwin kernel.
const ProgramStateRef & getState() const
void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const
const RefVal * getRefBinding(ProgramStateRef State, SymbolRef Sym)
bool hasStackStorage() const
Definition: MemRegion.cpp:1138
Stores options for the analyzer from the command line.
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:513
QualType getResultType() const
Returns the result type, adjusted for references.
Definition: CallEvent.cpp:70
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:13954
ArgEffect withKind(ArgEffectKind NewK)
All typestate tracking of the object ceases.
static RefVal makeNotOwned(ObjKind o, QualType t)
Create a state for an object whose lifetime is not the responsibility of the current function...
virtual unsigned getNumArgs() const =0
Returns the number of arguments (explicit and implicit).
The argument is a pointer to a retain-counted object; on exit, the new value of the pointer is a +1 v...
void checkSummary(const RetainSummary &Summ, const CallEvent &Call, CheckerContext &C) const
SValBuilder & getSValBuilder()
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2396
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:954
The argument is a pointer to a retain-counted object; on exit, the new value of the pointer is a +1 v...
virtual SVal getArgSVal(unsigned Index) const
Returns the value of a given argument at the time of the call.
Definition: CallEvent.cpp:401
QualType getType() const
Definition: Decl.h:648
void processSummaryOfInlined(const RetainSummary &Summ, const CallEvent &Call, CheckerContext &C) const
A trivial tuple used to represent a source range.
An ArgEffect summarizes the retain count behavior on an argument or receiver to a function or method...
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.
bool inTopFrame() const
Return true if the current LocationContext has no caller context.
const char * getDescription() const override
const LocationContext * getLocationContext() const
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3055
const LangOptions & getLangOpts() const
Definition: ASTContext.h:707
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...
RetEffect summarizes a call&#39;s retain/release behavior with respect to its return value.