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