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