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