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