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