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