1 //===- BugReporterVisitors.cpp - Helpers for reporting bugs ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines a set of BugReporter "visitors" which can be used to 10 // enhance the diagnostics reported for a bug. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Decl.h" 17 #include "clang/AST/DeclBase.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/Expr.h" 20 #include "clang/AST/ExprCXX.h" 21 #include "clang/AST/ExprObjC.h" 22 #include "clang/AST/Stmt.h" 23 #include "clang/AST/Type.h" 24 #include "clang/ASTMatchers/ASTMatchFinder.h" 25 #include "clang/Analysis/Analyses/Dominators.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 static const Expr *peelOffPointerArithmetic(const BinaryOperator *B) { 75 if (B->isAdditiveOp() && B->getType()->isPointerType()) { 76 if (B->getLHS()->getType()->isPointerType()) { 77 return B->getLHS(); 78 } else if (B->getRHS()->getType()->isPointerType()) { 79 return B->getRHS(); 80 } 81 } 82 return nullptr; 83 } 84 85 /// Given that expression S represents a pointer that would be dereferenced, 86 /// try to find a sub-expression from which the pointer came from. 87 /// This is used for tracking down origins of a null or undefined value: 88 /// "this is null because that is null because that is null" etc. 89 /// We wipe away field and element offsets because they merely add offsets. 90 /// We also wipe away all casts except lvalue-to-rvalue casts, because the 91 /// latter represent an actual pointer dereference; however, we remove 92 /// the final lvalue-to-rvalue cast before returning from this function 93 /// because it demonstrates more clearly from where the pointer rvalue was 94 /// loaded. Examples: 95 /// x->y.z ==> x (lvalue) 96 /// foo()->y.z ==> foo() (rvalue) 97 const Expr *bugreporter::getDerefExpr(const Stmt *S) { 98 const auto *E = dyn_cast<Expr>(S); 99 if (!E) 100 return nullptr; 101 102 while (true) { 103 if (const auto *CE = dyn_cast<CastExpr>(E)) { 104 if (CE->getCastKind() == CK_LValueToRValue) { 105 // This cast represents the load we're looking for. 106 break; 107 } 108 E = CE->getSubExpr(); 109 } else if (const auto *B = dyn_cast<BinaryOperator>(E)) { 110 // Pointer arithmetic: '*(x + 2)' -> 'x') etc. 111 if (const Expr *Inner = peelOffPointerArithmetic(B)) { 112 E = Inner; 113 } else { 114 // Probably more arithmetic can be pattern-matched here, 115 // but for now give up. 116 break; 117 } 118 } else if (const auto *U = dyn_cast<UnaryOperator>(E)) { 119 if (U->getOpcode() == UO_Deref || U->getOpcode() == UO_AddrOf || 120 (U->isIncrementDecrementOp() && U->getType()->isPointerType())) { 121 // Operators '*' and '&' don't actually mean anything. 122 // We look at casts instead. 123 E = U->getSubExpr(); 124 } else { 125 // Probably more arithmetic can be pattern-matched here, 126 // but for now give up. 127 break; 128 } 129 } 130 // Pattern match for a few useful cases: a[0], p->f, *p etc. 131 else if (const auto *ME = dyn_cast<MemberExpr>(E)) { 132 E = ME->getBase(); 133 } else if (const auto *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) { 134 E = IvarRef->getBase(); 135 } else if (const auto *AE = dyn_cast<ArraySubscriptExpr>(E)) { 136 E = AE->getBase(); 137 } else if (const auto *PE = dyn_cast<ParenExpr>(E)) { 138 E = PE->getSubExpr(); 139 } else if (const auto *FE = dyn_cast<FullExpr>(E)) { 140 E = FE->getSubExpr(); 141 } else { 142 // Other arbitrary stuff. 143 break; 144 } 145 } 146 147 // Special case: remove the final lvalue-to-rvalue cast, but do not recurse 148 // deeper into the sub-expression. This way we return the lvalue from which 149 // our pointer rvalue was loaded. 150 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) 151 if (CE->getCastKind() == CK_LValueToRValue) 152 E = CE->getSubExpr(); 153 154 return E; 155 } 156 157 /// Comparing internal representations of symbolic values (via 158 /// SVal::operator==()) is a valid way to check if the value was updated, 159 /// unless it's a LazyCompoundVal that may have a different internal 160 /// representation every time it is loaded from the state. In this function we 161 /// do an approximate comparison for lazy compound values, checking that they 162 /// are the immediate snapshots of the tracked region's bindings within the 163 /// node's respective states but not really checking that these snapshots 164 /// actually contain the same set of bindings. 165 static bool hasVisibleUpdate(const ExplodedNode *LeftNode, SVal LeftVal, 166 const ExplodedNode *RightNode, SVal RightVal) { 167 if (LeftVal == RightVal) 168 return true; 169 170 const auto LLCV = LeftVal.getAs<nonloc::LazyCompoundVal>(); 171 if (!LLCV) 172 return false; 173 174 const auto RLCV = RightVal.getAs<nonloc::LazyCompoundVal>(); 175 if (!RLCV) 176 return false; 177 178 return LLCV->getRegion() == RLCV->getRegion() && 179 LLCV->getStore() == LeftNode->getState()->getStore() && 180 RLCV->getStore() == RightNode->getState()->getStore(); 181 } 182 183 static Optional<SVal> getSValForVar(const Expr *CondVarExpr, 184 const ExplodedNode *N) { 185 ProgramStateRef State = N->getState(); 186 const LocationContext *LCtx = N->getLocationContext(); 187 188 assert(CondVarExpr); 189 CondVarExpr = CondVarExpr->IgnoreImpCasts(); 190 191 // The declaration of the value may rely on a pointer so take its l-value. 192 // FIXME: As seen in VisitCommonDeclRefExpr, sometimes DeclRefExpr may 193 // evaluate to a FieldRegion when it refers to a declaration of a lambda 194 // capture variable. We most likely need to duplicate that logic here. 195 if (const auto *DRE = dyn_cast<DeclRefExpr>(CondVarExpr)) 196 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 197 return State->getSVal(State->getLValue(VD, LCtx)); 198 199 if (const auto *ME = dyn_cast<MemberExpr>(CondVarExpr)) 200 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 201 if (auto FieldL = State->getSVal(ME, LCtx).getAs<Loc>()) 202 return State->getRawSVal(*FieldL, FD->getType()); 203 204 return None; 205 } 206 207 static Optional<const llvm::APSInt *> 208 getConcreteIntegerValue(const Expr *CondVarExpr, const ExplodedNode *N) { 209 210 if (Optional<SVal> V = getSValForVar(CondVarExpr, N)) 211 if (auto CI = V->getAs<nonloc::ConcreteInt>()) 212 return &CI->getValue(); 213 return None; 214 } 215 216 static bool isVarAnInterestingCondition(const Expr *CondVarExpr, 217 const ExplodedNode *N, 218 const PathSensitiveBugReport *B) { 219 // Even if this condition is marked as interesting, it isn't *that* 220 // interesting if it didn't happen in a nested stackframe, the user could just 221 // follow the arrows. 222 if (!B->getErrorNode()->getStackFrame()->isParentOf(N->getStackFrame())) 223 return false; 224 225 if (Optional<SVal> V = getSValForVar(CondVarExpr, N)) 226 if (Optional<bugreporter::TrackingKind> K = B->getInterestingnessKind(*V)) 227 return *K == bugreporter::TrackingKind::Condition; 228 229 return false; 230 } 231 232 static bool isInterestingExpr(const Expr *E, const ExplodedNode *N, 233 const PathSensitiveBugReport *B) { 234 if (Optional<SVal> V = getSValForVar(E, N)) 235 return B->getInterestingnessKind(*V).hasValue(); 236 return false; 237 } 238 239 /// \return name of the macro inside the location \p Loc. 240 static StringRef getMacroName(SourceLocation Loc, 241 BugReporterContext &BRC) { 242 return Lexer::getImmediateMacroName( 243 Loc, 244 BRC.getSourceManager(), 245 BRC.getASTContext().getLangOpts()); 246 } 247 248 /// \return Whether given spelling location corresponds to an expansion 249 /// of a function-like macro. 250 static bool isFunctionMacroExpansion(SourceLocation Loc, 251 const SourceManager &SM) { 252 if (!Loc.isMacroID()) 253 return false; 254 while (SM.isMacroArgExpansion(Loc)) 255 Loc = SM.getImmediateExpansionRange(Loc).getBegin(); 256 std::pair<FileID, unsigned> TLInfo = SM.getDecomposedLoc(Loc); 257 SrcMgr::SLocEntry SE = SM.getSLocEntry(TLInfo.first); 258 const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion(); 259 return EInfo.isFunctionMacroExpansion(); 260 } 261 262 /// \return Whether \c RegionOfInterest was modified at \p N, 263 /// where \p ValueAfter is \c RegionOfInterest's value at the end of the 264 /// stack frame. 265 static bool wasRegionOfInterestModifiedAt(const SubRegion *RegionOfInterest, 266 const ExplodedNode *N, 267 SVal ValueAfter) { 268 ProgramStateRef State = N->getState(); 269 ProgramStateManager &Mgr = N->getState()->getStateManager(); 270 271 if (!N->getLocationAs<PostStore>() && !N->getLocationAs<PostInitializer>() && 272 !N->getLocationAs<PostStmt>()) 273 return false; 274 275 // Writing into region of interest. 276 if (auto PS = N->getLocationAs<PostStmt>()) 277 if (auto *BO = PS->getStmtAs<BinaryOperator>()) 278 if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf( 279 N->getSVal(BO->getLHS()).getAsRegion())) 280 return true; 281 282 // SVal after the state is possibly different. 283 SVal ValueAtN = N->getState()->getSVal(RegionOfInterest); 284 if (!Mgr.getSValBuilder() 285 .areEqual(State, ValueAtN, ValueAfter) 286 .isConstrainedTrue() && 287 (!ValueAtN.isUndef() || !ValueAfter.isUndef())) 288 return true; 289 290 return false; 291 } 292 293 //===----------------------------------------------------------------------===// 294 // Implementation of BugReporterVisitor. 295 //===----------------------------------------------------------------------===// 296 297 PathDiagnosticPieceRef BugReporterVisitor::getEndPath(BugReporterContext &, 298 const ExplodedNode *, 299 PathSensitiveBugReport &) { 300 return nullptr; 301 } 302 303 void BugReporterVisitor::finalizeVisitor(BugReporterContext &, 304 const ExplodedNode *, 305 PathSensitiveBugReport &) {} 306 307 PathDiagnosticPieceRef 308 BugReporterVisitor::getDefaultEndPath(const BugReporterContext &BRC, 309 const ExplodedNode *EndPathNode, 310 const PathSensitiveBugReport &BR) { 311 PathDiagnosticLocation L = 312 PathDiagnosticLocation::createEndOfPath(EndPathNode); 313 314 const auto &Ranges = BR.getRanges(); 315 316 // Only add the statement itself as a range if we didn't specify any 317 // special ranges for this report. 318 auto P = std::make_shared<PathDiagnosticEventPiece>( 319 L, BR.getDescription(), Ranges.begin() == Ranges.end()); 320 for (SourceRange Range : Ranges) 321 P->addRange(Range); 322 323 return P; 324 } 325 326 //===----------------------------------------------------------------------===// 327 // Implementation of NoStoreFuncVisitor. 328 //===----------------------------------------------------------------------===// 329 330 namespace { 331 332 /// Put a diagnostic on return statement of all inlined functions 333 /// for which the region of interest \p RegionOfInterest was passed into, 334 /// but not written inside, and it has caused an undefined read or a null 335 /// pointer dereference outside. 336 class NoStoreFuncVisitor final : public BugReporterVisitor { 337 const SubRegion *RegionOfInterest; 338 MemRegionManager &MmrMgr; 339 const SourceManager &SM; 340 const PrintingPolicy &PP; 341 bugreporter::TrackingKind TKind; 342 343 /// Recursion limit for dereferencing fields when looking for the 344 /// region of interest. 345 /// The limit of two indicates that we will dereference fields only once. 346 static const unsigned DEREFERENCE_LIMIT = 2; 347 348 /// Frames writing into \c RegionOfInterest. 349 /// This visitor generates a note only if a function does not write into 350 /// a region of interest. This information is not immediately available 351 /// by looking at the node associated with the exit from the function 352 /// (usually the return statement). To avoid recomputing the same information 353 /// many times (going up the path for each node and checking whether the 354 /// region was written into) we instead lazily compute the 355 /// stack frames along the path which write into the region of interest. 356 llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingRegion; 357 llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingCalculated; 358 359 using RegionVector = SmallVector<const MemRegion *, 5>; 360 361 public: 362 NoStoreFuncVisitor(const SubRegion *R, bugreporter::TrackingKind TKind) 363 : RegionOfInterest(R), MmrMgr(*R->getMemRegionManager()), 364 SM(MmrMgr.getContext().getSourceManager()), 365 PP(MmrMgr.getContext().getPrintingPolicy()), TKind(TKind) {} 366 367 void Profile(llvm::FoldingSetNodeID &ID) const override { 368 static int Tag = 0; 369 ID.AddPointer(&Tag); 370 ID.AddPointer(RegionOfInterest); 371 } 372 373 void *getTag() const { 374 static int Tag = 0; 375 return static_cast<void *>(&Tag); 376 } 377 378 PathDiagnosticPieceRef VisitNode(const ExplodedNode *N, 379 BugReporterContext &BR, 380 PathSensitiveBugReport &R) override; 381 382 private: 383 /// Attempts to find the region of interest in a given record decl, 384 /// by either following the base classes or fields. 385 /// Dereferences fields up to a given recursion limit. 386 /// Note that \p Vec is passed by value, leading to quadratic copying cost, 387 /// but it's OK in practice since its length is limited to DEREFERENCE_LIMIT. 388 /// \return A chain fields leading to the region of interest or None. 389 const Optional<RegionVector> 390 findRegionOfInterestInRecord(const RecordDecl *RD, ProgramStateRef State, 391 const MemRegion *R, const RegionVector &Vec = {}, 392 int depth = 0); 393 394 /// Check and lazily calculate whether the region of interest is 395 /// modified in the stack frame to which \p N belongs. 396 /// The calculation is cached in FramesModifyingRegion. 397 bool isRegionOfInterestModifiedInFrame(const ExplodedNode *N) { 398 const LocationContext *Ctx = N->getLocationContext(); 399 const StackFrameContext *SCtx = Ctx->getStackFrame(); 400 if (!FramesModifyingCalculated.count(SCtx)) 401 findModifyingFrames(N); 402 return FramesModifyingRegion.count(SCtx); 403 } 404 405 /// Write to \c FramesModifyingRegion all stack frames along 406 /// the path in the current stack frame which modify \c RegionOfInterest. 407 void findModifyingFrames(const ExplodedNode *N); 408 409 /// Consume the information on the no-store stack frame in order to 410 /// either emit a note or suppress the report enirely. 411 /// \return Diagnostics piece for region not modified in the current function, 412 /// if it decides to emit one. 413 PathDiagnosticPieceRef 414 maybeEmitNote(PathSensitiveBugReport &R, const CallEvent &Call, 415 const ExplodedNode *N, const RegionVector &FieldChain, 416 const MemRegion *MatchedRegion, StringRef FirstElement, 417 bool FirstIsReferenceType, unsigned IndirectionLevel); 418 419 /// Pretty-print region \p MatchedRegion to \p os. 420 /// \return Whether printing succeeded. 421 bool prettyPrintRegionName(StringRef FirstElement, bool FirstIsReferenceType, 422 const MemRegion *MatchedRegion, 423 const RegionVector &FieldChain, 424 int IndirectionLevel, 425 llvm::raw_svector_ostream &os); 426 427 /// Print first item in the chain, return new separator. 428 static StringRef prettyPrintFirstElement(StringRef FirstElement, 429 bool MoreItemsExpected, 430 int IndirectionLevel, 431 llvm::raw_svector_ostream &os); 432 }; 433 434 } // end of anonymous namespace 435 436 /// \return Whether the method declaration \p Parent 437 /// syntactically has a binary operation writing into the ivar \p Ivar. 438 static bool potentiallyWritesIntoIvar(const Decl *Parent, 439 const ObjCIvarDecl *Ivar) { 440 using namespace ast_matchers; 441 const char *IvarBind = "Ivar"; 442 if (!Parent || !Parent->hasBody()) 443 return false; 444 StatementMatcher WriteIntoIvarM = binaryOperator( 445 hasOperatorName("="), 446 hasLHS(ignoringParenImpCasts( 447 objcIvarRefExpr(hasDeclaration(equalsNode(Ivar))).bind(IvarBind)))); 448 StatementMatcher ParentM = stmt(hasDescendant(WriteIntoIvarM)); 449 auto Matches = match(ParentM, *Parent->getBody(), Parent->getASTContext()); 450 for (BoundNodes &Match : Matches) { 451 auto IvarRef = Match.getNodeAs<ObjCIvarRefExpr>(IvarBind); 452 if (IvarRef->isFreeIvar()) 453 return true; 454 455 const Expr *Base = IvarRef->getBase(); 456 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Base)) 457 Base = ICE->getSubExpr(); 458 459 if (const auto *DRE = dyn_cast<DeclRefExpr>(Base)) 460 if (const auto *ID = dyn_cast<ImplicitParamDecl>(DRE->getDecl())) 461 if (ID->getParameterKind() == ImplicitParamDecl::ObjCSelf) 462 return true; 463 464 return false; 465 } 466 return false; 467 } 468 469 /// Get parameters associated with runtime definition in order 470 /// to get the correct parameter name. 471 static ArrayRef<ParmVarDecl *> getCallParameters(CallEventRef<> Call) { 472 // Use runtime definition, if available. 473 RuntimeDefinition RD = Call->getRuntimeDefinition(); 474 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(RD.getDecl())) 475 return FD->parameters(); 476 if (const auto *MD = dyn_cast_or_null<ObjCMethodDecl>(RD.getDecl())) 477 return MD->parameters(); 478 479 return Call->parameters(); 480 } 481 482 /// \return whether \p Ty points to a const type, or is a const reference. 483 static bool isPointerToConst(QualType Ty) { 484 return !Ty->getPointeeType().isNull() && 485 Ty->getPointeeType().getCanonicalType().isConstQualified(); 486 } 487 488 /// Attempts to find the region of interest in a given CXX decl, 489 /// by either following the base classes or fields. 490 /// Dereferences fields up to a given recursion limit. 491 /// Note that \p Vec is passed by value, leading to quadratic copying cost, 492 /// but it's OK in practice since its length is limited to DEREFERENCE_LIMIT. 493 /// \return A chain fields leading to the region of interest or None. 494 const Optional<NoStoreFuncVisitor::RegionVector> 495 NoStoreFuncVisitor::findRegionOfInterestInRecord( 496 const RecordDecl *RD, ProgramStateRef State, const MemRegion *R, 497 const NoStoreFuncVisitor::RegionVector &Vec /* = {} */, 498 int depth /* = 0 */) { 499 500 if (depth == DEREFERENCE_LIMIT) // Limit the recursion depth. 501 return None; 502 503 if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD)) 504 if (!RDX->hasDefinition()) 505 return None; 506 507 // Recursively examine the base classes. 508 // Note that following base classes does not increase the recursion depth. 509 if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD)) 510 for (const auto II : RDX->bases()) 511 if (const RecordDecl *RRD = II.getType()->getAsRecordDecl()) 512 if (Optional<RegionVector> Out = 513 findRegionOfInterestInRecord(RRD, State, R, Vec, depth)) 514 return Out; 515 516 for (const FieldDecl *I : RD->fields()) { 517 QualType FT = I->getType(); 518 const FieldRegion *FR = MmrMgr.getFieldRegion(I, cast<SubRegion>(R)); 519 const SVal V = State->getSVal(FR); 520 const MemRegion *VR = V.getAsRegion(); 521 522 RegionVector VecF = Vec; 523 VecF.push_back(FR); 524 525 if (RegionOfInterest == VR) 526 return VecF; 527 528 if (const RecordDecl *RRD = FT->getAsRecordDecl()) 529 if (auto Out = 530 findRegionOfInterestInRecord(RRD, State, FR, VecF, depth + 1)) 531 return Out; 532 533 QualType PT = FT->getPointeeType(); 534 if (PT.isNull() || PT->isVoidType() || !VR) 535 continue; 536 537 if (const RecordDecl *RRD = PT->getAsRecordDecl()) 538 if (Optional<RegionVector> Out = 539 findRegionOfInterestInRecord(RRD, State, VR, VecF, depth + 1)) 540 return Out; 541 } 542 543 return None; 544 } 545 546 PathDiagnosticPieceRef 547 NoStoreFuncVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BR, 548 PathSensitiveBugReport &R) { 549 550 const LocationContext *Ctx = N->getLocationContext(); 551 const StackFrameContext *SCtx = Ctx->getStackFrame(); 552 ProgramStateRef State = N->getState(); 553 auto CallExitLoc = N->getLocationAs<CallExitBegin>(); 554 555 // No diagnostic if region was modified inside the frame. 556 if (!CallExitLoc || isRegionOfInterestModifiedInFrame(N)) 557 return nullptr; 558 559 CallEventRef<> Call = 560 BR.getStateManager().getCallEventManager().getCaller(SCtx, State); 561 562 // Region of interest corresponds to an IVar, exiting a method 563 // which could have written into that IVar, but did not. 564 if (const auto *MC = dyn_cast<ObjCMethodCall>(Call)) { 565 if (const auto *IvarR = dyn_cast<ObjCIvarRegion>(RegionOfInterest)) { 566 const MemRegion *SelfRegion = MC->getReceiverSVal().getAsRegion(); 567 if (RegionOfInterest->isSubRegionOf(SelfRegion) && 568 potentiallyWritesIntoIvar(Call->getRuntimeDefinition().getDecl(), 569 IvarR->getDecl())) 570 return maybeEmitNote(R, *Call, N, {}, SelfRegion, "self", 571 /*FirstIsReferenceType=*/false, 1); 572 } 573 } 574 575 if (const auto *CCall = dyn_cast<CXXConstructorCall>(Call)) { 576 const MemRegion *ThisR = CCall->getCXXThisVal().getAsRegion(); 577 if (RegionOfInterest->isSubRegionOf(ThisR) && 578 !CCall->getDecl()->isImplicit()) 579 return maybeEmitNote(R, *Call, N, {}, ThisR, "this", 580 /*FirstIsReferenceType=*/false, 1); 581 582 // Do not generate diagnostics for not modified parameters in 583 // constructors. 584 return nullptr; 585 } 586 587 ArrayRef<ParmVarDecl *> parameters = getCallParameters(Call); 588 for (unsigned I = 0; I < Call->getNumArgs() && I < parameters.size(); ++I) { 589 const ParmVarDecl *PVD = parameters[I]; 590 SVal V = Call->getArgSVal(I); 591 bool ParamIsReferenceType = PVD->getType()->isReferenceType(); 592 std::string ParamName = PVD->getNameAsString(); 593 594 int IndirectionLevel = 1; 595 QualType T = PVD->getType(); 596 while (const MemRegion *MR = V.getAsRegion()) { 597 if (RegionOfInterest->isSubRegionOf(MR) && !isPointerToConst(T)) 598 return maybeEmitNote(R, *Call, N, {}, MR, ParamName, 599 ParamIsReferenceType, IndirectionLevel); 600 601 QualType PT = T->getPointeeType(); 602 if (PT.isNull() || PT->isVoidType()) 603 break; 604 605 if (const RecordDecl *RD = PT->getAsRecordDecl()) 606 if (Optional<RegionVector> P = 607 findRegionOfInterestInRecord(RD, State, MR)) 608 return maybeEmitNote(R, *Call, N, *P, RegionOfInterest, ParamName, 609 ParamIsReferenceType, IndirectionLevel); 610 611 V = State->getSVal(MR, PT); 612 T = PT; 613 IndirectionLevel++; 614 } 615 } 616 617 return nullptr; 618 } 619 620 void NoStoreFuncVisitor::findModifyingFrames(const ExplodedNode *N) { 621 assert(N->getLocationAs<CallExitBegin>()); 622 ProgramStateRef LastReturnState = N->getState(); 623 SVal ValueAtReturn = LastReturnState->getSVal(RegionOfInterest); 624 const LocationContext *Ctx = N->getLocationContext(); 625 const StackFrameContext *OriginalSCtx = Ctx->getStackFrame(); 626 627 do { 628 ProgramStateRef State = N->getState(); 629 auto CallExitLoc = N->getLocationAs<CallExitBegin>(); 630 if (CallExitLoc) { 631 LastReturnState = State; 632 ValueAtReturn = LastReturnState->getSVal(RegionOfInterest); 633 } 634 635 FramesModifyingCalculated.insert(N->getLocationContext()->getStackFrame()); 636 637 if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtReturn)) { 638 const StackFrameContext *SCtx = N->getStackFrame(); 639 while (!SCtx->inTopFrame()) { 640 auto p = FramesModifyingRegion.insert(SCtx); 641 if (!p.second) 642 break; // Frame and all its parents already inserted. 643 SCtx = SCtx->getParent()->getStackFrame(); 644 } 645 } 646 647 // Stop calculation at the call to the current function. 648 if (auto CE = N->getLocationAs<CallEnter>()) 649 if (CE->getCalleeContext() == OriginalSCtx) 650 break; 651 652 N = N->getFirstPred(); 653 } while (N); 654 } 655 656 static llvm::StringLiteral WillBeUsedForACondition = 657 ", which participates in a condition later"; 658 659 PathDiagnosticPieceRef NoStoreFuncVisitor::maybeEmitNote( 660 PathSensitiveBugReport &R, const CallEvent &Call, const ExplodedNode *N, 661 const RegionVector &FieldChain, const MemRegion *MatchedRegion, 662 StringRef FirstElement, bool FirstIsReferenceType, 663 unsigned IndirectionLevel) { 664 // Optimistically suppress uninitialized value bugs that result 665 // from system headers having a chance to initialize the value 666 // but failing to do so. It's too unlikely a system header's fault. 667 // It's much more likely a situation in which the function has a failure 668 // mode that the user decided not to check. If we want to hunt such 669 // omitted checks, we should provide an explicit function-specific note 670 // describing the precondition under which the function isn't supposed to 671 // initialize its out-parameter, and additionally check that such 672 // precondition can actually be fulfilled on the current path. 673 if (Call.isInSystemHeader()) { 674 // We make an exception for system header functions that have no branches. 675 // Such functions unconditionally fail to initialize the variable. 676 // If they call other functions that have more paths within them, 677 // this suppression would still apply when we visit these inner functions. 678 // One common example of a standard function that doesn't ever initialize 679 // its out parameter is operator placement new; it's up to the follow-up 680 // constructor (if any) to initialize the memory. 681 if (!N->getStackFrame()->getCFG()->isLinear()) 682 R.markInvalid(getTag(), nullptr); 683 return nullptr; 684 } 685 686 PathDiagnosticLocation L = 687 PathDiagnosticLocation::create(N->getLocation(), SM); 688 689 // For now this shouldn't trigger, but once it does (as we add more 690 // functions to the body farm), we'll need to decide if these reports 691 // are worth suppressing as well. 692 if (!L.hasValidLocation()) 693 return nullptr; 694 695 SmallString<256> sbuf; 696 llvm::raw_svector_ostream os(sbuf); 697 os << "Returning without writing to '"; 698 699 // Do not generate the note if failed to pretty-print. 700 if (!prettyPrintRegionName(FirstElement, FirstIsReferenceType, MatchedRegion, 701 FieldChain, IndirectionLevel, os)) 702 return nullptr; 703 704 os << "'"; 705 if (TKind == bugreporter::TrackingKind::Condition) 706 os << WillBeUsedForACondition; 707 return std::make_shared<PathDiagnosticEventPiece>(L, os.str()); 708 } 709 710 bool NoStoreFuncVisitor::prettyPrintRegionName(StringRef FirstElement, 711 bool FirstIsReferenceType, 712 const MemRegion *MatchedRegion, 713 const RegionVector &FieldChain, 714 int IndirectionLevel, 715 llvm::raw_svector_ostream &os) { 716 717 if (FirstIsReferenceType) 718 IndirectionLevel--; 719 720 RegionVector RegionSequence; 721 722 // Add the regions in the reverse order, then reverse the resulting array. 723 assert(RegionOfInterest->isSubRegionOf(MatchedRegion)); 724 const MemRegion *R = RegionOfInterest; 725 while (R != MatchedRegion) { 726 RegionSequence.push_back(R); 727 R = cast<SubRegion>(R)->getSuperRegion(); 728 } 729 std::reverse(RegionSequence.begin(), RegionSequence.end()); 730 RegionSequence.append(FieldChain.begin(), FieldChain.end()); 731 732 StringRef Sep; 733 for (const MemRegion *R : RegionSequence) { 734 735 // Just keep going up to the base region. 736 // Element regions may appear due to casts. 737 if (isa<CXXBaseObjectRegion>(R) || isa<CXXTempObjectRegion>(R)) 738 continue; 739 740 if (Sep.empty()) 741 Sep = prettyPrintFirstElement(FirstElement, 742 /*MoreItemsExpected=*/true, 743 IndirectionLevel, os); 744 745 os << Sep; 746 747 // Can only reasonably pretty-print DeclRegions. 748 if (!isa<DeclRegion>(R)) 749 return false; 750 751 const auto *DR = cast<DeclRegion>(R); 752 Sep = DR->getValueType()->isAnyPointerType() ? "->" : "."; 753 DR->getDecl()->getDeclName().print(os, PP); 754 } 755 756 if (Sep.empty()) 757 prettyPrintFirstElement(FirstElement, 758 /*MoreItemsExpected=*/false, IndirectionLevel, os); 759 return true; 760 } 761 762 StringRef NoStoreFuncVisitor::prettyPrintFirstElement( 763 StringRef FirstElement, bool MoreItemsExpected, int IndirectionLevel, 764 llvm::raw_svector_ostream &os) { 765 StringRef Out = "."; 766 767 if (IndirectionLevel > 0 && MoreItemsExpected) { 768 IndirectionLevel--; 769 Out = "->"; 770 } 771 772 if (IndirectionLevel > 0 && MoreItemsExpected) 773 os << "("; 774 775 for (int i = 0; i < IndirectionLevel; i++) 776 os << "*"; 777 os << FirstElement; 778 779 if (IndirectionLevel > 0 && MoreItemsExpected) 780 os << ")"; 781 782 return Out; 783 } 784 785 //===----------------------------------------------------------------------===// 786 // Implementation of MacroNullReturnSuppressionVisitor. 787 //===----------------------------------------------------------------------===// 788 789 namespace { 790 791 /// Suppress null-pointer-dereference bugs where dereferenced null was returned 792 /// the macro. 793 class MacroNullReturnSuppressionVisitor final : public BugReporterVisitor { 794 const SubRegion *RegionOfInterest; 795 const SVal ValueAtDereference; 796 797 // Do not invalidate the reports where the value was modified 798 // after it got assigned to from the macro. 799 bool WasModified = false; 800 801 public: 802 MacroNullReturnSuppressionVisitor(const SubRegion *R, const SVal V) 803 : RegionOfInterest(R), ValueAtDereference(V) {} 804 805 PathDiagnosticPieceRef VisitNode(const ExplodedNode *N, 806 BugReporterContext &BRC, 807 PathSensitiveBugReport &BR) override { 808 if (WasModified) 809 return nullptr; 810 811 auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>(); 812 if (!BugPoint) 813 return nullptr; 814 815 const SourceManager &SMgr = BRC.getSourceManager(); 816 if (auto Loc = matchAssignment(N)) { 817 if (isFunctionMacroExpansion(*Loc, SMgr)) { 818 std::string MacroName = getMacroName(*Loc, BRC); 819 SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc(); 820 if (!BugLoc.isMacroID() || getMacroName(BugLoc, BRC) != MacroName) 821 BR.markInvalid(getTag(), MacroName.c_str()); 822 } 823 } 824 825 if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtDereference)) 826 WasModified = true; 827 828 return nullptr; 829 } 830 831 static void addMacroVisitorIfNecessary( 832 const ExplodedNode *N, const MemRegion *R, 833 bool EnableNullFPSuppression, PathSensitiveBugReport &BR, 834 const SVal V) { 835 AnalyzerOptions &Options = N->getState()->getAnalysisManager().options; 836 if (EnableNullFPSuppression && 837 Options.ShouldSuppressNullReturnPaths && V.getAs<Loc>()) 838 BR.addVisitor(std::make_unique<MacroNullReturnSuppressionVisitor>( 839 R->getAs<SubRegion>(), V)); 840 } 841 842 void* getTag() const { 843 static int Tag = 0; 844 return static_cast<void *>(&Tag); 845 } 846 847 void Profile(llvm::FoldingSetNodeID &ID) const override { 848 ID.AddPointer(getTag()); 849 } 850 851 private: 852 /// \return Source location of right hand side of an assignment 853 /// into \c RegionOfInterest, empty optional if none found. 854 Optional<SourceLocation> matchAssignment(const ExplodedNode *N) { 855 const Stmt *S = PathDiagnosticLocation::getStmt(N); 856 ProgramStateRef State = N->getState(); 857 auto *LCtx = N->getLocationContext(); 858 if (!S) 859 return None; 860 861 if (const auto *DS = dyn_cast<DeclStmt>(S)) { 862 if (const auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl())) 863 if (const Expr *RHS = VD->getInit()) 864 if (RegionOfInterest->isSubRegionOf( 865 State->getLValue(VD, LCtx).getAsRegion())) 866 return RHS->getBeginLoc(); 867 } else if (const auto *BO = dyn_cast<BinaryOperator>(S)) { 868 const MemRegion *R = N->getSVal(BO->getLHS()).getAsRegion(); 869 const Expr *RHS = BO->getRHS(); 870 if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(R)) { 871 return RHS->getBeginLoc(); 872 } 873 } 874 return None; 875 } 876 }; 877 878 } // end of anonymous namespace 879 880 namespace { 881 882 /// Emits an extra note at the return statement of an interesting stack frame. 883 /// 884 /// The returned value is marked as an interesting value, and if it's null, 885 /// adds a visitor to track where it became null. 886 /// 887 /// This visitor is intended to be used when another visitor discovers that an 888 /// interesting value comes from an inlined function call. 889 class ReturnVisitor : public BugReporterVisitor { 890 const StackFrameContext *CalleeSFC; 891 enum { 892 Initial, 893 MaybeUnsuppress, 894 Satisfied 895 } Mode = Initial; 896 897 bool EnableNullFPSuppression; 898 bool ShouldInvalidate = true; 899 AnalyzerOptions& Options; 900 bugreporter::TrackingKind TKind; 901 902 public: 903 ReturnVisitor(const StackFrameContext *Frame, bool Suppressed, 904 AnalyzerOptions &Options, bugreporter::TrackingKind TKind) 905 : CalleeSFC(Frame), EnableNullFPSuppression(Suppressed), 906 Options(Options), TKind(TKind) {} 907 908 static void *getTag() { 909 static int Tag = 0; 910 return static_cast<void *>(&Tag); 911 } 912 913 void Profile(llvm::FoldingSetNodeID &ID) const override { 914 ID.AddPointer(ReturnVisitor::getTag()); 915 ID.AddPointer(CalleeSFC); 916 ID.AddBoolean(EnableNullFPSuppression); 917 } 918 919 /// Adds a ReturnVisitor if the given statement represents a call that was 920 /// inlined. 921 /// 922 /// This will search back through the ExplodedGraph, starting from the given 923 /// node, looking for when the given statement was processed. If it turns out 924 /// the statement is a call that was inlined, we add the visitor to the 925 /// bug report, so it can print a note later. 926 static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S, 927 PathSensitiveBugReport &BR, 928 bool InEnableNullFPSuppression, 929 bugreporter::TrackingKind TKind) { 930 if (!CallEvent::isCallStmt(S)) 931 return; 932 933 // First, find when we processed the statement. 934 // If we work with a 'CXXNewExpr' that is going to be purged away before 935 // its call take place. We would catch that purge in the last condition 936 // as a 'StmtPoint' so we have to bypass it. 937 const bool BypassCXXNewExprEval = isa<CXXNewExpr>(S); 938 939 // This is moving forward when we enter into another context. 940 const StackFrameContext *CurrentSFC = Node->getStackFrame(); 941 942 do { 943 // If that is satisfied we found our statement as an inlined call. 944 if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>()) 945 if (CEE->getCalleeContext()->getCallSite() == S) 946 break; 947 948 // Try to move forward to the end of the call-chain. 949 Node = Node->getFirstPred(); 950 if (!Node) 951 break; 952 953 const StackFrameContext *PredSFC = Node->getStackFrame(); 954 955 // If that is satisfied we found our statement. 956 // FIXME: This code currently bypasses the call site for the 957 // conservatively evaluated allocator. 958 if (!BypassCXXNewExprEval) 959 if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>()) 960 // See if we do not enter into another context. 961 if (SP->getStmt() == S && CurrentSFC == PredSFC) 962 break; 963 964 CurrentSFC = PredSFC; 965 } while (Node->getStackFrame() == CurrentSFC); 966 967 // Next, step over any post-statement checks. 968 while (Node && Node->getLocation().getAs<PostStmt>()) 969 Node = Node->getFirstPred(); 970 if (!Node) 971 return; 972 973 // Finally, see if we inlined the call. 974 Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>(); 975 if (!CEE) 976 return; 977 978 const StackFrameContext *CalleeContext = CEE->getCalleeContext(); 979 if (CalleeContext->getCallSite() != S) 980 return; 981 982 // Check the return value. 983 ProgramStateRef State = Node->getState(); 984 SVal RetVal = Node->getSVal(S); 985 986 // Handle cases where a reference is returned and then immediately used. 987 if (cast<Expr>(S)->isGLValue()) 988 if (Optional<Loc> LValue = RetVal.getAs<Loc>()) 989 RetVal = State->getSVal(*LValue); 990 991 // See if the return value is NULL. If so, suppress the report. 992 AnalyzerOptions &Options = State->getAnalysisManager().options; 993 994 bool EnableNullFPSuppression = false; 995 if (InEnableNullFPSuppression && 996 Options.ShouldSuppressNullReturnPaths) 997 if (Optional<Loc> RetLoc = RetVal.getAs<Loc>()) 998 EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue(); 999 1000 BR.addVisitor(std::make_unique<ReturnVisitor>(CalleeContext, 1001 EnableNullFPSuppression, 1002 Options, TKind)); 1003 } 1004 1005 PathDiagnosticPieceRef visitNodeInitial(const ExplodedNode *N, 1006 BugReporterContext &BRC, 1007 PathSensitiveBugReport &BR) { 1008 // Only print a message at the interesting return statement. 1009 if (N->getLocationContext() != CalleeSFC) 1010 return nullptr; 1011 1012 Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>(); 1013 if (!SP) 1014 return nullptr; 1015 1016 const auto *Ret = dyn_cast<ReturnStmt>(SP->getStmt()); 1017 if (!Ret) 1018 return nullptr; 1019 1020 // Okay, we're at the right return statement, but do we have the return 1021 // value available? 1022 ProgramStateRef State = N->getState(); 1023 SVal V = State->getSVal(Ret, CalleeSFC); 1024 if (V.isUnknownOrUndef()) 1025 return nullptr; 1026 1027 // Don't print any more notes after this one. 1028 Mode = Satisfied; 1029 1030 const Expr *RetE = Ret->getRetValue(); 1031 assert(RetE && "Tracking a return value for a void function"); 1032 1033 // Handle cases where a reference is returned and then immediately used. 1034 Optional<Loc> LValue; 1035 if (RetE->isGLValue()) { 1036 if ((LValue = V.getAs<Loc>())) { 1037 SVal RValue = State->getRawSVal(*LValue, RetE->getType()); 1038 if (RValue.getAs<DefinedSVal>()) 1039 V = RValue; 1040 } 1041 } 1042 1043 // Ignore aggregate rvalues. 1044 if (V.getAs<nonloc::LazyCompoundVal>() || 1045 V.getAs<nonloc::CompoundVal>()) 1046 return nullptr; 1047 1048 RetE = RetE->IgnoreParenCasts(); 1049 1050 // Let's track the return value. 1051 bugreporter::trackExpressionValue( 1052 N, RetE, BR, TKind, EnableNullFPSuppression); 1053 1054 // Build an appropriate message based on the return value. 1055 SmallString<64> Msg; 1056 llvm::raw_svector_ostream Out(Msg); 1057 1058 bool WouldEventBeMeaningless = false; 1059 1060 if (State->isNull(V).isConstrainedTrue()) { 1061 if (V.getAs<Loc>()) { 1062 1063 // If we have counter-suppression enabled, make sure we keep visiting 1064 // future nodes. We want to emit a path note as well, in case 1065 // the report is resurrected as valid later on. 1066 if (EnableNullFPSuppression && 1067 Options.ShouldAvoidSuppressingNullArgumentPaths) 1068 Mode = MaybeUnsuppress; 1069 1070 if (RetE->getType()->isObjCObjectPointerType()) { 1071 Out << "Returning nil"; 1072 } else { 1073 Out << "Returning null pointer"; 1074 } 1075 } else { 1076 Out << "Returning zero"; 1077 } 1078 1079 } else { 1080 if (auto CI = V.getAs<nonloc::ConcreteInt>()) { 1081 Out << "Returning the value " << CI->getValue(); 1082 } else { 1083 // There is nothing interesting about returning a value, when it is 1084 // plain value without any constraints, and the function is guaranteed 1085 // to return that every time. We could use CFG::isLinear() here, but 1086 // constexpr branches are obvious to the compiler, not necesserily to 1087 // the programmer. 1088 if (N->getCFG().size() == 3) 1089 WouldEventBeMeaningless = true; 1090 1091 if (V.getAs<Loc>()) 1092 Out << "Returning pointer"; 1093 else 1094 Out << "Returning value"; 1095 } 1096 } 1097 1098 if (LValue) { 1099 if (const MemRegion *MR = LValue->getAsRegion()) { 1100 if (MR->canPrintPretty()) { 1101 Out << " (reference to "; 1102 MR->printPretty(Out); 1103 Out << ")"; 1104 } 1105 } 1106 } else { 1107 // FIXME: We should have a more generalized location printing mechanism. 1108 if (const auto *DR = dyn_cast<DeclRefExpr>(RetE)) 1109 if (const auto *DD = dyn_cast<DeclaratorDecl>(DR->getDecl())) 1110 Out << " (loaded from '" << *DD << "')"; 1111 } 1112 1113 PathDiagnosticLocation L(Ret, BRC.getSourceManager(), CalleeSFC); 1114 if (!L.isValid() || !L.asLocation().isValid()) 1115 return nullptr; 1116 1117 if (TKind == bugreporter::TrackingKind::Condition) 1118 Out << WillBeUsedForACondition; 1119 1120 auto EventPiece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str()); 1121 1122 // If we determined that the note is meaningless, make it prunable, and 1123 // don't mark the stackframe interesting. 1124 if (WouldEventBeMeaningless) 1125 EventPiece->setPrunable(true); 1126 else 1127 BR.markInteresting(CalleeSFC); 1128 1129 return EventPiece; 1130 } 1131 1132 PathDiagnosticPieceRef visitNodeMaybeUnsuppress(const ExplodedNode *N, 1133 BugReporterContext &BRC, 1134 PathSensitiveBugReport &BR) { 1135 assert(Options.ShouldAvoidSuppressingNullArgumentPaths); 1136 1137 // Are we at the entry node for this call? 1138 Optional<CallEnter> CE = N->getLocationAs<CallEnter>(); 1139 if (!CE) 1140 return nullptr; 1141 1142 if (CE->getCalleeContext() != CalleeSFC) 1143 return nullptr; 1144 1145 Mode = Satisfied; 1146 1147 // Don't automatically suppress a report if one of the arguments is 1148 // known to be a null pointer. Instead, start tracking /that/ null 1149 // value back to its origin. 1150 ProgramStateManager &StateMgr = BRC.getStateManager(); 1151 CallEventManager &CallMgr = StateMgr.getCallEventManager(); 1152 1153 ProgramStateRef State = N->getState(); 1154 CallEventRef<> Call = CallMgr.getCaller(CalleeSFC, State); 1155 for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) { 1156 Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>(); 1157 if (!ArgV) 1158 continue; 1159 1160 const Expr *ArgE = Call->getArgExpr(I); 1161 if (!ArgE) 1162 continue; 1163 1164 // Is it possible for this argument to be non-null? 1165 if (!State->isNull(*ArgV).isConstrainedTrue()) 1166 continue; 1167 1168 if (trackExpressionValue(N, ArgE, BR, TKind, EnableNullFPSuppression)) 1169 ShouldInvalidate = false; 1170 1171 // If we /can't/ track the null pointer, we should err on the side of 1172 // false negatives, and continue towards marking this report invalid. 1173 // (We will still look at the other arguments, though.) 1174 } 1175 1176 return nullptr; 1177 } 1178 1179 PathDiagnosticPieceRef VisitNode(const ExplodedNode *N, 1180 BugReporterContext &BRC, 1181 PathSensitiveBugReport &BR) override { 1182 switch (Mode) { 1183 case Initial: 1184 return visitNodeInitial(N, BRC, BR); 1185 case MaybeUnsuppress: 1186 return visitNodeMaybeUnsuppress(N, BRC, BR); 1187 case Satisfied: 1188 return nullptr; 1189 } 1190 1191 llvm_unreachable("Invalid visit mode!"); 1192 } 1193 1194 void finalizeVisitor(BugReporterContext &, const ExplodedNode *, 1195 PathSensitiveBugReport &BR) override { 1196 if (EnableNullFPSuppression && ShouldInvalidate) 1197 BR.markInvalid(ReturnVisitor::getTag(), CalleeSFC); 1198 } 1199 }; 1200 1201 } // end of anonymous namespace 1202 1203 //===----------------------------------------------------------------------===// 1204 // Implementation of FindLastStoreBRVisitor. 1205 //===----------------------------------------------------------------------===// 1206 1207 void FindLastStoreBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const { 1208 static int tag = 0; 1209 ID.AddPointer(&tag); 1210 ID.AddPointer(R); 1211 ID.Add(V); 1212 ID.AddInteger(static_cast<int>(TKind)); 1213 ID.AddBoolean(EnableNullFPSuppression); 1214 } 1215 1216 /// Returns true if \p N represents the DeclStmt declaring and initializing 1217 /// \p VR. 1218 static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) { 1219 Optional<PostStmt> P = N->getLocationAs<PostStmt>(); 1220 if (!P) 1221 return false; 1222 1223 const DeclStmt *DS = P->getStmtAs<DeclStmt>(); 1224 if (!DS) 1225 return false; 1226 1227 if (DS->getSingleDecl() != VR->getDecl()) 1228 return false; 1229 1230 const MemSpaceRegion *VarSpace = VR->getMemorySpace(); 1231 const auto *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace); 1232 if (!FrameSpace) { 1233 // If we ever directly evaluate global DeclStmts, this assertion will be 1234 // invalid, but this still seems preferable to silently accepting an 1235 // initialization that may be for a path-sensitive variable. 1236 assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion"); 1237 return true; 1238 } 1239 1240 assert(VR->getDecl()->hasLocalStorage()); 1241 const LocationContext *LCtx = N->getLocationContext(); 1242 return FrameSpace->getStackFrame() == LCtx->getStackFrame(); 1243 } 1244 1245 /// Show diagnostics for initializing or declaring a region \p R with a bad value. 1246 static void showBRDiagnostics(const char *action, llvm::raw_svector_ostream &os, 1247 const MemRegion *R, SVal V, const DeclStmt *DS) { 1248 if (R->canPrintPretty()) { 1249 R->printPretty(os); 1250 os << " "; 1251 } 1252 1253 if (V.getAs<loc::ConcreteInt>()) { 1254 bool b = false; 1255 if (R->isBoundable()) { 1256 if (const auto *TR = dyn_cast<TypedValueRegion>(R)) { 1257 if (TR->getValueType()->isObjCObjectPointerType()) { 1258 os << action << "nil"; 1259 b = true; 1260 } 1261 } 1262 } 1263 if (!b) 1264 os << action << "a null pointer value"; 1265 1266 } else if (auto CVal = V.getAs<nonloc::ConcreteInt>()) { 1267 os << action << CVal->getValue(); 1268 } else if (DS) { 1269 if (V.isUndef()) { 1270 if (isa<VarRegion>(R)) { 1271 const auto *VD = cast<VarDecl>(DS->getSingleDecl()); 1272 if (VD->getInit()) { 1273 os << (R->canPrintPretty() ? "initialized" : "Initializing") 1274 << " to a garbage value"; 1275 } else { 1276 os << (R->canPrintPretty() ? "declared" : "Declaring") 1277 << " without an initial value"; 1278 } 1279 } 1280 } else { 1281 os << (R->canPrintPretty() ? "initialized" : "Initialized") 1282 << " here"; 1283 } 1284 } 1285 } 1286 1287 /// Display diagnostics for passing bad region as a parameter. 1288 static void showBRParamDiagnostics(llvm::raw_svector_ostream& os, 1289 const VarRegion *VR, 1290 SVal V) { 1291 const auto *Param = cast<ParmVarDecl>(VR->getDecl()); 1292 1293 os << "Passing "; 1294 1295 if (V.getAs<loc::ConcreteInt>()) { 1296 if (Param->getType()->isObjCObjectPointerType()) 1297 os << "nil object reference"; 1298 else 1299 os << "null pointer value"; 1300 } else if (V.isUndef()) { 1301 os << "uninitialized value"; 1302 } else if (auto CI = V.getAs<nonloc::ConcreteInt>()) { 1303 os << "the value " << CI->getValue(); 1304 } else { 1305 os << "value"; 1306 } 1307 1308 // Printed parameter indexes are 1-based, not 0-based. 1309 unsigned Idx = Param->getFunctionScopeIndex() + 1; 1310 os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter"; 1311 if (VR->canPrintPretty()) { 1312 os << " "; 1313 VR->printPretty(os); 1314 } 1315 } 1316 1317 /// Show default diagnostics for storing bad region. 1318 static void showBRDefaultDiagnostics(llvm::raw_svector_ostream &os, 1319 const MemRegion *R, SVal V) { 1320 if (V.getAs<loc::ConcreteInt>()) { 1321 bool b = false; 1322 if (R->isBoundable()) { 1323 if (const auto *TR = dyn_cast<TypedValueRegion>(R)) { 1324 if (TR->getValueType()->isObjCObjectPointerType()) { 1325 os << "nil object reference stored"; 1326 b = true; 1327 } 1328 } 1329 } 1330 if (!b) { 1331 if (R->canPrintPretty()) 1332 os << "Null pointer value stored"; 1333 else 1334 os << "Storing null pointer value"; 1335 } 1336 1337 } else if (V.isUndef()) { 1338 if (R->canPrintPretty()) 1339 os << "Uninitialized value stored"; 1340 else 1341 os << "Storing uninitialized value"; 1342 1343 } else if (auto CV = V.getAs<nonloc::ConcreteInt>()) { 1344 if (R->canPrintPretty()) 1345 os << "The value " << CV->getValue() << " is assigned"; 1346 else 1347 os << "Assigning " << CV->getValue(); 1348 1349 } else { 1350 if (R->canPrintPretty()) 1351 os << "Value assigned"; 1352 else 1353 os << "Assigning value"; 1354 } 1355 1356 if (R->canPrintPretty()) { 1357 os << " to "; 1358 R->printPretty(os); 1359 } 1360 } 1361 1362 PathDiagnosticPieceRef 1363 FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ, 1364 BugReporterContext &BRC, 1365 PathSensitiveBugReport &BR) { 1366 if (Satisfied) 1367 return nullptr; 1368 1369 const ExplodedNode *StoreSite = nullptr; 1370 const ExplodedNode *Pred = Succ->getFirstPred(); 1371 const Expr *InitE = nullptr; 1372 bool IsParam = false; 1373 1374 // First see if we reached the declaration of the region. 1375 if (const auto *VR = dyn_cast<VarRegion>(R)) { 1376 if (isInitializationOfVar(Pred, VR)) { 1377 StoreSite = Pred; 1378 InitE = VR->getDecl()->getInit(); 1379 } 1380 } 1381 1382 // If this is a post initializer expression, initializing the region, we 1383 // should track the initializer expression. 1384 if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) { 1385 const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue(); 1386 if (FieldReg == R) { 1387 StoreSite = Pred; 1388 InitE = PIP->getInitializer()->getInit(); 1389 } 1390 } 1391 1392 // Otherwise, see if this is the store site: 1393 // (1) Succ has this binding and Pred does not, i.e. this is 1394 // where the binding first occurred. 1395 // (2) Succ has this binding and is a PostStore node for this region, i.e. 1396 // the same binding was re-assigned here. 1397 if (!StoreSite) { 1398 if (Succ->getState()->getSVal(R) != V) 1399 return nullptr; 1400 1401 if (hasVisibleUpdate(Pred, Pred->getState()->getSVal(R), Succ, V)) { 1402 Optional<PostStore> PS = Succ->getLocationAs<PostStore>(); 1403 if (!PS || PS->getLocationValue() != R) 1404 return nullptr; 1405 } 1406 1407 StoreSite = Succ; 1408 1409 // If this is an assignment expression, we can track the value 1410 // being assigned. 1411 if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>()) 1412 if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>()) 1413 if (BO->isAssignmentOp()) 1414 InitE = BO->getRHS(); 1415 1416 // If this is a call entry, the variable should be a parameter. 1417 // FIXME: Handle CXXThisRegion as well. (This is not a priority because 1418 // 'this' should never be NULL, but this visitor isn't just for NULL and 1419 // UndefinedVal.) 1420 if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) { 1421 if (const auto *VR = dyn_cast<VarRegion>(R)) { 1422 1423 const auto *Param = cast<ParmVarDecl>(VR->getDecl()); 1424 1425 ProgramStateManager &StateMgr = BRC.getStateManager(); 1426 CallEventManager &CallMgr = StateMgr.getCallEventManager(); 1427 1428 CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(), 1429 Succ->getState()); 1430 InitE = Call->getArgExpr(Param->getFunctionScopeIndex()); 1431 IsParam = true; 1432 } 1433 } 1434 1435 // If this is a CXXTempObjectRegion, the Expr responsible for its creation 1436 // is wrapped inside of it. 1437 if (const auto *TmpR = dyn_cast<CXXTempObjectRegion>(R)) 1438 InitE = TmpR->getExpr(); 1439 } 1440 1441 if (!StoreSite) 1442 return nullptr; 1443 Satisfied = true; 1444 1445 // If we have an expression that provided the value, try to track where it 1446 // came from. 1447 if (InitE) { 1448 if (!IsParam) 1449 InitE = InitE->IgnoreParenCasts(); 1450 1451 bugreporter::trackExpressionValue( 1452 StoreSite, InitE, BR, TKind, EnableNullFPSuppression); 1453 } 1454 1455 if (TKind == TrackingKind::Condition && 1456 !OriginSFC->isParentOf(StoreSite->getStackFrame())) 1457 return nullptr; 1458 1459 // Okay, we've found the binding. Emit an appropriate message. 1460 SmallString<256> sbuf; 1461 llvm::raw_svector_ostream os(sbuf); 1462 1463 if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) { 1464 const Stmt *S = PS->getStmt(); 1465 const char *action = nullptr; 1466 const auto *DS = dyn_cast<DeclStmt>(S); 1467 const auto *VR = dyn_cast<VarRegion>(R); 1468 1469 if (DS) { 1470 action = R->canPrintPretty() ? "initialized to " : 1471 "Initializing to "; 1472 } else if (isa<BlockExpr>(S)) { 1473 action = R->canPrintPretty() ? "captured by block as " : 1474 "Captured by block as "; 1475 if (VR) { 1476 // See if we can get the BlockVarRegion. 1477 ProgramStateRef State = StoreSite->getState(); 1478 SVal V = StoreSite->getSVal(S); 1479 if (const auto *BDR = 1480 dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) { 1481 if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) { 1482 if (auto KV = State->getSVal(OriginalR).getAs<KnownSVal>()) 1483 BR.addVisitor(std::make_unique<FindLastStoreBRVisitor>( 1484 *KV, OriginalR, EnableNullFPSuppression, TKind, OriginSFC)); 1485 } 1486 } 1487 } 1488 } 1489 if (action) 1490 showBRDiagnostics(action, os, R, V, DS); 1491 1492 } else if (StoreSite->getLocation().getAs<CallEnter>()) { 1493 if (const auto *VR = dyn_cast<VarRegion>(R)) 1494 showBRParamDiagnostics(os, VR, V); 1495 } 1496 1497 if (os.str().empty()) 1498 showBRDefaultDiagnostics(os, R, V); 1499 1500 if (TKind == bugreporter::TrackingKind::Condition) 1501 os << WillBeUsedForACondition; 1502 1503 // Construct a new PathDiagnosticPiece. 1504 ProgramPoint P = StoreSite->getLocation(); 1505 PathDiagnosticLocation L; 1506 if (P.getAs<CallEnter>() && InitE) 1507 L = PathDiagnosticLocation(InitE, BRC.getSourceManager(), 1508 P.getLocationContext()); 1509 1510 if (!L.isValid() || !L.asLocation().isValid()) 1511 L = PathDiagnosticLocation::create(P, BRC.getSourceManager()); 1512 1513 if (!L.isValid() || !L.asLocation().isValid()) 1514 return nullptr; 1515 1516 return std::make_shared<PathDiagnosticEventPiece>(L, os.str()); 1517 } 1518 1519 //===----------------------------------------------------------------------===// 1520 // Implementation of TrackConstraintBRVisitor. 1521 //===----------------------------------------------------------------------===// 1522 1523 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const { 1524 static int tag = 0; 1525 ID.AddPointer(&tag); 1526 ID.AddBoolean(Assumption); 1527 ID.Add(Constraint); 1528 } 1529 1530 /// Return the tag associated with this visitor. This tag will be used 1531 /// to make all PathDiagnosticPieces created by this visitor. 1532 const char *TrackConstraintBRVisitor::getTag() { 1533 return "TrackConstraintBRVisitor"; 1534 } 1535 1536 bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const { 1537 if (IsZeroCheck) 1538 return N->getState()->isNull(Constraint).isUnderconstrained(); 1539 return (bool)N->getState()->assume(Constraint, !Assumption); 1540 } 1541 1542 PathDiagnosticPieceRef TrackConstraintBRVisitor::VisitNode( 1543 const ExplodedNode *N, BugReporterContext &BRC, PathSensitiveBugReport &) { 1544 const ExplodedNode *PrevN = N->getFirstPred(); 1545 if (IsSatisfied) 1546 return nullptr; 1547 1548 // Start tracking after we see the first state in which the value is 1549 // constrained. 1550 if (!IsTrackingTurnedOn) 1551 if (!isUnderconstrained(N)) 1552 IsTrackingTurnedOn = true; 1553 if (!IsTrackingTurnedOn) 1554 return nullptr; 1555 1556 // Check if in the previous state it was feasible for this constraint 1557 // to *not* be true. 1558 if (isUnderconstrained(PrevN)) { 1559 IsSatisfied = true; 1560 1561 // As a sanity check, make sure that the negation of the constraint 1562 // was infeasible in the current state. If it is feasible, we somehow 1563 // missed the transition point. 1564 assert(!isUnderconstrained(N)); 1565 1566 // We found the transition point for the constraint. We now need to 1567 // pretty-print the constraint. (work-in-progress) 1568 SmallString<64> sbuf; 1569 llvm::raw_svector_ostream os(sbuf); 1570 1571 if (Constraint.getAs<Loc>()) { 1572 os << "Assuming pointer value is "; 1573 os << (Assumption ? "non-null" : "null"); 1574 } 1575 1576 if (os.str().empty()) 1577 return nullptr; 1578 1579 // Construct a new PathDiagnosticPiece. 1580 ProgramPoint P = N->getLocation(); 1581 PathDiagnosticLocation L = 1582 PathDiagnosticLocation::create(P, BRC.getSourceManager()); 1583 if (!L.isValid()) 1584 return nullptr; 1585 1586 auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str()); 1587 X->setTag(getTag()); 1588 return std::move(X); 1589 } 1590 1591 return nullptr; 1592 } 1593 1594 //===----------------------------------------------------------------------===// 1595 // Implementation of SuppressInlineDefensiveChecksVisitor. 1596 //===----------------------------------------------------------------------===// 1597 1598 SuppressInlineDefensiveChecksVisitor:: 1599 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N) 1600 : V(Value) { 1601 // Check if the visitor is disabled. 1602 AnalyzerOptions &Options = N->getState()->getAnalysisManager().options; 1603 if (!Options.ShouldSuppressInlinedDefensiveChecks) 1604 IsSatisfied = true; 1605 1606 assert(N->getState()->isNull(V).isConstrainedTrue() && 1607 "The visitor only tracks the cases where V is constrained to 0"); 1608 } 1609 1610 void SuppressInlineDefensiveChecksVisitor::Profile( 1611 llvm::FoldingSetNodeID &ID) const { 1612 static int id = 0; 1613 ID.AddPointer(&id); 1614 ID.Add(V); 1615 } 1616 1617 const char *SuppressInlineDefensiveChecksVisitor::getTag() { 1618 return "IDCVisitor"; 1619 } 1620 1621 PathDiagnosticPieceRef 1622 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ, 1623 BugReporterContext &BRC, 1624 PathSensitiveBugReport &BR) { 1625 const ExplodedNode *Pred = Succ->getFirstPred(); 1626 if (IsSatisfied) 1627 return nullptr; 1628 1629 // Start tracking after we see the first state in which the value is null. 1630 if (!IsTrackingTurnedOn) 1631 if (Succ->getState()->isNull(V).isConstrainedTrue()) 1632 IsTrackingTurnedOn = true; 1633 if (!IsTrackingTurnedOn) 1634 return nullptr; 1635 1636 // Check if in the previous state it was feasible for this value 1637 // to *not* be null. 1638 if (!Pred->getState()->isNull(V).isConstrainedTrue()) { 1639 IsSatisfied = true; 1640 1641 assert(Succ->getState()->isNull(V).isConstrainedTrue()); 1642 1643 // Check if this is inlined defensive checks. 1644 const LocationContext *CurLC =Succ->getLocationContext(); 1645 const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext(); 1646 if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) { 1647 BR.markInvalid("Suppress IDC", CurLC); 1648 return nullptr; 1649 } 1650 1651 // Treat defensive checks in function-like macros as if they were an inlined 1652 // defensive check. If the bug location is not in a macro and the 1653 // terminator for the current location is in a macro then suppress the 1654 // warning. 1655 auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>(); 1656 1657 if (!BugPoint) 1658 return nullptr; 1659 1660 ProgramPoint CurPoint = Succ->getLocation(); 1661 const Stmt *CurTerminatorStmt = nullptr; 1662 if (auto BE = CurPoint.getAs<BlockEdge>()) { 1663 CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt(); 1664 } else if (auto SP = CurPoint.getAs<StmtPoint>()) { 1665 const Stmt *CurStmt = SP->getStmt(); 1666 if (!CurStmt->getBeginLoc().isMacroID()) 1667 return nullptr; 1668 1669 CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap(); 1670 CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminatorStmt(); 1671 } else { 1672 return nullptr; 1673 } 1674 1675 if (!CurTerminatorStmt) 1676 return nullptr; 1677 1678 SourceLocation TerminatorLoc = CurTerminatorStmt->getBeginLoc(); 1679 if (TerminatorLoc.isMacroID()) { 1680 SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc(); 1681 1682 // Suppress reports unless we are in that same macro. 1683 if (!BugLoc.isMacroID() || 1684 getMacroName(BugLoc, BRC) != getMacroName(TerminatorLoc, BRC)) { 1685 BR.markInvalid("Suppress Macro IDC", CurLC); 1686 } 1687 return nullptr; 1688 } 1689 } 1690 return nullptr; 1691 } 1692 1693 //===----------------------------------------------------------------------===// 1694 // TrackControlDependencyCondBRVisitor. 1695 //===----------------------------------------------------------------------===// 1696 1697 namespace { 1698 /// Tracks the expressions that are a control dependency of the node that was 1699 /// supplied to the constructor. 1700 /// For example: 1701 /// 1702 /// cond = 1; 1703 /// if (cond) 1704 /// 10 / 0; 1705 /// 1706 /// An error is emitted at line 3. This visitor realizes that the branch 1707 /// on line 2 is a control dependency of line 3, and tracks it's condition via 1708 /// trackExpressionValue(). 1709 class TrackControlDependencyCondBRVisitor final : public BugReporterVisitor { 1710 const ExplodedNode *Origin; 1711 ControlDependencyCalculator ControlDeps; 1712 llvm::SmallSet<const CFGBlock *, 32> VisitedBlocks; 1713 1714 public: 1715 TrackControlDependencyCondBRVisitor(const ExplodedNode *O) 1716 : Origin(O), ControlDeps(&O->getCFG()) {} 1717 1718 void Profile(llvm::FoldingSetNodeID &ID) const override { 1719 static int x = 0; 1720 ID.AddPointer(&x); 1721 } 1722 1723 PathDiagnosticPieceRef VisitNode(const ExplodedNode *N, 1724 BugReporterContext &BRC, 1725 PathSensitiveBugReport &BR) override; 1726 }; 1727 } // end of anonymous namespace 1728 1729 static std::shared_ptr<PathDiagnosticEventPiece> 1730 constructDebugPieceForTrackedCondition(const Expr *Cond, 1731 const ExplodedNode *N, 1732 BugReporterContext &BRC) { 1733 1734 if (BRC.getAnalyzerOptions().AnalysisDiagOpt == PD_NONE || 1735 !BRC.getAnalyzerOptions().ShouldTrackConditionsDebug) 1736 return nullptr; 1737 1738 std::string ConditionText = Lexer::getSourceText( 1739 CharSourceRange::getTokenRange(Cond->getSourceRange()), 1740 BRC.getSourceManager(), 1741 BRC.getASTContext().getLangOpts()); 1742 1743 return std::make_shared<PathDiagnosticEventPiece>( 1744 PathDiagnosticLocation::createBegin( 1745 Cond, BRC.getSourceManager(), N->getLocationContext()), 1746 (Twine() + "Tracking condition '" + ConditionText + "'").str()); 1747 } 1748 1749 static bool isAssertlikeBlock(const CFGBlock *B, ASTContext &Context) { 1750 if (B->succ_size() != 2) 1751 return false; 1752 1753 const CFGBlock *Then = B->succ_begin()->getReachableBlock(); 1754 const CFGBlock *Else = (B->succ_begin() + 1)->getReachableBlock(); 1755 1756 if (!Then || !Else) 1757 return false; 1758 1759 if (Then->isInevitablySinking() != Else->isInevitablySinking()) 1760 return true; 1761 1762 // For the following condition the following CFG would be built: 1763 // 1764 // -------------> 1765 // / \ 1766 // [B1] -> [B2] -> [B3] -> [sink] 1767 // assert(A && B || C); \ \ 1768 // -----------> [go on with the execution] 1769 // 1770 // It so happens that CFGBlock::getTerminatorCondition returns 'A' for block 1771 // B1, 'A && B' for B2, and 'A && B || C' for B3. Let's check whether we 1772 // reached the end of the condition! 1773 if (const Stmt *ElseCond = Else->getTerminatorCondition()) 1774 if (const auto *BinOp = dyn_cast<BinaryOperator>(ElseCond)) 1775 if (BinOp->isLogicalOp()) 1776 return isAssertlikeBlock(Else, Context); 1777 1778 return false; 1779 } 1780 1781 PathDiagnosticPieceRef 1782 TrackControlDependencyCondBRVisitor::VisitNode(const ExplodedNode *N, 1783 BugReporterContext &BRC, 1784 PathSensitiveBugReport &BR) { 1785 // We can only reason about control dependencies within the same stack frame. 1786 if (Origin->getStackFrame() != N->getStackFrame()) 1787 return nullptr; 1788 1789 CFGBlock *NB = const_cast<CFGBlock *>(N->getCFGBlock()); 1790 1791 // Skip if we already inspected this block. 1792 if (!VisitedBlocks.insert(NB).second) 1793 return nullptr; 1794 1795 CFGBlock *OriginB = const_cast<CFGBlock *>(Origin->getCFGBlock()); 1796 1797 // TODO: Cache CFGBlocks for each ExplodedNode. 1798 if (!OriginB || !NB) 1799 return nullptr; 1800 1801 if (isAssertlikeBlock(NB, BRC.getASTContext())) 1802 return nullptr; 1803 1804 if (ControlDeps.isControlDependent(OriginB, NB)) { 1805 // We don't really want to explain for range loops. Evidence suggests that 1806 // the only thing that leads to is the addition of calls to operator!=. 1807 if (isa<CXXForRangeStmt>(NB->getTerminator())) 1808 return nullptr; 1809 1810 if (const Expr *Condition = NB->getLastCondition()) { 1811 // Keeping track of the already tracked conditions on a visitor level 1812 // isn't sufficient, because a new visitor is created for each tracked 1813 // expression, hence the BugReport level set. 1814 if (BR.addTrackedCondition(N)) { 1815 bugreporter::trackExpressionValue( 1816 N, Condition, BR, bugreporter::TrackingKind::Condition, 1817 /*EnableNullFPSuppression=*/false); 1818 return constructDebugPieceForTrackedCondition(Condition, N, BRC); 1819 } 1820 } 1821 } 1822 1823 return nullptr; 1824 } 1825 1826 //===----------------------------------------------------------------------===// 1827 // Implementation of trackExpressionValue. 1828 //===----------------------------------------------------------------------===// 1829 1830 static const MemRegion *getLocationRegionIfReference(const Expr *E, 1831 const ExplodedNode *N) { 1832 if (const auto *DR = dyn_cast<DeclRefExpr>(E)) { 1833 if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) { 1834 if (!VD->getType()->isReferenceType()) 1835 return nullptr; 1836 ProgramStateManager &StateMgr = N->getState()->getStateManager(); 1837 MemRegionManager &MRMgr = StateMgr.getRegionManager(); 1838 return MRMgr.getVarRegion(VD, N->getLocationContext()); 1839 } 1840 } 1841 1842 // FIXME: This does not handle other kinds of null references, 1843 // for example, references from FieldRegions: 1844 // struct Wrapper { int &ref; }; 1845 // Wrapper w = { *(int *)0 }; 1846 // w.ref = 1; 1847 1848 return nullptr; 1849 } 1850 1851 /// \return A subexpression of {@code Ex} which represents the 1852 /// expression-of-interest. 1853 static const Expr *peelOffOuterExpr(const Expr *Ex, 1854 const ExplodedNode *N) { 1855 Ex = Ex->IgnoreParenCasts(); 1856 if (const auto *FE = dyn_cast<FullExpr>(Ex)) 1857 return peelOffOuterExpr(FE->getSubExpr(), N); 1858 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ex)) 1859 return peelOffOuterExpr(OVE->getSourceExpr(), N); 1860 if (const auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) { 1861 const auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm()); 1862 if (PropRef && PropRef->isMessagingGetter()) { 1863 const Expr *GetterMessageSend = 1864 POE->getSemanticExpr(POE->getNumSemanticExprs() - 1); 1865 assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts())); 1866 return peelOffOuterExpr(GetterMessageSend, N); 1867 } 1868 } 1869 1870 // Peel off the ternary operator. 1871 if (const auto *CO = dyn_cast<ConditionalOperator>(Ex)) { 1872 // Find a node where the branching occurred and find out which branch 1873 // we took (true/false) by looking at the ExplodedGraph. 1874 const ExplodedNode *NI = N; 1875 do { 1876 ProgramPoint ProgPoint = NI->getLocation(); 1877 if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) { 1878 const CFGBlock *srcBlk = BE->getSrc(); 1879 if (const Stmt *term = srcBlk->getTerminatorStmt()) { 1880 if (term == CO) { 1881 bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst()); 1882 if (TookTrueBranch) 1883 return peelOffOuterExpr(CO->getTrueExpr(), N); 1884 else 1885 return peelOffOuterExpr(CO->getFalseExpr(), N); 1886 } 1887 } 1888 } 1889 NI = NI->getFirstPred(); 1890 } while (NI); 1891 } 1892 1893 if (auto *BO = dyn_cast<BinaryOperator>(Ex)) 1894 if (const Expr *SubEx = peelOffPointerArithmetic(BO)) 1895 return peelOffOuterExpr(SubEx, N); 1896 1897 if (auto *UO = dyn_cast<UnaryOperator>(Ex)) { 1898 if (UO->getOpcode() == UO_LNot) 1899 return peelOffOuterExpr(UO->getSubExpr(), N); 1900 1901 // FIXME: There's a hack in our Store implementation that always computes 1902 // field offsets around null pointers as if they are always equal to 0. 1903 // The idea here is to report accesses to fields as null dereferences 1904 // even though the pointer value that's being dereferenced is actually 1905 // the offset of the field rather than exactly 0. 1906 // See the FIXME in StoreManager's getLValueFieldOrIvar() method. 1907 // This code interacts heavily with this hack; otherwise the value 1908 // would not be null at all for most fields, so we'd be unable to track it. 1909 if (UO->getOpcode() == UO_AddrOf && UO->getSubExpr()->isLValue()) 1910 if (const Expr *DerefEx = bugreporter::getDerefExpr(UO->getSubExpr())) 1911 return peelOffOuterExpr(DerefEx, N); 1912 } 1913 1914 return Ex; 1915 } 1916 1917 /// Find the ExplodedNode where the lvalue (the value of 'Ex') 1918 /// was computed. 1919 static const ExplodedNode* findNodeForExpression(const ExplodedNode *N, 1920 const Expr *Inner) { 1921 while (N) { 1922 if (PathDiagnosticLocation::getStmt(N) == Inner) 1923 return N; 1924 N = N->getFirstPred(); 1925 } 1926 return N; 1927 } 1928 1929 bool bugreporter::trackExpressionValue(const ExplodedNode *InputNode, 1930 const Expr *E, 1931 PathSensitiveBugReport &report, 1932 bugreporter::TrackingKind TKind, 1933 bool EnableNullFPSuppression) { 1934 1935 if (!E || !InputNode) 1936 return false; 1937 1938 const Expr *Inner = peelOffOuterExpr(E, InputNode); 1939 const ExplodedNode *LVNode = findNodeForExpression(InputNode, Inner); 1940 if (!LVNode) 1941 return false; 1942 1943 ProgramStateRef LVState = LVNode->getState(); 1944 const StackFrameContext *SFC = LVNode->getStackFrame(); 1945 1946 // We only track expressions if we believe that they are important. Chances 1947 // are good that control dependencies to the tracking point are also improtant 1948 // because of this, let's explain why we believe control reached this point. 1949 // TODO: Shouldn't we track control dependencies of every bug location, rather 1950 // than only tracked expressions? 1951 if (LVState->getAnalysisManager().getAnalyzerOptions().ShouldTrackConditions) 1952 report.addVisitor(std::make_unique<TrackControlDependencyCondBRVisitor>( 1953 InputNode)); 1954 1955 // The message send could be nil due to the receiver being nil. 1956 // At this point in the path, the receiver should be live since we are at the 1957 // message send expr. If it is nil, start tracking it. 1958 if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(Inner, LVNode)) 1959 trackExpressionValue( 1960 LVNode, Receiver, report, TKind, EnableNullFPSuppression); 1961 1962 // Track the index if this is an array subscript. 1963 if (const auto *Arr = dyn_cast<ArraySubscriptExpr>(Inner)) 1964 trackExpressionValue( 1965 LVNode, Arr->getIdx(), report, TKind, /*EnableNullFPSuppression*/false); 1966 1967 // See if the expression we're interested refers to a variable. 1968 // If so, we can track both its contents and constraints on its value. 1969 if (ExplodedGraph::isInterestingLValueExpr(Inner)) { 1970 SVal LVal = LVNode->getSVal(Inner); 1971 1972 const MemRegion *RR = getLocationRegionIfReference(Inner, LVNode); 1973 bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue(); 1974 1975 // If this is a C++ reference to a null pointer, we are tracking the 1976 // pointer. In addition, we should find the store at which the reference 1977 // got initialized. 1978 if (RR && !LVIsNull) 1979 if (auto KV = LVal.getAs<KnownSVal>()) 1980 report.addVisitor(std::make_unique<FindLastStoreBRVisitor>( 1981 *KV, RR, EnableNullFPSuppression, TKind, SFC)); 1982 1983 // In case of C++ references, we want to differentiate between a null 1984 // reference and reference to null pointer. 1985 // If the LVal is null, check if we are dealing with null reference. 1986 // For those, we want to track the location of the reference. 1987 const MemRegion *R = (RR && LVIsNull) ? RR : 1988 LVNode->getSVal(Inner).getAsRegion(); 1989 1990 if (R) { 1991 1992 // Mark both the variable region and its contents as interesting. 1993 SVal V = LVState->getRawSVal(loc::MemRegionVal(R)); 1994 report.addVisitor( 1995 std::make_unique<NoStoreFuncVisitor>(cast<SubRegion>(R), TKind)); 1996 1997 MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary( 1998 LVNode, R, EnableNullFPSuppression, report, V); 1999 2000 report.markInteresting(V, TKind); 2001 report.addVisitor(std::make_unique<UndefOrNullArgVisitor>(R)); 2002 2003 // If the contents are symbolic and null, find out when they became null. 2004 if (V.getAsLocSymbol(/*IncludeBaseRegions=*/true)) 2005 if (LVState->isNull(V).isConstrainedTrue()) 2006 report.addVisitor(std::make_unique<TrackConstraintBRVisitor>( 2007 V.castAs<DefinedSVal>(), false)); 2008 2009 // Add visitor, which will suppress inline defensive checks. 2010 if (auto DV = V.getAs<DefinedSVal>()) 2011 if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() && 2012 EnableNullFPSuppression) 2013 report.addVisitor( 2014 std::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV, 2015 LVNode)); 2016 2017 if (auto KV = V.getAs<KnownSVal>()) 2018 report.addVisitor(std::make_unique<FindLastStoreBRVisitor>( 2019 *KV, R, EnableNullFPSuppression, TKind, SFC)); 2020 return true; 2021 } 2022 } 2023 2024 // If the expression is not an "lvalue expression", we can still 2025 // track the constraints on its contents. 2026 SVal V = LVState->getSValAsScalarOrLoc(Inner, LVNode->getLocationContext()); 2027 2028 ReturnVisitor::addVisitorIfNecessary( 2029 LVNode, Inner, report, EnableNullFPSuppression, TKind); 2030 2031 // Is it a symbolic value? 2032 if (auto L = V.getAs<loc::MemRegionVal>()) { 2033 report.addVisitor(std::make_unique<UndefOrNullArgVisitor>(L->getRegion())); 2034 2035 // FIXME: this is a hack for fixing a later crash when attempting to 2036 // dereference a void* pointer. 2037 // We should not try to dereference pointers at all when we don't care 2038 // what is written inside the pointer. 2039 bool CanDereference = true; 2040 if (const auto *SR = L->getRegionAs<SymbolicRegion>()) { 2041 if (SR->getSymbol()->getType()->getPointeeType()->isVoidType()) 2042 CanDereference = false; 2043 } else if (L->getRegionAs<AllocaRegion>()) 2044 CanDereference = false; 2045 2046 // At this point we are dealing with the region's LValue. 2047 // However, if the rvalue is a symbolic region, we should track it as well. 2048 // Try to use the correct type when looking up the value. 2049 SVal RVal; 2050 if (ExplodedGraph::isInterestingLValueExpr(Inner)) 2051 RVal = LVState->getRawSVal(L.getValue(), Inner->getType()); 2052 else if (CanDereference) 2053 RVal = LVState->getSVal(L->getRegion()); 2054 2055 if (CanDereference) 2056 if (auto KV = RVal.getAs<KnownSVal>()) 2057 report.addVisitor(std::make_unique<FindLastStoreBRVisitor>( 2058 *KV, L->getRegion(), EnableNullFPSuppression, TKind, SFC)); 2059 2060 const MemRegion *RegionRVal = RVal.getAsRegion(); 2061 if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) { 2062 report.markInteresting(RegionRVal, TKind); 2063 report.addVisitor(std::make_unique<TrackConstraintBRVisitor>( 2064 loc::MemRegionVal(RegionRVal), /*assumption=*/false)); 2065 } 2066 } 2067 return true; 2068 } 2069 2070 //===----------------------------------------------------------------------===// 2071 // Implementation of NulReceiverBRVisitor. 2072 //===----------------------------------------------------------------------===// 2073 2074 const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S, 2075 const ExplodedNode *N) { 2076 const auto *ME = dyn_cast<ObjCMessageExpr>(S); 2077 if (!ME) 2078 return nullptr; 2079 if (const Expr *Receiver = ME->getInstanceReceiver()) { 2080 ProgramStateRef state = N->getState(); 2081 SVal V = N->getSVal(Receiver); 2082 if (state->isNull(V).isConstrainedTrue()) 2083 return Receiver; 2084 } 2085 return nullptr; 2086 } 2087 2088 PathDiagnosticPieceRef 2089 NilReceiverBRVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC, 2090 PathSensitiveBugReport &BR) { 2091 Optional<PreStmt> P = N->getLocationAs<PreStmt>(); 2092 if (!P) 2093 return nullptr; 2094 2095 const Stmt *S = P->getStmt(); 2096 const Expr *Receiver = getNilReceiver(S, N); 2097 if (!Receiver) 2098 return nullptr; 2099 2100 llvm::SmallString<256> Buf; 2101 llvm::raw_svector_ostream OS(Buf); 2102 2103 if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) { 2104 OS << "'"; 2105 ME->getSelector().print(OS); 2106 OS << "' not called"; 2107 } 2108 else { 2109 OS << "No method is called"; 2110 } 2111 OS << " because the receiver is nil"; 2112 2113 // The receiver was nil, and hence the method was skipped. 2114 // Register a BugReporterVisitor to issue a message telling us how 2115 // the receiver was null. 2116 bugreporter::trackExpressionValue( 2117 N, Receiver, BR, bugreporter::TrackingKind::Thorough, 2118 /*EnableNullFPSuppression*/ false); 2119 // Issue a message saying that the method was skipped. 2120 PathDiagnosticLocation L(Receiver, BRC.getSourceManager(), 2121 N->getLocationContext()); 2122 return std::make_shared<PathDiagnosticEventPiece>(L, OS.str()); 2123 } 2124 2125 //===----------------------------------------------------------------------===// 2126 // Visitor that tries to report interesting diagnostics from conditions. 2127 //===----------------------------------------------------------------------===// 2128 2129 /// Return the tag associated with this visitor. This tag will be used 2130 /// to make all PathDiagnosticPieces created by this visitor. 2131 const char *ConditionBRVisitor::getTag() { return "ConditionBRVisitor"; } 2132 2133 PathDiagnosticPieceRef 2134 ConditionBRVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC, 2135 PathSensitiveBugReport &BR) { 2136 auto piece = VisitNodeImpl(N, BRC, BR); 2137 if (piece) { 2138 piece->setTag(getTag()); 2139 if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get())) 2140 ev->setPrunable(true, /* override */ false); 2141 } 2142 return piece; 2143 } 2144 2145 PathDiagnosticPieceRef 2146 ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N, 2147 BugReporterContext &BRC, 2148 PathSensitiveBugReport &BR) { 2149 ProgramPoint ProgPoint = N->getLocation(); 2150 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &Tags = 2151 ExprEngine::geteagerlyAssumeBinOpBifurcationTags(); 2152 2153 // If an assumption was made on a branch, it should be caught 2154 // here by looking at the state transition. 2155 if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) { 2156 const CFGBlock *SrcBlock = BE->getSrc(); 2157 if (const Stmt *Term = SrcBlock->getTerminatorStmt()) { 2158 // If the tag of the previous node is 'Eagerly Assume...' the current 2159 // 'BlockEdge' has the same constraint information. We do not want to 2160 // report the value as it is just an assumption on the predecessor node 2161 // which will be caught in the next VisitNode() iteration as a 'PostStmt'. 2162 const ProgramPointTag *PreviousNodeTag = 2163 N->getFirstPred()->getLocation().getTag(); 2164 if (PreviousNodeTag == Tags.first || PreviousNodeTag == Tags.second) 2165 return nullptr; 2166 2167 return VisitTerminator(Term, N, SrcBlock, BE->getDst(), BR, BRC); 2168 } 2169 return nullptr; 2170 } 2171 2172 if (Optional<PostStmt> PS = ProgPoint.getAs<PostStmt>()) { 2173 const ProgramPointTag *CurrentNodeTag = PS->getTag(); 2174 if (CurrentNodeTag != Tags.first && CurrentNodeTag != Tags.second) 2175 return nullptr; 2176 2177 bool TookTrue = CurrentNodeTag == Tags.first; 2178 return VisitTrueTest(cast<Expr>(PS->getStmt()), BRC, BR, N, TookTrue); 2179 } 2180 2181 return nullptr; 2182 } 2183 2184 PathDiagnosticPieceRef ConditionBRVisitor::VisitTerminator( 2185 const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk, 2186 const CFGBlock *dstBlk, PathSensitiveBugReport &R, 2187 BugReporterContext &BRC) { 2188 const Expr *Cond = nullptr; 2189 2190 // In the code below, Term is a CFG terminator and Cond is a branch condition 2191 // expression upon which the decision is made on this terminator. 2192 // 2193 // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator, 2194 // and "x == 0" is the respective condition. 2195 // 2196 // Another example: in "if (x && y)", we've got two terminators and two 2197 // conditions due to short-circuit nature of operator "&&": 2198 // 1. The "if (x && y)" statement is a terminator, 2199 // and "y" is the respective condition. 2200 // 2. Also "x && ..." is another terminator, 2201 // and "x" is its condition. 2202 2203 switch (Term->getStmtClass()) { 2204 // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit 2205 // more tricky because there are more than two branches to account for. 2206 default: 2207 return nullptr; 2208 case Stmt::IfStmtClass: 2209 Cond = cast<IfStmt>(Term)->getCond(); 2210 break; 2211 case Stmt::ConditionalOperatorClass: 2212 Cond = cast<ConditionalOperator>(Term)->getCond(); 2213 break; 2214 case Stmt::BinaryOperatorClass: 2215 // When we encounter a logical operator (&& or ||) as a CFG terminator, 2216 // then the condition is actually its LHS; otherwise, we'd encounter 2217 // the parent, such as if-statement, as a terminator. 2218 const auto *BO = cast<BinaryOperator>(Term); 2219 assert(BO->isLogicalOp() && 2220 "CFG terminator is not a short-circuit operator!"); 2221 Cond = BO->getLHS(); 2222 break; 2223 } 2224 2225 Cond = Cond->IgnoreParens(); 2226 2227 // However, when we encounter a logical operator as a branch condition, 2228 // then the condition is actually its RHS, because LHS would be 2229 // the condition for the logical operator terminator. 2230 while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) { 2231 if (!InnerBO->isLogicalOp()) 2232 break; 2233 Cond = InnerBO->getRHS()->IgnoreParens(); 2234 } 2235 2236 assert(Cond); 2237 assert(srcBlk->succ_size() == 2); 2238 const bool TookTrue = *(srcBlk->succ_begin()) == dstBlk; 2239 return VisitTrueTest(Cond, BRC, R, N, TookTrue); 2240 } 2241 2242 PathDiagnosticPieceRef 2243 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, BugReporterContext &BRC, 2244 PathSensitiveBugReport &R, 2245 const ExplodedNode *N, bool TookTrue) { 2246 ProgramStateRef CurrentState = N->getState(); 2247 ProgramStateRef PrevState = N->getFirstPred()->getState(); 2248 const LocationContext *LCtx = N->getLocationContext(); 2249 2250 // If the constraint information is changed between the current and the 2251 // previous program state we assuming the newly seen constraint information. 2252 // If we cannot evaluate the condition (and the constraints are the same) 2253 // the analyzer has no information about the value and just assuming it. 2254 bool IsAssuming = 2255 !BRC.getStateManager().haveEqualConstraints(CurrentState, PrevState) || 2256 CurrentState->getSVal(Cond, LCtx).isUnknownOrUndef(); 2257 2258 // These will be modified in code below, but we need to preserve the original 2259 // values in case we want to throw the generic message. 2260 const Expr *CondTmp = Cond; 2261 bool TookTrueTmp = TookTrue; 2262 2263 while (true) { 2264 CondTmp = CondTmp->IgnoreParenCasts(); 2265 switch (CondTmp->getStmtClass()) { 2266 default: 2267 break; 2268 case Stmt::BinaryOperatorClass: 2269 if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp), 2270 BRC, R, N, TookTrueTmp, IsAssuming)) 2271 return P; 2272 break; 2273 case Stmt::DeclRefExprClass: 2274 if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp), 2275 BRC, R, N, TookTrueTmp, IsAssuming)) 2276 return P; 2277 break; 2278 case Stmt::MemberExprClass: 2279 if (auto P = VisitTrueTest(Cond, cast<MemberExpr>(CondTmp), 2280 BRC, R, N, TookTrueTmp, IsAssuming)) 2281 return P; 2282 break; 2283 case Stmt::UnaryOperatorClass: { 2284 const auto *UO = cast<UnaryOperator>(CondTmp); 2285 if (UO->getOpcode() == UO_LNot) { 2286 TookTrueTmp = !TookTrueTmp; 2287 CondTmp = UO->getSubExpr(); 2288 continue; 2289 } 2290 break; 2291 } 2292 } 2293 break; 2294 } 2295 2296 // Condition too complex to explain? Just say something so that the user 2297 // knew we've made some path decision at this point. 2298 // If it is too complex and we know the evaluation of the condition do not 2299 // repeat the note from 'BugReporter.cpp' 2300 if (!IsAssuming) 2301 return nullptr; 2302 2303 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx); 2304 if (!Loc.isValid() || !Loc.asLocation().isValid()) 2305 return nullptr; 2306 2307 return std::make_shared<PathDiagnosticEventPiece>( 2308 Loc, TookTrue ? GenericTrueMessage : GenericFalseMessage); 2309 } 2310 2311 bool ConditionBRVisitor::patternMatch(const Expr *Ex, 2312 const Expr *ParentEx, 2313 raw_ostream &Out, 2314 BugReporterContext &BRC, 2315 PathSensitiveBugReport &report, 2316 const ExplodedNode *N, 2317 Optional<bool> &prunable, 2318 bool IsSameFieldName) { 2319 const Expr *OriginalExpr = Ex; 2320 Ex = Ex->IgnoreParenCasts(); 2321 2322 if (isa<GNUNullExpr>(Ex) || isa<ObjCBoolLiteralExpr>(Ex) || 2323 isa<CXXBoolLiteralExpr>(Ex) || isa<IntegerLiteral>(Ex) || 2324 isa<FloatingLiteral>(Ex)) { 2325 // Use heuristics to determine if the expression is a macro 2326 // expanding to a literal and if so, use the macro's name. 2327 SourceLocation BeginLoc = OriginalExpr->getBeginLoc(); 2328 SourceLocation EndLoc = OriginalExpr->getEndLoc(); 2329 if (BeginLoc.isMacroID() && EndLoc.isMacroID()) { 2330 const SourceManager &SM = BRC.getSourceManager(); 2331 const LangOptions &LO = BRC.getASTContext().getLangOpts(); 2332 if (Lexer::isAtStartOfMacroExpansion(BeginLoc, SM, LO) && 2333 Lexer::isAtEndOfMacroExpansion(EndLoc, SM, LO)) { 2334 CharSourceRange R = Lexer::getAsCharRange({BeginLoc, EndLoc}, SM, LO); 2335 Out << Lexer::getSourceText(R, SM, LO); 2336 return false; 2337 } 2338 } 2339 } 2340 2341 if (const auto *DR = dyn_cast<DeclRefExpr>(Ex)) { 2342 const bool quotes = isa<VarDecl>(DR->getDecl()); 2343 if (quotes) { 2344 Out << '\''; 2345 const LocationContext *LCtx = N->getLocationContext(); 2346 const ProgramState *state = N->getState().get(); 2347 if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()), 2348 LCtx).getAsRegion()) { 2349 if (report.isInteresting(R)) 2350 prunable = false; 2351 else { 2352 const ProgramState *state = N->getState().get(); 2353 SVal V = state->getSVal(R); 2354 if (report.isInteresting(V)) 2355 prunable = false; 2356 } 2357 } 2358 } 2359 Out << DR->getDecl()->getDeclName().getAsString(); 2360 if (quotes) 2361 Out << '\''; 2362 return quotes; 2363 } 2364 2365 if (const auto *IL = dyn_cast<IntegerLiteral>(Ex)) { 2366 QualType OriginalTy = OriginalExpr->getType(); 2367 if (OriginalTy->isPointerType()) { 2368 if (IL->getValue() == 0) { 2369 Out << "null"; 2370 return false; 2371 } 2372 } 2373 else if (OriginalTy->isObjCObjectPointerType()) { 2374 if (IL->getValue() == 0) { 2375 Out << "nil"; 2376 return false; 2377 } 2378 } 2379 2380 Out << IL->getValue(); 2381 return false; 2382 } 2383 2384 if (const auto *ME = dyn_cast<MemberExpr>(Ex)) { 2385 if (!IsSameFieldName) 2386 Out << "field '" << ME->getMemberDecl()->getName() << '\''; 2387 else 2388 Out << '\'' 2389 << Lexer::getSourceText( 2390 CharSourceRange::getTokenRange(Ex->getSourceRange()), 2391 BRC.getSourceManager(), BRC.getASTContext().getLangOpts(), 0) 2392 << '\''; 2393 } 2394 2395 return false; 2396 } 2397 2398 PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest( 2399 const Expr *Cond, const BinaryOperator *BExpr, BugReporterContext &BRC, 2400 PathSensitiveBugReport &R, const ExplodedNode *N, bool TookTrue, 2401 bool IsAssuming) { 2402 bool shouldInvert = false; 2403 Optional<bool> shouldPrune; 2404 2405 // Check if the field name of the MemberExprs is ambiguous. Example: 2406 // " 'a.d' is equal to 'h.d' " in 'test/Analysis/null-deref-path-notes.cpp'. 2407 bool IsSameFieldName = false; 2408 const auto *LhsME = dyn_cast<MemberExpr>(BExpr->getLHS()->IgnoreParenCasts()); 2409 const auto *RhsME = dyn_cast<MemberExpr>(BExpr->getRHS()->IgnoreParenCasts()); 2410 2411 if (LhsME && RhsME) 2412 IsSameFieldName = 2413 LhsME->getMemberDecl()->getName() == RhsME->getMemberDecl()->getName(); 2414 2415 SmallString<128> LhsString, RhsString; 2416 { 2417 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString); 2418 const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS, BRC, R, 2419 N, shouldPrune, IsSameFieldName); 2420 const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS, BRC, R, 2421 N, shouldPrune, IsSameFieldName); 2422 2423 shouldInvert = !isVarLHS && isVarRHS; 2424 } 2425 2426 BinaryOperator::Opcode Op = BExpr->getOpcode(); 2427 2428 if (BinaryOperator::isAssignmentOp(Op)) { 2429 // For assignment operators, all that we care about is that the LHS 2430 // evaluates to "true" or "false". 2431 return VisitConditionVariable(LhsString, BExpr->getLHS(), BRC, R, N, 2432 TookTrue); 2433 } 2434 2435 // For non-assignment operations, we require that we can understand 2436 // both the LHS and RHS. 2437 if (LhsString.empty() || RhsString.empty() || 2438 !BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp) 2439 return nullptr; 2440 2441 // Should we invert the strings if the LHS is not a variable name? 2442 SmallString<256> buf; 2443 llvm::raw_svector_ostream Out(buf); 2444 Out << (IsAssuming ? "Assuming " : "") 2445 << (shouldInvert ? RhsString : LhsString) << " is "; 2446 2447 // Do we need to invert the opcode? 2448 if (shouldInvert) 2449 switch (Op) { 2450 default: break; 2451 case BO_LT: Op = BO_GT; break; 2452 case BO_GT: Op = BO_LT; break; 2453 case BO_LE: Op = BO_GE; break; 2454 case BO_GE: Op = BO_LE; break; 2455 } 2456 2457 if (!TookTrue) 2458 switch (Op) { 2459 case BO_EQ: Op = BO_NE; break; 2460 case BO_NE: Op = BO_EQ; break; 2461 case BO_LT: Op = BO_GE; break; 2462 case BO_GT: Op = BO_LE; break; 2463 case BO_LE: Op = BO_GT; break; 2464 case BO_GE: Op = BO_LT; break; 2465 default: 2466 return nullptr; 2467 } 2468 2469 switch (Op) { 2470 case BO_EQ: 2471 Out << "equal to "; 2472 break; 2473 case BO_NE: 2474 Out << "not equal to "; 2475 break; 2476 default: 2477 Out << BinaryOperator::getOpcodeStr(Op) << ' '; 2478 break; 2479 } 2480 2481 Out << (shouldInvert ? LhsString : RhsString); 2482 const LocationContext *LCtx = N->getLocationContext(); 2483 const SourceManager &SM = BRC.getSourceManager(); 2484 2485 if (isVarAnInterestingCondition(BExpr->getLHS(), N, &R) || 2486 isVarAnInterestingCondition(BExpr->getRHS(), N, &R)) 2487 Out << WillBeUsedForACondition; 2488 2489 // Convert 'field ...' to 'Field ...' if it is a MemberExpr. 2490 std::string Message = Out.str(); 2491 Message[0] = toupper(Message[0]); 2492 2493 // If we know the value create a pop-up note to the value part of 'BExpr'. 2494 if (!IsAssuming) { 2495 PathDiagnosticLocation Loc; 2496 if (!shouldInvert) { 2497 if (LhsME && LhsME->getMemberLoc().isValid()) 2498 Loc = PathDiagnosticLocation(LhsME->getMemberLoc(), SM); 2499 else 2500 Loc = PathDiagnosticLocation(BExpr->getLHS(), SM, LCtx); 2501 } else { 2502 if (RhsME && RhsME->getMemberLoc().isValid()) 2503 Loc = PathDiagnosticLocation(RhsME->getMemberLoc(), SM); 2504 else 2505 Loc = PathDiagnosticLocation(BExpr->getRHS(), SM, LCtx); 2506 } 2507 2508 return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Message); 2509 } 2510 2511 PathDiagnosticLocation Loc(Cond, SM, LCtx); 2512 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Message); 2513 if (shouldPrune.hasValue()) 2514 event->setPrunable(shouldPrune.getValue()); 2515 return event; 2516 } 2517 2518 PathDiagnosticPieceRef ConditionBRVisitor::VisitConditionVariable( 2519 StringRef LhsString, const Expr *CondVarExpr, BugReporterContext &BRC, 2520 PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue) { 2521 // FIXME: If there's already a constraint tracker for this variable, 2522 // we shouldn't emit anything here (c.f. the double note in 2523 // test/Analysis/inlining/path-notes.c) 2524 SmallString<256> buf; 2525 llvm::raw_svector_ostream Out(buf); 2526 Out << "Assuming " << LhsString << " is "; 2527 2528 if (!printValue(CondVarExpr, Out, N, TookTrue, /*IsAssuming=*/true)) 2529 return nullptr; 2530 2531 const LocationContext *LCtx = N->getLocationContext(); 2532 PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx); 2533 2534 if (isVarAnInterestingCondition(CondVarExpr, N, &report)) 2535 Out << WillBeUsedForACondition; 2536 2537 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str()); 2538 2539 if (isInterestingExpr(CondVarExpr, N, &report)) 2540 event->setPrunable(false); 2541 2542 return event; 2543 } 2544 2545 PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest( 2546 const Expr *Cond, const DeclRefExpr *DRE, BugReporterContext &BRC, 2547 PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue, 2548 bool IsAssuming) { 2549 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); 2550 if (!VD) 2551 return nullptr; 2552 2553 SmallString<256> Buf; 2554 llvm::raw_svector_ostream Out(Buf); 2555 2556 Out << (IsAssuming ? "Assuming '" : "'") << VD->getDeclName() << "' is "; 2557 2558 if (!printValue(DRE, Out, N, TookTrue, IsAssuming)) 2559 return nullptr; 2560 2561 const LocationContext *LCtx = N->getLocationContext(); 2562 2563 if (isVarAnInterestingCondition(DRE, N, &report)) 2564 Out << WillBeUsedForACondition; 2565 2566 // If we know the value create a pop-up note to the 'DRE'. 2567 if (!IsAssuming) { 2568 PathDiagnosticLocation Loc(DRE, BRC.getSourceManager(), LCtx); 2569 return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str()); 2570 } 2571 2572 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx); 2573 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str()); 2574 2575 if (isInterestingExpr(DRE, N, &report)) 2576 event->setPrunable(false); 2577 2578 return std::move(event); 2579 } 2580 2581 PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest( 2582 const Expr *Cond, const MemberExpr *ME, BugReporterContext &BRC, 2583 PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue, 2584 bool IsAssuming) { 2585 SmallString<256> Buf; 2586 llvm::raw_svector_ostream Out(Buf); 2587 2588 Out << (IsAssuming ? "Assuming field '" : "Field '") 2589 << ME->getMemberDecl()->getName() << "' is "; 2590 2591 if (!printValue(ME, Out, N, TookTrue, IsAssuming)) 2592 return nullptr; 2593 2594 const LocationContext *LCtx = N->getLocationContext(); 2595 PathDiagnosticLocation Loc; 2596 2597 // If we know the value create a pop-up note to the member of the MemberExpr. 2598 if (!IsAssuming && ME->getMemberLoc().isValid()) 2599 Loc = PathDiagnosticLocation(ME->getMemberLoc(), BRC.getSourceManager()); 2600 else 2601 Loc = PathDiagnosticLocation(Cond, BRC.getSourceManager(), LCtx); 2602 2603 if (!Loc.isValid() || !Loc.asLocation().isValid()) 2604 return nullptr; 2605 2606 if (isVarAnInterestingCondition(ME, N, &report)) 2607 Out << WillBeUsedForACondition; 2608 2609 // If we know the value create a pop-up note. 2610 if (!IsAssuming) 2611 return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str()); 2612 2613 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str()); 2614 if (isInterestingExpr(ME, N, &report)) 2615 event->setPrunable(false); 2616 return event; 2617 } 2618 2619 bool ConditionBRVisitor::printValue(const Expr *CondVarExpr, raw_ostream &Out, 2620 const ExplodedNode *N, bool TookTrue, 2621 bool IsAssuming) { 2622 QualType Ty = CondVarExpr->getType(); 2623 2624 if (Ty->isPointerType()) { 2625 Out << (TookTrue ? "non-null" : "null"); 2626 return true; 2627 } 2628 2629 if (Ty->isObjCObjectPointerType()) { 2630 Out << (TookTrue ? "non-nil" : "nil"); 2631 return true; 2632 } 2633 2634 if (!Ty->isIntegralOrEnumerationType()) 2635 return false; 2636 2637 Optional<const llvm::APSInt *> IntValue; 2638 if (!IsAssuming) 2639 IntValue = getConcreteIntegerValue(CondVarExpr, N); 2640 2641 if (IsAssuming || !IntValue.hasValue()) { 2642 if (Ty->isBooleanType()) 2643 Out << (TookTrue ? "true" : "false"); 2644 else 2645 Out << (TookTrue ? "not equal to 0" : "0"); 2646 } else { 2647 if (Ty->isBooleanType()) 2648 Out << (IntValue.getValue()->getBoolValue() ? "true" : "false"); 2649 else 2650 Out << *IntValue.getValue(); 2651 } 2652 2653 return true; 2654 } 2655 2656 constexpr llvm::StringLiteral ConditionBRVisitor::GenericTrueMessage; 2657 constexpr llvm::StringLiteral ConditionBRVisitor::GenericFalseMessage; 2658 2659 bool ConditionBRVisitor::isPieceMessageGeneric( 2660 const PathDiagnosticPiece *Piece) { 2661 return Piece->getString() == GenericTrueMessage || 2662 Piece->getString() == GenericFalseMessage; 2663 } 2664 2665 //===----------------------------------------------------------------------===// 2666 // Implementation of LikelyFalsePositiveSuppressionBRVisitor. 2667 //===----------------------------------------------------------------------===// 2668 2669 void LikelyFalsePositiveSuppressionBRVisitor::finalizeVisitor( 2670 BugReporterContext &BRC, const ExplodedNode *N, 2671 PathSensitiveBugReport &BR) { 2672 // Here we suppress false positives coming from system headers. This list is 2673 // based on known issues. 2674 const AnalyzerOptions &Options = BRC.getAnalyzerOptions(); 2675 const Decl *D = N->getLocationContext()->getDecl(); 2676 2677 if (AnalysisDeclContext::isInStdNamespace(D)) { 2678 // Skip reports within the 'std' namespace. Although these can sometimes be 2679 // the user's fault, we currently don't report them very well, and 2680 // Note that this will not help for any other data structure libraries, like 2681 // TR1, Boost, or llvm/ADT. 2682 if (Options.ShouldSuppressFromCXXStandardLibrary) { 2683 BR.markInvalid(getTag(), nullptr); 2684 return; 2685 } else { 2686 // If the complete 'std' suppression is not enabled, suppress reports 2687 // from the 'std' namespace that are known to produce false positives. 2688 2689 // The analyzer issues a false use-after-free when std::list::pop_front 2690 // or std::list::pop_back are called multiple times because we cannot 2691 // reason about the internal invariants of the data structure. 2692 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) { 2693 const CXXRecordDecl *CD = MD->getParent(); 2694 if (CD->getName() == "list") { 2695 BR.markInvalid(getTag(), nullptr); 2696 return; 2697 } 2698 } 2699 2700 // The analyzer issues a false positive when the constructor of 2701 // std::__independent_bits_engine from algorithms is used. 2702 if (const auto *MD = dyn_cast<CXXConstructorDecl>(D)) { 2703 const CXXRecordDecl *CD = MD->getParent(); 2704 if (CD->getName() == "__independent_bits_engine") { 2705 BR.markInvalid(getTag(), nullptr); 2706 return; 2707 } 2708 } 2709 2710 for (const LocationContext *LCtx = N->getLocationContext(); LCtx; 2711 LCtx = LCtx->getParent()) { 2712 const auto *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl()); 2713 if (!MD) 2714 continue; 2715 2716 const CXXRecordDecl *CD = MD->getParent(); 2717 // The analyzer issues a false positive on 2718 // std::basic_string<uint8_t> v; v.push_back(1); 2719 // and 2720 // std::u16string s; s += u'a'; 2721 // because we cannot reason about the internal invariants of the 2722 // data structure. 2723 if (CD->getName() == "basic_string") { 2724 BR.markInvalid(getTag(), nullptr); 2725 return; 2726 } 2727 2728 // The analyzer issues a false positive on 2729 // std::shared_ptr<int> p(new int(1)); p = nullptr; 2730 // because it does not reason properly about temporary destructors. 2731 if (CD->getName() == "shared_ptr") { 2732 BR.markInvalid(getTag(), nullptr); 2733 return; 2734 } 2735 } 2736 } 2737 } 2738 2739 // Skip reports within the sys/queue.h macros as we do not have the ability to 2740 // reason about data structure shapes. 2741 const SourceManager &SM = BRC.getSourceManager(); 2742 FullSourceLoc Loc = BR.getLocation().asLocation(); 2743 while (Loc.isMacroID()) { 2744 Loc = Loc.getSpellingLoc(); 2745 if (SM.getFilename(Loc).endswith("sys/queue.h")) { 2746 BR.markInvalid(getTag(), nullptr); 2747 return; 2748 } 2749 } 2750 } 2751 2752 //===----------------------------------------------------------------------===// 2753 // Implementation of UndefOrNullArgVisitor. 2754 //===----------------------------------------------------------------------===// 2755 2756 PathDiagnosticPieceRef 2757 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC, 2758 PathSensitiveBugReport &BR) { 2759 ProgramStateRef State = N->getState(); 2760 ProgramPoint ProgLoc = N->getLocation(); 2761 2762 // We are only interested in visiting CallEnter nodes. 2763 Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>(); 2764 if (!CEnter) 2765 return nullptr; 2766 2767 // Check if one of the arguments is the region the visitor is tracking. 2768 CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager(); 2769 CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State); 2770 unsigned Idx = 0; 2771 ArrayRef<ParmVarDecl *> parms = Call->parameters(); 2772 2773 for (const auto ParamDecl : parms) { 2774 const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion(); 2775 ++Idx; 2776 2777 // Are we tracking the argument or its subregion? 2778 if ( !ArgReg || !R->isSubRegionOf(ArgReg->StripCasts())) 2779 continue; 2780 2781 // Check the function parameter type. 2782 assert(ParamDecl && "Formal parameter has no decl?"); 2783 QualType T = ParamDecl->getType(); 2784 2785 if (!(T->isAnyPointerType() || T->isReferenceType())) { 2786 // Function can only change the value passed in by address. 2787 continue; 2788 } 2789 2790 // If it is a const pointer value, the function does not intend to 2791 // change the value. 2792 if (T->getPointeeType().isConstQualified()) 2793 continue; 2794 2795 // Mark the call site (LocationContext) as interesting if the value of the 2796 // argument is undefined or '0'/'NULL'. 2797 SVal BoundVal = State->getSVal(R); 2798 if (BoundVal.isUndef() || BoundVal.isZeroConstant()) { 2799 BR.markInteresting(CEnter->getCalleeContext()); 2800 return nullptr; 2801 } 2802 } 2803 return nullptr; 2804 } 2805 2806 //===----------------------------------------------------------------------===// 2807 // Implementation of FalsePositiveRefutationBRVisitor. 2808 //===----------------------------------------------------------------------===// 2809 2810 FalsePositiveRefutationBRVisitor::FalsePositiveRefutationBRVisitor() 2811 : Constraints(ConstraintRangeTy::Factory().getEmptyMap()) {} 2812 2813 void FalsePositiveRefutationBRVisitor::finalizeVisitor( 2814 BugReporterContext &BRC, const ExplodedNode *EndPathNode, 2815 PathSensitiveBugReport &BR) { 2816 // Collect new constraints 2817 VisitNode(EndPathNode, BRC, BR); 2818 2819 // Create a refutation manager 2820 llvm::SMTSolverRef RefutationSolver = llvm::CreateZ3Solver(); 2821 ASTContext &Ctx = BRC.getASTContext(); 2822 2823 // Add constraints to the solver 2824 for (const auto &I : Constraints) { 2825 const SymbolRef Sym = I.first; 2826 auto RangeIt = I.second.begin(); 2827 2828 llvm::SMTExprRef Constraints = SMTConv::getRangeExpr( 2829 RefutationSolver, Ctx, Sym, RangeIt->From(), RangeIt->To(), 2830 /*InRange=*/true); 2831 while ((++RangeIt) != I.second.end()) { 2832 Constraints = RefutationSolver->mkOr( 2833 Constraints, SMTConv::getRangeExpr(RefutationSolver, Ctx, Sym, 2834 RangeIt->From(), RangeIt->To(), 2835 /*InRange=*/true)); 2836 } 2837 2838 RefutationSolver->addConstraint(Constraints); 2839 } 2840 2841 // And check for satisfiability 2842 Optional<bool> isSat = RefutationSolver->check(); 2843 if (!isSat.hasValue()) 2844 return; 2845 2846 if (!isSat.getValue()) 2847 BR.markInvalid("Infeasible constraints", EndPathNode->getLocationContext()); 2848 } 2849 2850 PathDiagnosticPieceRef FalsePositiveRefutationBRVisitor::VisitNode( 2851 const ExplodedNode *N, BugReporterContext &, PathSensitiveBugReport &) { 2852 // Collect new constraints 2853 const ConstraintRangeTy &NewCs = N->getState()->get<ConstraintRange>(); 2854 ConstraintRangeTy::Factory &CF = 2855 N->getState()->get_context<ConstraintRange>(); 2856 2857 // Add constraints if we don't have them yet 2858 for (auto const &C : NewCs) { 2859 const SymbolRef &Sym = C.first; 2860 if (!Constraints.contains(Sym)) { 2861 Constraints = CF.add(Constraints, Sym, C.second); 2862 } 2863 } 2864 2865 return nullptr; 2866 } 2867 2868 void FalsePositiveRefutationBRVisitor::Profile( 2869 llvm::FoldingSetNodeID &ID) const { 2870 static int Tag = 0; 2871 ID.AddPointer(&Tag); 2872 } 2873 2874 //===----------------------------------------------------------------------===// 2875 // Implementation of TagVisitor. 2876 //===----------------------------------------------------------------------===// 2877 2878 int NoteTag::Kind = 0; 2879 2880 void TagVisitor::Profile(llvm::FoldingSetNodeID &ID) const { 2881 static int Tag = 0; 2882 ID.AddPointer(&Tag); 2883 } 2884 2885 PathDiagnosticPieceRef TagVisitor::VisitNode(const ExplodedNode *N, 2886 BugReporterContext &BRC, 2887 PathSensitiveBugReport &R) { 2888 ProgramPoint PP = N->getLocation(); 2889 const NoteTag *T = dyn_cast_or_null<NoteTag>(PP.getTag()); 2890 if (!T) 2891 return nullptr; 2892 2893 if (Optional<std::string> Msg = T->generateMessage(BRC, R)) { 2894 PathDiagnosticLocation Loc = 2895 PathDiagnosticLocation::create(PP, BRC.getSourceManager()); 2896 auto Piece = std::make_shared<PathDiagnosticEventPiece>(Loc, *Msg); 2897 Piece->setPrunable(T->isPrunable()); 2898 return Piece; 2899 } 2900 2901 return nullptr; 2902 } 2903