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 bool DeallocSent) { 47 // Get the previous type state. 48 RefVal PrevV = *PrevT; 49 50 // Specially handle -dealloc. 51 if (DeallocSent) { 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() == ObjKind::CF) { 160 os << " returns a Core Foundation object of type " 161 << Sym->getType().getAsString() << " with a "; 162 } else if (CurrV.getObjKind() == ObjKind::OS) { 163 os << " returns an OSObject of type " << getPrettyTypeName(Sym->getType()) 164 << " with a "; 165 } else if (CurrV.getObjKind() == ObjKind::Generalized) { 166 os << " returns an object of type " << Sym->getType().getAsString() 167 << " with a "; 168 } else { 169 assert(CurrV.getObjKind() == ObjKind::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 196 public: 197 CFRefReportVisitor(SymbolRef sym) : Sym(sym) {} 198 199 void Profile(llvm::FoldingSetNodeID &ID) const override { 200 static int x = 0; 201 ID.AddPointer(&x); 202 ID.AddPointer(Sym); 203 } 204 205 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N, 206 BugReporterContext &BRC, 207 BugReport &BR) override; 208 209 std::shared_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC, 210 const ExplodedNode *N, 211 BugReport &BR) override; 212 }; 213 214 class CFRefLeakReportVisitor : public CFRefReportVisitor { 215 public: 216 CFRefLeakReportVisitor(SymbolRef sym) : CFRefReportVisitor(sym) {} 217 218 std::shared_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC, 219 const ExplodedNode *N, 220 BugReport &BR) override; 221 }; 222 223 } // end namespace retaincountchecker 224 } // end namespace ento 225 } // end namespace clang 226 227 228 /// Find the first node with the parent stack frame. 229 static const ExplodedNode *getCalleeNode(const ExplodedNode *Pred) { 230 const StackFrameContext *SC = Pred->getStackFrame(); 231 if (SC->inTopFrame()) 232 return nullptr; 233 const StackFrameContext *PC = SC->getParent()->getStackFrame(); 234 if (!PC) 235 return nullptr; 236 237 const ExplodedNode *N = Pred; 238 while (N && N->getStackFrame() != PC) { 239 N = N->getFirstPred(); 240 } 241 return N; 242 } 243 244 245 /// Insert a diagnostic piece at function exit 246 /// if a function parameter is annotated as "os_consumed", 247 /// but it does not actually consume the reference. 248 static std::shared_ptr<PathDiagnosticEventPiece> 249 annotateConsumedSummaryMismatch(const ExplodedNode *N, 250 CallExitBegin &CallExitLoc, 251 const SourceManager &SM, 252 CallEventManager &CEMgr) { 253 254 const ExplodedNode *CN = getCalleeNode(N); 255 if (!CN) 256 return nullptr; 257 258 CallEventRef<> Call = CEMgr.getCaller(N->getStackFrame(), N->getState()); 259 260 std::string sbuf; 261 llvm::raw_string_ostream os(sbuf); 262 ArrayRef<const ParmVarDecl *> Parameters = Call->parameters(); 263 for (unsigned I=0; I < Call->getNumArgs() && I < Parameters.size(); ++I) { 264 const ParmVarDecl *PVD = Parameters[I]; 265 266 if (!PVD->hasAttr<OSConsumedAttr>()) 267 continue; 268 269 if (SymbolRef SR = Call->getArgSVal(I).getAsLocSymbol()) { 270 const RefVal *CountBeforeCall = getRefBinding(CN->getState(), SR); 271 const RefVal *CountAtExit = getRefBinding(N->getState(), SR); 272 273 if (!CountBeforeCall || !CountAtExit) 274 continue; 275 276 unsigned CountBefore = CountBeforeCall->getCount(); 277 unsigned CountAfter = CountAtExit->getCount(); 278 279 bool AsExpected = CountBefore > 0 && CountAfter == CountBefore - 1; 280 if (!AsExpected) { 281 os << "Parameter '"; 282 PVD->getNameForDiagnostic(os, PVD->getASTContext().getPrintingPolicy(), 283 /*Qualified=*/false); 284 os << "' is marked as consuming, but the function did not consume " 285 << "the reference\n"; 286 } 287 } 288 } 289 290 if (os.str().empty()) 291 return nullptr; 292 293 // FIXME: remove the code duplication with NoStoreFuncVisitor. 294 PathDiagnosticLocation L; 295 if (const ReturnStmt *RS = CallExitLoc.getReturnStmt()) { 296 L = PathDiagnosticLocation::createBegin(RS, SM, N->getLocationContext()); 297 } else { 298 L = PathDiagnosticLocation( 299 Call->getRuntimeDefinition().getDecl()->getSourceRange().getEnd(), SM); 300 } 301 302 return std::make_shared<PathDiagnosticEventPiece>(L, os.str()); 303 } 304 305 std::shared_ptr<PathDiagnosticPiece> 306 CFRefReportVisitor::VisitNode(const ExplodedNode *N, 307 BugReporterContext &BRC, BugReport &BR) { 308 309 const SourceManager &SM = BRC.getSourceManager(); 310 CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager(); 311 if (auto CE = N->getLocationAs<CallExitBegin>()) 312 if (auto PD = annotateConsumedSummaryMismatch(N, *CE, SM, CEMgr)) 313 return PD; 314 315 // FIXME: We will eventually need to handle non-statement-based events 316 // (__attribute__((cleanup))). 317 if (!N->getLocation().getAs<StmtPoint>()) 318 return nullptr; 319 320 // Check if the type state has changed. 321 const ExplodedNode *PrevNode = N->getFirstPred(); 322 ProgramStateRef PrevSt = PrevNode->getState(); 323 ProgramStateRef CurrSt = N->getState(); 324 const LocationContext *LCtx = N->getLocationContext(); 325 326 const RefVal* CurrT = getRefBinding(CurrSt, Sym); 327 if (!CurrT) return nullptr; 328 329 const RefVal &CurrV = *CurrT; 330 const RefVal *PrevT = getRefBinding(PrevSt, Sym); 331 332 // Create a string buffer to constain all the useful things we want 333 // to tell the user. 334 std::string sbuf; 335 llvm::raw_string_ostream os(sbuf); 336 337 // This is the allocation site since the previous node had no bindings 338 // for this symbol. 339 if (!PrevT) { 340 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt(); 341 342 if (isa<ObjCIvarRefExpr>(S) && 343 isSynthesizedAccessor(LCtx->getStackFrame())) { 344 S = LCtx->getStackFrame()->getCallSite(); 345 } 346 347 if (isa<ObjCArrayLiteral>(S)) { 348 os << "NSArray literal is an object with a +0 retain count"; 349 } else if (isa<ObjCDictionaryLiteral>(S)) { 350 os << "NSDictionary literal is an object with a +0 retain count"; 351 } else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) { 352 if (isNumericLiteralExpression(BL->getSubExpr())) 353 os << "NSNumber literal is an object with a +0 retain count"; 354 else { 355 const ObjCInterfaceDecl *BoxClass = nullptr; 356 if (const ObjCMethodDecl *Method = BL->getBoxingMethod()) 357 BoxClass = Method->getClassInterface(); 358 359 // We should always be able to find the boxing class interface, 360 // but consider this future-proofing. 361 if (BoxClass) { 362 os << *BoxClass << " b"; 363 } else { 364 os << "B"; 365 } 366 367 os << "oxed expression produces an object with a +0 retain count"; 368 } 369 } else if (isa<ObjCIvarRefExpr>(S)) { 370 os << "Object loaded from instance variable"; 371 } else { 372 generateDiagnosticsForCallLike(CurrSt, LCtx, CurrV, Sym, S, os); 373 } 374 375 PathDiagnosticLocation Pos(S, SM, N->getLocationContext()); 376 return std::make_shared<PathDiagnosticEventPiece>(Pos, os.str()); 377 } 378 379 // Gather up the effects that were performed on the object at this 380 // program point 381 bool DeallocSent = false; 382 383 if (N->getLocation().getTag() && 384 N->getLocation().getTag()->getTagDescription().contains( 385 RetainCountChecker::DeallocTagDescription)) { 386 // We only have summaries attached to nodes after evaluating CallExpr and 387 // ObjCMessageExprs. 388 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt(); 389 390 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) { 391 // Iterate through the parameter expressions and see if the symbol 392 // was ever passed as an argument. 393 unsigned i = 0; 394 395 for (auto AI=CE->arg_begin(), AE=CE->arg_end(); AI!=AE; ++AI, ++i) { 396 397 // Retrieve the value of the argument. Is it the symbol 398 // we are interested in? 399 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym) 400 continue; 401 402 // We have an argument. Get the effect! 403 DeallocSent = true; 404 } 405 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) { 406 if (const Expr *receiver = ME->getInstanceReceiver()) { 407 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx) 408 .getAsLocSymbol() == Sym) { 409 // The symbol we are tracking is the receiver. 410 DeallocSent = true; 411 } 412 } 413 } 414 } 415 416 if (!shouldGenerateNote(os, PrevT, CurrV, DeallocSent)) 417 return nullptr; 418 419 if (os.str().empty()) 420 return nullptr; // We have nothing to say! 421 422 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt(); 423 PathDiagnosticLocation Pos(S, BRC.getSourceManager(), 424 N->getLocationContext()); 425 auto P = std::make_shared<PathDiagnosticEventPiece>(Pos, os.str()); 426 427 // Add the range by scanning the children of the statement for any bindings 428 // to Sym. 429 for (const Stmt *Child : S->children()) 430 if (const Expr *Exp = dyn_cast_or_null<Expr>(Child)) 431 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) { 432 P->addRange(Exp->getSourceRange()); 433 break; 434 } 435 436 return std::move(P); 437 } 438 439 static Optional<std::string> describeRegion(const MemRegion *MR) { 440 if (const auto *VR = dyn_cast_or_null<VarRegion>(MR)) 441 return std::string(VR->getDecl()->getName()); 442 // Once we support more storage locations for bindings, 443 // this would need to be improved. 444 return None; 445 } 446 447 namespace { 448 // Find the first node in the current function context that referred to the 449 // tracked symbol and the memory location that value was stored to. Note, the 450 // value is only reported if the allocation occurred in the same function as 451 // the leak. The function can also return a location context, which should be 452 // treated as interesting. 453 struct AllocationInfo { 454 const ExplodedNode* N; 455 const MemRegion *R; 456 const LocationContext *InterestingMethodContext; 457 AllocationInfo(const ExplodedNode *InN, 458 const MemRegion *InR, 459 const LocationContext *InInterestingMethodContext) : 460 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {} 461 }; 462 } // end anonymous namespace 463 464 static AllocationInfo GetAllocationSite(ProgramStateManager &StateMgr, 465 const ExplodedNode *N, SymbolRef Sym) { 466 const ExplodedNode *AllocationNode = N; 467 const ExplodedNode *AllocationNodeInCurrentOrParentContext = N; 468 const MemRegion *FirstBinding = nullptr; 469 const LocationContext *LeakContext = N->getLocationContext(); 470 471 // The location context of the init method called on the leaked object, if 472 // available. 473 const LocationContext *InitMethodContext = nullptr; 474 475 while (N) { 476 ProgramStateRef St = N->getState(); 477 const LocationContext *NContext = N->getLocationContext(); 478 479 if (!getRefBinding(St, Sym)) 480 break; 481 482 StoreManager::FindUniqueBinding FB(Sym); 483 StateMgr.iterBindings(St, FB); 484 485 if (FB) { 486 const MemRegion *R = FB.getRegion(); 487 // Do not show local variables belonging to a function other than 488 // where the error is reported. 489 if (auto MR = dyn_cast<StackSpaceRegion>(R->getMemorySpace())) 490 if (MR->getStackFrame() == LeakContext->getStackFrame()) 491 FirstBinding = R; 492 } 493 494 // AllocationNode is the last node in which the symbol was tracked. 495 AllocationNode = N; 496 497 // AllocationNodeInCurrentContext, is the last node in the current or 498 // parent context in which the symbol was tracked. 499 // 500 // Note that the allocation site might be in the parent context. For example, 501 // the case where an allocation happens in a block that captures a reference 502 // to it and that reference is overwritten/dropped by another call to 503 // the block. 504 if (NContext == LeakContext || NContext->isParentOf(LeakContext)) 505 AllocationNodeInCurrentOrParentContext = N; 506 507 // Find the last init that was called on the given symbol and store the 508 // init method's location context. 509 if (!InitMethodContext) 510 if (auto CEP = N->getLocation().getAs<CallEnter>()) { 511 const Stmt *CE = CEP->getCallExpr(); 512 if (const auto *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) { 513 const Stmt *RecExpr = ME->getInstanceReceiver(); 514 if (RecExpr) { 515 SVal RecV = St->getSVal(RecExpr, NContext); 516 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym) 517 InitMethodContext = CEP->getCalleeContext(); 518 } 519 } 520 } 521 522 N = N->getFirstPred(); 523 } 524 525 // If we are reporting a leak of the object that was allocated with alloc, 526 // mark its init method as interesting. 527 const LocationContext *InterestingMethodContext = nullptr; 528 if (InitMethodContext) { 529 const ProgramPoint AllocPP = AllocationNode->getLocation(); 530 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>()) 531 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>()) 532 if (ME->getMethodFamily() == OMF_alloc) 533 InterestingMethodContext = InitMethodContext; 534 } 535 536 // If allocation happened in a function different from the leak node context, 537 // do not report the binding. 538 assert(N && "Could not find allocation node"); 539 540 if (AllocationNodeInCurrentOrParentContext && 541 AllocationNodeInCurrentOrParentContext->getLocationContext() != 542 LeakContext) 543 FirstBinding = nullptr; 544 545 return AllocationInfo(AllocationNodeInCurrentOrParentContext, 546 FirstBinding, 547 InterestingMethodContext); 548 } 549 550 std::shared_ptr<PathDiagnosticPiece> 551 CFRefReportVisitor::getEndPath(BugReporterContext &BRC, 552 const ExplodedNode *EndN, BugReport &BR) { 553 BR.markInteresting(Sym); 554 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR); 555 } 556 557 std::shared_ptr<PathDiagnosticPiece> 558 CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC, 559 const ExplodedNode *EndN, BugReport &BR) { 560 561 // Tell the BugReporterContext to report cases when the tracked symbol is 562 // assigned to different variables, etc. 563 BR.markInteresting(Sym); 564 565 // We are reporting a leak. Walk up the graph to get to the first node where 566 // the symbol appeared, and also get the first VarDecl that tracked object 567 // is stored to. 568 AllocationInfo AllocI = GetAllocationSite(BRC.getStateManager(), EndN, Sym); 569 570 const MemRegion* FirstBinding = AllocI.R; 571 BR.markInteresting(AllocI.InterestingMethodContext); 572 573 SourceManager& SM = BRC.getSourceManager(); 574 575 // Compute an actual location for the leak. Sometimes a leak doesn't 576 // occur at an actual statement (e.g., transition between blocks; end 577 // of function) so we need to walk the graph and compute a real location. 578 const ExplodedNode *LeakN = EndN; 579 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM); 580 581 std::string sbuf; 582 llvm::raw_string_ostream os(sbuf); 583 584 os << "Object leaked: "; 585 586 Optional<std::string> RegionDescription = describeRegion(FirstBinding); 587 if (RegionDescription) { 588 os << "object allocated and stored into '" << *RegionDescription << '\''; 589 } else { 590 os << "allocated object of type " << getPrettyTypeName(Sym->getType()); 591 } 592 593 // Get the retain count. 594 const RefVal* RV = getRefBinding(EndN->getState(), Sym); 595 assert(RV); 596 597 if (RV->getKind() == RefVal::ErrorLeakReturned) { 598 // FIXME: Per comments in rdar://6320065, "create" only applies to CF 599 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership 600 // to the caller for NS objects. 601 const Decl *D = &EndN->getCodeDecl(); 602 603 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method " 604 : " is returned from a function "); 605 606 if (D->hasAttr<CFReturnsNotRetainedAttr>()) { 607 os << "that is annotated as CF_RETURNS_NOT_RETAINED"; 608 } else if (D->hasAttr<NSReturnsNotRetainedAttr>()) { 609 os << "that is annotated as NS_RETURNS_NOT_RETAINED"; 610 } else if (D->hasAttr<OSReturnsNotRetainedAttr>()) { 611 os << "that is annotated as OS_RETURNS_NOT_RETAINED"; 612 } else { 613 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 614 if (BRC.getASTContext().getLangOpts().ObjCAutoRefCount) { 615 os << "managed by Automatic Reference Counting"; 616 } else { 617 os << "whose name ('" << MD->getSelector().getAsString() 618 << "') does not start with " 619 "'copy', 'mutableCopy', 'alloc' or 'new'." 620 " This violates the naming convention rules" 621 " given in the Memory Management Guide for Cocoa"; 622 } 623 } else { 624 const FunctionDecl *FD = cast<FunctionDecl>(D); 625 os << "whose name ('" << *FD 626 << "') does not contain 'Copy' or 'Create'. This violates the naming" 627 " convention rules given in the Memory Management Guide for Core" 628 " Foundation"; 629 } 630 } 631 } else { 632 os << " is not referenced later in this execution path and has a retain " 633 "count of +" << RV->getCount(); 634 } 635 636 return std::make_shared<PathDiagnosticEventPiece>(L, os.str()); 637 } 638 639 CFRefReport::CFRefReport(CFRefBug &D, const LangOptions &LOpts, ExplodedNode *n, 640 SymbolRef sym, bool registerVisitor) 641 : BugReport(D, D.getDescription(), n), Sym(sym) { 642 if (registerVisitor) 643 addVisitor(llvm::make_unique<CFRefReportVisitor>(sym)); 644 } 645 646 CFRefReport::CFRefReport(CFRefBug &D, const LangOptions &LOpts, ExplodedNode *n, 647 SymbolRef sym, StringRef endText) 648 : BugReport(D, D.getDescription(), endText, n) { 649 650 addVisitor(llvm::make_unique<CFRefReportVisitor>(sym)); 651 } 652 653 void CFRefLeakReport::deriveParamLocation(CheckerContext &Ctx, SymbolRef sym) { 654 const SourceManager& SMgr = Ctx.getSourceManager(); 655 656 if (!sym->getOriginRegion()) 657 return; 658 659 auto *Region = dyn_cast<DeclRegion>(sym->getOriginRegion()); 660 if (Region) { 661 const Decl *PDecl = Region->getDecl(); 662 if (PDecl && isa<ParmVarDecl>(PDecl)) { 663 PathDiagnosticLocation ParamLocation = 664 PathDiagnosticLocation::create(PDecl, SMgr); 665 Location = ParamLocation; 666 UniqueingLocation = ParamLocation; 667 UniqueingDecl = Ctx.getLocationContext()->getDecl(); 668 } 669 } 670 } 671 672 void CFRefLeakReport::deriveAllocLocation(CheckerContext &Ctx, 673 SymbolRef sym) { 674 // Most bug reports are cached at the location where they occurred. 675 // With leaks, we want to unique them by the location where they were 676 // allocated, and only report a single path. To do this, we need to find 677 // the allocation site of a piece of tracked memory, which we do via a 678 // call to GetAllocationSite. This will walk the ExplodedGraph backwards. 679 // Note that this is *not* the trimmed graph; we are guaranteed, however, 680 // that all ancestor nodes that represent the allocation site have the 681 // same SourceLocation. 682 const ExplodedNode *AllocNode = nullptr; 683 684 const SourceManager& SMgr = Ctx.getSourceManager(); 685 686 AllocationInfo AllocI = 687 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym); 688 689 AllocNode = AllocI.N; 690 AllocBinding = AllocI.R; 691 markInteresting(AllocI.InterestingMethodContext); 692 693 // Get the SourceLocation for the allocation site. 694 // FIXME: This will crash the analyzer if an allocation comes from an 695 // implicit call (ex: a destructor call). 696 // (Currently there are no such allocations in Cocoa, though.) 697 AllocStmt = PathDiagnosticLocation::getStmt(AllocNode); 698 699 if (!AllocStmt) { 700 AllocBinding = nullptr; 701 return; 702 } 703 704 PathDiagnosticLocation AllocLocation = 705 PathDiagnosticLocation::createBegin(AllocStmt, SMgr, 706 AllocNode->getLocationContext()); 707 Location = AllocLocation; 708 709 // Set uniqieing info, which will be used for unique the bug reports. The 710 // leaks should be uniqued on the allocation site. 711 UniqueingLocation = AllocLocation; 712 UniqueingDecl = AllocNode->getLocationContext()->getDecl(); 713 } 714 715 void CFRefLeakReport::createDescription(CheckerContext &Ctx) { 716 assert(Location.isValid() && UniqueingDecl && UniqueingLocation.isValid()); 717 Description.clear(); 718 llvm::raw_string_ostream os(Description); 719 os << "Potential leak of an object"; 720 721 Optional<std::string> RegionDescription = describeRegion(AllocBinding); 722 if (RegionDescription) { 723 os << " stored into '" << *RegionDescription << '\''; 724 } else { 725 726 // If we can't figure out the name, just supply the type information. 727 os << " of type " << getPrettyTypeName(Sym->getType()); 728 } 729 } 730 731 CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, 732 ExplodedNode *n, SymbolRef sym, 733 CheckerContext &Ctx) 734 : CFRefReport(D, LOpts, n, sym, false) { 735 736 deriveAllocLocation(Ctx, sym); 737 if (!AllocBinding) 738 deriveParamLocation(Ctx, sym); 739 740 createDescription(Ctx); 741 742 addVisitor(llvm::make_unique<CFRefLeakReportVisitor>(sym)); 743 } 744