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