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