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 SourceLocation BugLoc = BugPoint->getStmt()->getLocStart(); 925 926 // Suppress reports unless we are in that same macro. 927 if (!BugLoc.isMacroID() || 928 getMacroName(BugLoc, BRC) != getMacroName(TerminatorLoc, BRC)) { 929 BR.markInvalid("Suppress Macro IDC", CurLC); 930 } 931 return nullptr; 932 } 933 } 934 return nullptr; 935 } 936 937 static const MemRegion *getLocationRegionIfReference(const Expr *E, 938 const ExplodedNode *N) { 939 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 940 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 941 if (!VD->getType()->isReferenceType()) 942 return nullptr; 943 ProgramStateManager &StateMgr = N->getState()->getStateManager(); 944 MemRegionManager &MRMgr = StateMgr.getRegionManager(); 945 return MRMgr.getVarRegion(VD, N->getLocationContext()); 946 } 947 } 948 949 // FIXME: This does not handle other kinds of null references, 950 // for example, references from FieldRegions: 951 // struct Wrapper { int &ref; }; 952 // Wrapper w = { *(int *)0 }; 953 // w.ref = 1; 954 955 return nullptr; 956 } 957 958 static const Expr *peelOffOuterExpr(const Expr *Ex, 959 const ExplodedNode *N) { 960 Ex = Ex->IgnoreParenCasts(); 961 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex)) 962 return peelOffOuterExpr(EWC->getSubExpr(), N); 963 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Ex)) 964 return peelOffOuterExpr(OVE->getSourceExpr(), N); 965 if (auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) { 966 auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm()); 967 if (PropRef && PropRef->isMessagingGetter()) { 968 const Expr *GetterMessageSend = 969 POE->getSemanticExpr(POE->getNumSemanticExprs() - 1); 970 assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts())); 971 return peelOffOuterExpr(GetterMessageSend, N); 972 } 973 } 974 975 // Peel off the ternary operator. 976 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Ex)) { 977 // Find a node where the branching occurred and find out which branch 978 // we took (true/false) by looking at the ExplodedGraph. 979 const ExplodedNode *NI = N; 980 do { 981 ProgramPoint ProgPoint = NI->getLocation(); 982 if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) { 983 const CFGBlock *srcBlk = BE->getSrc(); 984 if (const Stmt *term = srcBlk->getTerminator()) { 985 if (term == CO) { 986 bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst()); 987 if (TookTrueBranch) 988 return peelOffOuterExpr(CO->getTrueExpr(), N); 989 else 990 return peelOffOuterExpr(CO->getFalseExpr(), N); 991 } 992 } 993 } 994 NI = NI->getFirstPred(); 995 } while (NI); 996 } 997 return Ex; 998 } 999 1000 /// Walk through nodes until we get one that matches the statement exactly. 1001 /// Alternately, if we hit a known lvalue for the statement, we know we've 1002 /// gone too far (though we can likely track the lvalue better anyway). 1003 static const ExplodedNode* findNodeForStatement(const ExplodedNode *N, 1004 const Stmt *S, 1005 const Expr *Inner) { 1006 do { 1007 const ProgramPoint &pp = N->getLocation(); 1008 if (auto ps = pp.getAs<StmtPoint>()) { 1009 if (ps->getStmt() == S || ps->getStmt() == Inner) 1010 break; 1011 } else if (auto CEE = pp.getAs<CallExitEnd>()) { 1012 if (CEE->getCalleeContext()->getCallSite() == S || 1013 CEE->getCalleeContext()->getCallSite() == Inner) 1014 break; 1015 } 1016 N = N->getFirstPred(); 1017 } while (N); 1018 return N; 1019 } 1020 1021 /// Find the ExplodedNode where the lvalue (the value of 'Ex') 1022 /// was computed. 1023 static const ExplodedNode* findNodeForExpression(const ExplodedNode *N, 1024 const Expr *Inner) { 1025 while (N) { 1026 if (auto P = N->getLocation().getAs<PostStmt>()) { 1027 if (P->getStmt() == Inner) 1028 break; 1029 } 1030 N = N->getFirstPred(); 1031 } 1032 assert(N && "Unable to find the lvalue node."); 1033 return N; 1034 1035 } 1036 1037 /// Performing operator `&' on an lvalue expression is essentially a no-op. 1038 /// Then, if we are taking addresses of fields or elements, these are also 1039 /// unlikely to matter. 1040 static const Expr* peelOfOuterAddrOf(const Expr* Ex) { 1041 Ex = Ex->IgnoreParenCasts(); 1042 1043 // FIXME: There's a hack in our Store implementation that always computes 1044 // field offsets around null pointers as if they are always equal to 0. 1045 // The idea here is to report accesses to fields as null dereferences 1046 // even though the pointer value that's being dereferenced is actually 1047 // the offset of the field rather than exactly 0. 1048 // See the FIXME in StoreManager's getLValueFieldOrIvar() method. 1049 // This code interacts heavily with this hack; otherwise the value 1050 // would not be null at all for most fields, so we'd be unable to track it. 1051 if (const auto *Op = dyn_cast<UnaryOperator>(Ex)) 1052 if (Op->getOpcode() == UO_AddrOf && Op->getSubExpr()->isLValue()) 1053 if (const Expr *DerefEx = bugreporter::getDerefExpr(Op->getSubExpr())) 1054 return DerefEx; 1055 return Ex; 1056 1057 } 1058 1059 bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N, 1060 const Stmt *S, 1061 BugReport &report, bool IsArg, 1062 bool EnableNullFPSuppression) { 1063 if (!S || !N) 1064 return false; 1065 1066 if (const auto *Ex = dyn_cast<Expr>(S)) 1067 S = peelOffOuterExpr(Ex, N); 1068 1069 const Expr *Inner = nullptr; 1070 if (const auto *Ex = dyn_cast<Expr>(S)) { 1071 Ex = peelOfOuterAddrOf(Ex); 1072 Ex = Ex->IgnoreParenCasts(); 1073 1074 if (Ex && (ExplodedGraph::isInterestingLValueExpr(Ex) 1075 || CallEvent::isCallStmt(Ex))) 1076 Inner = Ex; 1077 } 1078 1079 if (IsArg && !Inner) { 1080 assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call"); 1081 } else { 1082 N = findNodeForStatement(N, S, Inner); 1083 if (!N) 1084 return false; 1085 } 1086 1087 ProgramStateRef state = N->getState(); 1088 1089 // The message send could be nil due to the receiver being nil. 1090 // At this point in the path, the receiver should be live since we are at the 1091 // message send expr. If it is nil, start tracking it. 1092 if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N)) 1093 trackNullOrUndefValue(N, Receiver, report, /* IsArg=*/ false, 1094 EnableNullFPSuppression); 1095 1096 // See if the expression we're interested refers to a variable. 1097 // If so, we can track both its contents and constraints on its value. 1098 if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) { 1099 const ExplodedNode *LVNode = findNodeForExpression(N, Inner); 1100 ProgramStateRef LVState = LVNode->getState(); 1101 SVal LVal = LVNode->getSVal(Inner); 1102 1103 const MemRegion *RR = getLocationRegionIfReference(Inner, N); 1104 bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue(); 1105 1106 // If this is a C++ reference to a null pointer, we are tracking the 1107 // pointer. In addition, we should find the store at which the reference 1108 // got initialized. 1109 if (RR && !LVIsNull) { 1110 if (auto KV = LVal.getAs<KnownSVal>()) 1111 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>( 1112 *KV, RR, EnableNullFPSuppression)); 1113 } 1114 1115 // In case of C++ references, we want to differentiate between a null 1116 // reference and reference to null pointer. 1117 // If the LVal is null, check if we are dealing with null reference. 1118 // For those, we want to track the location of the reference. 1119 const MemRegion *R = (RR && LVIsNull) ? RR : 1120 LVNode->getSVal(Inner).getAsRegion(); 1121 1122 if (R) { 1123 // Mark both the variable region and its contents as interesting. 1124 SVal V = LVState->getRawSVal(loc::MemRegionVal(R)); 1125 1126 report.markInteresting(R); 1127 report.markInteresting(V); 1128 report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R)); 1129 1130 // If the contents are symbolic, find out when they became null. 1131 if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true)) 1132 report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>( 1133 V.castAs<DefinedSVal>(), false)); 1134 1135 // Add visitor, which will suppress inline defensive checks. 1136 if (auto DV = V.getAs<DefinedSVal>()) { 1137 if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() && 1138 EnableNullFPSuppression) { 1139 report.addVisitor( 1140 llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV, 1141 LVNode)); 1142 } 1143 } 1144 1145 if (auto KV = V.getAs<KnownSVal>()) 1146 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>( 1147 *KV, R, EnableNullFPSuppression)); 1148 return true; 1149 } 1150 } 1151 1152 // If the expression is not an "lvalue expression", we can still 1153 // track the constraints on its contents. 1154 SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext()); 1155 1156 // If the value came from an inlined function call, we should at least make 1157 // sure that function isn't pruned in our output. 1158 if (const auto *E = dyn_cast<Expr>(S)) 1159 S = E->IgnoreParenCasts(); 1160 1161 ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression); 1162 1163 // Uncomment this to find cases where we aren't properly getting the 1164 // base value that was dereferenced. 1165 // assert(!V.isUnknownOrUndef()); 1166 // Is it a symbolic value? 1167 if (auto L = V.getAs<loc::MemRegionVal>()) { 1168 report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion())); 1169 1170 // At this point we are dealing with the region's LValue. 1171 // However, if the rvalue is a symbolic region, we should track it as well. 1172 // Try to use the correct type when looking up the value. 1173 SVal RVal; 1174 if (const auto *E = dyn_cast<Expr>(S)) 1175 RVal = state->getRawSVal(L.getValue(), E->getType()); 1176 else 1177 RVal = state->getSVal(L->getRegion()); 1178 1179 if (auto KV = RVal.getAs<KnownSVal>()) 1180 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>( 1181 *KV, L->getRegion(), EnableNullFPSuppression)); 1182 1183 const MemRegion *RegionRVal = RVal.getAsRegion(); 1184 if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) { 1185 report.markInteresting(RegionRVal); 1186 report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>( 1187 loc::MemRegionVal(RegionRVal), false)); 1188 } 1189 } 1190 return true; 1191 } 1192 1193 const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S, 1194 const ExplodedNode *N) { 1195 const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S); 1196 if (!ME) 1197 return nullptr; 1198 if (const Expr *Receiver = ME->getInstanceReceiver()) { 1199 ProgramStateRef state = N->getState(); 1200 SVal V = N->getSVal(Receiver); 1201 if (state->isNull(V).isConstrainedTrue()) 1202 return Receiver; 1203 } 1204 return nullptr; 1205 } 1206 1207 std::shared_ptr<PathDiagnosticPiece> 1208 NilReceiverBRVisitor::VisitNode(const ExplodedNode *N, 1209 const ExplodedNode *PrevN, 1210 BugReporterContext &BRC, BugReport &BR) { 1211 Optional<PreStmt> P = N->getLocationAs<PreStmt>(); 1212 if (!P) 1213 return nullptr; 1214 1215 const Stmt *S = P->getStmt(); 1216 const Expr *Receiver = getNilReceiver(S, N); 1217 if (!Receiver) 1218 return nullptr; 1219 1220 llvm::SmallString<256> Buf; 1221 llvm::raw_svector_ostream OS(Buf); 1222 1223 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) { 1224 OS << "'"; 1225 ME->getSelector().print(OS); 1226 OS << "' not called"; 1227 } 1228 else { 1229 OS << "No method is called"; 1230 } 1231 OS << " because the receiver is nil"; 1232 1233 // The receiver was nil, and hence the method was skipped. 1234 // Register a BugReporterVisitor to issue a message telling us how 1235 // the receiver was null. 1236 bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false, 1237 /*EnableNullFPSuppression*/ false); 1238 // Issue a message saying that the method was skipped. 1239 PathDiagnosticLocation L(Receiver, BRC.getSourceManager(), 1240 N->getLocationContext()); 1241 return std::make_shared<PathDiagnosticEventPiece>(L, OS.str()); 1242 } 1243 1244 // Registers every VarDecl inside a Stmt with a last store visitor. 1245 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR, 1246 const Stmt *S, 1247 bool EnableNullFPSuppression) { 1248 const ExplodedNode *N = BR.getErrorNode(); 1249 std::deque<const Stmt *> WorkList; 1250 WorkList.push_back(S); 1251 1252 while (!WorkList.empty()) { 1253 const Stmt *Head = WorkList.front(); 1254 WorkList.pop_front(); 1255 1256 ProgramStateManager &StateMgr = N->getState()->getStateManager(); 1257 1258 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) { 1259 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 1260 const VarRegion *R = 1261 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext()); 1262 1263 // What did we load? 1264 SVal V = N->getSVal(S); 1265 1266 if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) { 1267 // Register a new visitor with the BugReport. 1268 BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>( 1269 V.castAs<KnownSVal>(), R, EnableNullFPSuppression)); 1270 } 1271 } 1272 } 1273 1274 for (const Stmt *SubStmt : Head->children()) 1275 WorkList.push_back(SubStmt); 1276 } 1277 } 1278 1279 //===----------------------------------------------------------------------===// 1280 // Visitor that tries to report interesting diagnostics from conditions. 1281 //===----------------------------------------------------------------------===// 1282 1283 /// Return the tag associated with this visitor. This tag will be used 1284 /// to make all PathDiagnosticPieces created by this visitor. 1285 const char *ConditionBRVisitor::getTag() { 1286 return "ConditionBRVisitor"; 1287 } 1288 1289 std::shared_ptr<PathDiagnosticPiece> 1290 ConditionBRVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *Prev, 1291 BugReporterContext &BRC, BugReport &BR) { 1292 auto piece = VisitNodeImpl(N, Prev, BRC, BR); 1293 if (piece) { 1294 piece->setTag(getTag()); 1295 if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get())) 1296 ev->setPrunable(true, /* override */ false); 1297 } 1298 return piece; 1299 } 1300 1301 std::shared_ptr<PathDiagnosticPiece> 1302 ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N, 1303 const ExplodedNode *Prev, 1304 BugReporterContext &BRC, BugReport &BR) { 1305 1306 ProgramPoint progPoint = N->getLocation(); 1307 ProgramStateRef CurrentState = N->getState(); 1308 ProgramStateRef PrevState = Prev->getState(); 1309 1310 // Compare the GDMs of the state, because that is where constraints 1311 // are managed. Note that ensure that we only look at nodes that 1312 // were generated by the analyzer engine proper, not checkers. 1313 if (CurrentState->getGDM().getRoot() == 1314 PrevState->getGDM().getRoot()) 1315 return nullptr; 1316 1317 // If an assumption was made on a branch, it should be caught 1318 // here by looking at the state transition. 1319 if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) { 1320 const CFGBlock *srcBlk = BE->getSrc(); 1321 if (const Stmt *term = srcBlk->getTerminator()) 1322 return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC); 1323 return nullptr; 1324 } 1325 1326 if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) { 1327 // FIXME: Assuming that BugReporter is a GRBugReporter is a layering 1328 // violation. 1329 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags = 1330 cast<GRBugReporter>(BRC.getBugReporter()). 1331 getEngine().geteagerlyAssumeBinOpBifurcationTags(); 1332 1333 const ProgramPointTag *tag = PS->getTag(); 1334 if (tag == tags.first) 1335 return VisitTrueTest(cast<Expr>(PS->getStmt()), true, 1336 BRC, BR, N); 1337 if (tag == tags.second) 1338 return VisitTrueTest(cast<Expr>(PS->getStmt()), false, 1339 BRC, BR, N); 1340 1341 return nullptr; 1342 } 1343 1344 return nullptr; 1345 } 1346 1347 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTerminator( 1348 const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk, 1349 const CFGBlock *dstBlk, BugReport &R, BugReporterContext &BRC) { 1350 const Expr *Cond = nullptr; 1351 1352 // In the code below, Term is a CFG terminator and Cond is a branch condition 1353 // expression upon which the decision is made on this terminator. 1354 // 1355 // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator, 1356 // and "x == 0" is the respective condition. 1357 // 1358 // Another example: in "if (x && y)", we've got two terminators and two 1359 // conditions due to short-circuit nature of operator "&&": 1360 // 1. The "if (x && y)" statement is a terminator, 1361 // and "y" is the respective condition. 1362 // 2. Also "x && ..." is another terminator, 1363 // and "x" is its condition. 1364 1365 switch (Term->getStmtClass()) { 1366 // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit 1367 // more tricky because there are more than two branches to account for. 1368 default: 1369 return nullptr; 1370 case Stmt::IfStmtClass: 1371 Cond = cast<IfStmt>(Term)->getCond(); 1372 break; 1373 case Stmt::ConditionalOperatorClass: 1374 Cond = cast<ConditionalOperator>(Term)->getCond(); 1375 break; 1376 case Stmt::BinaryOperatorClass: 1377 // When we encounter a logical operator (&& or ||) as a CFG terminator, 1378 // then the condition is actually its LHS; otherwise, we'd encounter 1379 // the parent, such as if-statement, as a terminator. 1380 const auto *BO = cast<BinaryOperator>(Term); 1381 assert(BO->isLogicalOp() && 1382 "CFG terminator is not a short-circuit operator!"); 1383 Cond = BO->getLHS(); 1384 break; 1385 } 1386 1387 // However, when we encounter a logical operator as a branch condition, 1388 // then the condition is actually its RHS, because LHS would be 1389 // the condition for the logical operator terminator. 1390 while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) { 1391 if (!InnerBO->isLogicalOp()) 1392 break; 1393 Cond = InnerBO->getRHS()->IgnoreParens(); 1394 } 1395 1396 assert(Cond); 1397 assert(srcBlk->succ_size() == 2); 1398 const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk; 1399 return VisitTrueTest(Cond, tookTrue, BRC, R, N); 1400 } 1401 1402 std::shared_ptr<PathDiagnosticPiece> 1403 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, bool tookTrue, 1404 BugReporterContext &BRC, BugReport &R, 1405 const ExplodedNode *N) { 1406 // These will be modified in code below, but we need to preserve the original 1407 // values in case we want to throw the generic message. 1408 const Expr *CondTmp = Cond; 1409 bool tookTrueTmp = tookTrue; 1410 1411 while (true) { 1412 CondTmp = CondTmp->IgnoreParenCasts(); 1413 switch (CondTmp->getStmtClass()) { 1414 default: 1415 break; 1416 case Stmt::BinaryOperatorClass: 1417 if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp), 1418 tookTrueTmp, BRC, R, N)) 1419 return P; 1420 break; 1421 case Stmt::DeclRefExprClass: 1422 if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp), 1423 tookTrueTmp, BRC, R, N)) 1424 return P; 1425 break; 1426 case Stmt::UnaryOperatorClass: { 1427 const UnaryOperator *UO = cast<UnaryOperator>(CondTmp); 1428 if (UO->getOpcode() == UO_LNot) { 1429 tookTrueTmp = !tookTrueTmp; 1430 CondTmp = UO->getSubExpr(); 1431 continue; 1432 } 1433 break; 1434 } 1435 } 1436 break; 1437 } 1438 1439 // Condition too complex to explain? Just say something so that the user 1440 // knew we've made some path decision at this point. 1441 const LocationContext *LCtx = N->getLocationContext(); 1442 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx); 1443 if (!Loc.isValid() || !Loc.asLocation().isValid()) 1444 return nullptr; 1445 1446 return std::make_shared<PathDiagnosticEventPiece>( 1447 Loc, tookTrue ? GenericTrueMessage : GenericFalseMessage); 1448 } 1449 1450 bool ConditionBRVisitor::patternMatch(const Expr *Ex, 1451 const Expr *ParentEx, 1452 raw_ostream &Out, 1453 BugReporterContext &BRC, 1454 BugReport &report, 1455 const ExplodedNode *N, 1456 Optional<bool> &prunable) { 1457 const Expr *OriginalExpr = Ex; 1458 Ex = Ex->IgnoreParenCasts(); 1459 1460 // Use heuristics to determine if Ex is a macro expending to a literal and 1461 // if so, use the macro's name. 1462 SourceLocation LocStart = Ex->getLocStart(); 1463 SourceLocation LocEnd = Ex->getLocEnd(); 1464 if (LocStart.isMacroID() && LocEnd.isMacroID() && 1465 (isa<GNUNullExpr>(Ex) || 1466 isa<ObjCBoolLiteralExpr>(Ex) || 1467 isa<CXXBoolLiteralExpr>(Ex) || 1468 isa<IntegerLiteral>(Ex) || 1469 isa<FloatingLiteral>(Ex))) { 1470 1471 StringRef StartName = Lexer::getImmediateMacroNameForDiagnostics(LocStart, 1472 BRC.getSourceManager(), BRC.getASTContext().getLangOpts()); 1473 StringRef EndName = Lexer::getImmediateMacroNameForDiagnostics(LocEnd, 1474 BRC.getSourceManager(), BRC.getASTContext().getLangOpts()); 1475 bool beginAndEndAreTheSameMacro = StartName.equals(EndName); 1476 1477 bool partOfParentMacro = false; 1478 if (ParentEx->getLocStart().isMacroID()) { 1479 StringRef PName = Lexer::getImmediateMacroNameForDiagnostics( 1480 ParentEx->getLocStart(), BRC.getSourceManager(), 1481 BRC.getASTContext().getLangOpts()); 1482 partOfParentMacro = PName.equals(StartName); 1483 } 1484 1485 if (beginAndEndAreTheSameMacro && !partOfParentMacro ) { 1486 // Get the location of the macro name as written by the caller. 1487 SourceLocation Loc = LocStart; 1488 while (LocStart.isMacroID()) { 1489 Loc = LocStart; 1490 LocStart = BRC.getSourceManager().getImmediateMacroCallerLoc(LocStart); 1491 } 1492 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 1493 Loc, BRC.getSourceManager(), BRC.getASTContext().getLangOpts()); 1494 1495 // Return the macro name. 1496 Out << MacroName; 1497 return false; 1498 } 1499 } 1500 1501 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) { 1502 const bool quotes = isa<VarDecl>(DR->getDecl()); 1503 if (quotes) { 1504 Out << '\''; 1505 const LocationContext *LCtx = N->getLocationContext(); 1506 const ProgramState *state = N->getState().get(); 1507 if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()), 1508 LCtx).getAsRegion()) { 1509 if (report.isInteresting(R)) 1510 prunable = false; 1511 else { 1512 const ProgramState *state = N->getState().get(); 1513 SVal V = state->getSVal(R); 1514 if (report.isInteresting(V)) 1515 prunable = false; 1516 } 1517 } 1518 } 1519 Out << DR->getDecl()->getDeclName().getAsString(); 1520 if (quotes) 1521 Out << '\''; 1522 return quotes; 1523 } 1524 1525 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) { 1526 QualType OriginalTy = OriginalExpr->getType(); 1527 if (OriginalTy->isPointerType()) { 1528 if (IL->getValue() == 0) { 1529 Out << "null"; 1530 return false; 1531 } 1532 } 1533 else if (OriginalTy->isObjCObjectPointerType()) { 1534 if (IL->getValue() == 0) { 1535 Out << "nil"; 1536 return false; 1537 } 1538 } 1539 1540 Out << IL->getValue(); 1541 return false; 1542 } 1543 1544 return false; 1545 } 1546 1547 std::shared_ptr<PathDiagnosticPiece> 1548 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const BinaryOperator *BExpr, 1549 const bool tookTrue, BugReporterContext &BRC, 1550 BugReport &R, const ExplodedNode *N) { 1551 1552 bool shouldInvert = false; 1553 Optional<bool> shouldPrune; 1554 1555 SmallString<128> LhsString, RhsString; 1556 { 1557 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString); 1558 const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS, 1559 BRC, R, N, shouldPrune); 1560 const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS, 1561 BRC, R, N, shouldPrune); 1562 1563 shouldInvert = !isVarLHS && isVarRHS; 1564 } 1565 1566 BinaryOperator::Opcode Op = BExpr->getOpcode(); 1567 1568 if (BinaryOperator::isAssignmentOp(Op)) { 1569 // For assignment operators, all that we care about is that the LHS 1570 // evaluates to "true" or "false". 1571 return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue, 1572 BRC, R, N); 1573 } 1574 1575 // For non-assignment operations, we require that we can understand 1576 // both the LHS and RHS. 1577 if (LhsString.empty() || RhsString.empty() || 1578 !BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp) 1579 return nullptr; 1580 1581 // Should we invert the strings if the LHS is not a variable name? 1582 SmallString<256> buf; 1583 llvm::raw_svector_ostream Out(buf); 1584 Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is "; 1585 1586 // Do we need to invert the opcode? 1587 if (shouldInvert) 1588 switch (Op) { 1589 default: break; 1590 case BO_LT: Op = BO_GT; break; 1591 case BO_GT: Op = BO_LT; break; 1592 case BO_LE: Op = BO_GE; break; 1593 case BO_GE: Op = BO_LE; break; 1594 } 1595 1596 if (!tookTrue) 1597 switch (Op) { 1598 case BO_EQ: Op = BO_NE; break; 1599 case BO_NE: Op = BO_EQ; break; 1600 case BO_LT: Op = BO_GE; break; 1601 case BO_GT: Op = BO_LE; break; 1602 case BO_LE: Op = BO_GT; break; 1603 case BO_GE: Op = BO_LT; break; 1604 default: 1605 return nullptr; 1606 } 1607 1608 switch (Op) { 1609 case BO_EQ: 1610 Out << "equal to "; 1611 break; 1612 case BO_NE: 1613 Out << "not equal to "; 1614 break; 1615 default: 1616 Out << BinaryOperator::getOpcodeStr(Op) << ' '; 1617 break; 1618 } 1619 1620 Out << (shouldInvert ? LhsString : RhsString); 1621 const LocationContext *LCtx = N->getLocationContext(); 1622 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx); 1623 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str()); 1624 if (shouldPrune.hasValue()) 1625 event->setPrunable(shouldPrune.getValue()); 1626 return event; 1627 } 1628 1629 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitConditionVariable( 1630 StringRef LhsString, const Expr *CondVarExpr, const bool tookTrue, 1631 BugReporterContext &BRC, BugReport &report, const ExplodedNode *N) { 1632 // FIXME: If there's already a constraint tracker for this variable, 1633 // we shouldn't emit anything here (c.f. the double note in 1634 // test/Analysis/inlining/path-notes.c) 1635 SmallString<256> buf; 1636 llvm::raw_svector_ostream Out(buf); 1637 Out << "Assuming " << LhsString << " is "; 1638 1639 QualType Ty = CondVarExpr->getType(); 1640 1641 if (Ty->isPointerType()) 1642 Out << (tookTrue ? "not null" : "null"); 1643 else if (Ty->isObjCObjectPointerType()) 1644 Out << (tookTrue ? "not nil" : "nil"); 1645 else if (Ty->isBooleanType()) 1646 Out << (tookTrue ? "true" : "false"); 1647 else if (Ty->isIntegralOrEnumerationType()) 1648 Out << (tookTrue ? "non-zero" : "zero"); 1649 else 1650 return nullptr; 1651 1652 const LocationContext *LCtx = N->getLocationContext(); 1653 PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx); 1654 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str()); 1655 1656 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) { 1657 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 1658 const ProgramState *state = N->getState().get(); 1659 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) { 1660 if (report.isInteresting(R)) 1661 event->setPrunable(false); 1662 } 1663 } 1664 } 1665 1666 return event; 1667 } 1668 1669 std::shared_ptr<PathDiagnosticPiece> 1670 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const DeclRefExpr *DR, 1671 const bool tookTrue, BugReporterContext &BRC, 1672 BugReport &report, const ExplodedNode *N) { 1673 1674 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()); 1675 if (!VD) 1676 return nullptr; 1677 1678 SmallString<256> Buf; 1679 llvm::raw_svector_ostream Out(Buf); 1680 1681 Out << "Assuming '" << VD->getDeclName() << "' is "; 1682 1683 QualType VDTy = VD->getType(); 1684 1685 if (VDTy->isPointerType()) 1686 Out << (tookTrue ? "non-null" : "null"); 1687 else if (VDTy->isObjCObjectPointerType()) 1688 Out << (tookTrue ? "non-nil" : "nil"); 1689 else if (VDTy->isScalarType()) 1690 Out << (tookTrue ? "not equal to 0" : "0"); 1691 else 1692 return nullptr; 1693 1694 const LocationContext *LCtx = N->getLocationContext(); 1695 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx); 1696 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str()); 1697 1698 const ProgramState *state = N->getState().get(); 1699 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) { 1700 if (report.isInteresting(R)) 1701 event->setPrunable(false); 1702 else { 1703 SVal V = state->getSVal(R); 1704 if (report.isInteresting(V)) 1705 event->setPrunable(false); 1706 } 1707 } 1708 return std::move(event); 1709 } 1710 1711 const char *const ConditionBRVisitor::GenericTrueMessage = 1712 "Assuming the condition is true"; 1713 const char *const ConditionBRVisitor::GenericFalseMessage = 1714 "Assuming the condition is false"; 1715 1716 bool ConditionBRVisitor::isPieceMessageGeneric( 1717 const PathDiagnosticPiece *Piece) { 1718 return Piece->getString() == GenericTrueMessage || 1719 Piece->getString() == GenericFalseMessage; 1720 } 1721 1722 std::unique_ptr<PathDiagnosticPiece> 1723 LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC, 1724 const ExplodedNode *N, 1725 BugReport &BR) { 1726 // Here we suppress false positives coming from system headers. This list is 1727 // based on known issues. 1728 ExprEngine &Eng = BRC.getBugReporter().getEngine(); 1729 AnalyzerOptions &Options = Eng.getAnalysisManager().options; 1730 const Decl *D = N->getLocationContext()->getDecl(); 1731 1732 if (AnalysisDeclContext::isInStdNamespace(D)) { 1733 // Skip reports within the 'std' namespace. Although these can sometimes be 1734 // the user's fault, we currently don't report them very well, and 1735 // Note that this will not help for any other data structure libraries, like 1736 // TR1, Boost, or llvm/ADT. 1737 if (Options.shouldSuppressFromCXXStandardLibrary()) { 1738 BR.markInvalid(getTag(), nullptr); 1739 return nullptr; 1740 1741 } else { 1742 // If the complete 'std' suppression is not enabled, suppress reports 1743 // from the 'std' namespace that are known to produce false positives. 1744 1745 // The analyzer issues a false use-after-free when std::list::pop_front 1746 // or std::list::pop_back are called multiple times because we cannot 1747 // reason about the internal invariants of the data structure. 1748 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 1749 const CXXRecordDecl *CD = MD->getParent(); 1750 if (CD->getName() == "list") { 1751 BR.markInvalid(getTag(), nullptr); 1752 return nullptr; 1753 } 1754 } 1755 1756 // The analyzer issues a false positive when the constructor of 1757 // std::__independent_bits_engine from algorithms is used. 1758 if (const CXXConstructorDecl *MD = dyn_cast<CXXConstructorDecl>(D)) { 1759 const CXXRecordDecl *CD = MD->getParent(); 1760 if (CD->getName() == "__independent_bits_engine") { 1761 BR.markInvalid(getTag(), nullptr); 1762 return nullptr; 1763 } 1764 } 1765 1766 for (const LocationContext *LCtx = N->getLocationContext(); LCtx; 1767 LCtx = LCtx->getParent()) { 1768 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl()); 1769 if (!MD) 1770 continue; 1771 1772 const CXXRecordDecl *CD = MD->getParent(); 1773 // The analyzer issues a false positive on 1774 // std::basic_string<uint8_t> v; v.push_back(1); 1775 // and 1776 // std::u16string s; s += u'a'; 1777 // because we cannot reason about the internal invariants of the 1778 // data structure. 1779 if (CD->getName() == "basic_string") { 1780 BR.markInvalid(getTag(), nullptr); 1781 return nullptr; 1782 } 1783 1784 // The analyzer issues a false positive on 1785 // std::shared_ptr<int> p(new int(1)); p = nullptr; 1786 // because it does not reason properly about temporary destructors. 1787 if (CD->getName() == "shared_ptr") { 1788 BR.markInvalid(getTag(), nullptr); 1789 return nullptr; 1790 } 1791 } 1792 } 1793 } 1794 1795 // Skip reports within the sys/queue.h macros as we do not have the ability to 1796 // reason about data structure shapes. 1797 SourceManager &SM = BRC.getSourceManager(); 1798 FullSourceLoc Loc = BR.getLocation(SM).asLocation(); 1799 while (Loc.isMacroID()) { 1800 Loc = Loc.getSpellingLoc(); 1801 if (SM.getFilename(Loc).endswith("sys/queue.h")) { 1802 BR.markInvalid(getTag(), nullptr); 1803 return nullptr; 1804 } 1805 } 1806 1807 return nullptr; 1808 } 1809 1810 std::shared_ptr<PathDiagnosticPiece> 1811 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N, 1812 const ExplodedNode *PrevN, 1813 BugReporterContext &BRC, BugReport &BR) { 1814 1815 ProgramStateRef State = N->getState(); 1816 ProgramPoint ProgLoc = N->getLocation(); 1817 1818 // We are only interested in visiting CallEnter nodes. 1819 Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>(); 1820 if (!CEnter) 1821 return nullptr; 1822 1823 // Check if one of the arguments is the region the visitor is tracking. 1824 CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager(); 1825 CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State); 1826 unsigned Idx = 0; 1827 ArrayRef<ParmVarDecl*> parms = Call->parameters(); 1828 1829 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 1830 I != E; ++I, ++Idx) { 1831 const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion(); 1832 1833 // Are we tracking the argument or its subregion? 1834 if ( !ArgReg || !R->isSubRegionOf(ArgReg->StripCasts())) 1835 continue; 1836 1837 // Check the function parameter type. 1838 const ParmVarDecl *ParamDecl = *I; 1839 assert(ParamDecl && "Formal parameter has no decl?"); 1840 QualType T = ParamDecl->getType(); 1841 1842 if (!(T->isAnyPointerType() || T->isReferenceType())) { 1843 // Function can only change the value passed in by address. 1844 continue; 1845 } 1846 1847 // If it is a const pointer value, the function does not intend to 1848 // change the value. 1849 if (T->getPointeeType().isConstQualified()) 1850 continue; 1851 1852 // Mark the call site (LocationContext) as interesting if the value of the 1853 // argument is undefined or '0'/'NULL'. 1854 SVal BoundVal = State->getSVal(R); 1855 if (BoundVal.isUndef() || BoundVal.isZeroConstant()) { 1856 BR.markInteresting(CEnter->getCalleeContext()); 1857 return nullptr; 1858 } 1859 } 1860 return nullptr; 1861 } 1862 1863 std::shared_ptr<PathDiagnosticPiece> 1864 CXXSelfAssignmentBRVisitor::VisitNode(const ExplodedNode *Succ, 1865 const ExplodedNode *Pred, 1866 BugReporterContext &BRC, BugReport &BR) { 1867 if (Satisfied) 1868 return nullptr; 1869 1870 auto Edge = Succ->getLocation().getAs<BlockEdge>(); 1871 if (!Edge.hasValue()) 1872 return nullptr; 1873 1874 auto Tag = Edge->getTag(); 1875 if (!Tag) 1876 return nullptr; 1877 1878 if (Tag->getTagDescription() != "cplusplus.SelfAssignment") 1879 return nullptr; 1880 1881 Satisfied = true; 1882 1883 const auto *Met = 1884 dyn_cast<CXXMethodDecl>(Succ->getCodeDecl().getAsFunction()); 1885 assert(Met && "Not a C++ method."); 1886 assert((Met->isCopyAssignmentOperator() || Met->isMoveAssignmentOperator()) && 1887 "Not a copy/move assignment operator."); 1888 1889 const auto *LCtx = Edge->getLocationContext(); 1890 1891 const auto &State = Succ->getState(); 1892 auto &SVB = State->getStateManager().getSValBuilder(); 1893 1894 const auto Param = 1895 State->getSVal(State->getRegion(Met->getParamDecl(0), LCtx)); 1896 const auto This = 1897 State->getSVal(SVB.getCXXThis(Met, LCtx->getCurrentStackFrame())); 1898 1899 auto L = PathDiagnosticLocation::create(Met, BRC.getSourceManager()); 1900 1901 if (!L.isValid() || !L.asLocation().isValid()) 1902 return nullptr; 1903 1904 SmallString<256> Buf; 1905 llvm::raw_svector_ostream Out(Buf); 1906 1907 Out << "Assuming " << Met->getParamDecl(0)->getName() << 1908 ((Param == This) ? " == " : " != ") << "*this"; 1909 1910 auto Piece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str()); 1911 Piece->addRange(Met->getSourceRange()); 1912 1913 return std::move(Piece); 1914 } 1915