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