BugReporterVisitors.cpp revision 8c84707fd0fbe9f6f7d17fadd5a9fe162dff8445
1// BugReporterVisitors.cpp - Helpers for reporting 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 a set of BugReporter "visitors" which can be used to 11// enhance the diagnostics reported for a bug. 12// 13//===----------------------------------------------------------------------===// 14#include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h" 15#include "clang/AST/Expr.h" 16#include "clang/AST/ExprObjC.h" 17#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 18#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" 19#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 20#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h" 21#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 22#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 23#include "llvm/ADT/SmallString.h" 24#include "llvm/ADT/StringExtras.h" 25#include "llvm/Support/raw_ostream.h" 26 27using namespace clang; 28using namespace ento; 29 30using llvm::FoldingSetNodeID; 31 32//===----------------------------------------------------------------------===// 33// Utility functions. 34//===----------------------------------------------------------------------===// 35 36bool bugreporter::isDeclRefExprToReference(const Expr *E) { 37 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 38 return DRE->getDecl()->getType()->isReferenceType(); 39 } 40 return false; 41} 42 43const Expr *bugreporter::getDerefExpr(const Stmt *S) { 44 // Pattern match for a few useful cases (do something smarter later): 45 // a[0], p->f, *p 46 const Expr *E = dyn_cast<Expr>(S); 47 if (!E) 48 return 0; 49 E = E->IgnoreParenCasts(); 50 51 while (true) { 52 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) { 53 assert(B->isAssignmentOp()); 54 E = B->getLHS()->IgnoreParenCasts(); 55 continue; 56 } 57 else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 58 if (U->getOpcode() == UO_Deref) 59 return U->getSubExpr()->IgnoreParenCasts(); 60 } 61 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 62 if (ME->isArrow() || isDeclRefExprToReference(ME->getBase())) { 63 return ME->getBase()->IgnoreParenCasts(); 64 } 65 } 66 else if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) { 67 return IvarRef->getBase()->IgnoreParenCasts(); 68 } 69 else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(E)) { 70 return AE->getBase(); 71 } 72 break; 73 } 74 75 return NULL; 76} 77 78const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) { 79 const Stmt *S = N->getLocationAs<PreStmt>()->getStmt(); 80 if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S)) 81 return BE->getRHS(); 82 return NULL; 83} 84 85const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) { 86 const Stmt *S = N->getLocationAs<PostStmt>()->getStmt(); 87 if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S)) 88 return RS->getRetValue(); 89 return NULL; 90} 91 92//===----------------------------------------------------------------------===// 93// Definitions for bug reporter visitors. 94//===----------------------------------------------------------------------===// 95 96PathDiagnosticPiece* 97BugReporterVisitor::getEndPath(BugReporterContext &BRC, 98 const ExplodedNode *EndPathNode, 99 BugReport &BR) { 100 return 0; 101} 102 103PathDiagnosticPiece* 104BugReporterVisitor::getDefaultEndPath(BugReporterContext &BRC, 105 const ExplodedNode *EndPathNode, 106 BugReport &BR) { 107 PathDiagnosticLocation L = 108 PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager()); 109 110 BugReport::ranges_iterator Beg, End; 111 llvm::tie(Beg, End) = BR.getRanges(); 112 113 // Only add the statement itself as a range if we didn't specify any 114 // special ranges for this report. 115 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(L, 116 BR.getDescription(), 117 Beg == End); 118 for (; Beg != End; ++Beg) 119 P->addRange(*Beg); 120 121 return P; 122} 123 124 125namespace { 126/// Emits an extra note at the return statement of an interesting stack frame. 127/// 128/// The returned value is marked as an interesting value, and if it's null, 129/// adds a visitor to track where it became null. 130/// 131/// This visitor is intended to be used when another visitor discovers that an 132/// interesting value comes from an inlined function call. 133class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> { 134 const StackFrameContext *StackFrame; 135 enum { 136 Initial, 137 MaybeUnsuppress, 138 Satisfied 139 } Mode; 140 bool InitiallySuppressed; 141 142public: 143 ReturnVisitor(const StackFrameContext *Frame, bool Suppressed) 144 : StackFrame(Frame), Mode(Initial), InitiallySuppressed(Suppressed) {} 145 146 static void *getTag() { 147 static int Tag = 0; 148 return static_cast<void *>(&Tag); 149 } 150 151 virtual void Profile(llvm::FoldingSetNodeID &ID) const { 152 ID.AddPointer(ReturnVisitor::getTag()); 153 ID.AddPointer(StackFrame); 154 ID.AddBoolean(InitiallySuppressed); 155 } 156 157 /// Adds a ReturnVisitor if the given statement represents a call that was 158 /// inlined. 159 /// 160 /// This will search back through the ExplodedGraph, starting from the given 161 /// node, looking for when the given statement was processed. If it turns out 162 /// the statement is a call that was inlined, we add the visitor to the 163 /// bug report, so it can print a note later. 164 static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S, 165 BugReport &BR) { 166 if (!CallEvent::isCallStmt(S)) 167 return; 168 169 // First, find when we processed the statement. 170 do { 171 if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>()) 172 if (CEE->getCalleeContext()->getCallSite() == S) 173 break; 174 if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>()) 175 if (SP->getStmt() == S) 176 break; 177 178 Node = Node->getFirstPred(); 179 } while (Node); 180 181 // Next, step over any post-statement checks. 182 while (Node && Node->getLocation().getAs<PostStmt>()) 183 Node = Node->getFirstPred(); 184 if (!Node) 185 return; 186 187 // Finally, see if we inlined the call. 188 Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>(); 189 if (!CEE) 190 return; 191 192 const StackFrameContext *CalleeContext = CEE->getCalleeContext(); 193 if (CalleeContext->getCallSite() != S) 194 return; 195 196 // Check the return value. 197 ProgramStateRef State = Node->getState(); 198 SVal RetVal = State->getSVal(S, Node->getLocationContext()); 199 200 // Handle cases where a reference is returned and then immediately used. 201 if (cast<Expr>(S)->isGLValue()) 202 if (Optional<Loc> LValue = RetVal.getAs<Loc>()) 203 RetVal = State->getSVal(*LValue); 204 205 // See if the return value is NULL. If so, suppress the report. 206 SubEngine *Eng = State->getStateManager().getOwningEngine(); 207 assert(Eng && "Cannot file a bug report without an owning engine"); 208 AnalyzerOptions &Options = Eng->getAnalysisManager().options; 209 210 bool InitiallySuppressed = false; 211 if (Options.shouldSuppressNullReturnPaths()) 212 if (Optional<Loc> RetLoc = RetVal.getAs<Loc>()) 213 InitiallySuppressed = !State->assume(*RetLoc, true); 214 215 BR.markInteresting(CalleeContext); 216 BR.addVisitor(new ReturnVisitor(CalleeContext, InitiallySuppressed)); 217 } 218 219 /// Returns true if any counter-suppression heuristics are enabled for 220 /// ReturnVisitor. 221 static bool hasCounterSuppression(AnalyzerOptions &Options) { 222 return Options.shouldAvoidSuppressingNullArgumentPaths(); 223 } 224 225 PathDiagnosticPiece *visitNodeInitial(const ExplodedNode *N, 226 const ExplodedNode *PrevN, 227 BugReporterContext &BRC, 228 BugReport &BR) { 229 // Only print a message at the interesting return statement. 230 if (N->getLocationContext() != StackFrame) 231 return 0; 232 233 Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>(); 234 if (!SP) 235 return 0; 236 237 const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt()); 238 if (!Ret) 239 return 0; 240 241 // Okay, we're at the right return statement, but do we have the return 242 // value available? 243 ProgramStateRef State = N->getState(); 244 SVal V = State->getSVal(Ret, StackFrame); 245 if (V.isUnknownOrUndef()) 246 return 0; 247 248 // Don't print any more notes after this one. 249 Mode = Satisfied; 250 251 const Expr *RetE = Ret->getRetValue(); 252 assert(RetE && "Tracking a return value for a void function"); 253 254 // Handle cases where a reference is returned and then immediately used. 255 Optional<Loc> LValue; 256 if (RetE->isGLValue()) { 257 if ((LValue = V.getAs<Loc>())) { 258 SVal RValue = State->getRawSVal(*LValue, RetE->getType()); 259 if (RValue.getAs<DefinedSVal>()) 260 V = RValue; 261 } 262 } 263 264 // Ignore aggregate rvalues. 265 if (V.getAs<nonloc::LazyCompoundVal>() || 266 V.getAs<nonloc::CompoundVal>()) 267 return 0; 268 269 RetE = RetE->IgnoreParenCasts(); 270 271 // If we can't prove the return value is 0, just mark it interesting, and 272 // make sure to track it into any further inner functions. 273 if (State->assume(V.castAs<DefinedSVal>(), true)) { 274 BR.markInteresting(V); 275 ReturnVisitor::addVisitorIfNecessary(N, RetE, BR); 276 return 0; 277 } 278 279 // If we're returning 0, we should track where that 0 came from. 280 bugreporter::trackNullOrUndefValue(N, RetE, BR); 281 282 // Build an appropriate message based on the return value. 283 SmallString<64> Msg; 284 llvm::raw_svector_ostream Out(Msg); 285 286 if (V.getAs<Loc>()) { 287 // If we have counter-suppression enabled, make sure we keep visiting 288 // future nodes. We want to emit a path note as well, in case 289 // the report is resurrected as valid later on. 290 ExprEngine &Eng = BRC.getBugReporter().getEngine(); 291 AnalyzerOptions &Options = Eng.getAnalysisManager().options; 292 if (InitiallySuppressed && hasCounterSuppression(Options)) 293 Mode = MaybeUnsuppress; 294 295 if (RetE->getType()->isObjCObjectPointerType()) 296 Out << "Returning nil"; 297 else 298 Out << "Returning null pointer"; 299 } else { 300 Out << "Returning zero"; 301 } 302 303 if (LValue) { 304 if (const MemRegion *MR = LValue->getAsRegion()) { 305 if (MR->canPrintPretty()) { 306 Out << " (reference to '"; 307 MR->printPretty(Out); 308 Out << "')"; 309 } 310 } 311 } else { 312 // FIXME: We should have a more generalized location printing mechanism. 313 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE)) 314 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl())) 315 Out << " (loaded from '" << *DD << "')"; 316 } 317 318 PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame); 319 return new PathDiagnosticEventPiece(L, Out.str()); 320 } 321 322 PathDiagnosticPiece *visitNodeMaybeUnsuppress(const ExplodedNode *N, 323 const ExplodedNode *PrevN, 324 BugReporterContext &BRC, 325 BugReport &BR) { 326#ifndef NDEBUG 327 ExprEngine &Eng = BRC.getBugReporter().getEngine(); 328 AnalyzerOptions &Options = Eng.getAnalysisManager().options; 329 assert(hasCounterSuppression(Options)); 330#endif 331 332 // Are we at the entry node for this call? 333 Optional<CallEnter> CE = N->getLocationAs<CallEnter>(); 334 if (!CE) 335 return 0; 336 337 if (CE->getCalleeContext() != StackFrame) 338 return 0; 339 340 Mode = Satisfied; 341 342 // Don't automatically suppress a report if one of the arguments is 343 // known to be a null pointer. Instead, start tracking /that/ null 344 // value back to its origin. 345 ProgramStateManager &StateMgr = BRC.getStateManager(); 346 CallEventManager &CallMgr = StateMgr.getCallEventManager(); 347 348 ProgramStateRef State = N->getState(); 349 CallEventRef<> Call = CallMgr.getCaller(StackFrame, State); 350 for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) { 351 Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>(); 352 if (!ArgV) 353 continue; 354 355 const Expr *ArgE = Call->getArgExpr(I); 356 if (!ArgE) 357 continue; 358 359 // Is it possible for this argument to be non-null? 360 if (State->assume(*ArgV, true)) 361 continue; 362 363 if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true)) 364 BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame); 365 366 // If we /can't/ track the null pointer, we should err on the side of 367 // false negatives, and continue towards marking this report invalid. 368 // (We will still look at the other arguments, though.) 369 } 370 371 return 0; 372 } 373 374 PathDiagnosticPiece *VisitNode(const ExplodedNode *N, 375 const ExplodedNode *PrevN, 376 BugReporterContext &BRC, 377 BugReport &BR) { 378 switch (Mode) { 379 case Initial: 380 return visitNodeInitial(N, PrevN, BRC, BR); 381 case MaybeUnsuppress: 382 return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR); 383 case Satisfied: 384 return 0; 385 } 386 387 llvm_unreachable("Invalid visit mode!"); 388 } 389 390 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC, 391 const ExplodedNode *N, 392 BugReport &BR) { 393 if (InitiallySuppressed) 394 BR.markInvalid(ReturnVisitor::getTag(), StackFrame); 395 return 0; 396 } 397}; 398} // end anonymous namespace 399 400 401void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const { 402 static int tag = 0; 403 ID.AddPointer(&tag); 404 ID.AddPointer(R); 405 ID.Add(V); 406} 407 408PathDiagnosticPiece *FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ, 409 const ExplodedNode *Pred, 410 BugReporterContext &BRC, 411 BugReport &BR) { 412 413 if (Satisfied) 414 return NULL; 415 416 const ExplodedNode *StoreSite = 0; 417 const Expr *InitE = 0; 418 bool IsParam = false; 419 420 // First see if we reached the declaration of the region. 421 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) { 422 if (Optional<PostStmt> P = Pred->getLocationAs<PostStmt>()) { 423 if (const DeclStmt *DS = P->getStmtAs<DeclStmt>()) { 424 if (DS->getSingleDecl() == VR->getDecl()) { 425 StoreSite = Pred; 426 InitE = VR->getDecl()->getInit(); 427 } 428 } 429 } 430 } 431 432 // Otherwise, see if this is the store site: 433 // (1) Succ has this binding and Pred does not, i.e. this is 434 // where the binding first occurred. 435 // (2) Succ has this binding and is a PostStore node for this region, i.e. 436 // the same binding was re-assigned here. 437 if (!StoreSite) { 438 if (Succ->getState()->getSVal(R) != V) 439 return NULL; 440 441 if (Pred->getState()->getSVal(R) == V) { 442 Optional<PostStore> PS = Succ->getLocationAs<PostStore>(); 443 if (!PS || PS->getLocationValue() != R) 444 return NULL; 445 } 446 447 StoreSite = Succ; 448 449 // If this is an assignment expression, we can track the value 450 // being assigned. 451 if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>()) 452 if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>()) 453 if (BO->isAssignmentOp()) 454 InitE = BO->getRHS(); 455 456 // If this is a call entry, the variable should be a parameter. 457 // FIXME: Handle CXXThisRegion as well. (This is not a priority because 458 // 'this' should never be NULL, but this visitor isn't just for NULL and 459 // UndefinedVal.) 460 if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) { 461 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) { 462 const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl()); 463 464 ProgramStateManager &StateMgr = BRC.getStateManager(); 465 CallEventManager &CallMgr = StateMgr.getCallEventManager(); 466 467 CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(), 468 Succ->getState()); 469 InitE = Call->getArgExpr(Param->getFunctionScopeIndex()); 470 IsParam = true; 471 } 472 } 473 } 474 475 if (!StoreSite) 476 return NULL; 477 Satisfied = true; 478 479 // If we have an expression that provided the value, try to track where it 480 // came from. 481 if (InitE) { 482 if (V.isUndef() || V.getAs<loc::ConcreteInt>()) { 483 if (!IsParam) 484 InitE = InitE->IgnoreParenCasts(); 485 bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam); 486 } else { 487 ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(), 488 BR); 489 } 490 } 491 492 if (!R->canPrintPretty()) 493 return 0; 494 495 // Okay, we've found the binding. Emit an appropriate message. 496 SmallString<256> sbuf; 497 llvm::raw_svector_ostream os(sbuf); 498 499 if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) { 500 const Stmt *S = PS->getStmt(); 501 const char *action = 0; 502 const DeclStmt *DS = dyn_cast<DeclStmt>(S); 503 const VarRegion *VR = dyn_cast<VarRegion>(R); 504 505 if (DS) { 506 action = "initialized to "; 507 } else if (isa<BlockExpr>(S)) { 508 action = "captured by block as "; 509 if (VR) { 510 // See if we can get the BlockVarRegion. 511 ProgramStateRef State = StoreSite->getState(); 512 SVal V = State->getSVal(S, PS->getLocationContext()); 513 if (const BlockDataRegion *BDR = 514 dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) { 515 if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) { 516 if (Optional<KnownSVal> KV = 517 State->getSVal(OriginalR).getAs<KnownSVal>()) 518 BR.addVisitor(new FindLastStoreBRVisitor(*KV, OriginalR)); 519 } 520 } 521 } 522 } 523 524 if (action) { 525 if (!R) 526 return 0; 527 528 os << '\''; 529 R->printPretty(os); 530 os << "' "; 531 532 if (V.getAs<loc::ConcreteInt>()) { 533 bool b = false; 534 if (R->isBoundable()) { 535 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) { 536 if (TR->getValueType()->isObjCObjectPointerType()) { 537 os << action << "nil"; 538 b = true; 539 } 540 } 541 } 542 543 if (!b) 544 os << action << "a null pointer value"; 545 } else if (Optional<nonloc::ConcreteInt> CVal = 546 V.getAs<nonloc::ConcreteInt>()) { 547 os << action << CVal->getValue(); 548 } 549 else if (DS) { 550 if (V.isUndef()) { 551 if (isa<VarRegion>(R)) { 552 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl()); 553 if (VD->getInit()) 554 os << "initialized to a garbage value"; 555 else 556 os << "declared without an initial value"; 557 } 558 } 559 else { 560 os << "initialized here"; 561 } 562 } 563 } 564 } else if (StoreSite->getLocation().getAs<CallEnter>()) { 565 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) { 566 const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl()); 567 568 os << "Passing "; 569 570 if (V.getAs<loc::ConcreteInt>()) { 571 if (Param->getType()->isObjCObjectPointerType()) 572 os << "nil object reference"; 573 else 574 os << "null pointer value"; 575 } else if (V.isUndef()) { 576 os << "uninitialized value"; 577 } else if (Optional<nonloc::ConcreteInt> CI = 578 V.getAs<nonloc::ConcreteInt>()) { 579 os << "the value " << CI->getValue(); 580 } else { 581 os << "value"; 582 } 583 584 // Printed parameter indexes are 1-based, not 0-based. 585 unsigned Idx = Param->getFunctionScopeIndex() + 1; 586 os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter '"; 587 588 R->printPretty(os); 589 os << '\''; 590 } 591 } 592 593 if (os.str().empty()) { 594 if (V.getAs<loc::ConcreteInt>()) { 595 bool b = false; 596 if (R->isBoundable()) { 597 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) { 598 if (TR->getValueType()->isObjCObjectPointerType()) { 599 os << "nil object reference stored to "; 600 b = true; 601 } 602 } 603 } 604 605 if (!b) 606 os << "Null pointer value stored to "; 607 } 608 else if (V.isUndef()) { 609 os << "Uninitialized value stored to "; 610 } else if (Optional<nonloc::ConcreteInt> CV = 611 V.getAs<nonloc::ConcreteInt>()) { 612 os << "The value " << CV->getValue() << " is assigned to "; 613 } 614 else 615 os << "Value assigned to "; 616 617 os << '\''; 618 R->printPretty(os); 619 os << '\''; 620 } 621 622 // Construct a new PathDiagnosticPiece. 623 ProgramPoint P = StoreSite->getLocation(); 624 PathDiagnosticLocation L; 625 if (P.getAs<CallEnter>() && InitE) 626 L = PathDiagnosticLocation(InitE, BRC.getSourceManager(), 627 P.getLocationContext()); 628 else 629 L = PathDiagnosticLocation::create(P, BRC.getSourceManager()); 630 if (!L.isValid()) 631 return NULL; 632 return new PathDiagnosticEventPiece(L, os.str()); 633} 634 635void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const { 636 static int tag = 0; 637 ID.AddPointer(&tag); 638 ID.AddBoolean(Assumption); 639 ID.Add(Constraint); 640} 641 642/// Return the tag associated with this visitor. This tag will be used 643/// to make all PathDiagnosticPieces created by this visitor. 644const char *TrackConstraintBRVisitor::getTag() { 645 return "TrackConstraintBRVisitor"; 646} 647 648PathDiagnosticPiece * 649TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N, 650 const ExplodedNode *PrevN, 651 BugReporterContext &BRC, 652 BugReport &BR) { 653 if (isSatisfied) 654 return NULL; 655 656 // Check if in the previous state it was feasible for this constraint 657 // to *not* be true. 658 if (PrevN->getState()->assume(Constraint, !Assumption)) { 659 660 isSatisfied = true; 661 662 // As a sanity check, make sure that the negation of the constraint 663 // was infeasible in the current state. If it is feasible, we somehow 664 // missed the transition point. 665 if (N->getState()->assume(Constraint, !Assumption)) 666 return NULL; 667 668 // We found the transition point for the constraint. We now need to 669 // pretty-print the constraint. (work-in-progress) 670 std::string sbuf; 671 llvm::raw_string_ostream os(sbuf); 672 673 if (Constraint.getAs<Loc>()) { 674 os << "Assuming pointer value is "; 675 os << (Assumption ? "non-null" : "null"); 676 } 677 678 if (os.str().empty()) 679 return NULL; 680 681 // Construct a new PathDiagnosticPiece. 682 ProgramPoint P = N->getLocation(); 683 PathDiagnosticLocation L = 684 PathDiagnosticLocation::create(P, BRC.getSourceManager()); 685 if (!L.isValid()) 686 return NULL; 687 688 PathDiagnosticEventPiece *X = new PathDiagnosticEventPiece(L, os.str()); 689 X->setTag(getTag()); 690 return X; 691 } 692 693 return NULL; 694} 695 696SuppressInlineDefensiveChecksVisitor:: 697SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N) 698 : V(Value), IsSatisfied(false) { 699 700 assert(N->getState()->isNull(V).isConstrainedTrue() && 701 "The visitor only tracks the cases where V is constrained to 0"); 702} 703 704void SuppressInlineDefensiveChecksVisitor::Profile(FoldingSetNodeID &ID) const { 705 static int id = 0; 706 ID.AddPointer(&id); 707 ID.Add(V); 708} 709 710const char *SuppressInlineDefensiveChecksVisitor::getTag() { 711 return "IDCVisitor"; 712} 713 714PathDiagnosticPiece * 715SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *N, 716 const ExplodedNode *PrevN, 717 BugReporterContext &BRC, 718 BugReport &BR) { 719 if (IsSatisfied) 720 return 0; 721 722 AnalyzerOptions &Options = 723 BRC.getBugReporter().getEngine().getAnalysisManager().options; 724 if (!Options.shouldSuppressInlinedDefensiveChecks()) 725 return 0; 726 727 // Check if in the previous state it was feasible for this value 728 // to *not* be null. 729 if (PrevN->getState()->assume(V, true)) { 730 IsSatisfied = true; 731 732 // TODO: Investigate if missing the transition point, where V 733 // is non-null in N could lead to false negatives. 734 735 // Check if this is inline defensive checks. 736 const LocationContext *CurLC = N->getLocationContext(); 737 const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext(); 738 if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) 739 BR.markInvalid("Suppress IDC", CurLC); 740 } 741 return 0; 742} 743 744bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N, const Stmt *S, 745 BugReport &report, bool IsArg) { 746 if (!S || !N) 747 return false; 748 749 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S)) 750 S = OVE->getSourceExpr(); 751 752 if (IsArg) { 753 assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call"); 754 } else { 755 // Walk through nodes until we get one that matches the statement exactly. 756 do { 757 const ProgramPoint &pp = N->getLocation(); 758 if (Optional<PostStmt> ps = pp.getAs<PostStmt>()) { 759 if (ps->getStmt() == S) 760 break; 761 } else if (Optional<CallExitEnd> CEE = pp.getAs<CallExitEnd>()) { 762 if (CEE->getCalleeContext()->getCallSite() == S) 763 break; 764 } 765 N = N->getFirstPred(); 766 } while (N); 767 768 if (!N) 769 return false; 770 } 771 772 ProgramStateRef state = N->getState(); 773 774 // See if the expression we're interested refers to a variable. 775 // If so, we can track both its contents and constraints on its value. 776 if (const Expr *Ex = dyn_cast<Expr>(S)) { 777 // Strip off parens and casts. Note that this will never have issues with 778 // C++ user-defined implicit conversions, because those have a constructor 779 // or function call inside. 780 Ex = Ex->IgnoreParenCasts(); 781 782 if (ExplodedGraph::isInterestingLValueExpr(Ex)) { 783 const MemRegion *R = 0; 784 785 // First check if this is a DeclRefExpr for a C++ reference type. 786 // For those, we want the location of the reference. 787 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) { 788 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 789 if (VD->getType()->isReferenceType()) { 790 ProgramStateManager &StateMgr = state->getStateManager(); 791 MemRegionManager &MRMgr = StateMgr.getRegionManager(); 792 R = MRMgr.getVarRegion(VD, N->getLocationContext()); 793 } 794 } 795 } 796 797 // For all other cases, find the location by scouring the ExplodedGraph. 798 if (!R) { 799 // Find the ExplodedNode where the lvalue (the value of 'Ex') 800 // was computed. We need this for getting the location value. 801 const ExplodedNode *LVNode = N; 802 const Expr *SearchEx = Ex; 803 if (const OpaqueValueExpr *OPE = dyn_cast<OpaqueValueExpr>(Ex)) { 804 SearchEx = OPE->getSourceExpr(); 805 } 806 while (LVNode) { 807 if (Optional<PostStmt> P = LVNode->getLocation().getAs<PostStmt>()) { 808 if (P->getStmt() == SearchEx) 809 break; 810 } 811 LVNode = LVNode->getFirstPred(); 812 } 813 assert(LVNode && "Unable to find the lvalue node."); 814 ProgramStateRef LVState = LVNode->getState(); 815 if (Optional<Loc> L = 816 LVState->getSVal(Ex, LVNode->getLocationContext()).getAs<Loc>()) { 817 R = L->getAsRegion(); 818 } 819 } 820 821 if (R) { 822 // Mark both the variable region and its contents as interesting. 823 SVal V = state->getRawSVal(loc::MemRegionVal(R)); 824 825 // If the value matches the default for the variable region, that 826 // might mean that it's been cleared out of the state. Fall back to 827 // the full argument expression (with casts and such intact). 828 if (IsArg) { 829 bool UseArgValue = V.isUnknownOrUndef() || V.isZeroConstant(); 830 if (!UseArgValue) { 831 const SymbolRegionValue *SRV = 832 dyn_cast_or_null<SymbolRegionValue>(V.getAsLocSymbol()); 833 if (SRV) 834 UseArgValue = (SRV->getRegion() == R); 835 } 836 if (UseArgValue) 837 V = state->getSValAsScalarOrLoc(S, N->getLocationContext()); 838 } 839 840 report.markInteresting(R); 841 report.markInteresting(V); 842 report.addVisitor(new UndefOrNullArgVisitor(R)); 843 844 if (isa<SymbolicRegion>(R)) { 845 TrackConstraintBRVisitor *VI = 846 new TrackConstraintBRVisitor(loc::MemRegionVal(R), false); 847 report.addVisitor(VI); 848 } 849 850 // If the contents are symbolic, find out when they became null. 851 if (V.getAsLocSymbol()) { 852 BugReporterVisitor *ConstraintTracker = 853 new TrackConstraintBRVisitor(V.castAs<DefinedSVal>(), false); 854 report.addVisitor(ConstraintTracker); 855 856 // Add visitor, which will suppress inline defensive checks. 857 if (N->getState()->isNull(V).isConstrainedTrue()) { 858 BugReporterVisitor *IDCSuppressor = 859 new SuppressInlineDefensiveChecksVisitor(V.castAs<DefinedSVal>(), 860 N); 861 report.addVisitor(IDCSuppressor); 862 } 863 } 864 865 if (Optional<KnownSVal> KV = V.getAs<KnownSVal>()) 866 report.addVisitor(new FindLastStoreBRVisitor(*KV, R)); 867 return true; 868 } 869 } 870 } 871 872 // If the expression is not an "lvalue expression", we can still 873 // track the constraints on its contents. 874 SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext()); 875 876 // If the value came from an inlined function call, we should at least make 877 // sure that function isn't pruned in our output. 878 if (const Expr *E = dyn_cast<Expr>(S)) 879 S = E->IgnoreParenCasts(); 880 ReturnVisitor::addVisitorIfNecessary(N, S, report); 881 882 // Uncomment this to find cases where we aren't properly getting the 883 // base value that was dereferenced. 884 // assert(!V.isUnknownOrUndef()); 885 // Is it a symbolic value? 886 if (Optional<loc::MemRegionVal> L = V.getAs<loc::MemRegionVal>()) { 887 // At this point we are dealing with the region's LValue. 888 // However, if the rvalue is a symbolic region, we should track it as well. 889 SVal RVal = state->getSVal(L->getRegion()); 890 const MemRegion *RegionRVal = RVal.getAsRegion(); 891 report.addVisitor(new UndefOrNullArgVisitor(L->getRegion())); 892 893 if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) { 894 report.markInteresting(RegionRVal); 895 report.addVisitor(new TrackConstraintBRVisitor( 896 loc::MemRegionVal(RegionRVal), false)); 897 } 898 } 899 900 return true; 901} 902 903BugReporterVisitor * 904FindLastStoreBRVisitor::createVisitorObject(const ExplodedNode *N, 905 const MemRegion *R) { 906 assert(R && "The memory region is null."); 907 908 ProgramStateRef state = N->getState(); 909 if (Optional<KnownSVal> KV = state->getSVal(R).getAs<KnownSVal>()) 910 return new FindLastStoreBRVisitor(*KV, R); 911 return 0; 912} 913 914PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N, 915 const ExplodedNode *PrevN, 916 BugReporterContext &BRC, 917 BugReport &BR) { 918 Optional<PostStmt> P = N->getLocationAs<PostStmt>(); 919 if (!P) 920 return 0; 921 const ObjCMessageExpr *ME = P->getStmtAs<ObjCMessageExpr>(); 922 if (!ME) 923 return 0; 924 const Expr *Receiver = ME->getInstanceReceiver(); 925 if (!Receiver) 926 return 0; 927 ProgramStateRef state = N->getState(); 928 const SVal &V = state->getSVal(Receiver, N->getLocationContext()); 929 Optional<DefinedOrUnknownSVal> DV = V.getAs<DefinedOrUnknownSVal>(); 930 if (!DV) 931 return 0; 932 state = state->assume(*DV, true); 933 if (state) 934 return 0; 935 936 // The receiver was nil, and hence the method was skipped. 937 // Register a BugReporterVisitor to issue a message telling us how 938 // the receiver was null. 939 bugreporter::trackNullOrUndefValue(N, Receiver, BR); 940 // Issue a message saying that the method was skipped. 941 PathDiagnosticLocation L(Receiver, BRC.getSourceManager(), 942 N->getLocationContext()); 943 return new PathDiagnosticEventPiece(L, "No method is called " 944 "because the receiver is nil"); 945} 946 947// Registers every VarDecl inside a Stmt with a last store visitor. 948void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR, 949 const Stmt *S) { 950 const ExplodedNode *N = BR.getErrorNode(); 951 std::deque<const Stmt *> WorkList; 952 WorkList.push_back(S); 953 954 while (!WorkList.empty()) { 955 const Stmt *Head = WorkList.front(); 956 WorkList.pop_front(); 957 958 ProgramStateRef state = N->getState(); 959 ProgramStateManager &StateMgr = state->getStateManager(); 960 961 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) { 962 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 963 const VarRegion *R = 964 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext()); 965 966 // What did we load? 967 SVal V = state->getSVal(S, N->getLocationContext()); 968 969 if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) { 970 // Register a new visitor with the BugReport. 971 BR.addVisitor(new FindLastStoreBRVisitor(V.castAs<KnownSVal>(), R)); 972 } 973 } 974 } 975 976 for (Stmt::const_child_iterator I = Head->child_begin(); 977 I != Head->child_end(); ++I) 978 WorkList.push_back(*I); 979 } 980} 981 982//===----------------------------------------------------------------------===// 983// Visitor that tries to report interesting diagnostics from conditions. 984//===----------------------------------------------------------------------===// 985 986/// Return the tag associated with this visitor. This tag will be used 987/// to make all PathDiagnosticPieces created by this visitor. 988const char *ConditionBRVisitor::getTag() { 989 return "ConditionBRVisitor"; 990} 991 992PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N, 993 const ExplodedNode *Prev, 994 BugReporterContext &BRC, 995 BugReport &BR) { 996 PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR); 997 if (piece) { 998 piece->setTag(getTag()); 999 if (PathDiagnosticEventPiece *ev=dyn_cast<PathDiagnosticEventPiece>(piece)) 1000 ev->setPrunable(true, /* override */ false); 1001 } 1002 return piece; 1003} 1004 1005PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N, 1006 const ExplodedNode *Prev, 1007 BugReporterContext &BRC, 1008 BugReport &BR) { 1009 1010 ProgramPoint progPoint = N->getLocation(); 1011 ProgramStateRef CurrentState = N->getState(); 1012 ProgramStateRef PrevState = Prev->getState(); 1013 1014 // Compare the GDMs of the state, because that is where constraints 1015 // are managed. Note that ensure that we only look at nodes that 1016 // were generated by the analyzer engine proper, not checkers. 1017 if (CurrentState->getGDM().getRoot() == 1018 PrevState->getGDM().getRoot()) 1019 return 0; 1020 1021 // If an assumption was made on a branch, it should be caught 1022 // here by looking at the state transition. 1023 if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) { 1024 const CFGBlock *srcBlk = BE->getSrc(); 1025 if (const Stmt *term = srcBlk->getTerminator()) 1026 return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC); 1027 return 0; 1028 } 1029 1030 if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) { 1031 // FIXME: Assuming that BugReporter is a GRBugReporter is a layering 1032 // violation. 1033 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags = 1034 cast<GRBugReporter>(BRC.getBugReporter()). 1035 getEngine().geteagerlyAssumeBinOpBifurcationTags(); 1036 1037 const ProgramPointTag *tag = PS->getTag(); 1038 if (tag == tags.first) 1039 return VisitTrueTest(cast<Expr>(PS->getStmt()), true, 1040 BRC, BR, N); 1041 if (tag == tags.second) 1042 return VisitTrueTest(cast<Expr>(PS->getStmt()), false, 1043 BRC, BR, N); 1044 1045 return 0; 1046 } 1047 1048 return 0; 1049} 1050 1051PathDiagnosticPiece * 1052ConditionBRVisitor::VisitTerminator(const Stmt *Term, 1053 const ExplodedNode *N, 1054 const CFGBlock *srcBlk, 1055 const CFGBlock *dstBlk, 1056 BugReport &R, 1057 BugReporterContext &BRC) { 1058 const Expr *Cond = 0; 1059 1060 switch (Term->getStmtClass()) { 1061 default: 1062 return 0; 1063 case Stmt::IfStmtClass: 1064 Cond = cast<IfStmt>(Term)->getCond(); 1065 break; 1066 case Stmt::ConditionalOperatorClass: 1067 Cond = cast<ConditionalOperator>(Term)->getCond(); 1068 break; 1069 } 1070 1071 assert(Cond); 1072 assert(srcBlk->succ_size() == 2); 1073 const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk; 1074 return VisitTrueTest(Cond, tookTrue, BRC, R, N); 1075} 1076 1077PathDiagnosticPiece * 1078ConditionBRVisitor::VisitTrueTest(const Expr *Cond, 1079 bool tookTrue, 1080 BugReporterContext &BRC, 1081 BugReport &R, 1082 const ExplodedNode *N) { 1083 1084 const Expr *Ex = Cond; 1085 1086 while (true) { 1087 Ex = Ex->IgnoreParenCasts(); 1088 switch (Ex->getStmtClass()) { 1089 default: 1090 return 0; 1091 case Stmt::BinaryOperatorClass: 1092 return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC, 1093 R, N); 1094 case Stmt::DeclRefExprClass: 1095 return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC, 1096 R, N); 1097 case Stmt::UnaryOperatorClass: { 1098 const UnaryOperator *UO = cast<UnaryOperator>(Ex); 1099 if (UO->getOpcode() == UO_LNot) { 1100 tookTrue = !tookTrue; 1101 Ex = UO->getSubExpr(); 1102 continue; 1103 } 1104 return 0; 1105 } 1106 } 1107 } 1108} 1109 1110bool ConditionBRVisitor::patternMatch(const Expr *Ex, raw_ostream &Out, 1111 BugReporterContext &BRC, 1112 BugReport &report, 1113 const ExplodedNode *N, 1114 Optional<bool> &prunable) { 1115 const Expr *OriginalExpr = Ex; 1116 Ex = Ex->IgnoreParenCasts(); 1117 1118 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) { 1119 const bool quotes = isa<VarDecl>(DR->getDecl()); 1120 if (quotes) { 1121 Out << '\''; 1122 const LocationContext *LCtx = N->getLocationContext(); 1123 const ProgramState *state = N->getState().getPtr(); 1124 if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()), 1125 LCtx).getAsRegion()) { 1126 if (report.isInteresting(R)) 1127 prunable = false; 1128 else { 1129 const ProgramState *state = N->getState().getPtr(); 1130 SVal V = state->getSVal(R); 1131 if (report.isInteresting(V)) 1132 prunable = false; 1133 } 1134 } 1135 } 1136 Out << DR->getDecl()->getDeclName().getAsString(); 1137 if (quotes) 1138 Out << '\''; 1139 return quotes; 1140 } 1141 1142 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) { 1143 QualType OriginalTy = OriginalExpr->getType(); 1144 if (OriginalTy->isPointerType()) { 1145 if (IL->getValue() == 0) { 1146 Out << "null"; 1147 return false; 1148 } 1149 } 1150 else if (OriginalTy->isObjCObjectPointerType()) { 1151 if (IL->getValue() == 0) { 1152 Out << "nil"; 1153 return false; 1154 } 1155 } 1156 1157 Out << IL->getValue(); 1158 return false; 1159 } 1160 1161 return false; 1162} 1163 1164PathDiagnosticPiece * 1165ConditionBRVisitor::VisitTrueTest(const Expr *Cond, 1166 const BinaryOperator *BExpr, 1167 const bool tookTrue, 1168 BugReporterContext &BRC, 1169 BugReport &R, 1170 const ExplodedNode *N) { 1171 1172 bool shouldInvert = false; 1173 Optional<bool> shouldPrune; 1174 1175 SmallString<128> LhsString, RhsString; 1176 { 1177 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString); 1178 const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N, 1179 shouldPrune); 1180 const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N, 1181 shouldPrune); 1182 1183 shouldInvert = !isVarLHS && isVarRHS; 1184 } 1185 1186 BinaryOperator::Opcode Op = BExpr->getOpcode(); 1187 1188 if (BinaryOperator::isAssignmentOp(Op)) { 1189 // For assignment operators, all that we care about is that the LHS 1190 // evaluates to "true" or "false". 1191 return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue, 1192 BRC, R, N); 1193 } 1194 1195 // For non-assignment operations, we require that we can understand 1196 // both the LHS and RHS. 1197 if (LhsString.empty() || RhsString.empty()) 1198 return 0; 1199 1200 // Should we invert the strings if the LHS is not a variable name? 1201 SmallString<256> buf; 1202 llvm::raw_svector_ostream Out(buf); 1203 Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is "; 1204 1205 // Do we need to invert the opcode? 1206 if (shouldInvert) 1207 switch (Op) { 1208 default: break; 1209 case BO_LT: Op = BO_GT; break; 1210 case BO_GT: Op = BO_LT; break; 1211 case BO_LE: Op = BO_GE; break; 1212 case BO_GE: Op = BO_LE; break; 1213 } 1214 1215 if (!tookTrue) 1216 switch (Op) { 1217 case BO_EQ: Op = BO_NE; break; 1218 case BO_NE: Op = BO_EQ; break; 1219 case BO_LT: Op = BO_GE; break; 1220 case BO_GT: Op = BO_LE; break; 1221 case BO_LE: Op = BO_GT; break; 1222 case BO_GE: Op = BO_LT; break; 1223 default: 1224 return 0; 1225 } 1226 1227 switch (Op) { 1228 case BO_EQ: 1229 Out << "equal to "; 1230 break; 1231 case BO_NE: 1232 Out << "not equal to "; 1233 break; 1234 default: 1235 Out << BinaryOperator::getOpcodeStr(Op) << ' '; 1236 break; 1237 } 1238 1239 Out << (shouldInvert ? LhsString : RhsString); 1240 const LocationContext *LCtx = N->getLocationContext(); 1241 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx); 1242 PathDiagnosticEventPiece *event = 1243 new PathDiagnosticEventPiece(Loc, Out.str()); 1244 if (shouldPrune.hasValue()) 1245 event->setPrunable(shouldPrune.getValue()); 1246 return event; 1247} 1248 1249PathDiagnosticPiece * 1250ConditionBRVisitor::VisitConditionVariable(StringRef LhsString, 1251 const Expr *CondVarExpr, 1252 const bool tookTrue, 1253 BugReporterContext &BRC, 1254 BugReport &report, 1255 const ExplodedNode *N) { 1256 // FIXME: If there's already a constraint tracker for this variable, 1257 // we shouldn't emit anything here (c.f. the double note in 1258 // test/Analysis/inlining/path-notes.c) 1259 SmallString<256> buf; 1260 llvm::raw_svector_ostream Out(buf); 1261 Out << "Assuming " << LhsString << " is "; 1262 1263 QualType Ty = CondVarExpr->getType(); 1264 1265 if (Ty->isPointerType()) 1266 Out << (tookTrue ? "not null" : "null"); 1267 else if (Ty->isObjCObjectPointerType()) 1268 Out << (tookTrue ? "not nil" : "nil"); 1269 else if (Ty->isBooleanType()) 1270 Out << (tookTrue ? "true" : "false"); 1271 else if (Ty->isIntegerType()) 1272 Out << (tookTrue ? "non-zero" : "zero"); 1273 else 1274 return 0; 1275 1276 const LocationContext *LCtx = N->getLocationContext(); 1277 PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx); 1278 PathDiagnosticEventPiece *event = 1279 new PathDiagnosticEventPiece(Loc, Out.str()); 1280 1281 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) { 1282 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 1283 const ProgramState *state = N->getState().getPtr(); 1284 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) { 1285 if (report.isInteresting(R)) 1286 event->setPrunable(false); 1287 } 1288 } 1289 } 1290 1291 return event; 1292} 1293 1294PathDiagnosticPiece * 1295ConditionBRVisitor::VisitTrueTest(const Expr *Cond, 1296 const DeclRefExpr *DR, 1297 const bool tookTrue, 1298 BugReporterContext &BRC, 1299 BugReport &report, 1300 const ExplodedNode *N) { 1301 1302 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()); 1303 if (!VD) 1304 return 0; 1305 1306 SmallString<256> Buf; 1307 llvm::raw_svector_ostream Out(Buf); 1308 1309 Out << "Assuming '"; 1310 VD->getDeclName().printName(Out); 1311 Out << "' is "; 1312 1313 QualType VDTy = VD->getType(); 1314 1315 if (VDTy->isPointerType()) 1316 Out << (tookTrue ? "non-null" : "null"); 1317 else if (VDTy->isObjCObjectPointerType()) 1318 Out << (tookTrue ? "non-nil" : "nil"); 1319 else if (VDTy->isScalarType()) 1320 Out << (tookTrue ? "not equal to 0" : "0"); 1321 else 1322 return 0; 1323 1324 const LocationContext *LCtx = N->getLocationContext(); 1325 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx); 1326 PathDiagnosticEventPiece *event = 1327 new PathDiagnosticEventPiece(Loc, Out.str()); 1328 1329 const ProgramState *state = N->getState().getPtr(); 1330 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) { 1331 if (report.isInteresting(R)) 1332 event->setPrunable(false); 1333 else { 1334 SVal V = state->getSVal(R); 1335 if (report.isInteresting(V)) 1336 event->setPrunable(false); 1337 } 1338 } 1339 return event; 1340} 1341 1342PathDiagnosticPiece * 1343LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC, 1344 const ExplodedNode *N, 1345 BugReport &BR) { 1346 const Stmt *S = BR.getStmt(); 1347 if (!S) 1348 return 0; 1349 1350 // Here we suppress false positives coming from system macros. This list is 1351 // based on known issues. 1352 1353 // Skip reports within the sys/queue.h macros as we do not have the ability to 1354 // reason about data structure shapes. 1355 SourceManager &SM = BRC.getSourceManager(); 1356 SourceLocation Loc = S->getLocStart(); 1357 while (Loc.isMacroID()) { 1358 if (SM.isInSystemMacro(Loc) && 1359 (SM.getFilename(SM.getSpellingLoc(Loc)).endswith("sys/queue.h"))) { 1360 BR.markInvalid(getTag(), 0); 1361 return 0; 1362 } 1363 Loc = SM.getSpellingLoc(Loc); 1364 } 1365 1366 return 0; 1367} 1368 1369PathDiagnosticPiece * 1370UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N, 1371 const ExplodedNode *PrevN, 1372 BugReporterContext &BRC, 1373 BugReport &BR) { 1374 1375 ProgramStateRef State = N->getState(); 1376 ProgramPoint ProgLoc = N->getLocation(); 1377 1378 // We are only interested in visiting CallEnter nodes. 1379 Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>(); 1380 if (!CEnter) 1381 return 0; 1382 1383 // Check if one of the arguments is the region the visitor is tracking. 1384 CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager(); 1385 CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State); 1386 unsigned Idx = 0; 1387 for (CallEvent::param_iterator I = Call->param_begin(), 1388 E = Call->param_end(); I != E; ++I, ++Idx) { 1389 const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion(); 1390 1391 // Are we tracking the argument or its subregion? 1392 if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts()))) 1393 continue; 1394 1395 // Check the function parameter type. 1396 const ParmVarDecl *ParamDecl = *I; 1397 assert(ParamDecl && "Formal parameter has no decl?"); 1398 QualType T = ParamDecl->getType(); 1399 1400 if (!(T->isAnyPointerType() || T->isReferenceType())) { 1401 // Function can only change the value passed in by address. 1402 continue; 1403 } 1404 1405 // If it is a const pointer value, the function does not intend to 1406 // change the value. 1407 if (T->getPointeeType().isConstQualified()) 1408 continue; 1409 1410 // Mark the call site (LocationContext) as interesting if the value of the 1411 // argument is undefined or '0'/'NULL'. 1412 SVal BoundVal = State->getSVal(R); 1413 if (BoundVal.isUndef() || BoundVal.isZeroConstant()) { 1414 BR.markInteresting(CEnter->getCalleeContext()); 1415 return 0; 1416 } 1417 } 1418 return 0; 1419} 1420