17330f729Sjoerg // RetainCountDiagnostics.cpp - Checks for leaks and other issues -*- C++ -*--//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg //  This file defines diagnostics for RetainCountChecker, which implements
107330f729Sjoerg //  a reference count checker for Core Foundation and Cocoa on (Mac OS X).
117330f729Sjoerg //
127330f729Sjoerg //===----------------------------------------------------------------------===//
137330f729Sjoerg 
147330f729Sjoerg #include "RetainCountDiagnostics.h"
157330f729Sjoerg #include "RetainCountChecker.h"
16*e038c9c4Sjoerg #include "llvm/ADT/STLExtras.h"
17*e038c9c4Sjoerg #include "llvm/ADT/SmallVector.h"
187330f729Sjoerg 
197330f729Sjoerg using namespace clang;
207330f729Sjoerg using namespace ento;
217330f729Sjoerg using namespace retaincountchecker;
227330f729Sjoerg 
bugTypeToName(RefCountBug::RefCountBugKind BT)23*e038c9c4Sjoerg StringRef RefCountBug::bugTypeToName(RefCountBug::RefCountBugKind BT) {
247330f729Sjoerg   switch (BT) {
257330f729Sjoerg   case UseAfterRelease:
267330f729Sjoerg     return "Use-after-release";
277330f729Sjoerg   case ReleaseNotOwned:
287330f729Sjoerg     return "Bad release";
297330f729Sjoerg   case DeallocNotOwned:
307330f729Sjoerg     return "-dealloc sent to non-exclusively owned object";
317330f729Sjoerg   case FreeNotOwned:
327330f729Sjoerg     return "freeing non-exclusively owned object";
337330f729Sjoerg   case OverAutorelease:
347330f729Sjoerg     return "Object autoreleased too many times";
357330f729Sjoerg   case ReturnNotOwnedForOwned:
367330f729Sjoerg     return "Method should return an owned object";
377330f729Sjoerg   case LeakWithinFunction:
387330f729Sjoerg     return "Leak";
397330f729Sjoerg   case LeakAtReturn:
407330f729Sjoerg     return "Leak of returned object";
417330f729Sjoerg   }
42*e038c9c4Sjoerg   llvm_unreachable("Unknown RefCountBugKind");
437330f729Sjoerg }
447330f729Sjoerg 
getDescription() const457330f729Sjoerg StringRef RefCountBug::getDescription() const {
467330f729Sjoerg   switch (BT) {
477330f729Sjoerg   case UseAfterRelease:
487330f729Sjoerg     return "Reference-counted object is used after it is released";
497330f729Sjoerg   case ReleaseNotOwned:
507330f729Sjoerg     return "Incorrect decrement of the reference count of an object that is "
517330f729Sjoerg            "not owned at this point by the caller";
527330f729Sjoerg   case DeallocNotOwned:
537330f729Sjoerg     return "-dealloc sent to object that may be referenced elsewhere";
547330f729Sjoerg   case FreeNotOwned:
557330f729Sjoerg     return  "'free' called on an object that may be referenced elsewhere";
567330f729Sjoerg   case OverAutorelease:
577330f729Sjoerg     return "Object autoreleased too many times";
587330f729Sjoerg   case ReturnNotOwnedForOwned:
597330f729Sjoerg     return "Object with a +0 retain count returned to caller where a +1 "
607330f729Sjoerg            "(owning) retain count is expected";
617330f729Sjoerg   case LeakWithinFunction:
627330f729Sjoerg   case LeakAtReturn:
637330f729Sjoerg     return "";
647330f729Sjoerg   }
65*e038c9c4Sjoerg   llvm_unreachable("Unknown RefCountBugKind");
667330f729Sjoerg }
677330f729Sjoerg 
RefCountBug(CheckerNameRef Checker,RefCountBugKind BT)68*e038c9c4Sjoerg RefCountBug::RefCountBug(CheckerNameRef Checker, RefCountBugKind BT)
697330f729Sjoerg     : BugType(Checker, bugTypeToName(BT), categories::MemoryRefCount,
70*e038c9c4Sjoerg               /*SuppressOnSink=*/BT == LeakWithinFunction ||
71*e038c9c4Sjoerg                   BT == LeakAtReturn),
72*e038c9c4Sjoerg       BT(BT) {}
737330f729Sjoerg 
isNumericLiteralExpression(const Expr * E)747330f729Sjoerg static bool isNumericLiteralExpression(const Expr *E) {
757330f729Sjoerg   // FIXME: This set of cases was copied from SemaExprObjC.
767330f729Sjoerg   return isa<IntegerLiteral>(E) ||
777330f729Sjoerg          isa<CharacterLiteral>(E) ||
787330f729Sjoerg          isa<FloatingLiteral>(E) ||
797330f729Sjoerg          isa<ObjCBoolLiteralExpr>(E) ||
807330f729Sjoerg          isa<CXXBoolLiteralExpr>(E);
817330f729Sjoerg }
827330f729Sjoerg 
837330f729Sjoerg /// If type represents a pointer to CXXRecordDecl,
847330f729Sjoerg /// and is not a typedef, return the decl name.
857330f729Sjoerg /// Otherwise, return the serialization of type.
getPrettyTypeName(QualType QT)867330f729Sjoerg static std::string getPrettyTypeName(QualType QT) {
877330f729Sjoerg   QualType PT = QT->getPointeeType();
887330f729Sjoerg   if (!PT.isNull() && !QT->getAs<TypedefType>())
897330f729Sjoerg     if (const auto *RD = PT->getAsCXXRecordDecl())
90*e038c9c4Sjoerg       return std::string(RD->getName());
917330f729Sjoerg   return QT.getAsString();
927330f729Sjoerg }
937330f729Sjoerg 
94*e038c9c4Sjoerg /// Write information about the type state change to @c os,
957330f729Sjoerg /// return whether the note should be generated.
shouldGenerateNote(llvm::raw_string_ostream & os,const RefVal * PrevT,const RefVal & CurrV,bool DeallocSent)967330f729Sjoerg static bool shouldGenerateNote(llvm::raw_string_ostream &os,
977330f729Sjoerg                                const RefVal *PrevT,
987330f729Sjoerg                                const RefVal &CurrV,
997330f729Sjoerg                                bool DeallocSent) {
1007330f729Sjoerg   // Get the previous type state.
1017330f729Sjoerg   RefVal PrevV = *PrevT;
1027330f729Sjoerg 
1037330f729Sjoerg   // Specially handle -dealloc.
1047330f729Sjoerg   if (DeallocSent) {
1057330f729Sjoerg     // Determine if the object's reference count was pushed to zero.
1067330f729Sjoerg     assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
1077330f729Sjoerg     // We may not have transitioned to 'release' if we hit an error.
1087330f729Sjoerg     // This case is handled elsewhere.
1097330f729Sjoerg     if (CurrV.getKind() == RefVal::Released) {
1107330f729Sjoerg       assert(CurrV.getCombinedCounts() == 0);
1117330f729Sjoerg       os << "Object released by directly sending the '-dealloc' message";
1127330f729Sjoerg       return true;
1137330f729Sjoerg     }
1147330f729Sjoerg   }
1157330f729Sjoerg 
1167330f729Sjoerg   // Determine if the typestate has changed.
1177330f729Sjoerg   if (!PrevV.hasSameState(CurrV))
1187330f729Sjoerg     switch (CurrV.getKind()) {
1197330f729Sjoerg     case RefVal::Owned:
1207330f729Sjoerg     case RefVal::NotOwned:
1217330f729Sjoerg       if (PrevV.getCount() == CurrV.getCount()) {
1227330f729Sjoerg         // Did an autorelease message get sent?
1237330f729Sjoerg         if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
1247330f729Sjoerg           return false;
1257330f729Sjoerg 
1267330f729Sjoerg         assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
1277330f729Sjoerg         os << "Object autoreleased";
1287330f729Sjoerg         return true;
1297330f729Sjoerg       }
1307330f729Sjoerg 
1317330f729Sjoerg       if (PrevV.getCount() > CurrV.getCount())
1327330f729Sjoerg         os << "Reference count decremented.";
1337330f729Sjoerg       else
1347330f729Sjoerg         os << "Reference count incremented.";
1357330f729Sjoerg 
1367330f729Sjoerg       if (unsigned Count = CurrV.getCount())
1377330f729Sjoerg         os << " The object now has a +" << Count << " retain count.";
1387330f729Sjoerg 
1397330f729Sjoerg       return true;
1407330f729Sjoerg 
1417330f729Sjoerg     case RefVal::Released:
1427330f729Sjoerg       if (CurrV.getIvarAccessHistory() ==
1437330f729Sjoerg               RefVal::IvarAccessHistory::ReleasedAfterDirectAccess &&
1447330f729Sjoerg           CurrV.getIvarAccessHistory() != PrevV.getIvarAccessHistory()) {
1457330f729Sjoerg         os << "Strong instance variable relinquished. ";
1467330f729Sjoerg       }
1477330f729Sjoerg       os << "Object released.";
1487330f729Sjoerg       return true;
1497330f729Sjoerg 
1507330f729Sjoerg     case RefVal::ReturnedOwned:
1517330f729Sjoerg       // Autoreleases can be applied after marking a node ReturnedOwned.
1527330f729Sjoerg       if (CurrV.getAutoreleaseCount())
1537330f729Sjoerg         return false;
1547330f729Sjoerg 
1557330f729Sjoerg       os << "Object returned to caller as an owning reference (single "
1567330f729Sjoerg             "retain count transferred to caller)";
1577330f729Sjoerg       return true;
1587330f729Sjoerg 
1597330f729Sjoerg     case RefVal::ReturnedNotOwned:
1607330f729Sjoerg       os << "Object returned to caller with a +0 retain count";
1617330f729Sjoerg       return true;
1627330f729Sjoerg 
1637330f729Sjoerg     default:
1647330f729Sjoerg       return false;
1657330f729Sjoerg     }
1667330f729Sjoerg   return true;
1677330f729Sjoerg }
1687330f729Sjoerg 
169*e038c9c4Sjoerg /// Finds argument index of the out paramter in the call @c S
170*e038c9c4Sjoerg /// corresponding to the symbol @c Sym.
1717330f729Sjoerg /// If none found, returns None.
findArgIdxOfSymbol(ProgramStateRef CurrSt,const LocationContext * LCtx,SymbolRef & Sym,Optional<CallEventRef<>> CE)1727330f729Sjoerg static Optional<unsigned> findArgIdxOfSymbol(ProgramStateRef CurrSt,
1737330f729Sjoerg                                              const LocationContext *LCtx,
1747330f729Sjoerg                                              SymbolRef &Sym,
1757330f729Sjoerg                                              Optional<CallEventRef<>> CE) {
1767330f729Sjoerg   if (!CE)
1777330f729Sjoerg     return None;
1787330f729Sjoerg 
1797330f729Sjoerg   for (unsigned Idx = 0; Idx < (*CE)->getNumArgs(); Idx++)
1807330f729Sjoerg     if (const MemRegion *MR = (*CE)->getArgSVal(Idx).getAsRegion())
1817330f729Sjoerg       if (const auto *TR = dyn_cast<TypedValueRegion>(MR))
182*e038c9c4Sjoerg         if (CurrSt->getSVal(MR, TR->getValueType()).getAsSymbol() == Sym)
1837330f729Sjoerg           return Idx;
1847330f729Sjoerg 
1857330f729Sjoerg   return None;
1867330f729Sjoerg }
1877330f729Sjoerg 
findMetaClassAlloc(const Expr * Callee)1887330f729Sjoerg static Optional<std::string> findMetaClassAlloc(const Expr *Callee) {
1897330f729Sjoerg   if (const auto *ME = dyn_cast<MemberExpr>(Callee)) {
1907330f729Sjoerg     if (ME->getMemberDecl()->getNameAsString() != "alloc")
1917330f729Sjoerg       return None;
1927330f729Sjoerg     const Expr *This = ME->getBase()->IgnoreParenImpCasts();
1937330f729Sjoerg     if (const auto *DRE = dyn_cast<DeclRefExpr>(This)) {
1947330f729Sjoerg       const ValueDecl *VD = DRE->getDecl();
1957330f729Sjoerg       if (VD->getNameAsString() != "metaClass")
1967330f729Sjoerg         return None;
1977330f729Sjoerg 
1987330f729Sjoerg       if (const auto *RD = dyn_cast<CXXRecordDecl>(VD->getDeclContext()))
1997330f729Sjoerg         return RD->getNameAsString();
2007330f729Sjoerg 
2017330f729Sjoerg     }
2027330f729Sjoerg   }
2037330f729Sjoerg   return None;
2047330f729Sjoerg }
2057330f729Sjoerg 
findAllocatedObjectName(const Stmt * S,QualType QT)2067330f729Sjoerg static std::string findAllocatedObjectName(const Stmt *S, QualType QT) {
2077330f729Sjoerg   if (const auto *CE = dyn_cast<CallExpr>(S))
2087330f729Sjoerg     if (auto Out = findMetaClassAlloc(CE->getCallee()))
2097330f729Sjoerg       return *Out;
2107330f729Sjoerg   return getPrettyTypeName(QT);
2117330f729Sjoerg }
2127330f729Sjoerg 
generateDiagnosticsForCallLike(ProgramStateRef CurrSt,const LocationContext * LCtx,const RefVal & CurrV,SymbolRef & Sym,const Stmt * S,llvm::raw_string_ostream & os)2137330f729Sjoerg static void generateDiagnosticsForCallLike(ProgramStateRef CurrSt,
2147330f729Sjoerg                                            const LocationContext *LCtx,
2157330f729Sjoerg                                            const RefVal &CurrV, SymbolRef &Sym,
2167330f729Sjoerg                                            const Stmt *S,
2177330f729Sjoerg                                            llvm::raw_string_ostream &os) {
2187330f729Sjoerg   CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
2197330f729Sjoerg   if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
2207330f729Sjoerg     // Get the name of the callee (if it is available)
2217330f729Sjoerg     // from the tracked SVal.
2227330f729Sjoerg     SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
2237330f729Sjoerg     const FunctionDecl *FD = X.getAsFunctionDecl();
2247330f729Sjoerg 
2257330f729Sjoerg     // If failed, try to get it from AST.
2267330f729Sjoerg     if (!FD)
2277330f729Sjoerg       FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
2287330f729Sjoerg 
2297330f729Sjoerg     if (const auto *MD = dyn_cast<CXXMethodDecl>(CE->getCalleeDecl())) {
2307330f729Sjoerg       os << "Call to method '" << MD->getQualifiedNameAsString() << '\'';
2317330f729Sjoerg     } else if (FD) {
2327330f729Sjoerg       os << "Call to function '" << FD->getQualifiedNameAsString() << '\'';
2337330f729Sjoerg     } else {
2347330f729Sjoerg       os << "function call";
2357330f729Sjoerg     }
2367330f729Sjoerg   } else if (isa<CXXNewExpr>(S)) {
2377330f729Sjoerg     os << "Operator 'new'";
2387330f729Sjoerg   } else {
2397330f729Sjoerg     assert(isa<ObjCMessageExpr>(S));
2407330f729Sjoerg     CallEventRef<ObjCMethodCall> Call =
2417330f729Sjoerg         Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
2427330f729Sjoerg 
2437330f729Sjoerg     switch (Call->getMessageKind()) {
2447330f729Sjoerg     case OCM_Message:
2457330f729Sjoerg       os << "Method";
2467330f729Sjoerg       break;
2477330f729Sjoerg     case OCM_PropertyAccess:
2487330f729Sjoerg       os << "Property";
2497330f729Sjoerg       break;
2507330f729Sjoerg     case OCM_Subscript:
2517330f729Sjoerg       os << "Subscript";
2527330f729Sjoerg       break;
2537330f729Sjoerg     }
2547330f729Sjoerg   }
2557330f729Sjoerg 
2567330f729Sjoerg   Optional<CallEventRef<>> CE = Mgr.getCall(S, CurrSt, LCtx);
2577330f729Sjoerg   auto Idx = findArgIdxOfSymbol(CurrSt, LCtx, Sym, CE);
2587330f729Sjoerg 
2597330f729Sjoerg   // If index is not found, we assume that the symbol was returned.
2607330f729Sjoerg   if (!Idx) {
2617330f729Sjoerg     os << " returns ";
2627330f729Sjoerg   } else {
2637330f729Sjoerg     os << " writes ";
2647330f729Sjoerg   }
2657330f729Sjoerg 
2667330f729Sjoerg   if (CurrV.getObjKind() == ObjKind::CF) {
2677330f729Sjoerg     os << "a Core Foundation object of type '"
2687330f729Sjoerg        << Sym->getType().getAsString() << "' with a ";
2697330f729Sjoerg   } else if (CurrV.getObjKind() == ObjKind::OS) {
2707330f729Sjoerg     os << "an OSObject of type '" << findAllocatedObjectName(S, Sym->getType())
2717330f729Sjoerg        << "' with a ";
2727330f729Sjoerg   } else if (CurrV.getObjKind() == ObjKind::Generalized) {
2737330f729Sjoerg     os << "an object of type '" << Sym->getType().getAsString()
2747330f729Sjoerg        << "' with a ";
2757330f729Sjoerg   } else {
2767330f729Sjoerg     assert(CurrV.getObjKind() == ObjKind::ObjC);
2777330f729Sjoerg     QualType T = Sym->getType();
2787330f729Sjoerg     if (!isa<ObjCObjectPointerType>(T)) {
2797330f729Sjoerg       os << "an Objective-C object with a ";
2807330f729Sjoerg     } else {
2817330f729Sjoerg       const ObjCObjectPointerType *PT = cast<ObjCObjectPointerType>(T);
2827330f729Sjoerg       os << "an instance of " << PT->getPointeeType().getAsString()
2837330f729Sjoerg          << " with a ";
2847330f729Sjoerg     }
2857330f729Sjoerg   }
2867330f729Sjoerg 
2877330f729Sjoerg   if (CurrV.isOwned()) {
2887330f729Sjoerg     os << "+1 retain count";
2897330f729Sjoerg   } else {
2907330f729Sjoerg     assert(CurrV.isNotOwned());
2917330f729Sjoerg     os << "+0 retain count";
2927330f729Sjoerg   }
2937330f729Sjoerg 
2947330f729Sjoerg   if (Idx) {
2957330f729Sjoerg     os << " into an out parameter '";
2967330f729Sjoerg     const ParmVarDecl *PVD = (*CE)->parameters()[*Idx];
2977330f729Sjoerg     PVD->getNameForDiagnostic(os, PVD->getASTContext().getPrintingPolicy(),
2987330f729Sjoerg                               /*Qualified=*/false);
2997330f729Sjoerg     os << "'";
3007330f729Sjoerg 
3017330f729Sjoerg     QualType RT = (*CE)->getResultType();
3027330f729Sjoerg     if (!RT.isNull() && !RT->isVoidType()) {
3037330f729Sjoerg       SVal RV = (*CE)->getReturnValue();
3047330f729Sjoerg       if (CurrSt->isNull(RV).isConstrainedTrue()) {
3057330f729Sjoerg         os << " (assuming the call returns zero)";
3067330f729Sjoerg       } else if (CurrSt->isNonNull(RV).isConstrainedTrue()) {
3077330f729Sjoerg         os << " (assuming the call returns non-zero)";
3087330f729Sjoerg       }
3097330f729Sjoerg 
3107330f729Sjoerg     }
3117330f729Sjoerg   }
3127330f729Sjoerg }
3137330f729Sjoerg 
3147330f729Sjoerg namespace clang {
3157330f729Sjoerg namespace ento {
3167330f729Sjoerg namespace retaincountchecker {
3177330f729Sjoerg 
3187330f729Sjoerg class RefCountReportVisitor : public BugReporterVisitor {
3197330f729Sjoerg protected:
3207330f729Sjoerg   SymbolRef Sym;
3217330f729Sjoerg 
3227330f729Sjoerg public:
RefCountReportVisitor(SymbolRef sym)3237330f729Sjoerg   RefCountReportVisitor(SymbolRef sym) : Sym(sym) {}
3247330f729Sjoerg 
Profile(llvm::FoldingSetNodeID & ID) const3257330f729Sjoerg   void Profile(llvm::FoldingSetNodeID &ID) const override {
3267330f729Sjoerg     static int x = 0;
3277330f729Sjoerg     ID.AddPointer(&x);
3287330f729Sjoerg     ID.AddPointer(Sym);
3297330f729Sjoerg   }
3307330f729Sjoerg 
3317330f729Sjoerg   PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
3327330f729Sjoerg                                    BugReporterContext &BRC,
3337330f729Sjoerg                                    PathSensitiveBugReport &BR) override;
3347330f729Sjoerg 
3357330f729Sjoerg   PathDiagnosticPieceRef getEndPath(BugReporterContext &BRC,
3367330f729Sjoerg                                     const ExplodedNode *N,
3377330f729Sjoerg                                     PathSensitiveBugReport &BR) override;
3387330f729Sjoerg };
3397330f729Sjoerg 
3407330f729Sjoerg class RefLeakReportVisitor : public RefCountReportVisitor {
3417330f729Sjoerg public:
RefLeakReportVisitor(SymbolRef Sym,const MemRegion * LastBinding)342*e038c9c4Sjoerg   RefLeakReportVisitor(SymbolRef Sym, const MemRegion *LastBinding)
343*e038c9c4Sjoerg       : RefCountReportVisitor(Sym), LastBinding(LastBinding) {}
3447330f729Sjoerg 
3457330f729Sjoerg   PathDiagnosticPieceRef getEndPath(BugReporterContext &BRC,
3467330f729Sjoerg                                     const ExplodedNode *N,
3477330f729Sjoerg                                     PathSensitiveBugReport &BR) override;
348*e038c9c4Sjoerg 
349*e038c9c4Sjoerg private:
350*e038c9c4Sjoerg   const MemRegion *LastBinding;
3517330f729Sjoerg };
3527330f729Sjoerg 
3537330f729Sjoerg } // end namespace retaincountchecker
3547330f729Sjoerg } // end namespace ento
3557330f729Sjoerg } // end namespace clang
3567330f729Sjoerg 
3577330f729Sjoerg 
3587330f729Sjoerg /// Find the first node with the parent stack frame.
getCalleeNode(const ExplodedNode * Pred)3597330f729Sjoerg static const ExplodedNode *getCalleeNode(const ExplodedNode *Pred) {
3607330f729Sjoerg   const StackFrameContext *SC = Pred->getStackFrame();
3617330f729Sjoerg   if (SC->inTopFrame())
3627330f729Sjoerg     return nullptr;
3637330f729Sjoerg   const StackFrameContext *PC = SC->getParent()->getStackFrame();
3647330f729Sjoerg   if (!PC)
3657330f729Sjoerg     return nullptr;
3667330f729Sjoerg 
3677330f729Sjoerg   const ExplodedNode *N = Pred;
3687330f729Sjoerg   while (N && N->getStackFrame() != PC) {
3697330f729Sjoerg     N = N->getFirstPred();
3707330f729Sjoerg   }
3717330f729Sjoerg   return N;
3727330f729Sjoerg }
3737330f729Sjoerg 
3747330f729Sjoerg 
3757330f729Sjoerg /// Insert a diagnostic piece at function exit
3767330f729Sjoerg /// if a function parameter is annotated as "os_consumed",
3777330f729Sjoerg /// but it does not actually consume the reference.
3787330f729Sjoerg static std::shared_ptr<PathDiagnosticEventPiece>
annotateConsumedSummaryMismatch(const ExplodedNode * N,CallExitBegin & CallExitLoc,const SourceManager & SM,CallEventManager & CEMgr)3797330f729Sjoerg annotateConsumedSummaryMismatch(const ExplodedNode *N,
3807330f729Sjoerg                                 CallExitBegin &CallExitLoc,
3817330f729Sjoerg                                 const SourceManager &SM,
3827330f729Sjoerg                                 CallEventManager &CEMgr) {
3837330f729Sjoerg 
3847330f729Sjoerg   const ExplodedNode *CN = getCalleeNode(N);
3857330f729Sjoerg   if (!CN)
3867330f729Sjoerg     return nullptr;
3877330f729Sjoerg 
3887330f729Sjoerg   CallEventRef<> Call = CEMgr.getCaller(N->getStackFrame(), N->getState());
3897330f729Sjoerg 
3907330f729Sjoerg   std::string sbuf;
3917330f729Sjoerg   llvm::raw_string_ostream os(sbuf);
3927330f729Sjoerg   ArrayRef<const ParmVarDecl *> Parameters = Call->parameters();
3937330f729Sjoerg   for (unsigned I=0; I < Call->getNumArgs() && I < Parameters.size(); ++I) {
3947330f729Sjoerg     const ParmVarDecl *PVD = Parameters[I];
3957330f729Sjoerg 
3967330f729Sjoerg     if (!PVD->hasAttr<OSConsumedAttr>())
3977330f729Sjoerg       continue;
3987330f729Sjoerg 
3997330f729Sjoerg     if (SymbolRef SR = Call->getArgSVal(I).getAsLocSymbol()) {
4007330f729Sjoerg       const RefVal *CountBeforeCall = getRefBinding(CN->getState(), SR);
4017330f729Sjoerg       const RefVal *CountAtExit = getRefBinding(N->getState(), SR);
4027330f729Sjoerg 
4037330f729Sjoerg       if (!CountBeforeCall || !CountAtExit)
4047330f729Sjoerg         continue;
4057330f729Sjoerg 
4067330f729Sjoerg       unsigned CountBefore = CountBeforeCall->getCount();
4077330f729Sjoerg       unsigned CountAfter = CountAtExit->getCount();
4087330f729Sjoerg 
4097330f729Sjoerg       bool AsExpected = CountBefore > 0 && CountAfter == CountBefore - 1;
4107330f729Sjoerg       if (!AsExpected) {
4117330f729Sjoerg         os << "Parameter '";
4127330f729Sjoerg         PVD->getNameForDiagnostic(os, PVD->getASTContext().getPrintingPolicy(),
4137330f729Sjoerg                                   /*Qualified=*/false);
4147330f729Sjoerg         os << "' is marked as consuming, but the function did not consume "
4157330f729Sjoerg            << "the reference\n";
4167330f729Sjoerg       }
4177330f729Sjoerg     }
4187330f729Sjoerg   }
4197330f729Sjoerg 
4207330f729Sjoerg   if (os.str().empty())
4217330f729Sjoerg     return nullptr;
4227330f729Sjoerg 
4237330f729Sjoerg   PathDiagnosticLocation L = PathDiagnosticLocation::create(CallExitLoc, SM);
4247330f729Sjoerg   return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
4257330f729Sjoerg }
4267330f729Sjoerg 
4277330f729Sjoerg /// Annotate the parameter at the analysis entry point.
4287330f729Sjoerg static std::shared_ptr<PathDiagnosticEventPiece>
annotateStartParameter(const ExplodedNode * N,SymbolRef Sym,const SourceManager & SM)4297330f729Sjoerg annotateStartParameter(const ExplodedNode *N, SymbolRef Sym,
4307330f729Sjoerg                        const SourceManager &SM) {
4317330f729Sjoerg   auto PP = N->getLocationAs<BlockEdge>();
4327330f729Sjoerg   if (!PP)
4337330f729Sjoerg     return nullptr;
4347330f729Sjoerg 
4357330f729Sjoerg   const CFGBlock *Src = PP->getSrc();
4367330f729Sjoerg   const RefVal *CurrT = getRefBinding(N->getState(), Sym);
4377330f729Sjoerg 
4387330f729Sjoerg   if (&Src->getParent()->getEntry() != Src || !CurrT ||
4397330f729Sjoerg       getRefBinding(N->getFirstPred()->getState(), Sym))
4407330f729Sjoerg     return nullptr;
4417330f729Sjoerg 
4427330f729Sjoerg   const auto *VR = cast<VarRegion>(cast<SymbolRegionValue>(Sym)->getRegion());
4437330f729Sjoerg   const auto *PVD = cast<ParmVarDecl>(VR->getDecl());
4447330f729Sjoerg   PathDiagnosticLocation L = PathDiagnosticLocation(PVD, SM);
4457330f729Sjoerg 
4467330f729Sjoerg   std::string s;
4477330f729Sjoerg   llvm::raw_string_ostream os(s);
448*e038c9c4Sjoerg   os << "Parameter '" << PVD->getDeclName() << "' starts at +";
4497330f729Sjoerg   if (CurrT->getCount() == 1) {
4507330f729Sjoerg     os << "1, as it is marked as consuming";
4517330f729Sjoerg   } else {
4527330f729Sjoerg     assert(CurrT->getCount() == 0);
4537330f729Sjoerg     os << "0";
4547330f729Sjoerg   }
4557330f729Sjoerg   return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
4567330f729Sjoerg }
4577330f729Sjoerg 
4587330f729Sjoerg PathDiagnosticPieceRef
VisitNode(const ExplodedNode * N,BugReporterContext & BRC,PathSensitiveBugReport & BR)4597330f729Sjoerg RefCountReportVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
4607330f729Sjoerg                                  PathSensitiveBugReport &BR) {
4617330f729Sjoerg 
4627330f729Sjoerg   const auto &BT = static_cast<const RefCountBug&>(BR.getBugType());
4637330f729Sjoerg 
4647330f729Sjoerg   bool IsFreeUnowned = BT.getBugType() == RefCountBug::FreeNotOwned ||
4657330f729Sjoerg                        BT.getBugType() == RefCountBug::DeallocNotOwned;
4667330f729Sjoerg 
4677330f729Sjoerg   const SourceManager &SM = BRC.getSourceManager();
4687330f729Sjoerg   CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
4697330f729Sjoerg   if (auto CE = N->getLocationAs<CallExitBegin>())
4707330f729Sjoerg     if (auto PD = annotateConsumedSummaryMismatch(N, *CE, SM, CEMgr))
4717330f729Sjoerg       return PD;
4727330f729Sjoerg 
4737330f729Sjoerg   if (auto PD = annotateStartParameter(N, Sym, SM))
4747330f729Sjoerg     return PD;
4757330f729Sjoerg 
4767330f729Sjoerg   // FIXME: We will eventually need to handle non-statement-based events
4777330f729Sjoerg   // (__attribute__((cleanup))).
4787330f729Sjoerg   if (!N->getLocation().getAs<StmtPoint>())
4797330f729Sjoerg     return nullptr;
4807330f729Sjoerg 
4817330f729Sjoerg   // Check if the type state has changed.
4827330f729Sjoerg   const ExplodedNode *PrevNode = N->getFirstPred();
4837330f729Sjoerg   ProgramStateRef PrevSt = PrevNode->getState();
4847330f729Sjoerg   ProgramStateRef CurrSt = N->getState();
4857330f729Sjoerg   const LocationContext *LCtx = N->getLocationContext();
4867330f729Sjoerg 
4877330f729Sjoerg   const RefVal* CurrT = getRefBinding(CurrSt, Sym);
4887330f729Sjoerg   if (!CurrT)
4897330f729Sjoerg     return nullptr;
4907330f729Sjoerg 
4917330f729Sjoerg   const RefVal &CurrV = *CurrT;
4927330f729Sjoerg   const RefVal *PrevT = getRefBinding(PrevSt, Sym);
4937330f729Sjoerg 
4947330f729Sjoerg   // Create a string buffer to constain all the useful things we want
4957330f729Sjoerg   // to tell the user.
4967330f729Sjoerg   std::string sbuf;
4977330f729Sjoerg   llvm::raw_string_ostream os(sbuf);
4987330f729Sjoerg 
4997330f729Sjoerg   if (PrevT && IsFreeUnowned && CurrV.isNotOwned() && PrevT->isOwned()) {
5007330f729Sjoerg     os << "Object is now not exclusively owned";
5017330f729Sjoerg     auto Pos = PathDiagnosticLocation::create(N->getLocation(), SM);
5027330f729Sjoerg     return std::make_shared<PathDiagnosticEventPiece>(Pos, os.str());
5037330f729Sjoerg   }
5047330f729Sjoerg 
5057330f729Sjoerg   // This is the allocation site since the previous node had no bindings
5067330f729Sjoerg   // for this symbol.
5077330f729Sjoerg   if (!PrevT) {
5087330f729Sjoerg     const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
5097330f729Sjoerg 
5107330f729Sjoerg     if (isa<ObjCIvarRefExpr>(S) &&
5117330f729Sjoerg         isSynthesizedAccessor(LCtx->getStackFrame())) {
5127330f729Sjoerg       S = LCtx->getStackFrame()->getCallSite();
5137330f729Sjoerg     }
5147330f729Sjoerg 
5157330f729Sjoerg     if (isa<ObjCArrayLiteral>(S)) {
5167330f729Sjoerg       os << "NSArray literal is an object with a +0 retain count";
5177330f729Sjoerg     } else if (isa<ObjCDictionaryLiteral>(S)) {
5187330f729Sjoerg       os << "NSDictionary literal is an object with a +0 retain count";
5197330f729Sjoerg     } else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
5207330f729Sjoerg       if (isNumericLiteralExpression(BL->getSubExpr()))
5217330f729Sjoerg         os << "NSNumber literal is an object with a +0 retain count";
5227330f729Sjoerg       else {
5237330f729Sjoerg         const ObjCInterfaceDecl *BoxClass = nullptr;
5247330f729Sjoerg         if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
5257330f729Sjoerg           BoxClass = Method->getClassInterface();
5267330f729Sjoerg 
5277330f729Sjoerg         // We should always be able to find the boxing class interface,
5287330f729Sjoerg         // but consider this future-proofing.
5297330f729Sjoerg         if (BoxClass) {
5307330f729Sjoerg           os << *BoxClass << " b";
5317330f729Sjoerg         } else {
5327330f729Sjoerg           os << "B";
5337330f729Sjoerg         }
5347330f729Sjoerg 
5357330f729Sjoerg         os << "oxed expression produces an object with a +0 retain count";
5367330f729Sjoerg       }
5377330f729Sjoerg     } else if (isa<ObjCIvarRefExpr>(S)) {
5387330f729Sjoerg       os << "Object loaded from instance variable";
5397330f729Sjoerg     } else {
5407330f729Sjoerg       generateDiagnosticsForCallLike(CurrSt, LCtx, CurrV, Sym, S, os);
5417330f729Sjoerg     }
5427330f729Sjoerg 
5437330f729Sjoerg     PathDiagnosticLocation Pos(S, SM, N->getLocationContext());
5447330f729Sjoerg     return std::make_shared<PathDiagnosticEventPiece>(Pos, os.str());
5457330f729Sjoerg   }
5467330f729Sjoerg 
5477330f729Sjoerg   // Gather up the effects that were performed on the object at this
5487330f729Sjoerg   // program point
5497330f729Sjoerg   bool DeallocSent = false;
5507330f729Sjoerg 
5517330f729Sjoerg   const ProgramPointTag *Tag = N->getLocation().getTag();
5527330f729Sjoerg 
553*e038c9c4Sjoerg   if (Tag == &RetainCountChecker::getCastFailTag()) {
5547330f729Sjoerg     os << "Assuming dynamic cast returns null due to type mismatch";
5557330f729Sjoerg   }
5567330f729Sjoerg 
557*e038c9c4Sjoerg   if (Tag == &RetainCountChecker::getDeallocSentTag()) {
5587330f729Sjoerg     // We only have summaries attached to nodes after evaluating CallExpr and
5597330f729Sjoerg     // ObjCMessageExprs.
5607330f729Sjoerg     const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
5617330f729Sjoerg 
5627330f729Sjoerg     if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
5637330f729Sjoerg       // Iterate through the parameter expressions and see if the symbol
5647330f729Sjoerg       // was ever passed as an argument.
5657330f729Sjoerg       unsigned i = 0;
5667330f729Sjoerg 
5677330f729Sjoerg       for (auto AI=CE->arg_begin(), AE=CE->arg_end(); AI!=AE; ++AI, ++i) {
5687330f729Sjoerg 
5697330f729Sjoerg         // Retrieve the value of the argument.  Is it the symbol
5707330f729Sjoerg         // we are interested in?
5717330f729Sjoerg         if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
5727330f729Sjoerg           continue;
5737330f729Sjoerg 
5747330f729Sjoerg         // We have an argument.  Get the effect!
5757330f729Sjoerg         DeallocSent = true;
5767330f729Sjoerg       }
5777330f729Sjoerg     } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
5787330f729Sjoerg       if (const Expr *receiver = ME->getInstanceReceiver()) {
5797330f729Sjoerg         if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
5807330f729Sjoerg               .getAsLocSymbol() == Sym) {
5817330f729Sjoerg           // The symbol we are tracking is the receiver.
5827330f729Sjoerg           DeallocSent = true;
5837330f729Sjoerg         }
5847330f729Sjoerg       }
5857330f729Sjoerg     }
5867330f729Sjoerg   }
5877330f729Sjoerg 
5887330f729Sjoerg   if (!shouldGenerateNote(os, PrevT, CurrV, DeallocSent))
5897330f729Sjoerg     return nullptr;
5907330f729Sjoerg 
5917330f729Sjoerg   if (os.str().empty())
5927330f729Sjoerg     return nullptr; // We have nothing to say!
5937330f729Sjoerg 
5947330f729Sjoerg   const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
5957330f729Sjoerg   PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
5967330f729Sjoerg                                 N->getLocationContext());
5977330f729Sjoerg   auto P = std::make_shared<PathDiagnosticEventPiece>(Pos, os.str());
5987330f729Sjoerg 
5997330f729Sjoerg   // Add the range by scanning the children of the statement for any bindings
6007330f729Sjoerg   // to Sym.
6017330f729Sjoerg   for (const Stmt *Child : S->children())
6027330f729Sjoerg     if (const Expr *Exp = dyn_cast_or_null<Expr>(Child))
6037330f729Sjoerg       if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
6047330f729Sjoerg         P->addRange(Exp->getSourceRange());
6057330f729Sjoerg         break;
6067330f729Sjoerg       }
6077330f729Sjoerg 
6087330f729Sjoerg   return std::move(P);
6097330f729Sjoerg }
6107330f729Sjoerg 
describeRegion(const MemRegion * MR)6117330f729Sjoerg static Optional<std::string> describeRegion(const MemRegion *MR) {
6127330f729Sjoerg   if (const auto *VR = dyn_cast_or_null<VarRegion>(MR))
6137330f729Sjoerg     return std::string(VR->getDecl()->getName());
6147330f729Sjoerg   // Once we support more storage locations for bindings,
6157330f729Sjoerg   // this would need to be improved.
6167330f729Sjoerg   return None;
6177330f729Sjoerg }
6187330f729Sjoerg 
619*e038c9c4Sjoerg using Bindings = llvm::SmallVector<std::pair<const MemRegion *, SVal>, 4>;
620*e038c9c4Sjoerg 
621*e038c9c4Sjoerg class VarBindingsCollector : public StoreManager::BindingsHandler {
622*e038c9c4Sjoerg   SymbolRef Sym;
623*e038c9c4Sjoerg   Bindings &Result;
624*e038c9c4Sjoerg 
625*e038c9c4Sjoerg public:
VarBindingsCollector(SymbolRef Sym,Bindings & ToFill)626*e038c9c4Sjoerg   VarBindingsCollector(SymbolRef Sym, Bindings &ToFill)
627*e038c9c4Sjoerg       : Sym(Sym), Result(ToFill) {}
628*e038c9c4Sjoerg 
HandleBinding(StoreManager & SMgr,Store Store,const MemRegion * R,SVal Val)629*e038c9c4Sjoerg   bool HandleBinding(StoreManager &SMgr, Store Store, const MemRegion *R,
630*e038c9c4Sjoerg                      SVal Val) override {
631*e038c9c4Sjoerg     SymbolRef SymV = Val.getAsLocSymbol();
632*e038c9c4Sjoerg     if (!SymV || SymV != Sym)
633*e038c9c4Sjoerg       return true;
634*e038c9c4Sjoerg 
635*e038c9c4Sjoerg     if (isa<NonParamVarRegion>(R))
636*e038c9c4Sjoerg       Result.emplace_back(R, Val);
637*e038c9c4Sjoerg 
638*e038c9c4Sjoerg     return true;
639*e038c9c4Sjoerg   }
640*e038c9c4Sjoerg };
641*e038c9c4Sjoerg 
getAllVarBindingsForSymbol(ProgramStateManager & Manager,const ExplodedNode * Node,SymbolRef Sym)642*e038c9c4Sjoerg Bindings getAllVarBindingsForSymbol(ProgramStateManager &Manager,
643*e038c9c4Sjoerg                                     const ExplodedNode *Node, SymbolRef Sym) {
644*e038c9c4Sjoerg   Bindings Result;
645*e038c9c4Sjoerg   VarBindingsCollector Collector{Sym, Result};
646*e038c9c4Sjoerg   while (Result.empty() && Node) {
647*e038c9c4Sjoerg     Manager.iterBindings(Node->getState(), Collector);
648*e038c9c4Sjoerg     Node = Node->getFirstPred();
649*e038c9c4Sjoerg   }
650*e038c9c4Sjoerg 
651*e038c9c4Sjoerg   return Result;
652*e038c9c4Sjoerg }
653*e038c9c4Sjoerg 
6547330f729Sjoerg namespace {
6557330f729Sjoerg // Find the first node in the current function context that referred to the
6567330f729Sjoerg // tracked symbol and the memory location that value was stored to. Note, the
6577330f729Sjoerg // value is only reported if the allocation occurred in the same function as
6587330f729Sjoerg // the leak. The function can also return a location context, which should be
6597330f729Sjoerg // treated as interesting.
6607330f729Sjoerg struct AllocationInfo {
6617330f729Sjoerg   const ExplodedNode* N;
6627330f729Sjoerg   const MemRegion *R;
6637330f729Sjoerg   const LocationContext *InterestingMethodContext;
AllocationInfo__anonbd0af4ad0111::AllocationInfo6647330f729Sjoerg   AllocationInfo(const ExplodedNode *InN,
6657330f729Sjoerg                  const MemRegion *InR,
6667330f729Sjoerg                  const LocationContext *InInterestingMethodContext) :
6677330f729Sjoerg     N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
6687330f729Sjoerg };
6697330f729Sjoerg } // end anonymous namespace
6707330f729Sjoerg 
GetAllocationSite(ProgramStateManager & StateMgr,const ExplodedNode * N,SymbolRef Sym)6717330f729Sjoerg static AllocationInfo GetAllocationSite(ProgramStateManager &StateMgr,
6727330f729Sjoerg                                         const ExplodedNode *N, SymbolRef Sym) {
6737330f729Sjoerg   const ExplodedNode *AllocationNode = N;
6747330f729Sjoerg   const ExplodedNode *AllocationNodeInCurrentOrParentContext = N;
6757330f729Sjoerg   const MemRegion *FirstBinding = nullptr;
6767330f729Sjoerg   const LocationContext *LeakContext = N->getLocationContext();
6777330f729Sjoerg 
6787330f729Sjoerg   // The location context of the init method called on the leaked object, if
6797330f729Sjoerg   // available.
6807330f729Sjoerg   const LocationContext *InitMethodContext = nullptr;
6817330f729Sjoerg 
6827330f729Sjoerg   while (N) {
6837330f729Sjoerg     ProgramStateRef St = N->getState();
6847330f729Sjoerg     const LocationContext *NContext = N->getLocationContext();
6857330f729Sjoerg 
6867330f729Sjoerg     if (!getRefBinding(St, Sym))
6877330f729Sjoerg       break;
6887330f729Sjoerg 
6897330f729Sjoerg     StoreManager::FindUniqueBinding FB(Sym);
6907330f729Sjoerg     StateMgr.iterBindings(St, FB);
6917330f729Sjoerg 
6927330f729Sjoerg     if (FB) {
6937330f729Sjoerg       const MemRegion *R = FB.getRegion();
6947330f729Sjoerg       // Do not show local variables belonging to a function other than
6957330f729Sjoerg       // where the error is reported.
6967330f729Sjoerg       if (auto MR = dyn_cast<StackSpaceRegion>(R->getMemorySpace()))
6977330f729Sjoerg         if (MR->getStackFrame() == LeakContext->getStackFrame())
6987330f729Sjoerg           FirstBinding = R;
6997330f729Sjoerg     }
7007330f729Sjoerg 
7017330f729Sjoerg     // AllocationNode is the last node in which the symbol was tracked.
7027330f729Sjoerg     AllocationNode = N;
7037330f729Sjoerg 
7047330f729Sjoerg     // AllocationNodeInCurrentContext, is the last node in the current or
7057330f729Sjoerg     // parent context in which the symbol was tracked.
7067330f729Sjoerg     //
7077330f729Sjoerg     // Note that the allocation site might be in the parent context. For example,
7087330f729Sjoerg     // the case where an allocation happens in a block that captures a reference
7097330f729Sjoerg     // to it and that reference is overwritten/dropped by another call to
7107330f729Sjoerg     // the block.
7117330f729Sjoerg     if (NContext == LeakContext || NContext->isParentOf(LeakContext))
7127330f729Sjoerg       AllocationNodeInCurrentOrParentContext = N;
7137330f729Sjoerg 
7147330f729Sjoerg     // Find the last init that was called on the given symbol and store the
7157330f729Sjoerg     // init method's location context.
7167330f729Sjoerg     if (!InitMethodContext)
7177330f729Sjoerg       if (auto CEP = N->getLocation().getAs<CallEnter>()) {
7187330f729Sjoerg         const Stmt *CE = CEP->getCallExpr();
7197330f729Sjoerg         if (const auto *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
7207330f729Sjoerg           const Stmt *RecExpr = ME->getInstanceReceiver();
7217330f729Sjoerg           if (RecExpr) {
7227330f729Sjoerg             SVal RecV = St->getSVal(RecExpr, NContext);
7237330f729Sjoerg             if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
7247330f729Sjoerg               InitMethodContext = CEP->getCalleeContext();
7257330f729Sjoerg           }
7267330f729Sjoerg         }
7277330f729Sjoerg       }
7287330f729Sjoerg 
7297330f729Sjoerg     N = N->getFirstPred();
7307330f729Sjoerg   }
7317330f729Sjoerg 
7327330f729Sjoerg   // If we are reporting a leak of the object that was allocated with alloc,
7337330f729Sjoerg   // mark its init method as interesting.
7347330f729Sjoerg   const LocationContext *InterestingMethodContext = nullptr;
7357330f729Sjoerg   if (InitMethodContext) {
7367330f729Sjoerg     const ProgramPoint AllocPP = AllocationNode->getLocation();
7377330f729Sjoerg     if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
7387330f729Sjoerg       if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
7397330f729Sjoerg         if (ME->getMethodFamily() == OMF_alloc)
7407330f729Sjoerg           InterestingMethodContext = InitMethodContext;
7417330f729Sjoerg   }
7427330f729Sjoerg 
7437330f729Sjoerg   // If allocation happened in a function different from the leak node context,
7447330f729Sjoerg   // do not report the binding.
7457330f729Sjoerg   assert(N && "Could not find allocation node");
7467330f729Sjoerg 
7477330f729Sjoerg   if (AllocationNodeInCurrentOrParentContext &&
7487330f729Sjoerg       AllocationNodeInCurrentOrParentContext->getLocationContext() !=
7497330f729Sjoerg       LeakContext)
7507330f729Sjoerg     FirstBinding = nullptr;
7517330f729Sjoerg 
7527330f729Sjoerg   return AllocationInfo(AllocationNodeInCurrentOrParentContext, FirstBinding,
7537330f729Sjoerg                         InterestingMethodContext);
7547330f729Sjoerg }
7557330f729Sjoerg 
7567330f729Sjoerg PathDiagnosticPieceRef
getEndPath(BugReporterContext & BRC,const ExplodedNode * EndN,PathSensitiveBugReport & BR)7577330f729Sjoerg RefCountReportVisitor::getEndPath(BugReporterContext &BRC,
7587330f729Sjoerg                                   const ExplodedNode *EndN,
7597330f729Sjoerg                                   PathSensitiveBugReport &BR) {
7607330f729Sjoerg   BR.markInteresting(Sym);
7617330f729Sjoerg   return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
7627330f729Sjoerg }
7637330f729Sjoerg 
7647330f729Sjoerg PathDiagnosticPieceRef
getEndPath(BugReporterContext & BRC,const ExplodedNode * EndN,PathSensitiveBugReport & BR)7657330f729Sjoerg RefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
7667330f729Sjoerg                                  const ExplodedNode *EndN,
7677330f729Sjoerg                                  PathSensitiveBugReport &BR) {
7687330f729Sjoerg 
7697330f729Sjoerg   // Tell the BugReporterContext to report cases when the tracked symbol is
7707330f729Sjoerg   // assigned to different variables, etc.
7717330f729Sjoerg   BR.markInteresting(Sym);
7727330f729Sjoerg 
7737330f729Sjoerg   PathDiagnosticLocation L = cast<RefLeakReport>(BR).getEndOfPath();
7747330f729Sjoerg 
7757330f729Sjoerg   std::string sbuf;
7767330f729Sjoerg   llvm::raw_string_ostream os(sbuf);
7777330f729Sjoerg 
7787330f729Sjoerg   os << "Object leaked: ";
7797330f729Sjoerg 
780*e038c9c4Sjoerg   Optional<std::string> RegionDescription = describeRegion(LastBinding);
7817330f729Sjoerg   if (RegionDescription) {
7827330f729Sjoerg     os << "object allocated and stored into '" << *RegionDescription << '\'';
7837330f729Sjoerg   } else {
7847330f729Sjoerg     os << "allocated object of type '" << getPrettyTypeName(Sym->getType())
7857330f729Sjoerg        << "'";
7867330f729Sjoerg   }
7877330f729Sjoerg 
7887330f729Sjoerg   // Get the retain count.
7897330f729Sjoerg   const RefVal *RV = getRefBinding(EndN->getState(), Sym);
7907330f729Sjoerg   assert(RV);
7917330f729Sjoerg 
7927330f729Sjoerg   if (RV->getKind() == RefVal::ErrorLeakReturned) {
7937330f729Sjoerg     // FIXME: Per comments in rdar://6320065, "create" only applies to CF
7947330f729Sjoerg     // objects.  Only "copy", "alloc", "retain" and "new" transfer ownership
7957330f729Sjoerg     // to the caller for NS objects.
7967330f729Sjoerg     const Decl *D = &EndN->getCodeDecl();
7977330f729Sjoerg 
7987330f729Sjoerg     os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
7997330f729Sjoerg                                   : " is returned from a function ");
8007330f729Sjoerg 
8017330f729Sjoerg     if (D->hasAttr<CFReturnsNotRetainedAttr>()) {
8027330f729Sjoerg       os << "that is annotated as CF_RETURNS_NOT_RETAINED";
8037330f729Sjoerg     } else if (D->hasAttr<NSReturnsNotRetainedAttr>()) {
8047330f729Sjoerg       os << "that is annotated as NS_RETURNS_NOT_RETAINED";
8057330f729Sjoerg     } else if (D->hasAttr<OSReturnsNotRetainedAttr>()) {
8067330f729Sjoerg       os << "that is annotated as OS_RETURNS_NOT_RETAINED";
8077330f729Sjoerg     } else {
8087330f729Sjoerg       if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
8097330f729Sjoerg         if (BRC.getASTContext().getLangOpts().ObjCAutoRefCount) {
8107330f729Sjoerg           os << "managed by Automatic Reference Counting";
8117330f729Sjoerg         } else {
8127330f729Sjoerg           os << "whose name ('" << MD->getSelector().getAsString()
8137330f729Sjoerg              << "') does not start with "
8147330f729Sjoerg                 "'copy', 'mutableCopy', 'alloc' or 'new'."
8157330f729Sjoerg                 "  This violates the naming convention rules"
8167330f729Sjoerg                 " given in the Memory Management Guide for Cocoa";
8177330f729Sjoerg         }
8187330f729Sjoerg       } else {
8197330f729Sjoerg         const FunctionDecl *FD = cast<FunctionDecl>(D);
8207330f729Sjoerg         ObjKind K = RV->getObjKind();
8217330f729Sjoerg         if (K == ObjKind::ObjC || K == ObjKind::CF) {
8227330f729Sjoerg           os << "whose name ('" << *FD
8237330f729Sjoerg              << "') does not contain 'Copy' or 'Create'.  This violates the "
8247330f729Sjoerg                 "naming"
8257330f729Sjoerg                 " convention rules given in the Memory Management Guide for "
8267330f729Sjoerg                 "Core"
8277330f729Sjoerg                 " Foundation";
8287330f729Sjoerg         } else if (RV->getObjKind() == ObjKind::OS) {
8297330f729Sjoerg           std::string FuncName = FD->getNameAsString();
830*e038c9c4Sjoerg           os << "whose name ('" << FuncName << "') starts with '"
831*e038c9c4Sjoerg              << StringRef(FuncName).substr(0, 3) << "'";
8327330f729Sjoerg         }
8337330f729Sjoerg       }
8347330f729Sjoerg     }
8357330f729Sjoerg   } else {
8367330f729Sjoerg     os << " is not referenced later in this execution path and has a retain "
837*e038c9c4Sjoerg           "count of +"
838*e038c9c4Sjoerg        << RV->getCount();
8397330f729Sjoerg   }
8407330f729Sjoerg 
8417330f729Sjoerg   return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
8427330f729Sjoerg }
8437330f729Sjoerg 
RefCountReport(const RefCountBug & D,const LangOptions & LOpts,ExplodedNode * n,SymbolRef sym,bool isLeak)8447330f729Sjoerg RefCountReport::RefCountReport(const RefCountBug &D, const LangOptions &LOpts,
8457330f729Sjoerg                                ExplodedNode *n, SymbolRef sym, bool isLeak)
8467330f729Sjoerg     : PathSensitiveBugReport(D, D.getDescription(), n), Sym(sym),
8477330f729Sjoerg       isLeak(isLeak) {
8487330f729Sjoerg   if (!isLeak)
8497330f729Sjoerg     addVisitor(std::make_unique<RefCountReportVisitor>(sym));
8507330f729Sjoerg }
8517330f729Sjoerg 
RefCountReport(const RefCountBug & D,const LangOptions & LOpts,ExplodedNode * n,SymbolRef sym,StringRef endText)8527330f729Sjoerg RefCountReport::RefCountReport(const RefCountBug &D, const LangOptions &LOpts,
8537330f729Sjoerg                                ExplodedNode *n, SymbolRef sym,
8547330f729Sjoerg                                StringRef endText)
8557330f729Sjoerg     : PathSensitiveBugReport(D, D.getDescription(), endText, n) {
8567330f729Sjoerg 
8577330f729Sjoerg   addVisitor(std::make_unique<RefCountReportVisitor>(sym));
8587330f729Sjoerg }
8597330f729Sjoerg 
deriveParamLocation(CheckerContext & Ctx)860*e038c9c4Sjoerg void RefLeakReport::deriveParamLocation(CheckerContext &Ctx) {
8617330f729Sjoerg   const SourceManager &SMgr = Ctx.getSourceManager();
8627330f729Sjoerg 
863*e038c9c4Sjoerg   if (!Sym->getOriginRegion())
8647330f729Sjoerg     return;
8657330f729Sjoerg 
866*e038c9c4Sjoerg   auto *Region = dyn_cast<DeclRegion>(Sym->getOriginRegion());
8677330f729Sjoerg   if (Region) {
8687330f729Sjoerg     const Decl *PDecl = Region->getDecl();
869*e038c9c4Sjoerg     if (isa_and_nonnull<ParmVarDecl>(PDecl)) {
8707330f729Sjoerg       PathDiagnosticLocation ParamLocation =
8717330f729Sjoerg           PathDiagnosticLocation::create(PDecl, SMgr);
8727330f729Sjoerg       Location = ParamLocation;
8737330f729Sjoerg       UniqueingLocation = ParamLocation;
8747330f729Sjoerg       UniqueingDecl = Ctx.getLocationContext()->getDecl();
8757330f729Sjoerg     }
8767330f729Sjoerg   }
8777330f729Sjoerg }
8787330f729Sjoerg 
deriveAllocLocation(CheckerContext & Ctx)879*e038c9c4Sjoerg void RefLeakReport::deriveAllocLocation(CheckerContext &Ctx) {
8807330f729Sjoerg   // Most bug reports are cached at the location where they occurred.
8817330f729Sjoerg   // With leaks, we want to unique them by the location where they were
8827330f729Sjoerg   // allocated, and only report a single path.  To do this, we need to find
8837330f729Sjoerg   // the allocation site of a piece of tracked memory, which we do via a
8847330f729Sjoerg   // call to GetAllocationSite.  This will walk the ExplodedGraph backwards.
8857330f729Sjoerg   // Note that this is *not* the trimmed graph; we are guaranteed, however,
8867330f729Sjoerg   // that all ancestor nodes that represent the allocation site have the
8877330f729Sjoerg   // same SourceLocation.
8887330f729Sjoerg   const ExplodedNode *AllocNode = nullptr;
8897330f729Sjoerg 
8907330f729Sjoerg   const SourceManager &SMgr = Ctx.getSourceManager();
8917330f729Sjoerg 
8927330f729Sjoerg   AllocationInfo AllocI =
893*e038c9c4Sjoerg       GetAllocationSite(Ctx.getStateManager(), getErrorNode(), Sym);
8947330f729Sjoerg 
8957330f729Sjoerg   AllocNode = AllocI.N;
896*e038c9c4Sjoerg   AllocFirstBinding = AllocI.R;
8977330f729Sjoerg   markInteresting(AllocI.InterestingMethodContext);
8987330f729Sjoerg 
8997330f729Sjoerg   // Get the SourceLocation for the allocation site.
9007330f729Sjoerg   // FIXME: This will crash the analyzer if an allocation comes from an
9017330f729Sjoerg   // implicit call (ex: a destructor call).
9027330f729Sjoerg   // (Currently there are no such allocations in Cocoa, though.)
9037330f729Sjoerg   AllocStmt = AllocNode->getStmtForDiagnostics();
9047330f729Sjoerg 
9057330f729Sjoerg   if (!AllocStmt) {
906*e038c9c4Sjoerg     AllocFirstBinding = nullptr;
9077330f729Sjoerg     return;
9087330f729Sjoerg   }
9097330f729Sjoerg 
910*e038c9c4Sjoerg   PathDiagnosticLocation AllocLocation = PathDiagnosticLocation::createBegin(
911*e038c9c4Sjoerg       AllocStmt, SMgr, AllocNode->getLocationContext());
9127330f729Sjoerg   Location = AllocLocation;
9137330f729Sjoerg 
9147330f729Sjoerg   // Set uniqieing info, which will be used for unique the bug reports. The
9157330f729Sjoerg   // leaks should be uniqued on the allocation site.
9167330f729Sjoerg   UniqueingLocation = AllocLocation;
9177330f729Sjoerg   UniqueingDecl = AllocNode->getLocationContext()->getDecl();
9187330f729Sjoerg }
9197330f729Sjoerg 
createDescription(CheckerContext & Ctx)9207330f729Sjoerg void RefLeakReport::createDescription(CheckerContext &Ctx) {
9217330f729Sjoerg   assert(Location.isValid() && UniqueingDecl && UniqueingLocation.isValid());
9227330f729Sjoerg   Description.clear();
9237330f729Sjoerg   llvm::raw_string_ostream os(Description);
9247330f729Sjoerg   os << "Potential leak of an object";
9257330f729Sjoerg 
926*e038c9c4Sjoerg   Optional<std::string> RegionDescription =
927*e038c9c4Sjoerg       describeRegion(AllocBindingToReport);
9287330f729Sjoerg   if (RegionDescription) {
9297330f729Sjoerg     os << " stored into '" << *RegionDescription << '\'';
9307330f729Sjoerg   } else {
9317330f729Sjoerg 
9327330f729Sjoerg     // If we can't figure out the name, just supply the type information.
9337330f729Sjoerg     os << " of type '" << getPrettyTypeName(Sym->getType()) << "'";
9347330f729Sjoerg   }
9357330f729Sjoerg }
9367330f729Sjoerg 
findBindingToReport(CheckerContext & Ctx,ExplodedNode * Node)937*e038c9c4Sjoerg void RefLeakReport::findBindingToReport(CheckerContext &Ctx,
938*e038c9c4Sjoerg                                         ExplodedNode *Node) {
939*e038c9c4Sjoerg   if (!AllocFirstBinding)
940*e038c9c4Sjoerg     // If we don't have any bindings, we won't be able to find any
941*e038c9c4Sjoerg     // better binding to report.
942*e038c9c4Sjoerg     return;
9437330f729Sjoerg 
944*e038c9c4Sjoerg   // If the original region still contains the leaking symbol...
945*e038c9c4Sjoerg   if (Node->getState()->getSVal(AllocFirstBinding).getAsSymbol() == Sym) {
946*e038c9c4Sjoerg     // ...it is the best binding to report.
947*e038c9c4Sjoerg     AllocBindingToReport = AllocFirstBinding;
948*e038c9c4Sjoerg     return;
949*e038c9c4Sjoerg   }
950*e038c9c4Sjoerg 
951*e038c9c4Sjoerg   // At this point, we know that the original region doesn't contain the leaking
952*e038c9c4Sjoerg   // when the actual leak happens.  It means that it can be confusing for the
953*e038c9c4Sjoerg   // user to see such description in the message.
954*e038c9c4Sjoerg   //
955*e038c9c4Sjoerg   // Let's consider the following example:
956*e038c9c4Sjoerg   //   Object *Original = allocate(...);
957*e038c9c4Sjoerg   //   Object *New = Original;
958*e038c9c4Sjoerg   //   Original = allocate(...);
959*e038c9c4Sjoerg   //   Original->release();
960*e038c9c4Sjoerg   //
961*e038c9c4Sjoerg   // Complaining about a leaking object "stored into Original" might cause a
962*e038c9c4Sjoerg   // rightful confusion because 'Original' is actually released.
963*e038c9c4Sjoerg   // We should complain about 'New' instead.
964*e038c9c4Sjoerg   Bindings AllVarBindings =
965*e038c9c4Sjoerg       getAllVarBindingsForSymbol(Ctx.getStateManager(), Node, Sym);
966*e038c9c4Sjoerg 
967*e038c9c4Sjoerg   // While looking for the last var bindings, we can still find
968*e038c9c4Sjoerg   // `AllocFirstBinding` to be one of them.  In situations like this,
969*e038c9c4Sjoerg   // it would still be the easiest case to explain to our users.
970*e038c9c4Sjoerg   if (!AllVarBindings.empty() &&
971*e038c9c4Sjoerg       llvm::count_if(AllVarBindings,
972*e038c9c4Sjoerg                      [this](const std::pair<const MemRegion *, SVal> Binding) {
973*e038c9c4Sjoerg                        return Binding.first == AllocFirstBinding;
974*e038c9c4Sjoerg                      }) == 0) {
975*e038c9c4Sjoerg     // Let's pick one of them at random (if there is something to pick from).
976*e038c9c4Sjoerg     AllocBindingToReport = AllVarBindings[0].first;
977*e038c9c4Sjoerg 
978*e038c9c4Sjoerg     // Because 'AllocBindingToReport' is not the the same as
979*e038c9c4Sjoerg     // 'AllocFirstBinding', we need to explain how the leaking object
980*e038c9c4Sjoerg     // got from one to another.
981*e038c9c4Sjoerg     //
982*e038c9c4Sjoerg     // NOTE: We use the actual SVal stored in AllocBindingToReport here because
983*e038c9c4Sjoerg     //       FindLastStoreBRVisitor compares SVal's and it can get trickier for
984*e038c9c4Sjoerg     //       something like derived regions if we want to construct SVal from
985*e038c9c4Sjoerg     //       Sym. Instead, we take the value that is definitely stored in that
986*e038c9c4Sjoerg     //       region, thus guaranteeing that FindLastStoreBRVisitor will work.
987*e038c9c4Sjoerg     addVisitor(std::make_unique<FindLastStoreBRVisitor>(
988*e038c9c4Sjoerg         AllVarBindings[0].second.castAs<KnownSVal>(), AllocBindingToReport,
989*e038c9c4Sjoerg         false, bugreporter::TrackingKind::Thorough));
990*e038c9c4Sjoerg   } else {
991*e038c9c4Sjoerg     AllocBindingToReport = AllocFirstBinding;
992*e038c9c4Sjoerg   }
993*e038c9c4Sjoerg }
994*e038c9c4Sjoerg 
RefLeakReport(const RefCountBug & D,const LangOptions & LOpts,ExplodedNode * N,SymbolRef Sym,CheckerContext & Ctx)995*e038c9c4Sjoerg RefLeakReport::RefLeakReport(const RefCountBug &D, const LangOptions &LOpts,
996*e038c9c4Sjoerg                              ExplodedNode *N, SymbolRef Sym,
997*e038c9c4Sjoerg                              CheckerContext &Ctx)
998*e038c9c4Sjoerg     : RefCountReport(D, LOpts, N, Sym, /*isLeak=*/true) {
999*e038c9c4Sjoerg 
1000*e038c9c4Sjoerg   deriveAllocLocation(Ctx);
1001*e038c9c4Sjoerg   findBindingToReport(Ctx, N);
1002*e038c9c4Sjoerg 
1003*e038c9c4Sjoerg   if (!AllocFirstBinding)
1004*e038c9c4Sjoerg     deriveParamLocation(Ctx);
10057330f729Sjoerg 
10067330f729Sjoerg   createDescription(Ctx);
10077330f729Sjoerg 
1008*e038c9c4Sjoerg   addVisitor(std::make_unique<RefLeakReportVisitor>(Sym, AllocBindingToReport));
10097330f729Sjoerg }
1010