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 = Node->getSVal(S); 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 = StoreSite->getSVal(S); 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 = LVNode->getSVal(Inner); 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 LVNode->getSVal(Inner).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 = N->getSVal(Receiver); 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 ProgramStateManager &StateMgr = N->getState()->getStateManager(); 1263 1264 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) { 1265 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 1266 const VarRegion *R = 1267 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext()); 1268 1269 // What did we load? 1270 SVal V = N->getSVal(S); 1271 1272 if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) { 1273 // Register a new visitor with the BugReport. 1274 BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>( 1275 V.castAs<KnownSVal>(), R, EnableNullFPSuppression)); 1276 } 1277 } 1278 } 1279 1280 for (const Stmt *SubStmt : Head->children()) 1281 WorkList.push_back(SubStmt); 1282 } 1283 } 1284 1285 //===----------------------------------------------------------------------===// 1286 // Visitor that tries to report interesting diagnostics from conditions. 1287 //===----------------------------------------------------------------------===// 1288 1289 /// Return the tag associated with this visitor. This tag will be used 1290 /// to make all PathDiagnosticPieces created by this visitor. 1291 const char *ConditionBRVisitor::getTag() { 1292 return "ConditionBRVisitor"; 1293 } 1294 1295 std::shared_ptr<PathDiagnosticPiece> 1296 ConditionBRVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *Prev, 1297 BugReporterContext &BRC, BugReport &BR) { 1298 auto piece = VisitNodeImpl(N, Prev, BRC, BR); 1299 if (piece) { 1300 piece->setTag(getTag()); 1301 if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get())) 1302 ev->setPrunable(true, /* override */ false); 1303 } 1304 return piece; 1305 } 1306 1307 std::shared_ptr<PathDiagnosticPiece> 1308 ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N, 1309 const ExplodedNode *Prev, 1310 BugReporterContext &BRC, BugReport &BR) { 1311 1312 ProgramPoint progPoint = N->getLocation(); 1313 ProgramStateRef CurrentState = N->getState(); 1314 ProgramStateRef PrevState = Prev->getState(); 1315 1316 // Compare the GDMs of the state, because that is where constraints 1317 // are managed. Note that ensure that we only look at nodes that 1318 // were generated by the analyzer engine proper, not checkers. 1319 if (CurrentState->getGDM().getRoot() == 1320 PrevState->getGDM().getRoot()) 1321 return nullptr; 1322 1323 // If an assumption was made on a branch, it should be caught 1324 // here by looking at the state transition. 1325 if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) { 1326 const CFGBlock *srcBlk = BE->getSrc(); 1327 if (const Stmt *term = srcBlk->getTerminator()) 1328 return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC); 1329 return nullptr; 1330 } 1331 1332 if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) { 1333 // FIXME: Assuming that BugReporter is a GRBugReporter is a layering 1334 // violation. 1335 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags = 1336 cast<GRBugReporter>(BRC.getBugReporter()). 1337 getEngine().geteagerlyAssumeBinOpBifurcationTags(); 1338 1339 const ProgramPointTag *tag = PS->getTag(); 1340 if (tag == tags.first) 1341 return VisitTrueTest(cast<Expr>(PS->getStmt()), true, 1342 BRC, BR, N); 1343 if (tag == tags.second) 1344 return VisitTrueTest(cast<Expr>(PS->getStmt()), false, 1345 BRC, BR, N); 1346 1347 return nullptr; 1348 } 1349 1350 return nullptr; 1351 } 1352 1353 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTerminator( 1354 const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk, 1355 const CFGBlock *dstBlk, BugReport &R, BugReporterContext &BRC) { 1356 const Expr *Cond = nullptr; 1357 1358 // In the code below, Term is a CFG terminator and Cond is a branch condition 1359 // expression upon which the decision is made on this terminator. 1360 // 1361 // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator, 1362 // and "x == 0" is the respective condition. 1363 // 1364 // Another example: in "if (x && y)", we've got two terminators and two 1365 // conditions due to short-circuit nature of operator "&&": 1366 // 1. The "if (x && y)" statement is a terminator, 1367 // and "y" is the respective condition. 1368 // 2. Also "x && ..." is another terminator, 1369 // and "x" is its condition. 1370 1371 switch (Term->getStmtClass()) { 1372 // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit 1373 // more tricky because there are more than two branches to account for. 1374 default: 1375 return nullptr; 1376 case Stmt::IfStmtClass: 1377 Cond = cast<IfStmt>(Term)->getCond(); 1378 break; 1379 case Stmt::ConditionalOperatorClass: 1380 Cond = cast<ConditionalOperator>(Term)->getCond(); 1381 break; 1382 case Stmt::BinaryOperatorClass: 1383 // When we encounter a logical operator (&& or ||) as a CFG terminator, 1384 // then the condition is actually its LHS; otherwise, we'd encounter 1385 // the parent, such as if-statement, as a terminator. 1386 const auto *BO = cast<BinaryOperator>(Term); 1387 assert(BO->isLogicalOp() && 1388 "CFG terminator is not a short-circuit operator!"); 1389 Cond = BO->getLHS(); 1390 break; 1391 } 1392 1393 // However, when we encounter a logical operator as a branch condition, 1394 // then the condition is actually its RHS, because LHS would be 1395 // the condition for the logical operator terminator. 1396 while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) { 1397 if (!InnerBO->isLogicalOp()) 1398 break; 1399 Cond = InnerBO->getRHS()->IgnoreParens(); 1400 } 1401 1402 assert(Cond); 1403 assert(srcBlk->succ_size() == 2); 1404 const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk; 1405 return VisitTrueTest(Cond, tookTrue, BRC, R, N); 1406 } 1407 1408 std::shared_ptr<PathDiagnosticPiece> 1409 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, bool tookTrue, 1410 BugReporterContext &BRC, BugReport &R, 1411 const ExplodedNode *N) { 1412 // These will be modified in code below, but we need to preserve the original 1413 // values in case we want to throw the generic message. 1414 const Expr *CondTmp = Cond; 1415 bool tookTrueTmp = tookTrue; 1416 1417 while (true) { 1418 CondTmp = CondTmp->IgnoreParenCasts(); 1419 switch (CondTmp->getStmtClass()) { 1420 default: 1421 break; 1422 case Stmt::BinaryOperatorClass: 1423 if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp), 1424 tookTrueTmp, BRC, R, N)) 1425 return P; 1426 break; 1427 case Stmt::DeclRefExprClass: 1428 if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp), 1429 tookTrueTmp, BRC, R, N)) 1430 return P; 1431 break; 1432 case Stmt::UnaryOperatorClass: { 1433 const UnaryOperator *UO = cast<UnaryOperator>(CondTmp); 1434 if (UO->getOpcode() == UO_LNot) { 1435 tookTrueTmp = !tookTrueTmp; 1436 CondTmp = UO->getSubExpr(); 1437 continue; 1438 } 1439 break; 1440 } 1441 } 1442 break; 1443 } 1444 1445 // Condition too complex to explain? Just say something so that the user 1446 // knew we've made some path decision at this point. 1447 const LocationContext *LCtx = N->getLocationContext(); 1448 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx); 1449 if (!Loc.isValid() || !Loc.asLocation().isValid()) 1450 return nullptr; 1451 1452 return std::make_shared<PathDiagnosticEventPiece>( 1453 Loc, tookTrue ? GenericTrueMessage : GenericFalseMessage); 1454 } 1455 1456 bool ConditionBRVisitor::patternMatch(const Expr *Ex, 1457 const Expr *ParentEx, 1458 raw_ostream &Out, 1459 BugReporterContext &BRC, 1460 BugReport &report, 1461 const ExplodedNode *N, 1462 Optional<bool> &prunable) { 1463 const Expr *OriginalExpr = Ex; 1464 Ex = Ex->IgnoreParenCasts(); 1465 1466 // Use heuristics to determine if Ex is a macro expending to a literal and 1467 // if so, use the macro's name. 1468 SourceLocation LocStart = Ex->getLocStart(); 1469 SourceLocation LocEnd = Ex->getLocEnd(); 1470 if (LocStart.isMacroID() && LocEnd.isMacroID() && 1471 (isa<GNUNullExpr>(Ex) || 1472 isa<ObjCBoolLiteralExpr>(Ex) || 1473 isa<CXXBoolLiteralExpr>(Ex) || 1474 isa<IntegerLiteral>(Ex) || 1475 isa<FloatingLiteral>(Ex))) { 1476 1477 StringRef StartName = Lexer::getImmediateMacroNameForDiagnostics(LocStart, 1478 BRC.getSourceManager(), BRC.getASTContext().getLangOpts()); 1479 StringRef EndName = Lexer::getImmediateMacroNameForDiagnostics(LocEnd, 1480 BRC.getSourceManager(), BRC.getASTContext().getLangOpts()); 1481 bool beginAndEndAreTheSameMacro = StartName.equals(EndName); 1482 1483 bool partOfParentMacro = false; 1484 if (ParentEx->getLocStart().isMacroID()) { 1485 StringRef PName = Lexer::getImmediateMacroNameForDiagnostics( 1486 ParentEx->getLocStart(), BRC.getSourceManager(), 1487 BRC.getASTContext().getLangOpts()); 1488 partOfParentMacro = PName.equals(StartName); 1489 } 1490 1491 if (beginAndEndAreTheSameMacro && !partOfParentMacro ) { 1492 // Get the location of the macro name as written by the caller. 1493 SourceLocation Loc = LocStart; 1494 while (LocStart.isMacroID()) { 1495 Loc = LocStart; 1496 LocStart = BRC.getSourceManager().getImmediateMacroCallerLoc(LocStart); 1497 } 1498 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 1499 Loc, BRC.getSourceManager(), BRC.getASTContext().getLangOpts()); 1500 1501 // Return the macro name. 1502 Out << MacroName; 1503 return false; 1504 } 1505 } 1506 1507 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) { 1508 const bool quotes = isa<VarDecl>(DR->getDecl()); 1509 if (quotes) { 1510 Out << '\''; 1511 const LocationContext *LCtx = N->getLocationContext(); 1512 const ProgramState *state = N->getState().get(); 1513 if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()), 1514 LCtx).getAsRegion()) { 1515 if (report.isInteresting(R)) 1516 prunable = false; 1517 else { 1518 const ProgramState *state = N->getState().get(); 1519 SVal V = state->getSVal(R); 1520 if (report.isInteresting(V)) 1521 prunable = false; 1522 } 1523 } 1524 } 1525 Out << DR->getDecl()->getDeclName().getAsString(); 1526 if (quotes) 1527 Out << '\''; 1528 return quotes; 1529 } 1530 1531 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) { 1532 QualType OriginalTy = OriginalExpr->getType(); 1533 if (OriginalTy->isPointerType()) { 1534 if (IL->getValue() == 0) { 1535 Out << "null"; 1536 return false; 1537 } 1538 } 1539 else if (OriginalTy->isObjCObjectPointerType()) { 1540 if (IL->getValue() == 0) { 1541 Out << "nil"; 1542 return false; 1543 } 1544 } 1545 1546 Out << IL->getValue(); 1547 return false; 1548 } 1549 1550 return false; 1551 } 1552 1553 std::shared_ptr<PathDiagnosticPiece> 1554 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const BinaryOperator *BExpr, 1555 const bool tookTrue, BugReporterContext &BRC, 1556 BugReport &R, const ExplodedNode *N) { 1557 1558 bool shouldInvert = false; 1559 Optional<bool> shouldPrune; 1560 1561 SmallString<128> LhsString, RhsString; 1562 { 1563 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString); 1564 const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS, 1565 BRC, R, N, shouldPrune); 1566 const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS, 1567 BRC, R, N, shouldPrune); 1568 1569 shouldInvert = !isVarLHS && isVarRHS; 1570 } 1571 1572 BinaryOperator::Opcode Op = BExpr->getOpcode(); 1573 1574 if (BinaryOperator::isAssignmentOp(Op)) { 1575 // For assignment operators, all that we care about is that the LHS 1576 // evaluates to "true" or "false". 1577 return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue, 1578 BRC, R, N); 1579 } 1580 1581 // For non-assignment operations, we require that we can understand 1582 // both the LHS and RHS. 1583 if (LhsString.empty() || RhsString.empty() || 1584 !BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp) 1585 return nullptr; 1586 1587 // Should we invert the strings if the LHS is not a variable name? 1588 SmallString<256> buf; 1589 llvm::raw_svector_ostream Out(buf); 1590 Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is "; 1591 1592 // Do we need to invert the opcode? 1593 if (shouldInvert) 1594 switch (Op) { 1595 default: break; 1596 case BO_LT: Op = BO_GT; break; 1597 case BO_GT: Op = BO_LT; break; 1598 case BO_LE: Op = BO_GE; break; 1599 case BO_GE: Op = BO_LE; break; 1600 } 1601 1602 if (!tookTrue) 1603 switch (Op) { 1604 case BO_EQ: Op = BO_NE; break; 1605 case BO_NE: Op = BO_EQ; break; 1606 case BO_LT: Op = BO_GE; break; 1607 case BO_GT: Op = BO_LE; break; 1608 case BO_LE: Op = BO_GT; break; 1609 case BO_GE: Op = BO_LT; break; 1610 default: 1611 return nullptr; 1612 } 1613 1614 switch (Op) { 1615 case BO_EQ: 1616 Out << "equal to "; 1617 break; 1618 case BO_NE: 1619 Out << "not equal to "; 1620 break; 1621 default: 1622 Out << BinaryOperator::getOpcodeStr(Op) << ' '; 1623 break; 1624 } 1625 1626 Out << (shouldInvert ? LhsString : RhsString); 1627 const LocationContext *LCtx = N->getLocationContext(); 1628 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx); 1629 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str()); 1630 if (shouldPrune.hasValue()) 1631 event->setPrunable(shouldPrune.getValue()); 1632 return event; 1633 } 1634 1635 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitConditionVariable( 1636 StringRef LhsString, const Expr *CondVarExpr, const bool tookTrue, 1637 BugReporterContext &BRC, BugReport &report, const ExplodedNode *N) { 1638 // FIXME: If there's already a constraint tracker for this variable, 1639 // we shouldn't emit anything here (c.f. the double note in 1640 // test/Analysis/inlining/path-notes.c) 1641 SmallString<256> buf; 1642 llvm::raw_svector_ostream Out(buf); 1643 Out << "Assuming " << LhsString << " is "; 1644 1645 QualType Ty = CondVarExpr->getType(); 1646 1647 if (Ty->isPointerType()) 1648 Out << (tookTrue ? "not null" : "null"); 1649 else if (Ty->isObjCObjectPointerType()) 1650 Out << (tookTrue ? "not nil" : "nil"); 1651 else if (Ty->isBooleanType()) 1652 Out << (tookTrue ? "true" : "false"); 1653 else if (Ty->isIntegralOrEnumerationType()) 1654 Out << (tookTrue ? "non-zero" : "zero"); 1655 else 1656 return nullptr; 1657 1658 const LocationContext *LCtx = N->getLocationContext(); 1659 PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx); 1660 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str()); 1661 1662 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) { 1663 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 1664 const ProgramState *state = N->getState().get(); 1665 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) { 1666 if (report.isInteresting(R)) 1667 event->setPrunable(false); 1668 } 1669 } 1670 } 1671 1672 return event; 1673 } 1674 1675 std::shared_ptr<PathDiagnosticPiece> 1676 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const DeclRefExpr *DR, 1677 const bool tookTrue, BugReporterContext &BRC, 1678 BugReport &report, const ExplodedNode *N) { 1679 1680 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()); 1681 if (!VD) 1682 return nullptr; 1683 1684 SmallString<256> Buf; 1685 llvm::raw_svector_ostream Out(Buf); 1686 1687 Out << "Assuming '" << VD->getDeclName() << "' is "; 1688 1689 QualType VDTy = VD->getType(); 1690 1691 if (VDTy->isPointerType()) 1692 Out << (tookTrue ? "non-null" : "null"); 1693 else if (VDTy->isObjCObjectPointerType()) 1694 Out << (tookTrue ? "non-nil" : "nil"); 1695 else if (VDTy->isScalarType()) 1696 Out << (tookTrue ? "not equal to 0" : "0"); 1697 else 1698 return nullptr; 1699 1700 const LocationContext *LCtx = N->getLocationContext(); 1701 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx); 1702 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str()); 1703 1704 const ProgramState *state = N->getState().get(); 1705 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) { 1706 if (report.isInteresting(R)) 1707 event->setPrunable(false); 1708 else { 1709 SVal V = state->getSVal(R); 1710 if (report.isInteresting(V)) 1711 event->setPrunable(false); 1712 } 1713 } 1714 return std::move(event); 1715 } 1716 1717 const char *const ConditionBRVisitor::GenericTrueMessage = 1718 "Assuming the condition is true"; 1719 const char *const ConditionBRVisitor::GenericFalseMessage = 1720 "Assuming the condition is false"; 1721 1722 bool ConditionBRVisitor::isPieceMessageGeneric( 1723 const PathDiagnosticPiece *Piece) { 1724 return Piece->getString() == GenericTrueMessage || 1725 Piece->getString() == GenericFalseMessage; 1726 } 1727 1728 std::unique_ptr<PathDiagnosticPiece> 1729 LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC, 1730 const ExplodedNode *N, 1731 BugReport &BR) { 1732 // Here we suppress false positives coming from system headers. This list is 1733 // based on known issues. 1734 ExprEngine &Eng = BRC.getBugReporter().getEngine(); 1735 AnalyzerOptions &Options = Eng.getAnalysisManager().options; 1736 const Decl *D = N->getLocationContext()->getDecl(); 1737 1738 if (AnalysisDeclContext::isInStdNamespace(D)) { 1739 // Skip reports within the 'std' namespace. Although these can sometimes be 1740 // the user's fault, we currently don't report them very well, and 1741 // Note that this will not help for any other data structure libraries, like 1742 // TR1, Boost, or llvm/ADT. 1743 if (Options.shouldSuppressFromCXXStandardLibrary()) { 1744 BR.markInvalid(getTag(), nullptr); 1745 return nullptr; 1746 1747 } else { 1748 // If the complete 'std' suppression is not enabled, suppress reports 1749 // from the 'std' namespace that are known to produce false positives. 1750 1751 // The analyzer issues a false use-after-free when std::list::pop_front 1752 // or std::list::pop_back are called multiple times because we cannot 1753 // reason about the internal invariants of the data structure. 1754 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 1755 const CXXRecordDecl *CD = MD->getParent(); 1756 if (CD->getName() == "list") { 1757 BR.markInvalid(getTag(), nullptr); 1758 return nullptr; 1759 } 1760 } 1761 1762 // The analyzer issues a false positive when the constructor of 1763 // std::__independent_bits_engine from algorithms is used. 1764 if (const CXXConstructorDecl *MD = dyn_cast<CXXConstructorDecl>(D)) { 1765 const CXXRecordDecl *CD = MD->getParent(); 1766 if (CD->getName() == "__independent_bits_engine") { 1767 BR.markInvalid(getTag(), nullptr); 1768 return nullptr; 1769 } 1770 } 1771 1772 for (const LocationContext *LCtx = N->getLocationContext(); LCtx; 1773 LCtx = LCtx->getParent()) { 1774 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl()); 1775 if (!MD) 1776 continue; 1777 1778 const CXXRecordDecl *CD = MD->getParent(); 1779 // The analyzer issues a false positive on 1780 // std::basic_string<uint8_t> v; v.push_back(1); 1781 // and 1782 // std::u16string s; s += u'a'; 1783 // because we cannot reason about the internal invariants of the 1784 // data structure. 1785 if (CD->getName() == "basic_string") { 1786 BR.markInvalid(getTag(), nullptr); 1787 return nullptr; 1788 } 1789 1790 // The analyzer issues a false positive on 1791 // std::shared_ptr<int> p(new int(1)); p = nullptr; 1792 // because it does not reason properly about temporary destructors. 1793 if (CD->getName() == "shared_ptr") { 1794 BR.markInvalid(getTag(), nullptr); 1795 return nullptr; 1796 } 1797 } 1798 } 1799 } 1800 1801 // Skip reports within the sys/queue.h macros as we do not have the ability to 1802 // reason about data structure shapes. 1803 SourceManager &SM = BRC.getSourceManager(); 1804 FullSourceLoc Loc = BR.getLocation(SM).asLocation(); 1805 while (Loc.isMacroID()) { 1806 Loc = Loc.getSpellingLoc(); 1807 if (SM.getFilename(Loc).endswith("sys/queue.h")) { 1808 BR.markInvalid(getTag(), nullptr); 1809 return nullptr; 1810 } 1811 } 1812 1813 return nullptr; 1814 } 1815 1816 std::shared_ptr<PathDiagnosticPiece> 1817 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N, 1818 const ExplodedNode *PrevN, 1819 BugReporterContext &BRC, BugReport &BR) { 1820 1821 ProgramStateRef State = N->getState(); 1822 ProgramPoint ProgLoc = N->getLocation(); 1823 1824 // We are only interested in visiting CallEnter nodes. 1825 Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>(); 1826 if (!CEnter) 1827 return nullptr; 1828 1829 // Check if one of the arguments is the region the visitor is tracking. 1830 CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager(); 1831 CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State); 1832 unsigned Idx = 0; 1833 ArrayRef<ParmVarDecl*> parms = Call->parameters(); 1834 1835 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 1836 I != E; ++I, ++Idx) { 1837 const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion(); 1838 1839 // Are we tracking the argument or its subregion? 1840 if ( !ArgReg || !R->isSubRegionOf(ArgReg->StripCasts())) 1841 continue; 1842 1843 // Check the function parameter type. 1844 const ParmVarDecl *ParamDecl = *I; 1845 assert(ParamDecl && "Formal parameter has no decl?"); 1846 QualType T = ParamDecl->getType(); 1847 1848 if (!(T->isAnyPointerType() || T->isReferenceType())) { 1849 // Function can only change the value passed in by address. 1850 continue; 1851 } 1852 1853 // If it is a const pointer value, the function does not intend to 1854 // change the value. 1855 if (T->getPointeeType().isConstQualified()) 1856 continue; 1857 1858 // Mark the call site (LocationContext) as interesting if the value of the 1859 // argument is undefined or '0'/'NULL'. 1860 SVal BoundVal = State->getSVal(R); 1861 if (BoundVal.isUndef() || BoundVal.isZeroConstant()) { 1862 BR.markInteresting(CEnter->getCalleeContext()); 1863 return nullptr; 1864 } 1865 } 1866 return nullptr; 1867 } 1868 1869 std::shared_ptr<PathDiagnosticPiece> 1870 CXXSelfAssignmentBRVisitor::VisitNode(const ExplodedNode *Succ, 1871 const ExplodedNode *Pred, 1872 BugReporterContext &BRC, BugReport &BR) { 1873 if (Satisfied) 1874 return nullptr; 1875 1876 auto Edge = Succ->getLocation().getAs<BlockEdge>(); 1877 if (!Edge.hasValue()) 1878 return nullptr; 1879 1880 auto Tag = Edge->getTag(); 1881 if (!Tag) 1882 return nullptr; 1883 1884 if (Tag->getTagDescription() != "cplusplus.SelfAssignment") 1885 return nullptr; 1886 1887 Satisfied = true; 1888 1889 const auto *Met = 1890 dyn_cast<CXXMethodDecl>(Succ->getCodeDecl().getAsFunction()); 1891 assert(Met && "Not a C++ method."); 1892 assert((Met->isCopyAssignmentOperator() || Met->isMoveAssignmentOperator()) && 1893 "Not a copy/move assignment operator."); 1894 1895 const auto *LCtx = Edge->getLocationContext(); 1896 1897 const auto &State = Succ->getState(); 1898 auto &SVB = State->getStateManager().getSValBuilder(); 1899 1900 const auto Param = 1901 State->getSVal(State->getRegion(Met->getParamDecl(0), LCtx)); 1902 const auto This = 1903 State->getSVal(SVB.getCXXThis(Met, LCtx->getCurrentStackFrame())); 1904 1905 auto L = PathDiagnosticLocation::create(Met, BRC.getSourceManager()); 1906 1907 if (!L.isValid() || !L.asLocation().isValid()) 1908 return nullptr; 1909 1910 SmallString<256> Buf; 1911 llvm::raw_svector_ostream Out(Buf); 1912 1913 Out << "Assuming " << Met->getParamDecl(0)->getName() << 1914 ((Param == This) ? " == " : " != ") << "*this"; 1915 1916 auto Piece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str()); 1917 Piece->addRange(Met->getSourceRange()); 1918 1919 return std::move(Piece); 1920 } 1921