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