xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp (revision a9e295604a901437f409c0ce43ec9cad49cb29f3)
1 // RetainCountDiagnostics.cpp - Checks for leaks and other issues -*- C++ -*--//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines diagnostics for RetainCountChecker, which implements
10 //  a reference count checker for Core Foundation and Cocoa on (Mac OS X).
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RetainCountDiagnostics.h"
15 #include "RetainCountChecker.h"
16 
17 using namespace clang;
18 using namespace ento;
19 using namespace retaincountchecker;
20 
21 StringRef RefCountBug::bugTypeToName(RefCountBug::RefCountBugType BT) {
22   switch (BT) {
23   case UseAfterRelease:
24     return "Use-after-release";
25   case ReleaseNotOwned:
26     return "Bad release";
27   case DeallocNotOwned:
28     return "-dealloc sent to non-exclusively owned object";
29   case FreeNotOwned:
30     return "freeing non-exclusively owned object";
31   case OverAutorelease:
32     return "Object autoreleased too many times";
33   case ReturnNotOwnedForOwned:
34     return "Method should return an owned object";
35   case LeakWithinFunction:
36     return "Leak";
37   case LeakAtReturn:
38     return "Leak of returned object";
39   }
40   llvm_unreachable("Unknown RefCountBugType");
41 }
42 
43 StringRef RefCountBug::getDescription() const {
44   switch (BT) {
45   case UseAfterRelease:
46     return "Reference-counted object is used after it is released";
47   case ReleaseNotOwned:
48     return "Incorrect decrement of the reference count of an object that is "
49            "not owned at this point by the caller";
50   case DeallocNotOwned:
51     return "-dealloc sent to object that may be referenced elsewhere";
52   case FreeNotOwned:
53     return  "'free' called on an object that may be referenced elsewhere";
54   case OverAutorelease:
55     return "Object autoreleased too many times";
56   case ReturnNotOwnedForOwned:
57     return "Object with a +0 retain count returned to caller where a +1 "
58            "(owning) retain count is expected";
59   case LeakWithinFunction:
60   case LeakAtReturn:
61     return "";
62   }
63   llvm_unreachable("Unknown RefCountBugType");
64 }
65 
66 RefCountBug::RefCountBug(const CheckerBase *Checker, RefCountBugType BT)
67     : BugType(Checker, bugTypeToName(BT), categories::MemoryRefCount,
68               /*SupressOnSink=*/BT == LeakWithinFunction || BT == LeakAtReturn),
69       BT(BT), Checker(Checker) {}
70 
71 static bool isNumericLiteralExpression(const Expr *E) {
72   // FIXME: This set of cases was copied from SemaExprObjC.
73   return isa<IntegerLiteral>(E) ||
74          isa<CharacterLiteral>(E) ||
75          isa<FloatingLiteral>(E) ||
76          isa<ObjCBoolLiteralExpr>(E) ||
77          isa<CXXBoolLiteralExpr>(E);
78 }
79 
80 /// If type represents a pointer to CXXRecordDecl,
81 /// and is not a typedef, return the decl name.
82 /// Otherwise, return the serialization of type.
83 static std::string getPrettyTypeName(QualType QT) {
84   QualType PT = QT->getPointeeType();
85   if (!PT.isNull() && !QT->getAs<TypedefType>())
86     if (const auto *RD = PT->getAsCXXRecordDecl())
87       return RD->getName();
88   return QT.getAsString();
89 }
90 
91 /// Write information about the type state change to {@code os},
92 /// return whether the note should be generated.
93 static bool shouldGenerateNote(llvm::raw_string_ostream &os,
94                                const RefVal *PrevT,
95                                const RefVal &CurrV,
96                                bool DeallocSent) {
97   // Get the previous type state.
98   RefVal PrevV = *PrevT;
99 
100   // Specially handle -dealloc.
101   if (DeallocSent) {
102     // Determine if the object's reference count was pushed to zero.
103     assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
104     // We may not have transitioned to 'release' if we hit an error.
105     // This case is handled elsewhere.
106     if (CurrV.getKind() == RefVal::Released) {
107       assert(CurrV.getCombinedCounts() == 0);
108       os << "Object released by directly sending the '-dealloc' message";
109       return true;
110     }
111   }
112 
113   // Determine if the typestate has changed.
114   if (!PrevV.hasSameState(CurrV))
115     switch (CurrV.getKind()) {
116     case RefVal::Owned:
117     case RefVal::NotOwned:
118       if (PrevV.getCount() == CurrV.getCount()) {
119         // Did an autorelease message get sent?
120         if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
121           return false;
122 
123         assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
124         os << "Object autoreleased";
125         return true;
126       }
127 
128       if (PrevV.getCount() > CurrV.getCount())
129         os << "Reference count decremented.";
130       else
131         os << "Reference count incremented.";
132 
133       if (unsigned Count = CurrV.getCount())
134         os << " The object now has a +" << Count << " retain count.";
135 
136       return true;
137 
138     case RefVal::Released:
139       if (CurrV.getIvarAccessHistory() ==
140               RefVal::IvarAccessHistory::ReleasedAfterDirectAccess &&
141           CurrV.getIvarAccessHistory() != PrevV.getIvarAccessHistory()) {
142         os << "Strong instance variable relinquished. ";
143       }
144       os << "Object released.";
145       return true;
146 
147     case RefVal::ReturnedOwned:
148       // Autoreleases can be applied after marking a node ReturnedOwned.
149       if (CurrV.getAutoreleaseCount())
150         return false;
151 
152       os << "Object returned to caller as an owning reference (single "
153             "retain count transferred to caller)";
154       return true;
155 
156     case RefVal::ReturnedNotOwned:
157       os << "Object returned to caller with a +0 retain count";
158       return true;
159 
160     default:
161       return false;
162     }
163   return true;
164 }
165 
166 /// Finds argument index of the out paramter in the call {@code S}
167 /// corresponding to the symbol {@code Sym}.
168 /// If none found, returns None.
169 static Optional<unsigned> findArgIdxOfSymbol(ProgramStateRef CurrSt,
170                                              const LocationContext *LCtx,
171                                              SymbolRef &Sym,
172                                              Optional<CallEventRef<>> CE) {
173   if (!CE)
174     return None;
175 
176   for (unsigned Idx = 0; Idx < (*CE)->getNumArgs(); Idx++)
177     if (const MemRegion *MR = (*CE)->getArgSVal(Idx).getAsRegion())
178       if (const auto *TR = dyn_cast<TypedValueRegion>(MR))
179         if (CurrSt->getSVal(MR, TR->getValueType()).getAsSymExpr() == Sym)
180           return Idx;
181 
182   return None;
183 }
184 
185 Optional<std::string> findMetaClassAlloc(const Expr *Callee) {
186   if (const auto *ME = dyn_cast<MemberExpr>(Callee)) {
187     if (ME->getMemberDecl()->getNameAsString() != "alloc")
188       return None;
189     const Expr *This = ME->getBase()->IgnoreParenImpCasts();
190     if (const auto *DRE = dyn_cast<DeclRefExpr>(This)) {
191       const ValueDecl *VD = DRE->getDecl();
192       if (VD->getNameAsString() != "metaClass")
193         return None;
194 
195       if (const auto *RD = dyn_cast<CXXRecordDecl>(VD->getDeclContext()))
196         return RD->getNameAsString();
197 
198     }
199   }
200   return None;
201 }
202 
203 std::string findAllocatedObjectName(const Stmt *S,
204                                     QualType QT) {
205   if (const auto *CE = dyn_cast<CallExpr>(S))
206     if (auto Out = findMetaClassAlloc(CE->getCallee()))
207       return *Out;
208   return getPrettyTypeName(QT);
209 }
210 
211 static void generateDiagnosticsForCallLike(ProgramStateRef CurrSt,
212                                            const LocationContext *LCtx,
213                                            const RefVal &CurrV, SymbolRef &Sym,
214                                            const Stmt *S,
215                                            llvm::raw_string_ostream &os) {
216   CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
217   if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
218     // Get the name of the callee (if it is available)
219     // from the tracked SVal.
220     SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
221     const FunctionDecl *FD = X.getAsFunctionDecl();
222 
223     // If failed, try to get it from AST.
224     if (!FD)
225       FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
226 
227     if (const auto *MD = dyn_cast<CXXMethodDecl>(CE->getCalleeDecl())) {
228       os << "Call to method '" << MD->getQualifiedNameAsString() << '\'';
229     } else if (FD) {
230       os << "Call to function '" << FD->getQualifiedNameAsString() << '\'';
231     } else {
232       os << "function call";
233     }
234   } else if (isa<CXXNewExpr>(S)) {
235     os << "Operator 'new'";
236   } else {
237     assert(isa<ObjCMessageExpr>(S));
238     CallEventRef<ObjCMethodCall> Call =
239         Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
240 
241     switch (Call->getMessageKind()) {
242     case OCM_Message:
243       os << "Method";
244       break;
245     case OCM_PropertyAccess:
246       os << "Property";
247       break;
248     case OCM_Subscript:
249       os << "Subscript";
250       break;
251     }
252   }
253 
254   Optional<CallEventRef<>> CE = Mgr.getCall(S, CurrSt, LCtx);
255   auto Idx = findArgIdxOfSymbol(CurrSt, LCtx, Sym, CE);
256 
257   // If index is not found, we assume that the symbol was returned.
258   if (!Idx) {
259     os << " returns ";
260   } else {
261     os << " writes ";
262   }
263 
264   if (CurrV.getObjKind() == ObjKind::CF) {
265     os << "a Core Foundation object of type '"
266        << Sym->getType().getAsString() << "' with a ";
267   } else if (CurrV.getObjKind() == ObjKind::OS) {
268     os << "an OSObject of type '" << findAllocatedObjectName(S, Sym->getType())
269        << "' with a ";
270   } else if (CurrV.getObjKind() == ObjKind::Generalized) {
271     os << "an object of type '" << Sym->getType().getAsString()
272        << "' with a ";
273   } else {
274     assert(CurrV.getObjKind() == ObjKind::ObjC);
275     QualType T = Sym->getType();
276     if (!isa<ObjCObjectPointerType>(T)) {
277       os << "an Objective-C object with a ";
278     } else {
279       const ObjCObjectPointerType *PT = cast<ObjCObjectPointerType>(T);
280       os << "an instance of " << PT->getPointeeType().getAsString()
281          << " with a ";
282     }
283   }
284 
285   if (CurrV.isOwned()) {
286     os << "+1 retain count";
287   } else {
288     assert(CurrV.isNotOwned());
289     os << "+0 retain count";
290   }
291 
292   if (Idx) {
293     os << " into an out parameter '";
294     const ParmVarDecl *PVD = (*CE)->parameters()[*Idx];
295     PVD->getNameForDiagnostic(os, PVD->getASTContext().getPrintingPolicy(),
296                               /*Qualified=*/false);
297     os << "'";
298 
299     QualType RT = (*CE)->getResultType();
300     if (!RT.isNull() && !RT->isVoidType()) {
301       SVal RV = (*CE)->getReturnValue();
302       if (CurrSt->isNull(RV).isConstrainedTrue()) {
303         os << " (assuming the call returns zero)";
304       } else if (CurrSt->isNonNull(RV).isConstrainedTrue()) {
305         os << " (assuming the call returns non-zero)";
306       }
307 
308     }
309   }
310 }
311 
312 namespace clang {
313 namespace ento {
314 namespace retaincountchecker {
315 
316 class RefCountReportVisitor : public BugReporterVisitor {
317 protected:
318   SymbolRef Sym;
319 
320 public:
321   RefCountReportVisitor(SymbolRef sym) : Sym(sym) {}
322 
323   void Profile(llvm::FoldingSetNodeID &ID) const override {
324     static int x = 0;
325     ID.AddPointer(&x);
326     ID.AddPointer(Sym);
327   }
328 
329   std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
330                                                  BugReporterContext &BRC,
331                                                  BugReport &BR) override;
332 
333   std::shared_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
334                                                   const ExplodedNode *N,
335                                                   BugReport &BR) override;
336 };
337 
338 class RefLeakReportVisitor : public RefCountReportVisitor {
339 public:
340   RefLeakReportVisitor(SymbolRef sym) : RefCountReportVisitor(sym) {}
341 
342   std::shared_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
343                                                   const ExplodedNode *N,
344                                                   BugReport &BR) override;
345 };
346 
347 } // end namespace retaincountchecker
348 } // end namespace ento
349 } // end namespace clang
350 
351 
352 /// Find the first node with the parent stack frame.
353 static const ExplodedNode *getCalleeNode(const ExplodedNode *Pred) {
354   const StackFrameContext *SC = Pred->getStackFrame();
355   if (SC->inTopFrame())
356     return nullptr;
357   const StackFrameContext *PC = SC->getParent()->getStackFrame();
358   if (!PC)
359     return nullptr;
360 
361   const ExplodedNode *N = Pred;
362   while (N && N->getStackFrame() != PC) {
363     N = N->getFirstPred();
364   }
365   return N;
366 }
367 
368 
369 /// Insert a diagnostic piece at function exit
370 /// if a function parameter is annotated as "os_consumed",
371 /// but it does not actually consume the reference.
372 static std::shared_ptr<PathDiagnosticEventPiece>
373 annotateConsumedSummaryMismatch(const ExplodedNode *N,
374                                 CallExitBegin &CallExitLoc,
375                                 const SourceManager &SM,
376                                 CallEventManager &CEMgr) {
377 
378   const ExplodedNode *CN = getCalleeNode(N);
379   if (!CN)
380     return nullptr;
381 
382   CallEventRef<> Call = CEMgr.getCaller(N->getStackFrame(), N->getState());
383 
384   std::string sbuf;
385   llvm::raw_string_ostream os(sbuf);
386   ArrayRef<const ParmVarDecl *> Parameters = Call->parameters();
387   for (unsigned I=0; I < Call->getNumArgs() && I < Parameters.size(); ++I) {
388     const ParmVarDecl *PVD = Parameters[I];
389 
390     if (!PVD->hasAttr<OSConsumedAttr>())
391       continue;
392 
393     if (SymbolRef SR = Call->getArgSVal(I).getAsLocSymbol()) {
394       const RefVal *CountBeforeCall = getRefBinding(CN->getState(), SR);
395       const RefVal *CountAtExit = getRefBinding(N->getState(), SR);
396 
397       if (!CountBeforeCall || !CountAtExit)
398         continue;
399 
400       unsigned CountBefore = CountBeforeCall->getCount();
401       unsigned CountAfter = CountAtExit->getCount();
402 
403       bool AsExpected = CountBefore > 0 && CountAfter == CountBefore - 1;
404       if (!AsExpected) {
405         os << "Parameter '";
406         PVD->getNameForDiagnostic(os, PVD->getASTContext().getPrintingPolicy(),
407                                   /*Qualified=*/false);
408         os << "' is marked as consuming, but the function did not consume "
409            << "the reference\n";
410       }
411     }
412   }
413 
414   if (os.str().empty())
415     return nullptr;
416 
417   PathDiagnosticLocation L = PathDiagnosticLocation::create(CallExitLoc, SM);
418   return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
419 }
420 
421 std::shared_ptr<PathDiagnosticPiece>
422 RefCountReportVisitor::VisitNode(const ExplodedNode *N,
423                               BugReporterContext &BRC, BugReport &BR) {
424 
425   const auto &BT = static_cast<const RefCountBug&>(BR.getBugType());
426   const auto *Checker =
427       static_cast<const RetainCountChecker *>(BT.getChecker());
428 
429   bool IsFreeUnowned = BT.getBugType() == RefCountBug::FreeNotOwned ||
430                        BT.getBugType() == RefCountBug::DeallocNotOwned;
431 
432   const SourceManager &SM = BRC.getSourceManager();
433   CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
434   if (auto CE = N->getLocationAs<CallExitBegin>())
435     if (auto PD = annotateConsumedSummaryMismatch(N, *CE, SM, CEMgr))
436       return PD;
437 
438   // FIXME: We will eventually need to handle non-statement-based events
439   // (__attribute__((cleanup))).
440   if (!N->getLocation().getAs<StmtPoint>())
441     return nullptr;
442 
443   // Check if the type state has changed.
444   const ExplodedNode *PrevNode = N->getFirstPred();
445   ProgramStateRef PrevSt = PrevNode->getState();
446   ProgramStateRef CurrSt = N->getState();
447   const LocationContext *LCtx = N->getLocationContext();
448 
449   const RefVal* CurrT = getRefBinding(CurrSt, Sym);
450   if (!CurrT)
451     return nullptr;
452 
453   const RefVal &CurrV = *CurrT;
454   const RefVal *PrevT = getRefBinding(PrevSt, Sym);
455 
456   // Create a string buffer to constain all the useful things we want
457   // to tell the user.
458   std::string sbuf;
459   llvm::raw_string_ostream os(sbuf);
460 
461   if (PrevT && IsFreeUnowned && CurrV.isNotOwned() && PrevT->isOwned()) {
462     os << "Object is now not exclusively owned";
463     auto Pos = PathDiagnosticLocation::create(N->getLocation(), SM);
464     return std::make_shared<PathDiagnosticEventPiece>(Pos, os.str());
465   }
466 
467   // This is the allocation site since the previous node had no bindings
468   // for this symbol.
469   if (!PrevT) {
470     const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
471 
472     if (isa<ObjCIvarRefExpr>(S) &&
473         isSynthesizedAccessor(LCtx->getStackFrame())) {
474       S = LCtx->getStackFrame()->getCallSite();
475     }
476 
477     if (isa<ObjCArrayLiteral>(S)) {
478       os << "NSArray literal is an object with a +0 retain count";
479     } else if (isa<ObjCDictionaryLiteral>(S)) {
480       os << "NSDictionary literal is an object with a +0 retain count";
481     } else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
482       if (isNumericLiteralExpression(BL->getSubExpr()))
483         os << "NSNumber literal is an object with a +0 retain count";
484       else {
485         const ObjCInterfaceDecl *BoxClass = nullptr;
486         if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
487           BoxClass = Method->getClassInterface();
488 
489         // We should always be able to find the boxing class interface,
490         // but consider this future-proofing.
491         if (BoxClass) {
492           os << *BoxClass << " b";
493         } else {
494           os << "B";
495         }
496 
497         os << "oxed expression produces an object with a +0 retain count";
498       }
499     } else if (isa<ObjCIvarRefExpr>(S)) {
500       os << "Object loaded from instance variable";
501     } else {
502       generateDiagnosticsForCallLike(CurrSt, LCtx, CurrV, Sym, S, os);
503     }
504 
505     PathDiagnosticLocation Pos(S, SM, N->getLocationContext());
506     return std::make_shared<PathDiagnosticEventPiece>(Pos, os.str());
507   }
508 
509   // Gather up the effects that were performed on the object at this
510   // program point
511   bool DeallocSent = false;
512 
513   const ProgramPointTag *Tag = N->getLocation().getTag();
514 
515   if (Tag == &Checker->getCastFailTag()) {
516     os << "Assuming dynamic cast returns null due to type mismatch";
517   }
518 
519   if (Tag == &Checker->getDeallocSentTag()) {
520     // We only have summaries attached to nodes after evaluating CallExpr and
521     // ObjCMessageExprs.
522     const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
523 
524     if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
525       // Iterate through the parameter expressions and see if the symbol
526       // was ever passed as an argument.
527       unsigned i = 0;
528 
529       for (auto AI=CE->arg_begin(), AE=CE->arg_end(); AI!=AE; ++AI, ++i) {
530 
531         // Retrieve the value of the argument.  Is it the symbol
532         // we are interested in?
533         if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
534           continue;
535 
536         // We have an argument.  Get the effect!
537         DeallocSent = true;
538       }
539     } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
540       if (const Expr *receiver = ME->getInstanceReceiver()) {
541         if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
542               .getAsLocSymbol() == Sym) {
543           // The symbol we are tracking is the receiver.
544           DeallocSent = true;
545         }
546       }
547     }
548   }
549 
550   if (!shouldGenerateNote(os, PrevT, CurrV, DeallocSent))
551     return nullptr;
552 
553   if (os.str().empty())
554     return nullptr; // We have nothing to say!
555 
556   const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
557   PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
558                                 N->getLocationContext());
559   auto P = std::make_shared<PathDiagnosticEventPiece>(Pos, os.str());
560 
561   // Add the range by scanning the children of the statement for any bindings
562   // to Sym.
563   for (const Stmt *Child : S->children())
564     if (const Expr *Exp = dyn_cast_or_null<Expr>(Child))
565       if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
566         P->addRange(Exp->getSourceRange());
567         break;
568       }
569 
570   return std::move(P);
571 }
572 
573 static Optional<std::string> describeRegion(const MemRegion *MR) {
574   if (const auto *VR = dyn_cast_or_null<VarRegion>(MR))
575     return std::string(VR->getDecl()->getName());
576   // Once we support more storage locations for bindings,
577   // this would need to be improved.
578   return None;
579 }
580 
581 namespace {
582 // Find the first node in the current function context that referred to the
583 // tracked symbol and the memory location that value was stored to. Note, the
584 // value is only reported if the allocation occurred in the same function as
585 // the leak. The function can also return a location context, which should be
586 // treated as interesting.
587 struct AllocationInfo {
588   const ExplodedNode* N;
589   const MemRegion *R;
590   const LocationContext *InterestingMethodContext;
591   AllocationInfo(const ExplodedNode *InN,
592                  const MemRegion *InR,
593                  const LocationContext *InInterestingMethodContext) :
594     N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
595 };
596 } // end anonymous namespace
597 
598 static AllocationInfo GetAllocationSite(ProgramStateManager &StateMgr,
599                                         const ExplodedNode *N, SymbolRef Sym) {
600   const ExplodedNode *AllocationNode = N;
601   const ExplodedNode *AllocationNodeInCurrentOrParentContext = N;
602   const MemRegion *FirstBinding = nullptr;
603   const LocationContext *LeakContext = N->getLocationContext();
604 
605   // The location context of the init method called on the leaked object, if
606   // available.
607   const LocationContext *InitMethodContext = nullptr;
608 
609   while (N) {
610     ProgramStateRef St = N->getState();
611     const LocationContext *NContext = N->getLocationContext();
612 
613     if (!getRefBinding(St, Sym))
614       break;
615 
616     StoreManager::FindUniqueBinding FB(Sym);
617     StateMgr.iterBindings(St, FB);
618 
619     if (FB) {
620       const MemRegion *R = FB.getRegion();
621       // Do not show local variables belonging to a function other than
622       // where the error is reported.
623       if (auto MR = dyn_cast<StackSpaceRegion>(R->getMemorySpace()))
624         if (MR->getStackFrame() == LeakContext->getStackFrame())
625           FirstBinding = R;
626     }
627 
628     // AllocationNode is the last node in which the symbol was tracked.
629     AllocationNode = N;
630 
631     // AllocationNodeInCurrentContext, is the last node in the current or
632     // parent context in which the symbol was tracked.
633     //
634     // Note that the allocation site might be in the parent context. For example,
635     // the case where an allocation happens in a block that captures a reference
636     // to it and that reference is overwritten/dropped by another call to
637     // the block.
638     if (NContext == LeakContext || NContext->isParentOf(LeakContext))
639       AllocationNodeInCurrentOrParentContext = N;
640 
641     // Find the last init that was called on the given symbol and store the
642     // init method's location context.
643     if (!InitMethodContext)
644       if (auto CEP = N->getLocation().getAs<CallEnter>()) {
645         const Stmt *CE = CEP->getCallExpr();
646         if (const auto *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
647           const Stmt *RecExpr = ME->getInstanceReceiver();
648           if (RecExpr) {
649             SVal RecV = St->getSVal(RecExpr, NContext);
650             if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
651               InitMethodContext = CEP->getCalleeContext();
652           }
653         }
654       }
655 
656     N = N->getFirstPred();
657   }
658 
659   // If we are reporting a leak of the object that was allocated with alloc,
660   // mark its init method as interesting.
661   const LocationContext *InterestingMethodContext = nullptr;
662   if (InitMethodContext) {
663     const ProgramPoint AllocPP = AllocationNode->getLocation();
664     if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
665       if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
666         if (ME->getMethodFamily() == OMF_alloc)
667           InterestingMethodContext = InitMethodContext;
668   }
669 
670   // If allocation happened in a function different from the leak node context,
671   // do not report the binding.
672   assert(N && "Could not find allocation node");
673 
674   if (AllocationNodeInCurrentOrParentContext &&
675       AllocationNodeInCurrentOrParentContext->getLocationContext() !=
676           LeakContext)
677     FirstBinding = nullptr;
678 
679   return AllocationInfo(AllocationNodeInCurrentOrParentContext,
680                         FirstBinding,
681                         InterestingMethodContext);
682 }
683 
684 std::shared_ptr<PathDiagnosticPiece>
685 RefCountReportVisitor::getEndPath(BugReporterContext &BRC,
686                                const ExplodedNode *EndN, BugReport &BR) {
687   BR.markInteresting(Sym);
688   return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
689 }
690 
691 std::shared_ptr<PathDiagnosticPiece>
692 RefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
693                                    const ExplodedNode *EndN, BugReport &BR) {
694 
695   // Tell the BugReporterContext to report cases when the tracked symbol is
696   // assigned to different variables, etc.
697   BR.markInteresting(Sym);
698 
699   // We are reporting a leak.  Walk up the graph to get to the first node where
700   // the symbol appeared, and also get the first VarDecl that tracked object
701   // is stored to.
702   AllocationInfo AllocI = GetAllocationSite(BRC.getStateManager(), EndN, Sym);
703 
704   const MemRegion* FirstBinding = AllocI.R;
705   BR.markInteresting(AllocI.InterestingMethodContext);
706 
707   SourceManager& SM = BRC.getSourceManager();
708 
709   // Compute an actual location for the leak.  Sometimes a leak doesn't
710   // occur at an actual statement (e.g., transition between blocks; end
711   // of function) so we need to walk the graph and compute a real location.
712   const ExplodedNode *LeakN = EndN;
713   PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
714 
715   std::string sbuf;
716   llvm::raw_string_ostream os(sbuf);
717 
718   os << "Object leaked: ";
719 
720   Optional<std::string> RegionDescription = describeRegion(FirstBinding);
721   if (RegionDescription) {
722     os << "object allocated and stored into '" << *RegionDescription << '\'';
723   } else {
724     os << "allocated object of type '" << getPrettyTypeName(Sym->getType())
725        << "'";
726   }
727 
728   // Get the retain count.
729   const RefVal* RV = getRefBinding(EndN->getState(), Sym);
730   assert(RV);
731 
732   if (RV->getKind() == RefVal::ErrorLeakReturned) {
733     // FIXME: Per comments in rdar://6320065, "create" only applies to CF
734     // objects.  Only "copy", "alloc", "retain" and "new" transfer ownership
735     // to the caller for NS objects.
736     const Decl *D = &EndN->getCodeDecl();
737 
738     os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
739                                   : " is returned from a function ");
740 
741     if (D->hasAttr<CFReturnsNotRetainedAttr>()) {
742       os << "that is annotated as CF_RETURNS_NOT_RETAINED";
743     } else if (D->hasAttr<NSReturnsNotRetainedAttr>()) {
744       os << "that is annotated as NS_RETURNS_NOT_RETAINED";
745     } else if (D->hasAttr<OSReturnsNotRetainedAttr>()) {
746       os << "that is annotated as OS_RETURNS_NOT_RETAINED";
747     } else {
748       if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
749         if (BRC.getASTContext().getLangOpts().ObjCAutoRefCount) {
750           os << "managed by Automatic Reference Counting";
751         } else {
752           os << "whose name ('" << MD->getSelector().getAsString()
753              << "') does not start with "
754                 "'copy', 'mutableCopy', 'alloc' or 'new'."
755                 "  This violates the naming convention rules"
756                 " given in the Memory Management Guide for Cocoa";
757         }
758       } else {
759         const FunctionDecl *FD = cast<FunctionDecl>(D);
760         os << "whose name ('" << *FD
761            << "') does not contain 'Copy' or 'Create'.  This violates the naming"
762               " convention rules given in the Memory Management Guide for Core"
763               " Foundation";
764       }
765     }
766   } else {
767     os << " is not referenced later in this execution path and has a retain "
768           "count of +" << RV->getCount();
769   }
770 
771   return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
772 }
773 
774 RefCountReport::RefCountReport(const RefCountBug &D, const LangOptions &LOpts,
775                                ExplodedNode *n, SymbolRef sym,
776                                bool isLeak)
777     : BugReport(D, D.getDescription(), n), Sym(sym), isLeak(isLeak) {
778   if (!isLeak)
779     addVisitor(llvm::make_unique<RefCountReportVisitor>(sym));
780 }
781 
782 RefCountReport::RefCountReport(const RefCountBug &D, const LangOptions &LOpts,
783                                ExplodedNode *n, SymbolRef sym,
784                                StringRef endText)
785     : BugReport(D, D.getDescription(), endText, n) {
786 
787   addVisitor(llvm::make_unique<RefCountReportVisitor>(sym));
788 }
789 
790 void RefLeakReport::deriveParamLocation(CheckerContext &Ctx, SymbolRef sym) {
791   const SourceManager& SMgr = Ctx.getSourceManager();
792 
793   if (!sym->getOriginRegion())
794     return;
795 
796   auto *Region = dyn_cast<DeclRegion>(sym->getOriginRegion());
797   if (Region) {
798     const Decl *PDecl = Region->getDecl();
799     if (PDecl && isa<ParmVarDecl>(PDecl)) {
800       PathDiagnosticLocation ParamLocation =
801           PathDiagnosticLocation::create(PDecl, SMgr);
802       Location = ParamLocation;
803       UniqueingLocation = ParamLocation;
804       UniqueingDecl = Ctx.getLocationContext()->getDecl();
805     }
806   }
807 }
808 
809 void RefLeakReport::deriveAllocLocation(CheckerContext &Ctx,
810                                           SymbolRef sym) {
811   // Most bug reports are cached at the location where they occurred.
812   // With leaks, we want to unique them by the location where they were
813   // allocated, and only report a single path.  To do this, we need to find
814   // the allocation site of a piece of tracked memory, which we do via a
815   // call to GetAllocationSite.  This will walk the ExplodedGraph backwards.
816   // Note that this is *not* the trimmed graph; we are guaranteed, however,
817   // that all ancestor nodes that represent the allocation site have the
818   // same SourceLocation.
819   const ExplodedNode *AllocNode = nullptr;
820 
821   const SourceManager& SMgr = Ctx.getSourceManager();
822 
823   AllocationInfo AllocI =
824       GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
825 
826   AllocNode = AllocI.N;
827   AllocBinding = AllocI.R;
828   markInteresting(AllocI.InterestingMethodContext);
829 
830   // Get the SourceLocation for the allocation site.
831   // FIXME: This will crash the analyzer if an allocation comes from an
832   // implicit call (ex: a destructor call).
833   // (Currently there are no such allocations in Cocoa, though.)
834   AllocStmt = PathDiagnosticLocation::getStmt(AllocNode);
835 
836   if (!AllocStmt) {
837     AllocBinding = nullptr;
838     return;
839   }
840 
841   PathDiagnosticLocation AllocLocation =
842     PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
843                                         AllocNode->getLocationContext());
844   Location = AllocLocation;
845 
846   // Set uniqieing info, which will be used for unique the bug reports. The
847   // leaks should be uniqued on the allocation site.
848   UniqueingLocation = AllocLocation;
849   UniqueingDecl = AllocNode->getLocationContext()->getDecl();
850 }
851 
852 void RefLeakReport::createDescription(CheckerContext &Ctx) {
853   assert(Location.isValid() && UniqueingDecl && UniqueingLocation.isValid());
854   Description.clear();
855   llvm::raw_string_ostream os(Description);
856   os << "Potential leak of an object";
857 
858   Optional<std::string> RegionDescription = describeRegion(AllocBinding);
859   if (RegionDescription) {
860     os << " stored into '" << *RegionDescription << '\'';
861   } else {
862 
863     // If we can't figure out the name, just supply the type information.
864     os << " of type '" << getPrettyTypeName(Sym->getType()) << "'";
865   }
866 }
867 
868 RefLeakReport::RefLeakReport(const RefCountBug &D, const LangOptions &LOpts,
869                              ExplodedNode *n, SymbolRef sym,
870                              CheckerContext &Ctx)
871     : RefCountReport(D, LOpts, n, sym, /*isLeak=*/true) {
872 
873   deriveAllocLocation(Ctx, sym);
874   if (!AllocBinding)
875     deriveParamLocation(Ctx, sym);
876 
877   createDescription(Ctx);
878 
879   addVisitor(llvm::make_unique<RefLeakReportVisitor>(sym));
880 }
881