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