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