1 // BugReporter.cpp - Generate PathDiagnostics for Bugs ------------*- 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 BugReporter, a utility class for generating 11 // PathDiagnostics. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 16 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 17 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 18 #include "clang/AST/ASTContext.h" 19 #include "clang/Analysis/CFG.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/ParentMap.h" 23 #include "clang/AST/StmtObjC.h" 24 #include "clang/Basic/SourceManager.h" 25 #include "clang/Analysis/ProgramPoint.h" 26 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" 27 #include "llvm/Support/raw_ostream.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/SmallString.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/OwningPtr.h" 32 #include "llvm/ADT/IntrusiveRefCntPtr.h" 33 #include <queue> 34 35 using namespace clang; 36 using namespace ento; 37 38 BugReporterVisitor::~BugReporterVisitor() {} 39 40 void BugReporterContext::anchor() {} 41 42 //===----------------------------------------------------------------------===// 43 // Helper routines for walking the ExplodedGraph and fetching statements. 44 //===----------------------------------------------------------------------===// 45 46 static inline const Stmt *GetStmt(const ProgramPoint &P) { 47 if (const StmtPoint* SP = dyn_cast<StmtPoint>(&P)) 48 return SP->getStmt(); 49 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) 50 return BE->getSrc()->getTerminator(); 51 else if (const CallEnter *CE = dyn_cast<CallEnter>(&P)) 52 return CE->getCallExpr(); 53 else if (const CallExitEnd *CEE = dyn_cast<CallExitEnd>(&P)) 54 return CEE->getCalleeContext()->getCallSite(); 55 56 return 0; 57 } 58 59 static inline const ExplodedNode* 60 GetPredecessorNode(const ExplodedNode *N) { 61 return N->pred_empty() ? NULL : *(N->pred_begin()); 62 } 63 64 static inline const ExplodedNode* 65 GetSuccessorNode(const ExplodedNode *N) { 66 return N->succ_empty() ? NULL : *(N->succ_begin()); 67 } 68 69 static const Stmt *GetPreviousStmt(const ExplodedNode *N) { 70 for (N = GetPredecessorNode(N); N; N = GetPredecessorNode(N)) 71 if (const Stmt *S = GetStmt(N->getLocation())) 72 return S; 73 74 return 0; 75 } 76 77 static const Stmt *GetNextStmt(const ExplodedNode *N) { 78 for (N = GetSuccessorNode(N); N; N = GetSuccessorNode(N)) 79 if (const Stmt *S = GetStmt(N->getLocation())) { 80 // Check if the statement is '?' or '&&'/'||'. These are "merges", 81 // not actual statement points. 82 switch (S->getStmtClass()) { 83 case Stmt::ChooseExprClass: 84 case Stmt::BinaryConditionalOperatorClass: continue; 85 case Stmt::ConditionalOperatorClass: continue; 86 case Stmt::BinaryOperatorClass: { 87 BinaryOperatorKind Op = cast<BinaryOperator>(S)->getOpcode(); 88 if (Op == BO_LAnd || Op == BO_LOr) 89 continue; 90 break; 91 } 92 default: 93 break; 94 } 95 return S; 96 } 97 98 return 0; 99 } 100 101 static inline const Stmt* 102 GetCurrentOrPreviousStmt(const ExplodedNode *N) { 103 if (const Stmt *S = GetStmt(N->getLocation())) 104 return S; 105 106 return GetPreviousStmt(N); 107 } 108 109 static inline const Stmt* 110 GetCurrentOrNextStmt(const ExplodedNode *N) { 111 if (const Stmt *S = GetStmt(N->getLocation())) 112 return S; 113 114 return GetNextStmt(N); 115 } 116 117 //===----------------------------------------------------------------------===// 118 // Diagnostic cleanup. 119 //===----------------------------------------------------------------------===// 120 121 /// Recursively scan through a path and prune out calls and macros pieces 122 /// that aren't needed. Return true if afterwards the path contains 123 /// "interesting stuff" which means it should be pruned from the parent path. 124 static bool RemoveUneededCalls(PathPieces &pieces) { 125 bool containsSomethingInteresting = false; 126 const unsigned N = pieces.size(); 127 128 for (unsigned i = 0 ; i < N ; ++i) { 129 // Remove the front piece from the path. If it is still something we 130 // want to keep once we are done, we will push it back on the end. 131 IntrusiveRefCntPtr<PathDiagnosticPiece> piece(pieces.front()); 132 pieces.pop_front(); 133 134 switch (piece->getKind()) { 135 case PathDiagnosticPiece::Call: { 136 PathDiagnosticCallPiece *call = cast<PathDiagnosticCallPiece>(piece); 137 // Recursively clean out the subclass. Keep this call around if 138 // it contains any informative diagnostics. 139 if (!RemoveUneededCalls(call->path)) 140 continue; 141 containsSomethingInteresting = true; 142 break; 143 } 144 case PathDiagnosticPiece::Macro: { 145 PathDiagnosticMacroPiece *macro = cast<PathDiagnosticMacroPiece>(piece); 146 if (!RemoveUneededCalls(macro->subPieces)) 147 continue; 148 containsSomethingInteresting = true; 149 break; 150 } 151 case PathDiagnosticPiece::Event: { 152 PathDiagnosticEventPiece *event = cast<PathDiagnosticEventPiece>(piece); 153 // We never throw away an event, but we do throw it away wholesale 154 // as part of a path if we throw the entire path away. 155 if (event->isPrunable()) 156 continue; 157 containsSomethingInteresting = true; 158 break; 159 } 160 case PathDiagnosticPiece::ControlFlow: 161 break; 162 } 163 164 pieces.push_back(piece); 165 } 166 167 return containsSomethingInteresting; 168 } 169 170 //===----------------------------------------------------------------------===// 171 // PathDiagnosticBuilder and its associated routines and helper objects. 172 //===----------------------------------------------------------------------===// 173 174 typedef llvm::DenseMap<const ExplodedNode*, 175 const ExplodedNode*> NodeBackMap; 176 177 namespace { 178 class NodeMapClosure : public BugReport::NodeResolver { 179 NodeBackMap& M; 180 public: 181 NodeMapClosure(NodeBackMap *m) : M(*m) {} 182 ~NodeMapClosure() {} 183 184 const ExplodedNode *getOriginalNode(const ExplodedNode *N) { 185 NodeBackMap::iterator I = M.find(N); 186 return I == M.end() ? 0 : I->second; 187 } 188 }; 189 190 class PathDiagnosticBuilder : public BugReporterContext { 191 BugReport *R; 192 PathDiagnosticConsumer *PDC; 193 OwningPtr<ParentMap> PM; 194 NodeMapClosure NMC; 195 public: 196 const LocationContext *LC; 197 198 PathDiagnosticBuilder(GRBugReporter &br, 199 BugReport *r, NodeBackMap *Backmap, 200 PathDiagnosticConsumer *pdc) 201 : BugReporterContext(br), 202 R(r), PDC(pdc), NMC(Backmap), LC(r->getErrorNode()->getLocationContext()) 203 {} 204 205 PathDiagnosticLocation ExecutionContinues(const ExplodedNode *N); 206 207 PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream &os, 208 const ExplodedNode *N); 209 210 BugReport *getBugReport() { return R; } 211 212 Decl const &getCodeDecl() { return R->getErrorNode()->getCodeDecl(); } 213 214 ParentMap& getParentMap() { return LC->getParentMap(); } 215 216 const Stmt *getParent(const Stmt *S) { 217 return getParentMap().getParent(S); 218 } 219 220 virtual NodeMapClosure& getNodeResolver() { return NMC; } 221 222 PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S); 223 224 PathDiagnosticConsumer::PathGenerationScheme getGenerationScheme() const { 225 return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Extensive; 226 } 227 228 bool supportsLogicalOpControlFlow() const { 229 return PDC ? PDC->supportsLogicalOpControlFlow() : true; 230 } 231 }; 232 } // end anonymous namespace 233 234 PathDiagnosticLocation 235 PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode *N) { 236 if (const Stmt *S = GetNextStmt(N)) 237 return PathDiagnosticLocation(S, getSourceManager(), LC); 238 239 return PathDiagnosticLocation::createDeclEnd(N->getLocationContext(), 240 getSourceManager()); 241 } 242 243 PathDiagnosticLocation 244 PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream &os, 245 const ExplodedNode *N) { 246 247 // Slow, but probably doesn't matter. 248 if (os.str().empty()) 249 os << ' '; 250 251 const PathDiagnosticLocation &Loc = ExecutionContinues(N); 252 253 if (Loc.asStmt()) 254 os << "Execution continues on line " 255 << getSourceManager().getExpansionLineNumber(Loc.asLocation()) 256 << '.'; 257 else { 258 os << "Execution jumps to the end of the "; 259 const Decl *D = N->getLocationContext()->getDecl(); 260 if (isa<ObjCMethodDecl>(D)) 261 os << "method"; 262 else if (isa<FunctionDecl>(D)) 263 os << "function"; 264 else { 265 assert(isa<BlockDecl>(D)); 266 os << "anonymous block"; 267 } 268 os << '.'; 269 } 270 271 return Loc; 272 } 273 274 static bool IsNested(const Stmt *S, ParentMap &PM) { 275 if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S))) 276 return true; 277 278 const Stmt *Parent = PM.getParentIgnoreParens(S); 279 280 if (Parent) 281 switch (Parent->getStmtClass()) { 282 case Stmt::ForStmtClass: 283 case Stmt::DoStmtClass: 284 case Stmt::WhileStmtClass: 285 return true; 286 default: 287 break; 288 } 289 290 return false; 291 } 292 293 PathDiagnosticLocation 294 PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) { 295 assert(S && "Null Stmt *passed to getEnclosingStmtLocation"); 296 ParentMap &P = getParentMap(); 297 SourceManager &SMgr = getSourceManager(); 298 299 while (IsNested(S, P)) { 300 const Stmt *Parent = P.getParentIgnoreParens(S); 301 302 if (!Parent) 303 break; 304 305 switch (Parent->getStmtClass()) { 306 case Stmt::BinaryOperatorClass: { 307 const BinaryOperator *B = cast<BinaryOperator>(Parent); 308 if (B->isLogicalOp()) 309 return PathDiagnosticLocation(S, SMgr, LC); 310 break; 311 } 312 case Stmt::CompoundStmtClass: 313 case Stmt::StmtExprClass: 314 return PathDiagnosticLocation(S, SMgr, LC); 315 case Stmt::ChooseExprClass: 316 // Similar to '?' if we are referring to condition, just have the edge 317 // point to the entire choose expression. 318 if (cast<ChooseExpr>(Parent)->getCond() == S) 319 return PathDiagnosticLocation(Parent, SMgr, LC); 320 else 321 return PathDiagnosticLocation(S, SMgr, LC); 322 case Stmt::BinaryConditionalOperatorClass: 323 case Stmt::ConditionalOperatorClass: 324 // For '?', if we are referring to condition, just have the edge point 325 // to the entire '?' expression. 326 if (cast<AbstractConditionalOperator>(Parent)->getCond() == S) 327 return PathDiagnosticLocation(Parent, SMgr, LC); 328 else 329 return PathDiagnosticLocation(S, SMgr, LC); 330 case Stmt::DoStmtClass: 331 return PathDiagnosticLocation(S, SMgr, LC); 332 case Stmt::ForStmtClass: 333 if (cast<ForStmt>(Parent)->getBody() == S) 334 return PathDiagnosticLocation(S, SMgr, LC); 335 break; 336 case Stmt::IfStmtClass: 337 if (cast<IfStmt>(Parent)->getCond() != S) 338 return PathDiagnosticLocation(S, SMgr, LC); 339 break; 340 case Stmt::ObjCForCollectionStmtClass: 341 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S) 342 return PathDiagnosticLocation(S, SMgr, LC); 343 break; 344 case Stmt::WhileStmtClass: 345 if (cast<WhileStmt>(Parent)->getCond() != S) 346 return PathDiagnosticLocation(S, SMgr, LC); 347 break; 348 default: 349 break; 350 } 351 352 S = Parent; 353 } 354 355 assert(S && "Cannot have null Stmt for PathDiagnosticLocation"); 356 357 // Special case: DeclStmts can appear in for statement declarations, in which 358 // case the ForStmt is the context. 359 if (isa<DeclStmt>(S)) { 360 if (const Stmt *Parent = P.getParent(S)) { 361 switch (Parent->getStmtClass()) { 362 case Stmt::ForStmtClass: 363 case Stmt::ObjCForCollectionStmtClass: 364 return PathDiagnosticLocation(Parent, SMgr, LC); 365 default: 366 break; 367 } 368 } 369 } 370 else if (isa<BinaryOperator>(S)) { 371 // Special case: the binary operator represents the initialization 372 // code in a for statement (this can happen when the variable being 373 // initialized is an old variable. 374 if (const ForStmt *FS = 375 dyn_cast_or_null<ForStmt>(P.getParentIgnoreParens(S))) { 376 if (FS->getInit() == S) 377 return PathDiagnosticLocation(FS, SMgr, LC); 378 } 379 } 380 381 return PathDiagnosticLocation(S, SMgr, LC); 382 } 383 384 //===----------------------------------------------------------------------===// 385 // "Minimal" path diagnostic generation algorithm. 386 //===----------------------------------------------------------------------===// 387 typedef std::pair<PathDiagnosticCallPiece*, const ExplodedNode*> StackDiagPair; 388 typedef SmallVector<StackDiagPair, 6> StackDiagVector; 389 390 static void updateStackPiecesWithMessage(PathDiagnosticPiece *P, 391 StackDiagVector &CallStack) { 392 // If the piece contains a special message, add it to all the call 393 // pieces on the active stack. 394 if (PathDiagnosticEventPiece *ep = 395 dyn_cast<PathDiagnosticEventPiece>(P)) { 396 397 if (ep->hasCallStackHint()) 398 for (StackDiagVector::iterator I = CallStack.begin(), 399 E = CallStack.end(); I != E; ++I) { 400 PathDiagnosticCallPiece *CP = I->first; 401 const ExplodedNode *N = I->second; 402 std::string stackMsg = ep->getCallStackMessage(N); 403 404 // The last message on the path to final bug is the most important 405 // one. Since we traverse the path backwards, do not add the message 406 // if one has been previously added. 407 if (!CP->hasCallStackMessage()) 408 CP->setCallStackMessage(stackMsg); 409 } 410 } 411 } 412 413 static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM); 414 415 static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD, 416 PathDiagnosticBuilder &PDB, 417 const ExplodedNode *N, 418 ArrayRef<BugReporterVisitor *> visitors) { 419 420 SourceManager& SMgr = PDB.getSourceManager(); 421 const LocationContext *LC = PDB.LC; 422 const ExplodedNode *NextNode = N->pred_empty() 423 ? NULL : *(N->pred_begin()); 424 425 StackDiagVector CallStack; 426 427 while (NextNode) { 428 N = NextNode; 429 PDB.LC = N->getLocationContext(); 430 NextNode = GetPredecessorNode(N); 431 432 ProgramPoint P = N->getLocation(); 433 434 if (const CallExitEnd *CE = dyn_cast<CallExitEnd>(&P)) { 435 PathDiagnosticCallPiece *C = 436 PathDiagnosticCallPiece::construct(N, *CE, SMgr); 437 PD.getActivePath().push_front(C); 438 PD.pushActivePath(&C->path); 439 CallStack.push_back(StackDiagPair(C, N)); 440 continue; 441 } 442 443 if (const CallEnter *CE = dyn_cast<CallEnter>(&P)) { 444 PD.popActivePath(); 445 // The current active path should never be empty. Either we 446 // just added a bunch of stuff to the top-level path, or 447 // we have a previous CallExitEnd. If the front of the active 448 // path is not a PathDiagnosticCallPiece, it means that the 449 // path terminated within a function call. We must then take the 450 // current contents of the active path and place it within 451 // a new PathDiagnosticCallPiece. 452 assert(!PD.getActivePath().empty()); 453 PathDiagnosticCallPiece *C = 454 dyn_cast<PathDiagnosticCallPiece>(PD.getActivePath().front()); 455 if (!C) { 456 const Decl *Caller = CE->getLocationContext()->getDecl(); 457 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller); 458 } 459 C->setCallee(*CE, SMgr); 460 if (!CallStack.empty()) { 461 assert(CallStack.back().first == C); 462 CallStack.pop_back(); 463 } 464 continue; 465 } 466 467 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) { 468 const CFGBlock *Src = BE->getSrc(); 469 const CFGBlock *Dst = BE->getDst(); 470 const Stmt *T = Src->getTerminator(); 471 472 if (!T) 473 continue; 474 475 PathDiagnosticLocation Start = 476 PathDiagnosticLocation::createBegin(T, SMgr, 477 N->getLocationContext()); 478 479 switch (T->getStmtClass()) { 480 default: 481 break; 482 483 case Stmt::GotoStmtClass: 484 case Stmt::IndirectGotoStmtClass: { 485 const Stmt *S = GetNextStmt(N); 486 487 if (!S) 488 continue; 489 490 std::string sbuf; 491 llvm::raw_string_ostream os(sbuf); 492 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S); 493 494 os << "Control jumps to line " 495 << End.asLocation().getExpansionLineNumber(); 496 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End, 497 os.str())); 498 break; 499 } 500 501 case Stmt::SwitchStmtClass: { 502 // Figure out what case arm we took. 503 std::string sbuf; 504 llvm::raw_string_ostream os(sbuf); 505 506 if (const Stmt *S = Dst->getLabel()) { 507 PathDiagnosticLocation End(S, SMgr, LC); 508 509 switch (S->getStmtClass()) { 510 default: 511 os << "No cases match in the switch statement. " 512 "Control jumps to line " 513 << End.asLocation().getExpansionLineNumber(); 514 break; 515 case Stmt::DefaultStmtClass: 516 os << "Control jumps to the 'default' case at line " 517 << End.asLocation().getExpansionLineNumber(); 518 break; 519 520 case Stmt::CaseStmtClass: { 521 os << "Control jumps to 'case "; 522 const CaseStmt *Case = cast<CaseStmt>(S); 523 const Expr *LHS = Case->getLHS()->IgnoreParenCasts(); 524 525 // Determine if it is an enum. 526 bool GetRawInt = true; 527 528 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) { 529 // FIXME: Maybe this should be an assertion. Are there cases 530 // were it is not an EnumConstantDecl? 531 const EnumConstantDecl *D = 532 dyn_cast<EnumConstantDecl>(DR->getDecl()); 533 534 if (D) { 535 GetRawInt = false; 536 os << *D; 537 } 538 } 539 540 if (GetRawInt) 541 os << LHS->EvaluateKnownConstInt(PDB.getASTContext()); 542 543 os << ":' at line " 544 << End.asLocation().getExpansionLineNumber(); 545 break; 546 } 547 } 548 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End, 549 os.str())); 550 } 551 else { 552 os << "'Default' branch taken. "; 553 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N); 554 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End, 555 os.str())); 556 } 557 558 break; 559 } 560 561 case Stmt::BreakStmtClass: 562 case Stmt::ContinueStmtClass: { 563 std::string sbuf; 564 llvm::raw_string_ostream os(sbuf); 565 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N); 566 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End, 567 os.str())); 568 break; 569 } 570 571 // Determine control-flow for ternary '?'. 572 case Stmt::BinaryConditionalOperatorClass: 573 case Stmt::ConditionalOperatorClass: { 574 std::string sbuf; 575 llvm::raw_string_ostream os(sbuf); 576 os << "'?' condition is "; 577 578 if (*(Src->succ_begin()+1) == Dst) 579 os << "false"; 580 else 581 os << "true"; 582 583 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 584 585 if (const Stmt *S = End.asStmt()) 586 End = PDB.getEnclosingStmtLocation(S); 587 588 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End, 589 os.str())); 590 break; 591 } 592 593 // Determine control-flow for short-circuited '&&' and '||'. 594 case Stmt::BinaryOperatorClass: { 595 if (!PDB.supportsLogicalOpControlFlow()) 596 break; 597 598 const BinaryOperator *B = cast<BinaryOperator>(T); 599 std::string sbuf; 600 llvm::raw_string_ostream os(sbuf); 601 os << "Left side of '"; 602 603 if (B->getOpcode() == BO_LAnd) { 604 os << "&&" << "' is "; 605 606 if (*(Src->succ_begin()+1) == Dst) { 607 os << "false"; 608 PathDiagnosticLocation End(B->getLHS(), SMgr, LC); 609 PathDiagnosticLocation Start = 610 PathDiagnosticLocation::createOperatorLoc(B, SMgr); 611 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End, 612 os.str())); 613 } 614 else { 615 os << "true"; 616 PathDiagnosticLocation Start(B->getLHS(), SMgr, LC); 617 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 618 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End, 619 os.str())); 620 } 621 } 622 else { 623 assert(B->getOpcode() == BO_LOr); 624 os << "||" << "' is "; 625 626 if (*(Src->succ_begin()+1) == Dst) { 627 os << "false"; 628 PathDiagnosticLocation Start(B->getLHS(), SMgr, LC); 629 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 630 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End, 631 os.str())); 632 } 633 else { 634 os << "true"; 635 PathDiagnosticLocation End(B->getLHS(), SMgr, LC); 636 PathDiagnosticLocation Start = 637 PathDiagnosticLocation::createOperatorLoc(B, SMgr); 638 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End, 639 os.str())); 640 } 641 } 642 643 break; 644 } 645 646 case Stmt::DoStmtClass: { 647 if (*(Src->succ_begin()) == Dst) { 648 std::string sbuf; 649 llvm::raw_string_ostream os(sbuf); 650 651 os << "Loop condition is true. "; 652 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N); 653 654 if (const Stmt *S = End.asStmt()) 655 End = PDB.getEnclosingStmtLocation(S); 656 657 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End, 658 os.str())); 659 } 660 else { 661 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 662 663 if (const Stmt *S = End.asStmt()) 664 End = PDB.getEnclosingStmtLocation(S); 665 666 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End, 667 "Loop condition is false. Exiting loop")); 668 } 669 670 break; 671 } 672 673 case Stmt::WhileStmtClass: 674 case Stmt::ForStmtClass: { 675 if (*(Src->succ_begin()+1) == Dst) { 676 std::string sbuf; 677 llvm::raw_string_ostream os(sbuf); 678 679 os << "Loop condition is false. "; 680 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N); 681 if (const Stmt *S = End.asStmt()) 682 End = PDB.getEnclosingStmtLocation(S); 683 684 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End, 685 os.str())); 686 } 687 else { 688 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 689 if (const Stmt *S = End.asStmt()) 690 End = PDB.getEnclosingStmtLocation(S); 691 692 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End, 693 "Loop condition is true. Entering loop body")); 694 } 695 696 break; 697 } 698 699 case Stmt::IfStmtClass: { 700 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 701 702 if (const Stmt *S = End.asStmt()) 703 End = PDB.getEnclosingStmtLocation(S); 704 705 if (*(Src->succ_begin()+1) == Dst) 706 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End, 707 "Taking false branch")); 708 else 709 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End, 710 "Taking true branch")); 711 712 break; 713 } 714 } 715 } 716 717 if (NextNode) { 718 // Add diagnostic pieces from custom visitors. 719 BugReport *R = PDB.getBugReport(); 720 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(), 721 E = visitors.end(); 722 I != E; ++I) { 723 if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) { 724 PD.getActivePath().push_front(p); 725 updateStackPiecesWithMessage(p, CallStack); 726 } 727 } 728 } 729 } 730 731 // After constructing the full PathDiagnostic, do a pass over it to compact 732 // PathDiagnosticPieces that occur within a macro. 733 CompactPathDiagnostic(PD.getMutablePieces(), PDB.getSourceManager()); 734 } 735 736 //===----------------------------------------------------------------------===// 737 // "Extensive" PathDiagnostic generation. 738 //===----------------------------------------------------------------------===// 739 740 static bool IsControlFlowExpr(const Stmt *S) { 741 const Expr *E = dyn_cast<Expr>(S); 742 743 if (!E) 744 return false; 745 746 E = E->IgnoreParenCasts(); 747 748 if (isa<AbstractConditionalOperator>(E)) 749 return true; 750 751 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) 752 if (B->isLogicalOp()) 753 return true; 754 755 return false; 756 } 757 758 namespace { 759 class ContextLocation : public PathDiagnosticLocation { 760 bool IsDead; 761 public: 762 ContextLocation(const PathDiagnosticLocation &L, bool isdead = false) 763 : PathDiagnosticLocation(L), IsDead(isdead) {} 764 765 void markDead() { IsDead = true; } 766 bool isDead() const { return IsDead; } 767 }; 768 769 class EdgeBuilder { 770 std::vector<ContextLocation> CLocs; 771 typedef std::vector<ContextLocation>::iterator iterator; 772 PathDiagnostic &PD; 773 PathDiagnosticBuilder &PDB; 774 PathDiagnosticLocation PrevLoc; 775 776 bool IsConsumedExpr(const PathDiagnosticLocation &L); 777 778 bool containsLocation(const PathDiagnosticLocation &Container, 779 const PathDiagnosticLocation &Containee); 780 781 PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L); 782 783 PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L, 784 bool firstCharOnly = false) { 785 if (const Stmt *S = L.asStmt()) { 786 const Stmt *Original = S; 787 while (1) { 788 // Adjust the location for some expressions that are best referenced 789 // by one of their subexpressions. 790 switch (S->getStmtClass()) { 791 default: 792 break; 793 case Stmt::ParenExprClass: 794 case Stmt::GenericSelectionExprClass: 795 S = cast<Expr>(S)->IgnoreParens(); 796 firstCharOnly = true; 797 continue; 798 case Stmt::BinaryConditionalOperatorClass: 799 case Stmt::ConditionalOperatorClass: 800 S = cast<AbstractConditionalOperator>(S)->getCond(); 801 firstCharOnly = true; 802 continue; 803 case Stmt::ChooseExprClass: 804 S = cast<ChooseExpr>(S)->getCond(); 805 firstCharOnly = true; 806 continue; 807 case Stmt::BinaryOperatorClass: 808 S = cast<BinaryOperator>(S)->getLHS(); 809 firstCharOnly = true; 810 continue; 811 } 812 813 break; 814 } 815 816 if (S != Original) 817 L = PathDiagnosticLocation(S, L.getManager(), PDB.LC); 818 } 819 820 if (firstCharOnly) 821 L = PathDiagnosticLocation::createSingleLocation(L); 822 823 return L; 824 } 825 826 void popLocation() { 827 if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) { 828 // For contexts, we only one the first character as the range. 829 rawAddEdge(cleanUpLocation(CLocs.back(), true)); 830 } 831 CLocs.pop_back(); 832 } 833 834 public: 835 EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb) 836 : PD(pd), PDB(pdb) { 837 838 // If the PathDiagnostic already has pieces, add the enclosing statement 839 // of the first piece as a context as well. 840 if (!PD.path.empty()) { 841 PrevLoc = (*PD.path.begin())->getLocation(); 842 843 if (const Stmt *S = PrevLoc.asStmt()) 844 addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt()); 845 } 846 } 847 848 ~EdgeBuilder() { 849 while (!CLocs.empty()) popLocation(); 850 851 // Finally, add an initial edge from the start location of the first 852 // statement (if it doesn't already exist). 853 PathDiagnosticLocation L = PathDiagnosticLocation::createDeclBegin( 854 PDB.LC, 855 PDB.getSourceManager()); 856 if (L.isValid()) 857 rawAddEdge(L); 858 } 859 860 void flushLocations() { 861 while (!CLocs.empty()) 862 popLocation(); 863 PrevLoc = PathDiagnosticLocation(); 864 } 865 866 void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false); 867 868 void rawAddEdge(PathDiagnosticLocation NewLoc); 869 870 void addContext(const Stmt *S); 871 void addExtendedContext(const Stmt *S); 872 }; 873 } // end anonymous namespace 874 875 876 PathDiagnosticLocation 877 EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) { 878 if (const Stmt *S = L.asStmt()) { 879 if (IsControlFlowExpr(S)) 880 return L; 881 882 return PDB.getEnclosingStmtLocation(S); 883 } 884 885 return L; 886 } 887 888 bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container, 889 const PathDiagnosticLocation &Containee) { 890 891 if (Container == Containee) 892 return true; 893 894 if (Container.asDecl()) 895 return true; 896 897 if (const Stmt *S = Containee.asStmt()) 898 if (const Stmt *ContainerS = Container.asStmt()) { 899 while (S) { 900 if (S == ContainerS) 901 return true; 902 S = PDB.getParent(S); 903 } 904 return false; 905 } 906 907 // Less accurate: compare using source ranges. 908 SourceRange ContainerR = Container.asRange(); 909 SourceRange ContaineeR = Containee.asRange(); 910 911 SourceManager &SM = PDB.getSourceManager(); 912 SourceLocation ContainerRBeg = SM.getExpansionLoc(ContainerR.getBegin()); 913 SourceLocation ContainerREnd = SM.getExpansionLoc(ContainerR.getEnd()); 914 SourceLocation ContaineeRBeg = SM.getExpansionLoc(ContaineeR.getBegin()); 915 SourceLocation ContaineeREnd = SM.getExpansionLoc(ContaineeR.getEnd()); 916 917 unsigned ContainerBegLine = SM.getExpansionLineNumber(ContainerRBeg); 918 unsigned ContainerEndLine = SM.getExpansionLineNumber(ContainerREnd); 919 unsigned ContaineeBegLine = SM.getExpansionLineNumber(ContaineeRBeg); 920 unsigned ContaineeEndLine = SM.getExpansionLineNumber(ContaineeREnd); 921 922 assert(ContainerBegLine <= ContainerEndLine); 923 assert(ContaineeBegLine <= ContaineeEndLine); 924 925 return (ContainerBegLine <= ContaineeBegLine && 926 ContainerEndLine >= ContaineeEndLine && 927 (ContainerBegLine != ContaineeBegLine || 928 SM.getExpansionColumnNumber(ContainerRBeg) <= 929 SM.getExpansionColumnNumber(ContaineeRBeg)) && 930 (ContainerEndLine != ContaineeEndLine || 931 SM.getExpansionColumnNumber(ContainerREnd) >= 932 SM.getExpansionColumnNumber(ContaineeREnd))); 933 } 934 935 void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) { 936 if (!PrevLoc.isValid()) { 937 PrevLoc = NewLoc; 938 return; 939 } 940 941 const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc); 942 const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc); 943 944 if (NewLocClean.asLocation() == PrevLocClean.asLocation()) 945 return; 946 947 // FIXME: Ignore intra-macro edges for now. 948 if (NewLocClean.asLocation().getExpansionLoc() == 949 PrevLocClean.asLocation().getExpansionLoc()) 950 return; 951 952 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean)); 953 PrevLoc = NewLoc; 954 } 955 956 void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) { 957 958 if (!alwaysAdd && NewLoc.asLocation().isMacroID()) 959 return; 960 961 const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc); 962 963 while (!CLocs.empty()) { 964 ContextLocation &TopContextLoc = CLocs.back(); 965 966 // Is the top location context the same as the one for the new location? 967 if (TopContextLoc == CLoc) { 968 if (alwaysAdd) { 969 if (IsConsumedExpr(TopContextLoc) && 970 !IsControlFlowExpr(TopContextLoc.asStmt())) 971 TopContextLoc.markDead(); 972 973 rawAddEdge(NewLoc); 974 } 975 976 return; 977 } 978 979 if (containsLocation(TopContextLoc, CLoc)) { 980 if (alwaysAdd) { 981 rawAddEdge(NewLoc); 982 983 if (IsConsumedExpr(CLoc) && !IsControlFlowExpr(CLoc.asStmt())) { 984 CLocs.push_back(ContextLocation(CLoc, true)); 985 return; 986 } 987 } 988 989 CLocs.push_back(CLoc); 990 return; 991 } 992 993 // Context does not contain the location. Flush it. 994 popLocation(); 995 } 996 997 // If we reach here, there is no enclosing context. Just add the edge. 998 rawAddEdge(NewLoc); 999 } 1000 1001 bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) { 1002 if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt())) 1003 return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X); 1004 1005 return false; 1006 } 1007 1008 void EdgeBuilder::addExtendedContext(const Stmt *S) { 1009 if (!S) 1010 return; 1011 1012 const Stmt *Parent = PDB.getParent(S); 1013 while (Parent) { 1014 if (isa<CompoundStmt>(Parent)) 1015 Parent = PDB.getParent(Parent); 1016 else 1017 break; 1018 } 1019 1020 if (Parent) { 1021 switch (Parent->getStmtClass()) { 1022 case Stmt::DoStmtClass: 1023 case Stmt::ObjCAtSynchronizedStmtClass: 1024 addContext(Parent); 1025 default: 1026 break; 1027 } 1028 } 1029 1030 addContext(S); 1031 } 1032 1033 void EdgeBuilder::addContext(const Stmt *S) { 1034 if (!S) 1035 return; 1036 1037 PathDiagnosticLocation L(S, PDB.getSourceManager(), PDB.LC); 1038 1039 while (!CLocs.empty()) { 1040 const PathDiagnosticLocation &TopContextLoc = CLocs.back(); 1041 1042 // Is the top location context the same as the one for the new location? 1043 if (TopContextLoc == L) 1044 return; 1045 1046 if (containsLocation(TopContextLoc, L)) { 1047 CLocs.push_back(L); 1048 return; 1049 } 1050 1051 // Context does not contain the location. Flush it. 1052 popLocation(); 1053 } 1054 1055 CLocs.push_back(L); 1056 } 1057 1058 // Cone-of-influence: support the reverse propagation of "interesting" symbols 1059 // and values by tracing interesting calculations backwards through evaluated 1060 // expressions along a path. This is probably overly complicated, but the idea 1061 // is that if an expression computed an "interesting" value, the child 1062 // expressions are are also likely to be "interesting" as well (which then 1063 // propagates to the values they in turn compute). This reverse propagation 1064 // is needed to track interesting correlations across function call boundaries, 1065 // where formal arguments bind to actual arguments, etc. This is also needed 1066 // because the constraint solver sometimes simplifies certain symbolic values 1067 // into constants when appropriate, and this complicates reasoning about 1068 // interesting values. 1069 typedef llvm::DenseSet<const Expr *> InterestingExprs; 1070 1071 static void reversePropagateIntererstingSymbols(BugReport &R, 1072 InterestingExprs &IE, 1073 const ProgramState *State, 1074 const Expr *Ex, 1075 const LocationContext *LCtx) { 1076 SVal V = State->getSVal(Ex, LCtx); 1077 if (!(R.isInteresting(V) || IE.count(Ex))) 1078 return; 1079 1080 switch (Ex->getStmtClass()) { 1081 default: 1082 if (!isa<CastExpr>(Ex)) 1083 break; 1084 // Fall through. 1085 case Stmt::BinaryOperatorClass: 1086 case Stmt::UnaryOperatorClass: { 1087 for (Stmt::const_child_iterator CI = Ex->child_begin(), 1088 CE = Ex->child_end(); 1089 CI != CE; ++CI) { 1090 if (const Expr *child = dyn_cast_or_null<Expr>(*CI)) { 1091 IE.insert(child); 1092 SVal ChildV = State->getSVal(child, LCtx); 1093 R.markInteresting(ChildV); 1094 } 1095 break; 1096 } 1097 } 1098 } 1099 1100 R.markInteresting(V); 1101 } 1102 1103 static void reversePropagateInterestingSymbols(BugReport &R, 1104 InterestingExprs &IE, 1105 const ProgramState *State, 1106 const LocationContext *CalleeCtx, 1107 const LocationContext *CallerCtx) 1108 { 1109 // FIXME: Handle non-CallExpr-based CallEvents. 1110 const StackFrameContext *Callee = CalleeCtx->getCurrentStackFrame(); 1111 const Stmt *CallSite = Callee->getCallSite(); 1112 if (const CallExpr *CE = dyn_cast_or_null<CallExpr>(CallSite)) { 1113 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CalleeCtx->getDecl())) { 1114 FunctionDecl::param_const_iterator PI = FD->param_begin(), 1115 PE = FD->param_end(); 1116 CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end(); 1117 for (; AI != AE && PI != PE; ++AI, ++PI) { 1118 if (const Expr *ArgE = *AI) { 1119 if (const ParmVarDecl *PD = *PI) { 1120 Loc LV = State->getLValue(PD, CalleeCtx); 1121 if (R.isInteresting(LV) || R.isInteresting(State->getRawSVal(LV))) 1122 IE.insert(ArgE); 1123 } 1124 } 1125 } 1126 } 1127 } 1128 } 1129 1130 static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD, 1131 PathDiagnosticBuilder &PDB, 1132 const ExplodedNode *N, 1133 ArrayRef<BugReporterVisitor *> visitors) { 1134 EdgeBuilder EB(PD, PDB); 1135 const SourceManager& SM = PDB.getSourceManager(); 1136 StackDiagVector CallStack; 1137 InterestingExprs IE; 1138 1139 const ExplodedNode *NextNode = N->pred_empty() ? NULL : *(N->pred_begin()); 1140 while (NextNode) { 1141 N = NextNode; 1142 NextNode = GetPredecessorNode(N); 1143 ProgramPoint P = N->getLocation(); 1144 1145 do { 1146 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) { 1147 if (const Expr *Ex = PS->getStmtAs<Expr>()) 1148 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE, 1149 N->getState().getPtr(), Ex, 1150 N->getLocationContext()); 1151 } 1152 1153 if (const CallExitEnd *CE = dyn_cast<CallExitEnd>(&P)) { 1154 const StackFrameContext *LCtx = 1155 CE->getLocationContext()->getCurrentStackFrame(); 1156 // FIXME: This needs to handle implicit calls. 1157 if (const Stmt *S = CE->getCalleeContext()->getCallSite()) { 1158 if (const Expr *Ex = dyn_cast<Expr>(S)) 1159 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE, 1160 N->getState().getPtr(), Ex, 1161 N->getLocationContext()); 1162 PathDiagnosticLocation Loc(S, 1163 PDB.getSourceManager(), 1164 LCtx); 1165 EB.addEdge(Loc, true); 1166 EB.flushLocations(); 1167 PathDiagnosticCallPiece *C = 1168 PathDiagnosticCallPiece::construct(N, *CE, SM); 1169 PD.getActivePath().push_front(C); 1170 PD.pushActivePath(&C->path); 1171 CallStack.push_back(StackDiagPair(C, N)); 1172 } 1173 break; 1174 } 1175 1176 // Pop the call hierarchy if we are done walking the contents 1177 // of a function call. 1178 if (const CallEnter *CE = dyn_cast<CallEnter>(&P)) { 1179 // Add an edge to the start of the function. 1180 const Decl *D = CE->getCalleeContext()->getDecl(); 1181 PathDiagnosticLocation pos = 1182 PathDiagnosticLocation::createBegin(D, SM); 1183 EB.addEdge(pos); 1184 1185 // Flush all locations, and pop the active path. 1186 EB.flushLocations(); 1187 PD.popActivePath(); 1188 assert(!PD.getActivePath().empty()); 1189 PDB.LC = N->getLocationContext(); 1190 1191 // The current active path should never be empty. Either we 1192 // just added a bunch of stuff to the top-level path, or 1193 // we have a previous CallExitEnd. If the front of the active 1194 // path is not a PathDiagnosticCallPiece, it means that the 1195 // path terminated within a function call. We must then take the 1196 // current contents of the active path and place it within 1197 // a new PathDiagnosticCallPiece. 1198 PathDiagnosticCallPiece *C = 1199 dyn_cast<PathDiagnosticCallPiece>(PD.getActivePath().front()); 1200 if (!C) { 1201 const Decl * Caller = CE->getLocationContext()->getDecl(); 1202 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller); 1203 } 1204 1205 // FIXME: We still need a location for implicit calls. 1206 if (CE->getCallExpr()) { 1207 C->setCallee(*CE, SM); 1208 EB.addContext(CE->getCallExpr()); 1209 } 1210 1211 if (!CallStack.empty()) { 1212 assert(CallStack.back().first == C); 1213 CallStack.pop_back(); 1214 } 1215 break; 1216 } 1217 1218 // Note that is important that we update the LocationContext 1219 // after looking at CallExits. CallExit basically adds an 1220 // edge in the *caller*, so we don't want to update the LocationContext 1221 // too soon. 1222 PDB.LC = N->getLocationContext(); 1223 1224 // Block edges. 1225 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) { 1226 // Does this represent entering a call? If so, look at propagating 1227 // interesting symbols across call boundaries. 1228 if (NextNode) { 1229 const LocationContext *CallerCtx = NextNode->getLocationContext(); 1230 const LocationContext *CalleeCtx = PDB.LC; 1231 if (CallerCtx != CalleeCtx) { 1232 reversePropagateInterestingSymbols(*PDB.getBugReport(), IE, 1233 N->getState().getPtr(), 1234 CalleeCtx, CallerCtx); 1235 } 1236 } 1237 1238 const CFGBlock &Blk = *BE->getSrc(); 1239 const Stmt *Term = Blk.getTerminator(); 1240 1241 // Are we jumping to the head of a loop? Add a special diagnostic. 1242 if (const Stmt *Loop = BE->getDst()->getLoopTarget()) { 1243 PathDiagnosticLocation L(Loop, SM, PDB.LC); 1244 const CompoundStmt *CS = NULL; 1245 1246 if (!Term) { 1247 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop)) 1248 CS = dyn_cast<CompoundStmt>(FS->getBody()); 1249 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop)) 1250 CS = dyn_cast<CompoundStmt>(WS->getBody()); 1251 } 1252 1253 PathDiagnosticEventPiece *p = 1254 new PathDiagnosticEventPiece(L, 1255 "Looping back to the head of the loop"); 1256 p->setPrunable(true); 1257 1258 EB.addEdge(p->getLocation(), true); 1259 PD.getActivePath().push_front(p); 1260 1261 if (CS) { 1262 PathDiagnosticLocation BL = 1263 PathDiagnosticLocation::createEndBrace(CS, SM); 1264 EB.addEdge(BL); 1265 } 1266 } 1267 1268 if (Term) 1269 EB.addContext(Term); 1270 1271 break; 1272 } 1273 1274 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) { 1275 if (const CFGStmt *S = BE->getFirstElement().getAs<CFGStmt>()) { 1276 const Stmt *stmt = S->getStmt(); 1277 if (IsControlFlowExpr(stmt)) { 1278 // Add the proper context for '&&', '||', and '?'. 1279 EB.addContext(stmt); 1280 } 1281 else 1282 EB.addExtendedContext(PDB.getEnclosingStmtLocation(stmt).asStmt()); 1283 } 1284 1285 break; 1286 } 1287 1288 1289 } while (0); 1290 1291 if (!NextNode) 1292 continue; 1293 1294 // Add pieces from custom visitors. 1295 BugReport *R = PDB.getBugReport(); 1296 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(), 1297 E = visitors.end(); 1298 I != E; ++I) { 1299 if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) { 1300 const PathDiagnosticLocation &Loc = p->getLocation(); 1301 EB.addEdge(Loc, true); 1302 PD.getActivePath().push_front(p); 1303 updateStackPiecesWithMessage(p, CallStack); 1304 1305 if (const Stmt *S = Loc.asStmt()) 1306 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt()); 1307 } 1308 } 1309 } 1310 } 1311 1312 //===----------------------------------------------------------------------===// 1313 // Methods for BugType and subclasses. 1314 //===----------------------------------------------------------------------===// 1315 BugType::~BugType() { } 1316 1317 void BugType::FlushReports(BugReporter &BR) {} 1318 1319 void BuiltinBug::anchor() {} 1320 1321 //===----------------------------------------------------------------------===// 1322 // Methods for BugReport and subclasses. 1323 //===----------------------------------------------------------------------===// 1324 1325 void BugReport::NodeResolver::anchor() {} 1326 1327 void BugReport::addVisitor(BugReporterVisitor* visitor) { 1328 if (!visitor) 1329 return; 1330 1331 llvm::FoldingSetNodeID ID; 1332 visitor->Profile(ID); 1333 void *InsertPos; 1334 1335 if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) { 1336 delete visitor; 1337 return; 1338 } 1339 1340 CallbacksSet.InsertNode(visitor, InsertPos); 1341 Callbacks.push_back(visitor); 1342 ++ConfigurationChangeToken; 1343 } 1344 1345 BugReport::~BugReport() { 1346 for (visitor_iterator I = visitor_begin(), E = visitor_end(); I != E; ++I) { 1347 delete *I; 1348 } 1349 } 1350 1351 const Decl *BugReport::getDeclWithIssue() const { 1352 if (DeclWithIssue) 1353 return DeclWithIssue; 1354 1355 const ExplodedNode *N = getErrorNode(); 1356 if (!N) 1357 return 0; 1358 1359 const LocationContext *LC = N->getLocationContext(); 1360 return LC->getCurrentStackFrame()->getDecl(); 1361 } 1362 1363 void BugReport::Profile(llvm::FoldingSetNodeID& hash) const { 1364 hash.AddPointer(&BT); 1365 hash.AddString(Description); 1366 if (UniqueingLocation.isValid()) { 1367 UniqueingLocation.Profile(hash); 1368 } else if (Location.isValid()) { 1369 Location.Profile(hash); 1370 } else { 1371 assert(ErrorNode); 1372 hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode)); 1373 } 1374 1375 for (SmallVectorImpl<SourceRange>::const_iterator I = 1376 Ranges.begin(), E = Ranges.end(); I != E; ++I) { 1377 const SourceRange range = *I; 1378 if (!range.isValid()) 1379 continue; 1380 hash.AddInteger(range.getBegin().getRawEncoding()); 1381 hash.AddInteger(range.getEnd().getRawEncoding()); 1382 } 1383 } 1384 1385 void BugReport::markInteresting(SymbolRef sym) { 1386 if (!sym) 1387 return; 1388 1389 // If the symbol wasn't already in our set, note a configuration change. 1390 if (interestingSymbols.insert(sym).second) 1391 ++ConfigurationChangeToken; 1392 1393 if (const SymbolMetadata *meta = dyn_cast<SymbolMetadata>(sym)) 1394 interestingRegions.insert(meta->getRegion()); 1395 } 1396 1397 void BugReport::markInteresting(const MemRegion *R) { 1398 if (!R) 1399 return; 1400 1401 // If the base region wasn't already in our set, note a configuration change. 1402 R = R->getBaseRegion(); 1403 if (interestingRegions.insert(R).second) 1404 ++ConfigurationChangeToken; 1405 1406 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) 1407 interestingSymbols.insert(SR->getSymbol()); 1408 } 1409 1410 void BugReport::markInteresting(SVal V) { 1411 markInteresting(V.getAsRegion()); 1412 markInteresting(V.getAsSymbol()); 1413 } 1414 1415 bool BugReport::isInteresting(SVal V) const { 1416 return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol()); 1417 } 1418 1419 bool BugReport::isInteresting(SymbolRef sym) const { 1420 if (!sym) 1421 return false; 1422 // We don't currently consider metadata symbols to be interesting 1423 // even if we know their region is interesting. Is that correct behavior? 1424 return interestingSymbols.count(sym); 1425 } 1426 1427 bool BugReport::isInteresting(const MemRegion *R) const { 1428 if (!R) 1429 return false; 1430 R = R->getBaseRegion(); 1431 bool b = interestingRegions.count(R); 1432 if (b) 1433 return true; 1434 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) 1435 return interestingSymbols.count(SR->getSymbol()); 1436 return false; 1437 } 1438 1439 1440 const Stmt *BugReport::getStmt() const { 1441 if (!ErrorNode) 1442 return 0; 1443 1444 ProgramPoint ProgP = ErrorNode->getLocation(); 1445 const Stmt *S = NULL; 1446 1447 if (BlockEntrance *BE = dyn_cast<BlockEntrance>(&ProgP)) { 1448 CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit(); 1449 if (BE->getBlock() == &Exit) 1450 S = GetPreviousStmt(ErrorNode); 1451 } 1452 if (!S) 1453 S = GetStmt(ProgP); 1454 1455 return S; 1456 } 1457 1458 std::pair<BugReport::ranges_iterator, BugReport::ranges_iterator> 1459 BugReport::getRanges() { 1460 // If no custom ranges, add the range of the statement corresponding to 1461 // the error node. 1462 if (Ranges.empty()) { 1463 if (const Expr *E = dyn_cast_or_null<Expr>(getStmt())) 1464 addRange(E->getSourceRange()); 1465 else 1466 return std::make_pair(ranges_iterator(), ranges_iterator()); 1467 } 1468 1469 // User-specified absence of range info. 1470 if (Ranges.size() == 1 && !Ranges.begin()->isValid()) 1471 return std::make_pair(ranges_iterator(), ranges_iterator()); 1472 1473 return std::make_pair(Ranges.begin(), Ranges.end()); 1474 } 1475 1476 PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const { 1477 if (ErrorNode) { 1478 assert(!Location.isValid() && 1479 "Either Location or ErrorNode should be specified but not both."); 1480 1481 if (const Stmt *S = GetCurrentOrPreviousStmt(ErrorNode)) { 1482 const LocationContext *LC = ErrorNode->getLocationContext(); 1483 1484 // For member expressions, return the location of the '.' or '->'. 1485 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) 1486 return PathDiagnosticLocation::createMemberLoc(ME, SM); 1487 // For binary operators, return the location of the operator. 1488 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(S)) 1489 return PathDiagnosticLocation::createOperatorLoc(B, SM); 1490 1491 return PathDiagnosticLocation::createBegin(S, SM, LC); 1492 } 1493 } else { 1494 assert(Location.isValid()); 1495 return Location; 1496 } 1497 1498 return PathDiagnosticLocation(); 1499 } 1500 1501 //===----------------------------------------------------------------------===// 1502 // Methods for BugReporter and subclasses. 1503 //===----------------------------------------------------------------------===// 1504 1505 BugReportEquivClass::~BugReportEquivClass() { } 1506 GRBugReporter::~GRBugReporter() { } 1507 BugReporterData::~BugReporterData() {} 1508 1509 ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); } 1510 1511 ProgramStateManager& 1512 GRBugReporter::getStateManager() { return Eng.getStateManager(); } 1513 1514 BugReporter::~BugReporter() { 1515 FlushReports(); 1516 1517 // Free the bug reports we are tracking. 1518 typedef std::vector<BugReportEquivClass *> ContTy; 1519 for (ContTy::iterator I = EQClassesVector.begin(), E = EQClassesVector.end(); 1520 I != E; ++I) { 1521 delete *I; 1522 } 1523 } 1524 1525 void BugReporter::FlushReports() { 1526 if (BugTypes.isEmpty()) 1527 return; 1528 1529 // First flush the warnings for each BugType. This may end up creating new 1530 // warnings and new BugTypes. 1531 // FIXME: Only NSErrorChecker needs BugType's FlushReports. 1532 // Turn NSErrorChecker into a proper checker and remove this. 1533 SmallVector<const BugType*, 16> bugTypes; 1534 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) 1535 bugTypes.push_back(*I); 1536 for (SmallVector<const BugType*, 16>::iterator 1537 I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I) 1538 const_cast<BugType*>(*I)->FlushReports(*this); 1539 1540 typedef llvm::FoldingSet<BugReportEquivClass> SetTy; 1541 for (SetTy::iterator EI=EQClasses.begin(), EE=EQClasses.end(); EI!=EE;++EI){ 1542 BugReportEquivClass& EQ = *EI; 1543 FlushReport(EQ); 1544 } 1545 1546 // BugReporter owns and deletes only BugTypes created implicitly through 1547 // EmitBasicReport. 1548 // FIXME: There are leaks from checkers that assume that the BugTypes they 1549 // create will be destroyed by the BugReporter. 1550 for (llvm::StringMap<BugType*>::iterator 1551 I = StrBugTypes.begin(), E = StrBugTypes.end(); I != E; ++I) 1552 delete I->second; 1553 1554 // Remove all references to the BugType objects. 1555 BugTypes = F.getEmptySet(); 1556 } 1557 1558 //===----------------------------------------------------------------------===// 1559 // PathDiagnostics generation. 1560 //===----------------------------------------------------------------------===// 1561 1562 static std::pair<std::pair<ExplodedGraph*, NodeBackMap*>, 1563 std::pair<ExplodedNode*, unsigned> > 1564 MakeReportGraph(const ExplodedGraph* G, 1565 SmallVectorImpl<const ExplodedNode*> &nodes) { 1566 1567 // Create the trimmed graph. It will contain the shortest paths from the 1568 // error nodes to the root. In the new graph we should only have one 1569 // error node unless there are two or more error nodes with the same minimum 1570 // path length. 1571 ExplodedGraph* GTrim; 1572 InterExplodedGraphMap* NMap; 1573 1574 llvm::DenseMap<const void*, const void*> InverseMap; 1575 llvm::tie(GTrim, NMap) = G->Trim(nodes.data(), nodes.data() + nodes.size(), 1576 &InverseMap); 1577 1578 // Create owning pointers for GTrim and NMap just to ensure that they are 1579 // released when this function exists. 1580 OwningPtr<ExplodedGraph> AutoReleaseGTrim(GTrim); 1581 OwningPtr<InterExplodedGraphMap> AutoReleaseNMap(NMap); 1582 1583 // Find the (first) error node in the trimmed graph. We just need to consult 1584 // the node map (NMap) which maps from nodes in the original graph to nodes 1585 // in the new graph. 1586 1587 std::queue<const ExplodedNode*> WS; 1588 typedef llvm::DenseMap<const ExplodedNode*, unsigned> IndexMapTy; 1589 IndexMapTy IndexMap; 1590 1591 for (unsigned nodeIndex = 0 ; nodeIndex < nodes.size(); ++nodeIndex) { 1592 const ExplodedNode *originalNode = nodes[nodeIndex]; 1593 if (const ExplodedNode *N = NMap->getMappedNode(originalNode)) { 1594 WS.push(N); 1595 IndexMap[originalNode] = nodeIndex; 1596 } 1597 } 1598 1599 assert(!WS.empty() && "No error node found in the trimmed graph."); 1600 1601 // Create a new (third!) graph with a single path. This is the graph 1602 // that will be returned to the caller. 1603 ExplodedGraph *GNew = new ExplodedGraph(); 1604 1605 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS 1606 // to the root node, and then construct a new graph that contains only 1607 // a single path. 1608 llvm::DenseMap<const void*,unsigned> Visited; 1609 1610 unsigned cnt = 0; 1611 const ExplodedNode *Root = 0; 1612 1613 while (!WS.empty()) { 1614 const ExplodedNode *Node = WS.front(); 1615 WS.pop(); 1616 1617 if (Visited.find(Node) != Visited.end()) 1618 continue; 1619 1620 Visited[Node] = cnt++; 1621 1622 if (Node->pred_empty()) { 1623 Root = Node; 1624 break; 1625 } 1626 1627 for (ExplodedNode::const_pred_iterator I=Node->pred_begin(), 1628 E=Node->pred_end(); I!=E; ++I) 1629 WS.push(*I); 1630 } 1631 1632 assert(Root); 1633 1634 // Now walk from the root down the BFS path, always taking the successor 1635 // with the lowest number. 1636 ExplodedNode *Last = 0, *First = 0; 1637 NodeBackMap *BM = new NodeBackMap(); 1638 unsigned NodeIndex = 0; 1639 1640 for ( const ExplodedNode *N = Root ;;) { 1641 // Lookup the number associated with the current node. 1642 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N); 1643 assert(I != Visited.end()); 1644 1645 // Create the equivalent node in the new graph with the same state 1646 // and location. 1647 ExplodedNode *NewN = GNew->getNode(N->getLocation(), N->getState()); 1648 1649 // Store the mapping to the original node. 1650 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N); 1651 assert(IMitr != InverseMap.end() && "No mapping to original node."); 1652 (*BM)[NewN] = (const ExplodedNode*) IMitr->second; 1653 1654 // Link up the new node with the previous node. 1655 if (Last) 1656 NewN->addPredecessor(Last, *GNew); 1657 1658 Last = NewN; 1659 1660 // Are we at the final node? 1661 IndexMapTy::iterator IMI = 1662 IndexMap.find((const ExplodedNode*)(IMitr->second)); 1663 if (IMI != IndexMap.end()) { 1664 First = NewN; 1665 NodeIndex = IMI->second; 1666 break; 1667 } 1668 1669 // Find the next successor node. We choose the node that is marked 1670 // with the lowest DFS number. 1671 ExplodedNode::const_succ_iterator SI = N->succ_begin(); 1672 ExplodedNode::const_succ_iterator SE = N->succ_end(); 1673 N = 0; 1674 1675 for (unsigned MinVal = 0; SI != SE; ++SI) { 1676 1677 I = Visited.find(*SI); 1678 1679 if (I == Visited.end()) 1680 continue; 1681 1682 if (!N || I->second < MinVal) { 1683 N = *SI; 1684 MinVal = I->second; 1685 } 1686 } 1687 1688 assert(N); 1689 } 1690 1691 assert(First); 1692 1693 return std::make_pair(std::make_pair(GNew, BM), 1694 std::make_pair(First, NodeIndex)); 1695 } 1696 1697 /// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object 1698 /// and collapses PathDiagosticPieces that are expanded by macros. 1699 static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM) { 1700 typedef std::vector<std::pair<IntrusiveRefCntPtr<PathDiagnosticMacroPiece>, 1701 SourceLocation> > MacroStackTy; 1702 1703 typedef std::vector<IntrusiveRefCntPtr<PathDiagnosticPiece> > 1704 PiecesTy; 1705 1706 MacroStackTy MacroStack; 1707 PiecesTy Pieces; 1708 1709 for (PathPieces::const_iterator I = path.begin(), E = path.end(); 1710 I!=E; ++I) { 1711 1712 PathDiagnosticPiece *piece = I->getPtr(); 1713 1714 // Recursively compact calls. 1715 if (PathDiagnosticCallPiece *call=dyn_cast<PathDiagnosticCallPiece>(piece)){ 1716 CompactPathDiagnostic(call->path, SM); 1717 } 1718 1719 // Get the location of the PathDiagnosticPiece. 1720 const FullSourceLoc Loc = piece->getLocation().asLocation(); 1721 1722 // Determine the instantiation location, which is the location we group 1723 // related PathDiagnosticPieces. 1724 SourceLocation InstantiationLoc = Loc.isMacroID() ? 1725 SM.getExpansionLoc(Loc) : 1726 SourceLocation(); 1727 1728 if (Loc.isFileID()) { 1729 MacroStack.clear(); 1730 Pieces.push_back(piece); 1731 continue; 1732 } 1733 1734 assert(Loc.isMacroID()); 1735 1736 // Is the PathDiagnosticPiece within the same macro group? 1737 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) { 1738 MacroStack.back().first->subPieces.push_back(piece); 1739 continue; 1740 } 1741 1742 // We aren't in the same group. Are we descending into a new macro 1743 // or are part of an old one? 1744 IntrusiveRefCntPtr<PathDiagnosticMacroPiece> MacroGroup; 1745 1746 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ? 1747 SM.getExpansionLoc(Loc) : 1748 SourceLocation(); 1749 1750 // Walk the entire macro stack. 1751 while (!MacroStack.empty()) { 1752 if (InstantiationLoc == MacroStack.back().second) { 1753 MacroGroup = MacroStack.back().first; 1754 break; 1755 } 1756 1757 if (ParentInstantiationLoc == MacroStack.back().second) { 1758 MacroGroup = MacroStack.back().first; 1759 break; 1760 } 1761 1762 MacroStack.pop_back(); 1763 } 1764 1765 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) { 1766 // Create a new macro group and add it to the stack. 1767 PathDiagnosticMacroPiece *NewGroup = 1768 new PathDiagnosticMacroPiece( 1769 PathDiagnosticLocation::createSingleLocation(piece->getLocation())); 1770 1771 if (MacroGroup) 1772 MacroGroup->subPieces.push_back(NewGroup); 1773 else { 1774 assert(InstantiationLoc.isFileID()); 1775 Pieces.push_back(NewGroup); 1776 } 1777 1778 MacroGroup = NewGroup; 1779 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc)); 1780 } 1781 1782 // Finally, add the PathDiagnosticPiece to the group. 1783 MacroGroup->subPieces.push_back(piece); 1784 } 1785 1786 // Now take the pieces and construct a new PathDiagnostic. 1787 path.clear(); 1788 1789 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) 1790 path.push_back(*I); 1791 } 1792 1793 void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD, 1794 SmallVectorImpl<BugReport *> &bugReports) { 1795 1796 assert(!bugReports.empty()); 1797 SmallVector<const ExplodedNode *, 10> errorNodes; 1798 for (SmallVectorImpl<BugReport*>::iterator I = bugReports.begin(), 1799 E = bugReports.end(); I != E; ++I) { 1800 errorNodes.push_back((*I)->getErrorNode()); 1801 } 1802 1803 // Construct a new graph that contains only a single path from the error 1804 // node to a root. 1805 const std::pair<std::pair<ExplodedGraph*, NodeBackMap*>, 1806 std::pair<ExplodedNode*, unsigned> >& 1807 GPair = MakeReportGraph(&getGraph(), errorNodes); 1808 1809 // Find the BugReport with the original location. 1810 assert(GPair.second.second < bugReports.size()); 1811 BugReport *R = bugReports[GPair.second.second]; 1812 assert(R && "No original report found for sliced graph."); 1813 1814 OwningPtr<ExplodedGraph> ReportGraph(GPair.first.first); 1815 OwningPtr<NodeBackMap> BackMap(GPair.first.second); 1816 const ExplodedNode *N = GPair.second.first; 1817 1818 // Start building the path diagnostic... 1819 PathDiagnosticBuilder PDB(*this, R, BackMap.get(), 1820 getPathDiagnosticConsumer()); 1821 1822 // Register additional node visitors. 1823 R->addVisitor(new NilReceiverBRVisitor()); 1824 R->addVisitor(new ConditionBRVisitor()); 1825 1826 BugReport::VisitorList visitors; 1827 unsigned originalReportConfigToken, finalReportConfigToken; 1828 1829 // While generating diagnostics, it's possible the visitors will decide 1830 // new symbols and regions are interesting, or add other visitors based on 1831 // the information they find. If they do, we need to regenerate the path 1832 // based on our new report configuration. 1833 do { 1834 // Get a clean copy of all the visitors. 1835 for (BugReport::visitor_iterator I = R->visitor_begin(), 1836 E = R->visitor_end(); I != E; ++I) 1837 visitors.push_back((*I)->clone()); 1838 1839 // Clear out the active path from any previous work. 1840 PD.getActivePath().clear(); 1841 originalReportConfigToken = R->getConfigurationChangeToken(); 1842 1843 // Generate the very last diagnostic piece - the piece is visible before 1844 // the trace is expanded. 1845 PathDiagnosticPiece *LastPiece = 0; 1846 for (BugReport::visitor_iterator I = visitors.begin(), E = visitors.end(); 1847 I != E; ++I) { 1848 if (PathDiagnosticPiece *Piece = (*I)->getEndPath(PDB, N, *R)) { 1849 assert (!LastPiece && 1850 "There can only be one final piece in a diagnostic."); 1851 LastPiece = Piece; 1852 } 1853 } 1854 if (!LastPiece) 1855 LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, N, *R); 1856 if (LastPiece) 1857 PD.getActivePath().push_back(LastPiece); 1858 else 1859 return; 1860 1861 switch (PDB.getGenerationScheme()) { 1862 case PathDiagnosticConsumer::Extensive: 1863 GenerateExtensivePathDiagnostic(PD, PDB, N, visitors); 1864 break; 1865 case PathDiagnosticConsumer::Minimal: 1866 GenerateMinimalPathDiagnostic(PD, PDB, N, visitors); 1867 break; 1868 } 1869 1870 // Clean up the visitors we used. 1871 llvm::DeleteContainerPointers(visitors); 1872 1873 // Did anything change while generating this path? 1874 finalReportConfigToken = R->getConfigurationChangeToken(); 1875 } while(finalReportConfigToken != originalReportConfigToken); 1876 1877 // Finally, prune the diagnostic path of uninteresting stuff. 1878 if (R->shouldPrunePath()) { 1879 bool hasSomethingInteresting = RemoveUneededCalls(PD.getMutablePieces()); 1880 assert(hasSomethingInteresting); 1881 (void) hasSomethingInteresting; 1882 } 1883 } 1884 1885 void BugReporter::Register(BugType *BT) { 1886 BugTypes = F.add(BugTypes, BT); 1887 } 1888 1889 void BugReporter::EmitReport(BugReport* R) { 1890 // Compute the bug report's hash to determine its equivalence class. 1891 llvm::FoldingSetNodeID ID; 1892 R->Profile(ID); 1893 1894 // Lookup the equivance class. If there isn't one, create it. 1895 BugType& BT = R->getBugType(); 1896 Register(&BT); 1897 void *InsertPos; 1898 BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos); 1899 1900 if (!EQ) { 1901 EQ = new BugReportEquivClass(R); 1902 EQClasses.InsertNode(EQ, InsertPos); 1903 EQClassesVector.push_back(EQ); 1904 } 1905 else 1906 EQ->AddReport(R); 1907 } 1908 1909 1910 //===----------------------------------------------------------------------===// 1911 // Emitting reports in equivalence classes. 1912 //===----------------------------------------------------------------------===// 1913 1914 namespace { 1915 struct FRIEC_WLItem { 1916 const ExplodedNode *N; 1917 ExplodedNode::const_succ_iterator I, E; 1918 1919 FRIEC_WLItem(const ExplodedNode *n) 1920 : N(n), I(N->succ_begin()), E(N->succ_end()) {} 1921 }; 1922 } 1923 1924 static BugReport * 1925 FindReportInEquivalenceClass(BugReportEquivClass& EQ, 1926 SmallVectorImpl<BugReport*> &bugReports) { 1927 1928 BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end(); 1929 assert(I != E); 1930 BugType& BT = I->getBugType(); 1931 1932 // If we don't need to suppress any of the nodes because they are 1933 // post-dominated by a sink, simply add all the nodes in the equivalence class 1934 // to 'Nodes'. Any of the reports will serve as a "representative" report. 1935 if (!BT.isSuppressOnSink()) { 1936 BugReport *R = I; 1937 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) { 1938 const ExplodedNode *N = I->getErrorNode(); 1939 if (N) { 1940 R = I; 1941 bugReports.push_back(R); 1942 } 1943 } 1944 return R; 1945 } 1946 1947 // For bug reports that should be suppressed when all paths are post-dominated 1948 // by a sink node, iterate through the reports in the equivalence class 1949 // until we find one that isn't post-dominated (if one exists). We use a 1950 // DFS traversal of the ExplodedGraph to find a non-sink node. We could write 1951 // this as a recursive function, but we don't want to risk blowing out the 1952 // stack for very long paths. 1953 BugReport *exampleReport = 0; 1954 1955 for (; I != E; ++I) { 1956 const ExplodedNode *errorNode = I->getErrorNode(); 1957 1958 if (!errorNode) 1959 continue; 1960 if (errorNode->isSink()) { 1961 llvm_unreachable( 1962 "BugType::isSuppressSink() should not be 'true' for sink end nodes"); 1963 } 1964 // No successors? By definition this nodes isn't post-dominated by a sink. 1965 if (errorNode->succ_empty()) { 1966 bugReports.push_back(I); 1967 if (!exampleReport) 1968 exampleReport = I; 1969 continue; 1970 } 1971 1972 // At this point we know that 'N' is not a sink and it has at least one 1973 // successor. Use a DFS worklist to find a non-sink end-of-path node. 1974 typedef FRIEC_WLItem WLItem; 1975 typedef SmallVector<WLItem, 10> DFSWorkList; 1976 llvm::DenseMap<const ExplodedNode *, unsigned> Visited; 1977 1978 DFSWorkList WL; 1979 WL.push_back(errorNode); 1980 Visited[errorNode] = 1; 1981 1982 while (!WL.empty()) { 1983 WLItem &WI = WL.back(); 1984 assert(!WI.N->succ_empty()); 1985 1986 for (; WI.I != WI.E; ++WI.I) { 1987 const ExplodedNode *Succ = *WI.I; 1988 // End-of-path node? 1989 if (Succ->succ_empty()) { 1990 // If we found an end-of-path node that is not a sink. 1991 if (!Succ->isSink()) { 1992 bugReports.push_back(I); 1993 if (!exampleReport) 1994 exampleReport = I; 1995 WL.clear(); 1996 break; 1997 } 1998 // Found a sink? Continue on to the next successor. 1999 continue; 2000 } 2001 // Mark the successor as visited. If it hasn't been explored, 2002 // enqueue it to the DFS worklist. 2003 unsigned &mark = Visited[Succ]; 2004 if (!mark) { 2005 mark = 1; 2006 WL.push_back(Succ); 2007 break; 2008 } 2009 } 2010 2011 // The worklist may have been cleared at this point. First 2012 // check if it is empty before checking the last item. 2013 if (!WL.empty() && &WL.back() == &WI) 2014 WL.pop_back(); 2015 } 2016 } 2017 2018 // ExampleReport will be NULL if all the nodes in the equivalence class 2019 // were post-dominated by sinks. 2020 return exampleReport; 2021 } 2022 2023 //===----------------------------------------------------------------------===// 2024 // DiagnosticCache. This is a hack to cache analyzer diagnostics. It 2025 // uses global state, which eventually should go elsewhere. 2026 //===----------------------------------------------------------------------===// 2027 namespace { 2028 class DiagCacheItem : public llvm::FoldingSetNode { 2029 llvm::FoldingSetNodeID ID; 2030 public: 2031 DiagCacheItem(BugReport *R, PathDiagnostic *PD) { 2032 R->Profile(ID); 2033 PD->Profile(ID); 2034 } 2035 2036 void Profile(llvm::FoldingSetNodeID &id) { 2037 id = ID; 2038 } 2039 2040 llvm::FoldingSetNodeID &getID() { return ID; } 2041 }; 2042 } 2043 2044 static bool IsCachedDiagnostic(BugReport *R, PathDiagnostic *PD) { 2045 // FIXME: Eventually this diagnostic cache should reside in something 2046 // like AnalysisManager instead of being a static variable. This is 2047 // really unsafe in the long term. 2048 typedef llvm::FoldingSet<DiagCacheItem> DiagnosticCache; 2049 static DiagnosticCache DC; 2050 2051 void *InsertPos; 2052 DiagCacheItem *Item = new DiagCacheItem(R, PD); 2053 2054 if (DC.FindNodeOrInsertPos(Item->getID(), InsertPos)) { 2055 delete Item; 2056 return true; 2057 } 2058 2059 DC.InsertNode(Item, InsertPos); 2060 return false; 2061 } 2062 2063 void BugReporter::FlushReport(BugReportEquivClass& EQ) { 2064 SmallVector<BugReport*, 10> bugReports; 2065 BugReport *exampleReport = FindReportInEquivalenceClass(EQ, bugReports); 2066 if (!exampleReport) 2067 return; 2068 2069 PathDiagnosticConsumer* PD = getPathDiagnosticConsumer(); 2070 2071 // FIXME: Make sure we use the 'R' for the path that was actually used. 2072 // Probably doesn't make a difference in practice. 2073 BugType& BT = exampleReport->getBugType(); 2074 2075 OwningPtr<PathDiagnostic> 2076 D(new PathDiagnostic(exampleReport->getDeclWithIssue(), 2077 exampleReport->getBugType().getName(), 2078 !PD || PD->useVerboseDescription() 2079 ? exampleReport->getDescription() 2080 : exampleReport->getShortDescription(), 2081 BT.getCategory())); 2082 2083 if (!bugReports.empty()) 2084 GeneratePathDiagnostic(*D.get(), bugReports); 2085 2086 // Get the meta data. 2087 const BugReport::ExtraTextList &Meta = 2088 exampleReport->getExtraText(); 2089 for (BugReport::ExtraTextList::const_iterator i = Meta.begin(), 2090 e = Meta.end(); i != e; ++i) { 2091 D->addMeta(*i); 2092 } 2093 2094 // Emit a summary diagnostic to the regular Diagnostics engine. 2095 BugReport::ranges_iterator Beg, End; 2096 llvm::tie(Beg, End) = exampleReport->getRanges(); 2097 DiagnosticsEngine &Diag = getDiagnostic(); 2098 2099 if (!IsCachedDiagnostic(exampleReport, D.get())) { 2100 // Search the description for '%', as that will be interpretted as a 2101 // format character by FormatDiagnostics. 2102 StringRef desc = exampleReport->getShortDescription(); 2103 2104 SmallString<512> TmpStr; 2105 llvm::raw_svector_ostream Out(TmpStr); 2106 for (StringRef::iterator I=desc.begin(), E=desc.end(); I!=E; ++I) { 2107 if (*I == '%') 2108 Out << "%%"; 2109 else 2110 Out << *I; 2111 } 2112 2113 Out.flush(); 2114 unsigned ErrorDiag = Diag.getCustomDiagID(DiagnosticsEngine::Warning, TmpStr); 2115 2116 DiagnosticBuilder diagBuilder = Diag.Report( 2117 exampleReport->getLocation(getSourceManager()).asLocation(), ErrorDiag); 2118 for (BugReport::ranges_iterator I = Beg; I != End; ++I) 2119 diagBuilder << *I; 2120 } 2121 2122 // Emit a full diagnostic for the path if we have a PathDiagnosticConsumer. 2123 if (!PD) 2124 return; 2125 2126 if (D->path.empty()) { 2127 PathDiagnosticPiece *piece = new PathDiagnosticEventPiece( 2128 exampleReport->getLocation(getSourceManager()), 2129 exampleReport->getDescription()); 2130 for ( ; Beg != End; ++Beg) 2131 piece->addRange(*Beg); 2132 2133 D->getActivePath().push_back(piece); 2134 } 2135 2136 PD->HandlePathDiagnostic(D.take()); 2137 } 2138 2139 void BugReporter::EmitBasicReport(const Decl *DeclWithIssue, 2140 StringRef name, 2141 StringRef category, 2142 StringRef str, PathDiagnosticLocation Loc, 2143 SourceRange* RBeg, unsigned NumRanges) { 2144 2145 // 'BT' is owned by BugReporter. 2146 BugType *BT = getBugTypeForName(name, category); 2147 BugReport *R = new BugReport(*BT, str, Loc); 2148 R->setDeclWithIssue(DeclWithIssue); 2149 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg); 2150 EmitReport(R); 2151 } 2152 2153 BugType *BugReporter::getBugTypeForName(StringRef name, 2154 StringRef category) { 2155 SmallString<136> fullDesc; 2156 llvm::raw_svector_ostream(fullDesc) << name << ":" << category; 2157 llvm::StringMapEntry<BugType *> & 2158 entry = StrBugTypes.GetOrCreateValue(fullDesc); 2159 BugType *BT = entry.getValue(); 2160 if (!BT) { 2161 BT = new BugType(name, category); 2162 entry.setValue(BT); 2163 } 2164 return BT; 2165 } 2166