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