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