1 //=-- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- C++ -*-= 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 meta-engine for path-sensitive dataflow analysis that 11 // is built on GREngine, but provides the boilerplate to execute transfer 12 // functions and build the ExplodedGraph at the expression level. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 17 #include "PrettyStackTraceLocationContext.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/ParentMap.h" 20 #include "clang/AST/StmtCXX.h" 21 #include "clang/AST/StmtObjC.h" 22 #include "clang/Basic/Builtins.h" 23 #include "clang/Basic/PrettyStackTrace.h" 24 #include "clang/Basic/SourceManager.h" 25 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 26 #include "clang/StaticAnalyzer/Core/CheckerManager.h" 27 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 28 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 29 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h" 30 #include "llvm/ADT/Statistic.h" 31 #include "llvm/Support/SaveAndRestore.h" 32 #include "llvm/Support/raw_ostream.h" 33 34 #ifndef NDEBUG 35 #include "llvm/Support/GraphWriter.h" 36 #endif 37 38 using namespace clang; 39 using namespace ento; 40 using llvm::APSInt; 41 42 #define DEBUG_TYPE "ExprEngine" 43 44 STATISTIC(NumRemoveDeadBindings, 45 "The # of times RemoveDeadBindings is called"); 46 STATISTIC(NumMaxBlockCountReached, 47 "The # of aborted paths due to reaching the maximum block count in " 48 "a top level function"); 49 STATISTIC(NumMaxBlockCountReachedInInlined, 50 "The # of aborted paths due to reaching the maximum block count in " 51 "an inlined function"); 52 STATISTIC(NumTimesRetriedWithoutInlining, 53 "The # of times we re-evaluated a call without inlining"); 54 55 typedef std::pair<const CXXBindTemporaryExpr *, const StackFrameContext *> 56 CXXBindTemporaryContext; 57 58 // Keeps track of whether CXXBindTemporaryExpr nodes have been evaluated. 59 // The StackFrameContext assures that nested calls due to inlined recursive 60 // functions do not interfere. 61 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedTemporariesSet, 62 llvm::ImmutableSet<CXXBindTemporaryContext>) 63 64 //===----------------------------------------------------------------------===// 65 // Engine construction and deletion. 66 //===----------------------------------------------------------------------===// 67 68 static const char* TagProviderName = "ExprEngine"; 69 70 ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled, 71 SetOfConstDecls *VisitedCalleesIn, 72 FunctionSummariesTy *FS, 73 InliningModes HowToInlineIn) 74 : AMgr(mgr), 75 AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()), 76 Engine(*this, FS), 77 G(Engine.getGraph()), 78 StateMgr(getContext(), mgr.getStoreManagerCreator(), 79 mgr.getConstraintManagerCreator(), G.getAllocator(), 80 this), 81 SymMgr(StateMgr.getSymbolManager()), 82 svalBuilder(StateMgr.getSValBuilder()), 83 currStmtIdx(0), currBldrCtx(nullptr), 84 ObjCNoRet(mgr.getASTContext()), 85 ObjCGCEnabled(gcEnabled), BR(mgr, *this), 86 VisitedCallees(VisitedCalleesIn), 87 HowToInline(HowToInlineIn) 88 { 89 unsigned TrimInterval = mgr.options.getGraphTrimInterval(); 90 if (TrimInterval != 0) { 91 // Enable eager node reclaimation when constructing the ExplodedGraph. 92 G.enableNodeReclamation(TrimInterval); 93 } 94 } 95 96 ExprEngine::~ExprEngine() { 97 BR.FlushReports(); 98 } 99 100 //===----------------------------------------------------------------------===// 101 // Utility methods. 102 //===----------------------------------------------------------------------===// 103 104 ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) { 105 ProgramStateRef state = StateMgr.getInitialState(InitLoc); 106 const Decl *D = InitLoc->getDecl(); 107 108 // Preconditions. 109 // FIXME: It would be nice if we had a more general mechanism to add 110 // such preconditions. Some day. 111 do { 112 113 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 114 // Precondition: the first argument of 'main' is an integer guaranteed 115 // to be > 0. 116 const IdentifierInfo *II = FD->getIdentifier(); 117 if (!II || !(II->getName() == "main" && FD->getNumParams() > 0)) 118 break; 119 120 const ParmVarDecl *PD = FD->getParamDecl(0); 121 QualType T = PD->getType(); 122 const BuiltinType *BT = dyn_cast<BuiltinType>(T); 123 if (!BT || !BT->isInteger()) 124 break; 125 126 const MemRegion *R = state->getRegion(PD, InitLoc); 127 if (!R) 128 break; 129 130 SVal V = state->getSVal(loc::MemRegionVal(R)); 131 SVal Constraint_untested = evalBinOp(state, BO_GT, V, 132 svalBuilder.makeZeroVal(T), 133 svalBuilder.getConditionType()); 134 135 Optional<DefinedOrUnknownSVal> Constraint = 136 Constraint_untested.getAs<DefinedOrUnknownSVal>(); 137 138 if (!Constraint) 139 break; 140 141 if (ProgramStateRef newState = state->assume(*Constraint, true)) 142 state = newState; 143 } 144 break; 145 } 146 while (0); 147 148 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 149 // Precondition: 'self' is always non-null upon entry to an Objective-C 150 // method. 151 const ImplicitParamDecl *SelfD = MD->getSelfDecl(); 152 const MemRegion *R = state->getRegion(SelfD, InitLoc); 153 SVal V = state->getSVal(loc::MemRegionVal(R)); 154 155 if (Optional<Loc> LV = V.getAs<Loc>()) { 156 // Assume that the pointer value in 'self' is non-null. 157 state = state->assume(*LV, true); 158 assert(state && "'self' cannot be null"); 159 } 160 } 161 162 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 163 if (!MD->isStatic()) { 164 // Precondition: 'this' is always non-null upon entry to the 165 // top-level function. This is our starting assumption for 166 // analyzing an "open" program. 167 const StackFrameContext *SFC = InitLoc->getCurrentStackFrame(); 168 if (SFC->getParent() == nullptr) { 169 loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC); 170 SVal V = state->getSVal(L); 171 if (Optional<Loc> LV = V.getAs<Loc>()) { 172 state = state->assume(*LV, true); 173 assert(state && "'this' cannot be null"); 174 } 175 } 176 } 177 } 178 179 return state; 180 } 181 182 ProgramStateRef 183 ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State, 184 const LocationContext *LC, 185 const Expr *Ex, 186 const Expr *Result) { 187 SVal V = State->getSVal(Ex, LC); 188 if (!Result) { 189 // If we don't have an explicit result expression, we're in "if needed" 190 // mode. Only create a region if the current value is a NonLoc. 191 if (!V.getAs<NonLoc>()) 192 return State; 193 Result = Ex; 194 } else { 195 // We need to create a region no matter what. For sanity, make sure we don't 196 // try to stuff a Loc into a non-pointer temporary region. 197 assert(!V.getAs<Loc>() || Loc::isLocType(Result->getType()) || 198 Result->getType()->isMemberPointerType()); 199 } 200 201 ProgramStateManager &StateMgr = State->getStateManager(); 202 MemRegionManager &MRMgr = StateMgr.getRegionManager(); 203 StoreManager &StoreMgr = StateMgr.getStoreManager(); 204 205 // We need to be careful about treating a derived type's value as 206 // bindings for a base type. Unless we're creating a temporary pointer region, 207 // start by stripping and recording base casts. 208 SmallVector<const CastExpr *, 4> Casts; 209 const Expr *Inner = Ex->IgnoreParens(); 210 if (!Loc::isLocType(Result->getType())) { 211 while (const CastExpr *CE = dyn_cast<CastExpr>(Inner)) { 212 if (CE->getCastKind() == CK_DerivedToBase || 213 CE->getCastKind() == CK_UncheckedDerivedToBase) 214 Casts.push_back(CE); 215 else if (CE->getCastKind() != CK_NoOp) 216 break; 217 218 Inner = CE->getSubExpr()->IgnoreParens(); 219 } 220 } 221 222 // Create a temporary object region for the inner expression (which may have 223 // a more derived type) and bind the value into it. 224 const TypedValueRegion *TR = nullptr; 225 if (const MaterializeTemporaryExpr *MT = 226 dyn_cast<MaterializeTemporaryExpr>(Result)) { 227 StorageDuration SD = MT->getStorageDuration(); 228 // If this object is bound to a reference with static storage duration, we 229 // put it in a different region to prevent "address leakage" warnings. 230 if (SD == SD_Static || SD == SD_Thread) 231 TR = MRMgr.getCXXStaticTempObjectRegion(Inner); 232 } 233 if (!TR) 234 TR = MRMgr.getCXXTempObjectRegion(Inner, LC); 235 236 SVal Reg = loc::MemRegionVal(TR); 237 238 if (V.isUnknown()) 239 V = getSValBuilder().conjureSymbolVal(Result, LC, TR->getValueType(), 240 currBldrCtx->blockCount()); 241 State = State->bindLoc(Reg, V); 242 243 // Re-apply the casts (from innermost to outermost) for type sanity. 244 for (SmallVectorImpl<const CastExpr *>::reverse_iterator I = Casts.rbegin(), 245 E = Casts.rend(); 246 I != E; ++I) { 247 Reg = StoreMgr.evalDerivedToBase(Reg, *I); 248 } 249 250 State = State->BindExpr(Result, LC, Reg); 251 return State; 252 } 253 254 //===----------------------------------------------------------------------===// 255 // Top-level transfer function logic (Dispatcher). 256 //===----------------------------------------------------------------------===// 257 258 /// evalAssume - Called by ConstraintManager. Used to call checker-specific 259 /// logic for handling assumptions on symbolic values. 260 ProgramStateRef ExprEngine::processAssume(ProgramStateRef state, 261 SVal cond, bool assumption) { 262 return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption); 263 } 264 265 bool ExprEngine::wantsRegionChangeUpdate(ProgramStateRef state) { 266 return getCheckerManager().wantsRegionChangeUpdate(state); 267 } 268 269 ProgramStateRef 270 ExprEngine::processRegionChanges(ProgramStateRef state, 271 const InvalidatedSymbols *invalidated, 272 ArrayRef<const MemRegion *> Explicits, 273 ArrayRef<const MemRegion *> Regions, 274 const CallEvent *Call) { 275 return getCheckerManager().runCheckersForRegionChanges(state, invalidated, 276 Explicits, Regions, Call); 277 } 278 279 void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State, 280 const char *NL, const char *Sep) { 281 getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep); 282 } 283 284 void ExprEngine::processEndWorklist(bool hasWorkRemaining) { 285 getCheckerManager().runCheckersForEndAnalysis(G, BR, *this); 286 } 287 288 void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred, 289 unsigned StmtIdx, NodeBuilderContext *Ctx) { 290 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 291 currStmtIdx = StmtIdx; 292 currBldrCtx = Ctx; 293 294 switch (E.getKind()) { 295 case CFGElement::Statement: 296 ProcessStmt(const_cast<Stmt*>(E.castAs<CFGStmt>().getStmt()), Pred); 297 return; 298 case CFGElement::Initializer: 299 ProcessInitializer(E.castAs<CFGInitializer>().getInitializer(), Pred); 300 return; 301 case CFGElement::NewAllocator: 302 ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(), 303 Pred); 304 return; 305 case CFGElement::AutomaticObjectDtor: 306 case CFGElement::DeleteDtor: 307 case CFGElement::BaseDtor: 308 case CFGElement::MemberDtor: 309 case CFGElement::TemporaryDtor: 310 ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred); 311 return; 312 } 313 } 314 315 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr, 316 const CFGStmt S, 317 const ExplodedNode *Pred, 318 const LocationContext *LC) { 319 320 // Are we never purging state values? 321 if (AMgr.options.AnalysisPurgeOpt == PurgeNone) 322 return false; 323 324 // Is this the beginning of a basic block? 325 if (Pred->getLocation().getAs<BlockEntrance>()) 326 return true; 327 328 // Is this on a non-expression? 329 if (!isa<Expr>(S.getStmt())) 330 return true; 331 332 // Run before processing a call. 333 if (CallEvent::isCallStmt(S.getStmt())) 334 return true; 335 336 // Is this an expression that is consumed by another expression? If so, 337 // postpone cleaning out the state. 338 ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap(); 339 return !PM.isConsumedExpr(cast<Expr>(S.getStmt())); 340 } 341 342 void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out, 343 const Stmt *ReferenceStmt, 344 const LocationContext *LC, 345 const Stmt *DiagnosticStmt, 346 ProgramPoint::Kind K) { 347 assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind || 348 ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt)) 349 && "PostStmt is not generally supported by the SymbolReaper yet"); 350 assert(LC && "Must pass the current (or expiring) LocationContext"); 351 352 if (!DiagnosticStmt) { 353 DiagnosticStmt = ReferenceStmt; 354 assert(DiagnosticStmt && "Required for clearing a LocationContext"); 355 } 356 357 NumRemoveDeadBindings++; 358 ProgramStateRef CleanedState = Pred->getState(); 359 360 // LC is the location context being destroyed, but SymbolReaper wants a 361 // location context that is still live. (If this is the top-level stack 362 // frame, this will be null.) 363 if (!ReferenceStmt) { 364 assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind && 365 "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext"); 366 LC = LC->getParent(); 367 } 368 369 const StackFrameContext *SFC = LC ? LC->getCurrentStackFrame() : nullptr; 370 SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager()); 371 372 getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper); 373 374 // Create a state in which dead bindings are removed from the environment 375 // and the store. TODO: The function should just return new env and store, 376 // not a new state. 377 CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper); 378 379 // Process any special transfer function for dead symbols. 380 // A tag to track convenience transitions, which can be removed at cleanup. 381 static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node"); 382 if (!SymReaper.hasDeadSymbols()) { 383 // Generate a CleanedNode that has the environment and store cleaned 384 // up. Since no symbols are dead, we can optimize and not clean out 385 // the constraint manager. 386 StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx); 387 Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K); 388 389 } else { 390 // Call checkers with the non-cleaned state so that they could query the 391 // values of the soon to be dead symbols. 392 ExplodedNodeSet CheckedSet; 393 getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper, 394 DiagnosticStmt, *this, K); 395 396 // For each node in CheckedSet, generate CleanedNodes that have the 397 // environment, the store, and the constraints cleaned up but have the 398 // user-supplied states as the predecessors. 399 StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx); 400 for (ExplodedNodeSet::const_iterator 401 I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) { 402 ProgramStateRef CheckerState = (*I)->getState(); 403 404 // The constraint manager has not been cleaned up yet, so clean up now. 405 CheckerState = getConstraintManager().removeDeadBindings(CheckerState, 406 SymReaper); 407 408 assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) && 409 "Checkers are not allowed to modify the Environment as a part of " 410 "checkDeadSymbols processing."); 411 assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) && 412 "Checkers are not allowed to modify the Store as a part of " 413 "checkDeadSymbols processing."); 414 415 // Create a state based on CleanedState with CheckerState GDM and 416 // generate a transition to that state. 417 ProgramStateRef CleanedCheckerSt = 418 StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState); 419 Bldr.generateNode(DiagnosticStmt, *I, CleanedCheckerSt, &cleanupTag, K); 420 } 421 } 422 } 423 424 void ExprEngine::ProcessStmt(const CFGStmt S, 425 ExplodedNode *Pred) { 426 // Reclaim any unnecessary nodes in the ExplodedGraph. 427 G.reclaimRecentlyAllocatedNodes(); 428 429 const Stmt *currStmt = S.getStmt(); 430 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 431 currStmt->getLocStart(), 432 "Error evaluating statement"); 433 434 // Remove dead bindings and symbols. 435 ExplodedNodeSet CleanedStates; 436 if (shouldRemoveDeadBindings(AMgr, S, Pred, Pred->getLocationContext())){ 437 removeDead(Pred, CleanedStates, currStmt, Pred->getLocationContext()); 438 } else 439 CleanedStates.Add(Pred); 440 441 // Visit the statement. 442 ExplodedNodeSet Dst; 443 for (ExplodedNodeSet::iterator I = CleanedStates.begin(), 444 E = CleanedStates.end(); I != E; ++I) { 445 ExplodedNodeSet DstI; 446 // Visit the statement. 447 Visit(currStmt, *I, DstI); 448 Dst.insert(DstI); 449 } 450 451 // Enqueue the new nodes onto the work list. 452 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 453 } 454 455 void ExprEngine::ProcessInitializer(const CFGInitializer Init, 456 ExplodedNode *Pred) { 457 const CXXCtorInitializer *BMI = Init.getInitializer(); 458 459 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 460 BMI->getSourceLocation(), 461 "Error evaluating initializer"); 462 463 // We don't clean up dead bindings here. 464 const StackFrameContext *stackFrame = 465 cast<StackFrameContext>(Pred->getLocationContext()); 466 const CXXConstructorDecl *decl = 467 cast<CXXConstructorDecl>(stackFrame->getDecl()); 468 469 ProgramStateRef State = Pred->getState(); 470 SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame)); 471 472 ExplodedNodeSet Tmp(Pred); 473 SVal FieldLoc; 474 475 // Evaluate the initializer, if necessary 476 if (BMI->isAnyMemberInitializer()) { 477 // Constructors build the object directly in the field, 478 // but non-objects must be copied in from the initializer. 479 if (auto *CtorExpr = findDirectConstructorForCurrentCFGElement()) { 480 assert(BMI->getInit()->IgnoreImplicit() == CtorExpr); 481 (void)CtorExpr; 482 // The field was directly constructed, so there is no need to bind. 483 } else { 484 const Expr *Init = BMI->getInit()->IgnoreImplicit(); 485 const ValueDecl *Field; 486 if (BMI->isIndirectMemberInitializer()) { 487 Field = BMI->getIndirectMember(); 488 FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal); 489 } else { 490 Field = BMI->getMember(); 491 FieldLoc = State->getLValue(BMI->getMember(), thisVal); 492 } 493 494 SVal InitVal; 495 if (BMI->getNumArrayIndices() > 0) { 496 // Handle arrays of trivial type. We can represent this with a 497 // primitive load/copy from the base array region. 498 const ArraySubscriptExpr *ASE; 499 while ((ASE = dyn_cast<ArraySubscriptExpr>(Init))) 500 Init = ASE->getBase()->IgnoreImplicit(); 501 502 SVal LValue = State->getSVal(Init, stackFrame); 503 if (Optional<Loc> LValueLoc = LValue.getAs<Loc>()) 504 InitVal = State->getSVal(*LValueLoc); 505 506 // If we fail to get the value for some reason, use a symbolic value. 507 if (InitVal.isUnknownOrUndef()) { 508 SValBuilder &SVB = getSValBuilder(); 509 InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame, 510 Field->getType(), 511 currBldrCtx->blockCount()); 512 } 513 } else { 514 InitVal = State->getSVal(BMI->getInit(), stackFrame); 515 } 516 517 assert(Tmp.size() == 1 && "have not generated any new nodes yet"); 518 assert(*Tmp.begin() == Pred && "have not generated any new nodes yet"); 519 Tmp.clear(); 520 521 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame); 522 evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP); 523 } 524 } else { 525 assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer()); 526 // We already did all the work when visiting the CXXConstructExpr. 527 } 528 529 // Construct PostInitializer nodes whether the state changed or not, 530 // so that the diagnostics don't get confused. 531 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame); 532 ExplodedNodeSet Dst; 533 NodeBuilder Bldr(Tmp, Dst, *currBldrCtx); 534 for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) { 535 ExplodedNode *N = *I; 536 Bldr.generateNode(PP, N->getState(), N); 537 } 538 539 // Enqueue the new nodes onto the work list. 540 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 541 } 542 543 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D, 544 ExplodedNode *Pred) { 545 ExplodedNodeSet Dst; 546 switch (D.getKind()) { 547 case CFGElement::AutomaticObjectDtor: 548 ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst); 549 break; 550 case CFGElement::BaseDtor: 551 ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst); 552 break; 553 case CFGElement::MemberDtor: 554 ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst); 555 break; 556 case CFGElement::TemporaryDtor: 557 ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst); 558 break; 559 case CFGElement::DeleteDtor: 560 ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst); 561 break; 562 default: 563 llvm_unreachable("Unexpected dtor kind."); 564 } 565 566 // Enqueue the new nodes onto the work list. 567 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 568 } 569 570 void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE, 571 ExplodedNode *Pred) { 572 ExplodedNodeSet Dst; 573 AnalysisManager &AMgr = getAnalysisManager(); 574 AnalyzerOptions &Opts = AMgr.options; 575 // TODO: We're not evaluating allocators for all cases just yet as 576 // we're not handling the return value correctly, which causes false 577 // positives when the alpha.cplusplus.NewDeleteLeaks check is on. 578 if (Opts.mayInlineCXXAllocator()) 579 VisitCXXNewAllocatorCall(NE, Pred, Dst); 580 else { 581 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 582 const LocationContext *LCtx = Pred->getLocationContext(); 583 PostImplicitCall PP(NE->getOperatorNew(), NE->getLocStart(), LCtx); 584 Bldr.generateNode(PP, Pred->getState(), Pred); 585 } 586 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 587 } 588 589 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor, 590 ExplodedNode *Pred, 591 ExplodedNodeSet &Dst) { 592 const VarDecl *varDecl = Dtor.getVarDecl(); 593 QualType varType = varDecl->getType(); 594 595 ProgramStateRef state = Pred->getState(); 596 SVal dest = state->getLValue(varDecl, Pred->getLocationContext()); 597 const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion(); 598 599 if (const ReferenceType *refType = varType->getAs<ReferenceType>()) { 600 varType = refType->getPointeeType(); 601 Region = state->getSVal(Region).getAsRegion(); 602 } 603 604 VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false, 605 Pred, Dst); 606 } 607 608 void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor, 609 ExplodedNode *Pred, 610 ExplodedNodeSet &Dst) { 611 ProgramStateRef State = Pred->getState(); 612 const LocationContext *LCtx = Pred->getLocationContext(); 613 const CXXDeleteExpr *DE = Dtor.getDeleteExpr(); 614 const Stmt *Arg = DE->getArgument(); 615 SVal ArgVal = State->getSVal(Arg, LCtx); 616 617 // If the argument to delete is known to be a null value, 618 // don't run destructor. 619 if (State->isNull(ArgVal).isConstrainedTrue()) { 620 QualType DTy = DE->getDestroyedType(); 621 QualType BTy = getContext().getBaseElementType(DTy); 622 const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl(); 623 const CXXDestructorDecl *Dtor = RD->getDestructor(); 624 625 PostImplicitCall PP(Dtor, DE->getLocStart(), LCtx); 626 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 627 Bldr.generateNode(PP, Pred->getState(), Pred); 628 return; 629 } 630 631 VisitCXXDestructor(DE->getDestroyedType(), 632 ArgVal.getAsRegion(), 633 DE, /*IsBase=*/ false, 634 Pred, Dst); 635 } 636 637 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D, 638 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 639 const LocationContext *LCtx = Pred->getLocationContext(); 640 641 const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl()); 642 Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor, 643 LCtx->getCurrentStackFrame()); 644 SVal ThisVal = Pred->getState()->getSVal(ThisPtr); 645 646 // Create the base object region. 647 const CXXBaseSpecifier *Base = D.getBaseSpecifier(); 648 QualType BaseTy = Base->getType(); 649 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy, 650 Base->isVirtual()); 651 652 VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(), 653 CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst); 654 } 655 656 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D, 657 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 658 const FieldDecl *Member = D.getFieldDecl(); 659 ProgramStateRef State = Pred->getState(); 660 const LocationContext *LCtx = Pred->getLocationContext(); 661 662 const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl()); 663 Loc ThisVal = getSValBuilder().getCXXThis(CurDtor, 664 LCtx->getCurrentStackFrame()); 665 SVal FieldVal = 666 State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>()); 667 668 VisitCXXDestructor(Member->getType(), 669 FieldVal.castAs<loc::MemRegionVal>().getRegion(), 670 CurDtor->getBody(), /*IsBase=*/false, Pred, Dst); 671 } 672 673 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D, 674 ExplodedNode *Pred, 675 ExplodedNodeSet &Dst) { 676 ExplodedNodeSet CleanDtorState; 677 StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx); 678 ProgramStateRef State = Pred->getState(); 679 if (State->contains<InitializedTemporariesSet>( 680 std::make_pair(D.getBindTemporaryExpr(), Pred->getStackFrame()))) { 681 // FIXME: Currently we insert temporary destructors for default parameters, 682 // but we don't insert the constructors. 683 State = State->remove<InitializedTemporariesSet>( 684 std::make_pair(D.getBindTemporaryExpr(), Pred->getStackFrame())); 685 } 686 StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State); 687 688 QualType varType = D.getBindTemporaryExpr()->getSubExpr()->getType(); 689 // FIXME: Currently CleanDtorState can be empty here due to temporaries being 690 // bound to default parameters. 691 assert(CleanDtorState.size() <= 1); 692 ExplodedNode *CleanPred = 693 CleanDtorState.empty() ? Pred : *CleanDtorState.begin(); 694 // FIXME: Inlining of temporary destructors is not supported yet anyway, so 695 // we just put a NULL region for now. This will need to be changed later. 696 VisitCXXDestructor(varType, nullptr, D.getBindTemporaryExpr(), 697 /*IsBase=*/false, CleanPred, Dst); 698 } 699 700 void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE, 701 NodeBuilderContext &BldCtx, 702 ExplodedNode *Pred, 703 ExplodedNodeSet &Dst, 704 const CFGBlock *DstT, 705 const CFGBlock *DstF) { 706 BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF); 707 if (Pred->getState()->contains<InitializedTemporariesSet>( 708 std::make_pair(BTE, Pred->getStackFrame()))) { 709 TempDtorBuilder.markInfeasible(false); 710 TempDtorBuilder.generateNode(Pred->getState(), true, Pred); 711 } else { 712 TempDtorBuilder.markInfeasible(true); 713 TempDtorBuilder.generateNode(Pred->getState(), false, Pred); 714 } 715 } 716 717 void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE, 718 ExplodedNodeSet &PreVisit, 719 ExplodedNodeSet &Dst) { 720 if (!getAnalysisManager().options.includeTemporaryDtorsInCFG()) { 721 // In case we don't have temporary destructors in the CFG, do not mark 722 // the initialization - we would otherwise never clean it up. 723 Dst = PreVisit; 724 return; 725 } 726 StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx); 727 for (ExplodedNode *Node : PreVisit) { 728 ProgramStateRef State = Node->getState(); 729 730 if (!State->contains<InitializedTemporariesSet>( 731 std::make_pair(BTE, Node->getStackFrame()))) { 732 // FIXME: Currently the state might already contain the marker due to 733 // incorrect handling of temporaries bound to default parameters; for 734 // those, we currently skip the CXXBindTemporaryExpr but rely on adding 735 // temporary destructor nodes. 736 State = State->add<InitializedTemporariesSet>( 737 std::make_pair(BTE, Node->getStackFrame())); 738 } 739 StmtBldr.generateNode(BTE, Node, State); 740 } 741 } 742 743 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred, 744 ExplodedNodeSet &DstTop) { 745 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 746 S->getLocStart(), 747 "Error evaluating statement"); 748 ExplodedNodeSet Dst; 749 StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx); 750 751 assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens()); 752 753 switch (S->getStmtClass()) { 754 // C++ and ARC stuff we don't support yet. 755 case Expr::ObjCIndirectCopyRestoreExprClass: 756 case Stmt::CXXDependentScopeMemberExprClass: 757 case Stmt::CXXInheritedCtorInitExprClass: 758 case Stmt::CXXTryStmtClass: 759 case Stmt::CXXTypeidExprClass: 760 case Stmt::CXXUuidofExprClass: 761 case Stmt::CXXFoldExprClass: 762 case Stmt::MSPropertyRefExprClass: 763 case Stmt::MSPropertySubscriptExprClass: 764 case Stmt::CXXUnresolvedConstructExprClass: 765 case Stmt::DependentScopeDeclRefExprClass: 766 case Stmt::ArrayTypeTraitExprClass: 767 case Stmt::ExpressionTraitExprClass: 768 case Stmt::UnresolvedLookupExprClass: 769 case Stmt::UnresolvedMemberExprClass: 770 case Stmt::TypoExprClass: 771 case Stmt::CXXNoexceptExprClass: 772 case Stmt::PackExpansionExprClass: 773 case Stmt::SubstNonTypeTemplateParmPackExprClass: 774 case Stmt::FunctionParmPackExprClass: 775 case Stmt::CoroutineBodyStmtClass: 776 case Stmt::CoawaitExprClass: 777 case Stmt::CoreturnStmtClass: 778 case Stmt::CoyieldExprClass: 779 case Stmt::SEHTryStmtClass: 780 case Stmt::SEHExceptStmtClass: 781 case Stmt::SEHLeaveStmtClass: 782 case Stmt::SEHFinallyStmtClass: { 783 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState()); 784 Engine.addAbortedBlock(node, currBldrCtx->getBlock()); 785 break; 786 } 787 788 case Stmt::ParenExprClass: 789 llvm_unreachable("ParenExprs already handled."); 790 case Stmt::GenericSelectionExprClass: 791 llvm_unreachable("GenericSelectionExprs already handled."); 792 // Cases that should never be evaluated simply because they shouldn't 793 // appear in the CFG. 794 case Stmt::BreakStmtClass: 795 case Stmt::CaseStmtClass: 796 case Stmt::CompoundStmtClass: 797 case Stmt::ContinueStmtClass: 798 case Stmt::CXXForRangeStmtClass: 799 case Stmt::DefaultStmtClass: 800 case Stmt::DoStmtClass: 801 case Stmt::ForStmtClass: 802 case Stmt::GotoStmtClass: 803 case Stmt::IfStmtClass: 804 case Stmt::IndirectGotoStmtClass: 805 case Stmt::LabelStmtClass: 806 case Stmt::NoStmtClass: 807 case Stmt::NullStmtClass: 808 case Stmt::SwitchStmtClass: 809 case Stmt::WhileStmtClass: 810 case Expr::MSDependentExistsStmtClass: 811 case Stmt::CapturedStmtClass: 812 case Stmt::OMPParallelDirectiveClass: 813 case Stmt::OMPSimdDirectiveClass: 814 case Stmt::OMPForDirectiveClass: 815 case Stmt::OMPForSimdDirectiveClass: 816 case Stmt::OMPSectionsDirectiveClass: 817 case Stmt::OMPSectionDirectiveClass: 818 case Stmt::OMPSingleDirectiveClass: 819 case Stmt::OMPMasterDirectiveClass: 820 case Stmt::OMPCriticalDirectiveClass: 821 case Stmt::OMPParallelForDirectiveClass: 822 case Stmt::OMPParallelForSimdDirectiveClass: 823 case Stmt::OMPParallelSectionsDirectiveClass: 824 case Stmt::OMPTaskDirectiveClass: 825 case Stmt::OMPTaskyieldDirectiveClass: 826 case Stmt::OMPBarrierDirectiveClass: 827 case Stmt::OMPTaskwaitDirectiveClass: 828 case Stmt::OMPTaskgroupDirectiveClass: 829 case Stmt::OMPFlushDirectiveClass: 830 case Stmt::OMPOrderedDirectiveClass: 831 case Stmt::OMPAtomicDirectiveClass: 832 case Stmt::OMPTargetDirectiveClass: 833 case Stmt::OMPTargetDataDirectiveClass: 834 case Stmt::OMPTargetEnterDataDirectiveClass: 835 case Stmt::OMPTargetExitDataDirectiveClass: 836 case Stmt::OMPTargetParallelDirectiveClass: 837 case Stmt::OMPTargetParallelForDirectiveClass: 838 case Stmt::OMPTargetUpdateDirectiveClass: 839 case Stmt::OMPTeamsDirectiveClass: 840 case Stmt::OMPCancellationPointDirectiveClass: 841 case Stmt::OMPCancelDirectiveClass: 842 case Stmt::OMPTaskLoopDirectiveClass: 843 case Stmt::OMPTaskLoopSimdDirectiveClass: 844 case Stmt::OMPDistributeDirectiveClass: 845 case Stmt::OMPDistributeParallelForDirectiveClass: 846 case Stmt::OMPDistributeParallelForSimdDirectiveClass: 847 case Stmt::OMPDistributeSimdDirectiveClass: 848 case Stmt::OMPTargetParallelForSimdDirectiveClass: 849 case Stmt::OMPTargetSimdDirectiveClass: 850 case Stmt::OMPTeamsDistributeDirectiveClass: 851 case Stmt::OMPTeamsDistributeSimdDirectiveClass: 852 llvm_unreachable("Stmt should not be in analyzer evaluation loop"); 853 854 case Stmt::ObjCSubscriptRefExprClass: 855 case Stmt::ObjCPropertyRefExprClass: 856 llvm_unreachable("These are handled by PseudoObjectExpr"); 857 858 case Stmt::GNUNullExprClass: { 859 // GNU __null is a pointer-width integer, not an actual pointer. 860 ProgramStateRef state = Pred->getState(); 861 state = state->BindExpr(S, Pred->getLocationContext(), 862 svalBuilder.makeIntValWithPtrWidth(0, false)); 863 Bldr.generateNode(S, Pred, state); 864 break; 865 } 866 867 case Stmt::ObjCAtSynchronizedStmtClass: 868 Bldr.takeNodes(Pred); 869 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst); 870 Bldr.addNodes(Dst); 871 break; 872 873 case Stmt::ExprWithCleanupsClass: 874 // Handled due to fully linearised CFG. 875 break; 876 877 case Stmt::CXXBindTemporaryExprClass: { 878 Bldr.takeNodes(Pred); 879 ExplodedNodeSet PreVisit; 880 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 881 ExplodedNodeSet Next; 882 VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next); 883 getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this); 884 Bldr.addNodes(Dst); 885 break; 886 } 887 888 // Cases not handled yet; but will handle some day. 889 case Stmt::DesignatedInitExprClass: 890 case Stmt::DesignatedInitUpdateExprClass: 891 case Stmt::ExtVectorElementExprClass: 892 case Stmt::ImaginaryLiteralClass: 893 case Stmt::ObjCAtCatchStmtClass: 894 case Stmt::ObjCAtFinallyStmtClass: 895 case Stmt::ObjCAtTryStmtClass: 896 case Stmt::ObjCAutoreleasePoolStmtClass: 897 case Stmt::ObjCEncodeExprClass: 898 case Stmt::ObjCIsaExprClass: 899 case Stmt::ObjCProtocolExprClass: 900 case Stmt::ObjCSelectorExprClass: 901 case Stmt::ParenListExprClass: 902 case Stmt::ShuffleVectorExprClass: 903 case Stmt::ConvertVectorExprClass: 904 case Stmt::VAArgExprClass: 905 case Stmt::CUDAKernelCallExprClass: 906 case Stmt::OpaqueValueExprClass: 907 case Stmt::AsTypeExprClass: 908 // Fall through. 909 910 // Cases we intentionally don't evaluate, since they don't need 911 // to be explicitly evaluated. 912 case Stmt::PredefinedExprClass: 913 case Stmt::AddrLabelExprClass: 914 case Stmt::AttributedStmtClass: 915 case Stmt::IntegerLiteralClass: 916 case Stmt::CharacterLiteralClass: 917 case Stmt::ImplicitValueInitExprClass: 918 case Stmt::CXXScalarValueInitExprClass: 919 case Stmt::CXXBoolLiteralExprClass: 920 case Stmt::ObjCBoolLiteralExprClass: 921 case Stmt::ObjCAvailabilityCheckExprClass: 922 case Stmt::FloatingLiteralClass: 923 case Stmt::NoInitExprClass: 924 case Stmt::SizeOfPackExprClass: 925 case Stmt::StringLiteralClass: 926 case Stmt::ObjCStringLiteralClass: 927 case Stmt::CXXPseudoDestructorExprClass: 928 case Stmt::SubstNonTypeTemplateParmExprClass: 929 case Stmt::CXXNullPtrLiteralExprClass: 930 case Stmt::OMPArraySectionExprClass: 931 case Stmt::TypeTraitExprClass: { 932 Bldr.takeNodes(Pred); 933 ExplodedNodeSet preVisit; 934 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this); 935 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this); 936 Bldr.addNodes(Dst); 937 break; 938 } 939 940 case Stmt::CXXDefaultArgExprClass: 941 case Stmt::CXXDefaultInitExprClass: { 942 Bldr.takeNodes(Pred); 943 ExplodedNodeSet PreVisit; 944 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 945 946 ExplodedNodeSet Tmp; 947 StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx); 948 949 const Expr *ArgE; 950 if (const CXXDefaultArgExpr *DefE = dyn_cast<CXXDefaultArgExpr>(S)) 951 ArgE = DefE->getExpr(); 952 else if (const CXXDefaultInitExpr *DefE = dyn_cast<CXXDefaultInitExpr>(S)) 953 ArgE = DefE->getExpr(); 954 else 955 llvm_unreachable("unknown constant wrapper kind"); 956 957 bool IsTemporary = false; 958 if (const MaterializeTemporaryExpr *MTE = 959 dyn_cast<MaterializeTemporaryExpr>(ArgE)) { 960 ArgE = MTE->GetTemporaryExpr(); 961 IsTemporary = true; 962 } 963 964 Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE); 965 if (!ConstantVal) 966 ConstantVal = UnknownVal(); 967 968 const LocationContext *LCtx = Pred->getLocationContext(); 969 for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end(); 970 I != E; ++I) { 971 ProgramStateRef State = (*I)->getState(); 972 State = State->BindExpr(S, LCtx, *ConstantVal); 973 if (IsTemporary) 974 State = createTemporaryRegionIfNeeded(State, LCtx, 975 cast<Expr>(S), 976 cast<Expr>(S)); 977 Bldr2.generateNode(S, *I, State); 978 } 979 980 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this); 981 Bldr.addNodes(Dst); 982 break; 983 } 984 985 // Cases we evaluate as opaque expressions, conjuring a symbol. 986 case Stmt::CXXStdInitializerListExprClass: 987 case Expr::ObjCArrayLiteralClass: 988 case Expr::ObjCDictionaryLiteralClass: 989 case Expr::ObjCBoxedExprClass: { 990 Bldr.takeNodes(Pred); 991 992 ExplodedNodeSet preVisit; 993 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this); 994 995 ExplodedNodeSet Tmp; 996 StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx); 997 998 const Expr *Ex = cast<Expr>(S); 999 QualType resultType = Ex->getType(); 1000 1001 for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end(); 1002 it != et; ++it) { 1003 ExplodedNode *N = *it; 1004 const LocationContext *LCtx = N->getLocationContext(); 1005 SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx, 1006 resultType, 1007 currBldrCtx->blockCount()); 1008 ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result); 1009 Bldr2.generateNode(S, N, state); 1010 } 1011 1012 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this); 1013 Bldr.addNodes(Dst); 1014 break; 1015 } 1016 1017 case Stmt::ArraySubscriptExprClass: 1018 Bldr.takeNodes(Pred); 1019 VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst); 1020 Bldr.addNodes(Dst); 1021 break; 1022 1023 case Stmt::GCCAsmStmtClass: 1024 Bldr.takeNodes(Pred); 1025 VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst); 1026 Bldr.addNodes(Dst); 1027 break; 1028 1029 case Stmt::MSAsmStmtClass: 1030 Bldr.takeNodes(Pred); 1031 VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst); 1032 Bldr.addNodes(Dst); 1033 break; 1034 1035 case Stmt::BlockExprClass: 1036 Bldr.takeNodes(Pred); 1037 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst); 1038 Bldr.addNodes(Dst); 1039 break; 1040 1041 case Stmt::LambdaExprClass: 1042 if (AMgr.options.shouldInlineLambdas()) { 1043 Bldr.takeNodes(Pred); 1044 VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst); 1045 Bldr.addNodes(Dst); 1046 } else { 1047 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState()); 1048 Engine.addAbortedBlock(node, currBldrCtx->getBlock()); 1049 } 1050 break; 1051 1052 case Stmt::BinaryOperatorClass: { 1053 const BinaryOperator* B = cast<BinaryOperator>(S); 1054 if (B->isLogicalOp()) { 1055 Bldr.takeNodes(Pred); 1056 VisitLogicalExpr(B, Pred, Dst); 1057 Bldr.addNodes(Dst); 1058 break; 1059 } 1060 else if (B->getOpcode() == BO_Comma) { 1061 ProgramStateRef state = Pred->getState(); 1062 Bldr.generateNode(B, Pred, 1063 state->BindExpr(B, Pred->getLocationContext(), 1064 state->getSVal(B->getRHS(), 1065 Pred->getLocationContext()))); 1066 break; 1067 } 1068 1069 Bldr.takeNodes(Pred); 1070 1071 if (AMgr.options.eagerlyAssumeBinOpBifurcation && 1072 (B->isRelationalOp() || B->isEqualityOp())) { 1073 ExplodedNodeSet Tmp; 1074 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp); 1075 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S)); 1076 } 1077 else 1078 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 1079 1080 Bldr.addNodes(Dst); 1081 break; 1082 } 1083 1084 case Stmt::CXXOperatorCallExprClass: { 1085 const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S); 1086 1087 // For instance method operators, make sure the 'this' argument has a 1088 // valid region. 1089 const Decl *Callee = OCE->getCalleeDecl(); 1090 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) { 1091 if (MD->isInstance()) { 1092 ProgramStateRef State = Pred->getState(); 1093 const LocationContext *LCtx = Pred->getLocationContext(); 1094 ProgramStateRef NewState = 1095 createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0)); 1096 if (NewState != State) { 1097 Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr, 1098 ProgramPoint::PreStmtKind); 1099 // Did we cache out? 1100 if (!Pred) 1101 break; 1102 } 1103 } 1104 } 1105 // FALLTHROUGH 1106 } 1107 case Stmt::CallExprClass: 1108 case Stmt::CXXMemberCallExprClass: 1109 case Stmt::UserDefinedLiteralClass: { 1110 Bldr.takeNodes(Pred); 1111 VisitCallExpr(cast<CallExpr>(S), Pred, Dst); 1112 Bldr.addNodes(Dst); 1113 break; 1114 } 1115 1116 case Stmt::CXXCatchStmtClass: { 1117 Bldr.takeNodes(Pred); 1118 VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst); 1119 Bldr.addNodes(Dst); 1120 break; 1121 } 1122 1123 case Stmt::CXXTemporaryObjectExprClass: 1124 case Stmt::CXXConstructExprClass: { 1125 Bldr.takeNodes(Pred); 1126 VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst); 1127 Bldr.addNodes(Dst); 1128 break; 1129 } 1130 1131 case Stmt::CXXNewExprClass: { 1132 Bldr.takeNodes(Pred); 1133 ExplodedNodeSet PostVisit; 1134 VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit); 1135 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this); 1136 Bldr.addNodes(Dst); 1137 break; 1138 } 1139 1140 case Stmt::CXXDeleteExprClass: { 1141 Bldr.takeNodes(Pred); 1142 ExplodedNodeSet PreVisit; 1143 const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S); 1144 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 1145 1146 for (ExplodedNodeSet::iterator i = PreVisit.begin(), 1147 e = PreVisit.end(); i != e ; ++i) 1148 VisitCXXDeleteExpr(CDE, *i, Dst); 1149 1150 Bldr.addNodes(Dst); 1151 break; 1152 } 1153 // FIXME: ChooseExpr is really a constant. We need to fix 1154 // the CFG do not model them as explicit control-flow. 1155 1156 case Stmt::ChooseExprClass: { // __builtin_choose_expr 1157 Bldr.takeNodes(Pred); 1158 const ChooseExpr *C = cast<ChooseExpr>(S); 1159 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst); 1160 Bldr.addNodes(Dst); 1161 break; 1162 } 1163 1164 case Stmt::CompoundAssignOperatorClass: 1165 Bldr.takeNodes(Pred); 1166 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 1167 Bldr.addNodes(Dst); 1168 break; 1169 1170 case Stmt::CompoundLiteralExprClass: 1171 Bldr.takeNodes(Pred); 1172 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst); 1173 Bldr.addNodes(Dst); 1174 break; 1175 1176 case Stmt::BinaryConditionalOperatorClass: 1177 case Stmt::ConditionalOperatorClass: { // '?' operator 1178 Bldr.takeNodes(Pred); 1179 const AbstractConditionalOperator *C 1180 = cast<AbstractConditionalOperator>(S); 1181 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst); 1182 Bldr.addNodes(Dst); 1183 break; 1184 } 1185 1186 case Stmt::CXXThisExprClass: 1187 Bldr.takeNodes(Pred); 1188 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst); 1189 Bldr.addNodes(Dst); 1190 break; 1191 1192 case Stmt::DeclRefExprClass: { 1193 Bldr.takeNodes(Pred); 1194 const DeclRefExpr *DE = cast<DeclRefExpr>(S); 1195 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst); 1196 Bldr.addNodes(Dst); 1197 break; 1198 } 1199 1200 case Stmt::DeclStmtClass: 1201 Bldr.takeNodes(Pred); 1202 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst); 1203 Bldr.addNodes(Dst); 1204 break; 1205 1206 case Stmt::ImplicitCastExprClass: 1207 case Stmt::CStyleCastExprClass: 1208 case Stmt::CXXStaticCastExprClass: 1209 case Stmt::CXXDynamicCastExprClass: 1210 case Stmt::CXXReinterpretCastExprClass: 1211 case Stmt::CXXConstCastExprClass: 1212 case Stmt::CXXFunctionalCastExprClass: 1213 case Stmt::ObjCBridgedCastExprClass: { 1214 Bldr.takeNodes(Pred); 1215 const CastExpr *C = cast<CastExpr>(S); 1216 ExplodedNodeSet dstExpr; 1217 VisitCast(C, C->getSubExpr(), Pred, dstExpr); 1218 1219 // Handle the postvisit checks. 1220 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this); 1221 Bldr.addNodes(Dst); 1222 break; 1223 } 1224 1225 case Expr::MaterializeTemporaryExprClass: { 1226 Bldr.takeNodes(Pred); 1227 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S); 1228 CreateCXXTemporaryObject(MTE, Pred, Dst); 1229 Bldr.addNodes(Dst); 1230 break; 1231 } 1232 1233 case Stmt::InitListExprClass: 1234 Bldr.takeNodes(Pred); 1235 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst); 1236 Bldr.addNodes(Dst); 1237 break; 1238 1239 case Stmt::MemberExprClass: 1240 Bldr.takeNodes(Pred); 1241 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst); 1242 Bldr.addNodes(Dst); 1243 break; 1244 1245 case Stmt::AtomicExprClass: 1246 Bldr.takeNodes(Pred); 1247 VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst); 1248 Bldr.addNodes(Dst); 1249 break; 1250 1251 case Stmt::ObjCIvarRefExprClass: 1252 Bldr.takeNodes(Pred); 1253 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst); 1254 Bldr.addNodes(Dst); 1255 break; 1256 1257 case Stmt::ObjCForCollectionStmtClass: 1258 Bldr.takeNodes(Pred); 1259 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst); 1260 Bldr.addNodes(Dst); 1261 break; 1262 1263 case Stmt::ObjCMessageExprClass: 1264 Bldr.takeNodes(Pred); 1265 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst); 1266 Bldr.addNodes(Dst); 1267 break; 1268 1269 case Stmt::ObjCAtThrowStmtClass: 1270 case Stmt::CXXThrowExprClass: 1271 // FIXME: This is not complete. We basically treat @throw as 1272 // an abort. 1273 Bldr.generateSink(S, Pred, Pred->getState()); 1274 break; 1275 1276 case Stmt::ReturnStmtClass: 1277 Bldr.takeNodes(Pred); 1278 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst); 1279 Bldr.addNodes(Dst); 1280 break; 1281 1282 case Stmt::OffsetOfExprClass: 1283 Bldr.takeNodes(Pred); 1284 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst); 1285 Bldr.addNodes(Dst); 1286 break; 1287 1288 case Stmt::UnaryExprOrTypeTraitExprClass: 1289 Bldr.takeNodes(Pred); 1290 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S), 1291 Pred, Dst); 1292 Bldr.addNodes(Dst); 1293 break; 1294 1295 case Stmt::StmtExprClass: { 1296 const StmtExpr *SE = cast<StmtExpr>(S); 1297 1298 if (SE->getSubStmt()->body_empty()) { 1299 // Empty statement expression. 1300 assert(SE->getType() == getContext().VoidTy 1301 && "Empty statement expression must have void type."); 1302 break; 1303 } 1304 1305 if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) { 1306 ProgramStateRef state = Pred->getState(); 1307 Bldr.generateNode(SE, Pred, 1308 state->BindExpr(SE, Pred->getLocationContext(), 1309 state->getSVal(LastExpr, 1310 Pred->getLocationContext()))); 1311 } 1312 break; 1313 } 1314 1315 case Stmt::UnaryOperatorClass: { 1316 Bldr.takeNodes(Pred); 1317 const UnaryOperator *U = cast<UnaryOperator>(S); 1318 if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) { 1319 ExplodedNodeSet Tmp; 1320 VisitUnaryOperator(U, Pred, Tmp); 1321 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U); 1322 } 1323 else 1324 VisitUnaryOperator(U, Pred, Dst); 1325 Bldr.addNodes(Dst); 1326 break; 1327 } 1328 1329 case Stmt::PseudoObjectExprClass: { 1330 Bldr.takeNodes(Pred); 1331 ProgramStateRef state = Pred->getState(); 1332 const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S); 1333 if (const Expr *Result = PE->getResultExpr()) { 1334 SVal V = state->getSVal(Result, Pred->getLocationContext()); 1335 Bldr.generateNode(S, Pred, 1336 state->BindExpr(S, Pred->getLocationContext(), V)); 1337 } 1338 else 1339 Bldr.generateNode(S, Pred, 1340 state->BindExpr(S, Pred->getLocationContext(), 1341 UnknownVal())); 1342 1343 Bldr.addNodes(Dst); 1344 break; 1345 } 1346 } 1347 } 1348 1349 bool ExprEngine::replayWithoutInlining(ExplodedNode *N, 1350 const LocationContext *CalleeLC) { 1351 const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame(); 1352 const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame(); 1353 assert(CalleeSF && CallerSF); 1354 ExplodedNode *BeforeProcessingCall = nullptr; 1355 const Stmt *CE = CalleeSF->getCallSite(); 1356 1357 // Find the first node before we started processing the call expression. 1358 while (N) { 1359 ProgramPoint L = N->getLocation(); 1360 BeforeProcessingCall = N; 1361 N = N->pred_empty() ? nullptr : *(N->pred_begin()); 1362 1363 // Skip the nodes corresponding to the inlined code. 1364 if (L.getLocationContext()->getCurrentStackFrame() != CallerSF) 1365 continue; 1366 // We reached the caller. Find the node right before we started 1367 // processing the call. 1368 if (L.isPurgeKind()) 1369 continue; 1370 if (L.getAs<PreImplicitCall>()) 1371 continue; 1372 if (L.getAs<CallEnter>()) 1373 continue; 1374 if (Optional<StmtPoint> SP = L.getAs<StmtPoint>()) 1375 if (SP->getStmt() == CE) 1376 continue; 1377 break; 1378 } 1379 1380 if (!BeforeProcessingCall) 1381 return false; 1382 1383 // TODO: Clean up the unneeded nodes. 1384 1385 // Build an Epsilon node from which we will restart the analyzes. 1386 // Note that CE is permitted to be NULL! 1387 ProgramPoint NewNodeLoc = 1388 EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE); 1389 // Add the special flag to GDM to signal retrying with no inlining. 1390 // Note, changing the state ensures that we are not going to cache out. 1391 ProgramStateRef NewNodeState = BeforeProcessingCall->getState(); 1392 NewNodeState = 1393 NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE)); 1394 1395 // Make the new node a successor of BeforeProcessingCall. 1396 bool IsNew = false; 1397 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew); 1398 // We cached out at this point. Caching out is common due to us backtracking 1399 // from the inlined function, which might spawn several paths. 1400 if (!IsNew) 1401 return true; 1402 1403 NewNode->addPredecessor(BeforeProcessingCall, G); 1404 1405 // Add the new node to the work list. 1406 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(), 1407 CalleeSF->getIndex()); 1408 NumTimesRetriedWithoutInlining++; 1409 return true; 1410 } 1411 1412 /// Block entrance. (Update counters). 1413 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L, 1414 NodeBuilderWithSinks &nodeBuilder, 1415 ExplodedNode *Pred) { 1416 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 1417 1418 // If this block is terminated by a loop and it has already been visited the 1419 // maximum number of times, widen the loop. 1420 unsigned int BlockCount = nodeBuilder.getContext().blockCount(); 1421 if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 && 1422 AMgr.options.shouldWidenLoops()) { 1423 const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator(); 1424 if (!(Term && 1425 (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term)))) 1426 return; 1427 // Widen. 1428 const LocationContext *LCtx = Pred->getLocationContext(); 1429 ProgramStateRef WidenedState = 1430 getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term); 1431 nodeBuilder.generateNode(WidenedState, Pred); 1432 return; 1433 } 1434 1435 // FIXME: Refactor this into a checker. 1436 if (BlockCount >= AMgr.options.maxBlockVisitOnPath) { 1437 static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded"); 1438 const ExplodedNode *Sink = 1439 nodeBuilder.generateSink(Pred->getState(), Pred, &tag); 1440 1441 // Check if we stopped at the top level function or not. 1442 // Root node should have the location context of the top most function. 1443 const LocationContext *CalleeLC = Pred->getLocation().getLocationContext(); 1444 const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame(); 1445 const LocationContext *RootLC = 1446 (*G.roots_begin())->getLocation().getLocationContext(); 1447 if (RootLC->getCurrentStackFrame() != CalleeSF) { 1448 Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl()); 1449 1450 // Re-run the call evaluation without inlining it, by storing the 1451 // no-inlining policy in the state and enqueuing the new work item on 1452 // the list. Replay should almost never fail. Use the stats to catch it 1453 // if it does. 1454 if ((!AMgr.options.NoRetryExhausted && 1455 replayWithoutInlining(Pred, CalleeLC))) 1456 return; 1457 NumMaxBlockCountReachedInInlined++; 1458 } else 1459 NumMaxBlockCountReached++; 1460 1461 // Make sink nodes as exhausted(for stats) only if retry failed. 1462 Engine.blocksExhausted.push_back(std::make_pair(L, Sink)); 1463 } 1464 } 1465 1466 //===----------------------------------------------------------------------===// 1467 // Branch processing. 1468 //===----------------------------------------------------------------------===// 1469 1470 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used 1471 /// to try to recover some path-sensitivity for casts of symbolic 1472 /// integers that promote their values (which are currently not tracked well). 1473 /// This function returns the SVal bound to Condition->IgnoreCasts if all the 1474 // cast(s) did was sign-extend the original value. 1475 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr, 1476 ProgramStateRef state, 1477 const Stmt *Condition, 1478 const LocationContext *LCtx, 1479 ASTContext &Ctx) { 1480 1481 const Expr *Ex = dyn_cast<Expr>(Condition); 1482 if (!Ex) 1483 return UnknownVal(); 1484 1485 uint64_t bits = 0; 1486 bool bitsInit = false; 1487 1488 while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) { 1489 QualType T = CE->getType(); 1490 1491 if (!T->isIntegralOrEnumerationType()) 1492 return UnknownVal(); 1493 1494 uint64_t newBits = Ctx.getTypeSize(T); 1495 if (!bitsInit || newBits < bits) { 1496 bitsInit = true; 1497 bits = newBits; 1498 } 1499 1500 Ex = CE->getSubExpr(); 1501 } 1502 1503 // We reached a non-cast. Is it a symbolic value? 1504 QualType T = Ex->getType(); 1505 1506 if (!bitsInit || !T->isIntegralOrEnumerationType() || 1507 Ctx.getTypeSize(T) > bits) 1508 return UnknownVal(); 1509 1510 return state->getSVal(Ex, LCtx); 1511 } 1512 1513 #ifndef NDEBUG 1514 static const Stmt *getRightmostLeaf(const Stmt *Condition) { 1515 while (Condition) { 1516 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition); 1517 if (!BO || !BO->isLogicalOp()) { 1518 return Condition; 1519 } 1520 Condition = BO->getRHS()->IgnoreParens(); 1521 } 1522 return nullptr; 1523 } 1524 #endif 1525 1526 // Returns the condition the branch at the end of 'B' depends on and whose value 1527 // has been evaluated within 'B'. 1528 // In most cases, the terminator condition of 'B' will be evaluated fully in 1529 // the last statement of 'B'; in those cases, the resolved condition is the 1530 // given 'Condition'. 1531 // If the condition of the branch is a logical binary operator tree, the CFG is 1532 // optimized: in that case, we know that the expression formed by all but the 1533 // rightmost leaf of the logical binary operator tree must be true, and thus 1534 // the branch condition is at this point equivalent to the truth value of that 1535 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf 1536 // expression in its final statement. As the full condition in that case was 1537 // not evaluated, and is thus not in the SVal cache, we need to use that leaf 1538 // expression to evaluate the truth value of the condition in the current state 1539 // space. 1540 static const Stmt *ResolveCondition(const Stmt *Condition, 1541 const CFGBlock *B) { 1542 if (const Expr *Ex = dyn_cast<Expr>(Condition)) 1543 Condition = Ex->IgnoreParens(); 1544 1545 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition); 1546 if (!BO || !BO->isLogicalOp()) 1547 return Condition; 1548 1549 assert(!B->getTerminator().isTemporaryDtorsBranch() && 1550 "Temporary destructor branches handled by processBindTemporary."); 1551 1552 // For logical operations, we still have the case where some branches 1553 // use the traditional "merge" approach and others sink the branch 1554 // directly into the basic blocks representing the logical operation. 1555 // We need to distinguish between those two cases here. 1556 1557 // The invariants are still shifting, but it is possible that the 1558 // last element in a CFGBlock is not a CFGStmt. Look for the last 1559 // CFGStmt as the value of the condition. 1560 CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend(); 1561 for (; I != E; ++I) { 1562 CFGElement Elem = *I; 1563 Optional<CFGStmt> CS = Elem.getAs<CFGStmt>(); 1564 if (!CS) 1565 continue; 1566 const Stmt *LastStmt = CS->getStmt(); 1567 assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition)); 1568 return LastStmt; 1569 } 1570 llvm_unreachable("could not resolve condition"); 1571 } 1572 1573 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term, 1574 NodeBuilderContext& BldCtx, 1575 ExplodedNode *Pred, 1576 ExplodedNodeSet &Dst, 1577 const CFGBlock *DstT, 1578 const CFGBlock *DstF) { 1579 assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) && 1580 "CXXBindTemporaryExprs are handled by processBindTemporary."); 1581 const LocationContext *LCtx = Pred->getLocationContext(); 1582 PrettyStackTraceLocationContext StackCrashInfo(LCtx); 1583 currBldrCtx = &BldCtx; 1584 1585 // Check for NULL conditions; e.g. "for(;;)" 1586 if (!Condition) { 1587 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF); 1588 NullCondBldr.markInfeasible(false); 1589 NullCondBldr.generateNode(Pred->getState(), true, Pred); 1590 return; 1591 } 1592 1593 if (const Expr *Ex = dyn_cast<Expr>(Condition)) 1594 Condition = Ex->IgnoreParens(); 1595 1596 Condition = ResolveCondition(Condition, BldCtx.getBlock()); 1597 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 1598 Condition->getLocStart(), 1599 "Error evaluating branch"); 1600 1601 ExplodedNodeSet CheckersOutSet; 1602 getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet, 1603 Pred, *this); 1604 // We generated only sinks. 1605 if (CheckersOutSet.empty()) 1606 return; 1607 1608 BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF); 1609 for (NodeBuilder::iterator I = CheckersOutSet.begin(), 1610 E = CheckersOutSet.end(); E != I; ++I) { 1611 ExplodedNode *PredI = *I; 1612 1613 if (PredI->isSink()) 1614 continue; 1615 1616 ProgramStateRef PrevState = PredI->getState(); 1617 SVal X = PrevState->getSVal(Condition, PredI->getLocationContext()); 1618 1619 if (X.isUnknownOrUndef()) { 1620 // Give it a chance to recover from unknown. 1621 if (const Expr *Ex = dyn_cast<Expr>(Condition)) { 1622 if (Ex->getType()->isIntegralOrEnumerationType()) { 1623 // Try to recover some path-sensitivity. Right now casts of symbolic 1624 // integers that promote their values are currently not tracked well. 1625 // If 'Condition' is such an expression, try and recover the 1626 // underlying value and use that instead. 1627 SVal recovered = RecoverCastedSymbol(getStateManager(), 1628 PrevState, Condition, 1629 PredI->getLocationContext(), 1630 getContext()); 1631 1632 if (!recovered.isUnknown()) { 1633 X = recovered; 1634 } 1635 } 1636 } 1637 } 1638 1639 // If the condition is still unknown, give up. 1640 if (X.isUnknownOrUndef()) { 1641 builder.generateNode(PrevState, true, PredI); 1642 builder.generateNode(PrevState, false, PredI); 1643 continue; 1644 } 1645 1646 DefinedSVal V = X.castAs<DefinedSVal>(); 1647 1648 ProgramStateRef StTrue, StFalse; 1649 std::tie(StTrue, StFalse) = PrevState->assume(V); 1650 1651 // Process the true branch. 1652 if (builder.isFeasible(true)) { 1653 if (StTrue) 1654 builder.generateNode(StTrue, true, PredI); 1655 else 1656 builder.markInfeasible(true); 1657 } 1658 1659 // Process the false branch. 1660 if (builder.isFeasible(false)) { 1661 if (StFalse) 1662 builder.generateNode(StFalse, false, PredI); 1663 else 1664 builder.markInfeasible(false); 1665 } 1666 } 1667 currBldrCtx = nullptr; 1668 } 1669 1670 /// The GDM component containing the set of global variables which have been 1671 /// previously initialized with explicit initializers. 1672 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet, 1673 llvm::ImmutableSet<const VarDecl *>) 1674 1675 void ExprEngine::processStaticInitializer(const DeclStmt *DS, 1676 NodeBuilderContext &BuilderCtx, 1677 ExplodedNode *Pred, 1678 clang::ento::ExplodedNodeSet &Dst, 1679 const CFGBlock *DstT, 1680 const CFGBlock *DstF) { 1681 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 1682 currBldrCtx = &BuilderCtx; 1683 1684 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl()); 1685 ProgramStateRef state = Pred->getState(); 1686 bool initHasRun = state->contains<InitializedGlobalsSet>(VD); 1687 BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF); 1688 1689 if (!initHasRun) { 1690 state = state->add<InitializedGlobalsSet>(VD); 1691 } 1692 1693 builder.generateNode(state, initHasRun, Pred); 1694 builder.markInfeasible(!initHasRun); 1695 1696 currBldrCtx = nullptr; 1697 } 1698 1699 /// processIndirectGoto - Called by CoreEngine. Used to generate successor 1700 /// nodes by processing the 'effects' of a computed goto jump. 1701 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) { 1702 1703 ProgramStateRef state = builder.getState(); 1704 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext()); 1705 1706 // Three possibilities: 1707 // 1708 // (1) We know the computed label. 1709 // (2) The label is NULL (or some other constant), or Undefined. 1710 // (3) We have no clue about the label. Dispatch to all targets. 1711 // 1712 1713 typedef IndirectGotoNodeBuilder::iterator iterator; 1714 1715 if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) { 1716 const LabelDecl *L = LV->getLabel(); 1717 1718 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) { 1719 if (I.getLabel() == L) { 1720 builder.generateNode(I, state); 1721 return; 1722 } 1723 } 1724 1725 llvm_unreachable("No block with label."); 1726 } 1727 1728 if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) { 1729 // Dispatch to the first target and mark it as a sink. 1730 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true); 1731 // FIXME: add checker visit. 1732 // UndefBranches.insert(N); 1733 return; 1734 } 1735 1736 // This is really a catch-all. We don't support symbolics yet. 1737 // FIXME: Implement dispatch for symbolic pointers. 1738 1739 for (iterator I=builder.begin(), E=builder.end(); I != E; ++I) 1740 builder.generateNode(I, state); 1741 } 1742 1743 #if 0 1744 static bool stackFrameDoesNotContainInitializedTemporaries(ExplodedNode &Pred) { 1745 const StackFrameContext* Frame = Pred.getStackFrame(); 1746 const llvm::ImmutableSet<CXXBindTemporaryContext> &Set = 1747 Pred.getState()->get<InitializedTemporariesSet>(); 1748 return std::find_if(Set.begin(), Set.end(), 1749 [&](const CXXBindTemporaryContext &Ctx) { 1750 if (Ctx.second == Frame) { 1751 Ctx.first->dump(); 1752 llvm::errs() << "\n"; 1753 } 1754 return Ctx.second == Frame; 1755 }) == Set.end(); 1756 } 1757 #endif 1758 1759 void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC, 1760 ExplodedNode *Pred, 1761 ExplodedNodeSet &Dst, 1762 const BlockEdge &L) { 1763 SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC); 1764 getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this); 1765 } 1766 1767 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path 1768 /// nodes when the control reaches the end of a function. 1769 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC, 1770 ExplodedNode *Pred, 1771 const ReturnStmt *RS) { 1772 // FIXME: Assert that stackFrameDoesNotContainInitializedTemporaries(*Pred)). 1773 // We currently cannot enable this assert, as lifetime extended temporaries 1774 // are not modelled correctly. 1775 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 1776 StateMgr.EndPath(Pred->getState()); 1777 1778 ExplodedNodeSet Dst; 1779 if (Pred->getLocationContext()->inTopFrame()) { 1780 // Remove dead symbols. 1781 ExplodedNodeSet AfterRemovedDead; 1782 removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead); 1783 1784 // Notify checkers. 1785 for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(), 1786 E = AfterRemovedDead.end(); I != E; ++I) { 1787 getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this); 1788 } 1789 } else { 1790 getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this); 1791 } 1792 1793 Engine.enqueueEndOfFunction(Dst, RS); 1794 } 1795 1796 /// ProcessSwitch - Called by CoreEngine. Used to generate successor 1797 /// nodes by processing the 'effects' of a switch statement. 1798 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) { 1799 typedef SwitchNodeBuilder::iterator iterator; 1800 ProgramStateRef state = builder.getState(); 1801 const Expr *CondE = builder.getCondition(); 1802 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext()); 1803 1804 if (CondV_untested.isUndef()) { 1805 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true); 1806 // FIXME: add checker 1807 //UndefBranches.insert(N); 1808 1809 return; 1810 } 1811 DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>(); 1812 1813 ProgramStateRef DefaultSt = state; 1814 1815 iterator I = builder.begin(), EI = builder.end(); 1816 bool defaultIsFeasible = I == EI; 1817 1818 for ( ; I != EI; ++I) { 1819 // Successor may be pruned out during CFG construction. 1820 if (!I.getBlock()) 1821 continue; 1822 1823 const CaseStmt *Case = I.getCase(); 1824 1825 // Evaluate the LHS of the case value. 1826 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext()); 1827 assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType())); 1828 1829 // Get the RHS of the case, if it exists. 1830 llvm::APSInt V2; 1831 if (const Expr *E = Case->getRHS()) 1832 V2 = E->EvaluateKnownConstInt(getContext()); 1833 else 1834 V2 = V1; 1835 1836 ProgramStateRef StateCase; 1837 if (Optional<NonLoc> NL = CondV.getAs<NonLoc>()) 1838 std::tie(StateCase, DefaultSt) = 1839 DefaultSt->assumeInclusiveRange(*NL, V1, V2); 1840 else // UnknownVal 1841 StateCase = DefaultSt; 1842 1843 if (StateCase) 1844 builder.generateCaseStmtNode(I, StateCase); 1845 1846 // Now "assume" that the case doesn't match. Add this state 1847 // to the default state (if it is feasible). 1848 if (DefaultSt) 1849 defaultIsFeasible = true; 1850 else { 1851 defaultIsFeasible = false; 1852 break; 1853 } 1854 } 1855 1856 if (!defaultIsFeasible) 1857 return; 1858 1859 // If we have switch(enum value), the default branch is not 1860 // feasible if all of the enum constants not covered by 'case:' statements 1861 // are not feasible values for the switch condition. 1862 // 1863 // Note that this isn't as accurate as it could be. Even if there isn't 1864 // a case for a particular enum value as long as that enum value isn't 1865 // feasible then it shouldn't be considered for making 'default:' reachable. 1866 const SwitchStmt *SS = builder.getSwitch(); 1867 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts(); 1868 if (CondExpr->getType()->getAs<EnumType>()) { 1869 if (SS->isAllEnumCasesCovered()) 1870 return; 1871 } 1872 1873 builder.generateDefaultCaseNode(DefaultSt); 1874 } 1875 1876 //===----------------------------------------------------------------------===// 1877 // Transfer functions: Loads and stores. 1878 //===----------------------------------------------------------------------===// 1879 1880 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D, 1881 ExplodedNode *Pred, 1882 ExplodedNodeSet &Dst) { 1883 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1884 1885 ProgramStateRef state = Pred->getState(); 1886 const LocationContext *LCtx = Pred->getLocationContext(); 1887 1888 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1889 // C permits "extern void v", and if you cast the address to a valid type, 1890 // you can even do things with it. We simply pretend 1891 assert(Ex->isGLValue() || VD->getType()->isVoidType()); 1892 const LocationContext *LocCtxt = Pred->getLocationContext(); 1893 const Decl *D = LocCtxt->getDecl(); 1894 const auto *MD = D ? dyn_cast<CXXMethodDecl>(D) : nullptr; 1895 const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex); 1896 SVal V; 1897 bool IsReference; 1898 if (AMgr.options.shouldInlineLambdas() && DeclRefEx && 1899 DeclRefEx->refersToEnclosingVariableOrCapture() && MD && 1900 MD->getParent()->isLambda()) { 1901 // Lookup the field of the lambda. 1902 const CXXRecordDecl *CXXRec = MD->getParent(); 1903 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 1904 FieldDecl *LambdaThisCaptureField; 1905 CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField); 1906 const FieldDecl *FD = LambdaCaptureFields[VD]; 1907 if (!FD) { 1908 // When a constant is captured, sometimes no corresponding field is 1909 // created in the lambda object. 1910 assert(VD->getType().isConstQualified()); 1911 V = state->getLValue(VD, LocCtxt); 1912 IsReference = false; 1913 } else { 1914 Loc CXXThis = 1915 svalBuilder.getCXXThis(MD, LocCtxt->getCurrentStackFrame()); 1916 SVal CXXThisVal = state->getSVal(CXXThis); 1917 V = state->getLValue(FD, CXXThisVal); 1918 IsReference = FD->getType()->isReferenceType(); 1919 } 1920 } else { 1921 V = state->getLValue(VD, LocCtxt); 1922 IsReference = VD->getType()->isReferenceType(); 1923 } 1924 1925 // For references, the 'lvalue' is the pointer address stored in the 1926 // reference region. 1927 if (IsReference) { 1928 if (const MemRegion *R = V.getAsRegion()) 1929 V = state->getSVal(R); 1930 else 1931 V = UnknownVal(); 1932 } 1933 1934 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr, 1935 ProgramPoint::PostLValueKind); 1936 return; 1937 } 1938 if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 1939 assert(!Ex->isGLValue()); 1940 SVal V = svalBuilder.makeIntVal(ED->getInitVal()); 1941 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V)); 1942 return; 1943 } 1944 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1945 SVal V = svalBuilder.getFunctionPointer(FD); 1946 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr, 1947 ProgramPoint::PostLValueKind); 1948 return; 1949 } 1950 if (isa<FieldDecl>(D)) { 1951 // FIXME: Compute lvalue of field pointers-to-member. 1952 // Right now we just use a non-null void pointer, so that it gives proper 1953 // results in boolean contexts. 1954 SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy, 1955 currBldrCtx->blockCount()); 1956 state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true); 1957 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr, 1958 ProgramPoint::PostLValueKind); 1959 return; 1960 } 1961 1962 llvm_unreachable("Support for this Decl not implemented."); 1963 } 1964 1965 /// VisitArraySubscriptExpr - Transfer function for array accesses 1966 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A, 1967 ExplodedNode *Pred, 1968 ExplodedNodeSet &Dst){ 1969 1970 const Expr *Base = A->getBase()->IgnoreParens(); 1971 const Expr *Idx = A->getIdx()->IgnoreParens(); 1972 1973 ExplodedNodeSet CheckerPreStmt; 1974 getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this); 1975 1976 ExplodedNodeSet EvalSet; 1977 StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx); 1978 assert(A->isGLValue() || 1979 (!AMgr.getLangOpts().CPlusPlus && 1980 A->getType().isCForbiddenLValueType())); 1981 1982 for (auto *Node : CheckerPreStmt) { 1983 const LocationContext *LCtx = Node->getLocationContext(); 1984 ProgramStateRef state = Node->getState(); 1985 SVal V = state->getLValue(A->getType(), 1986 state->getSVal(Idx, LCtx), 1987 state->getSVal(Base, LCtx)); 1988 Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr, 1989 ProgramPoint::PostLValueKind); 1990 } 1991 1992 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this); 1993 } 1994 1995 /// VisitMemberExpr - Transfer function for member expressions. 1996 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, 1997 ExplodedNodeSet &Dst) { 1998 1999 // FIXME: Prechecks eventually go in ::Visit(). 2000 ExplodedNodeSet CheckedSet; 2001 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this); 2002 2003 ExplodedNodeSet EvalSet; 2004 ValueDecl *Member = M->getMemberDecl(); 2005 2006 // Handle static member variables and enum constants accessed via 2007 // member syntax. 2008 if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) { 2009 ExplodedNodeSet Dst; 2010 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 2011 I != E; ++I) { 2012 VisitCommonDeclRefExpr(M, Member, Pred, EvalSet); 2013 } 2014 } else { 2015 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx); 2016 ExplodedNodeSet Tmp; 2017 2018 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 2019 I != E; ++I) { 2020 ProgramStateRef state = (*I)->getState(); 2021 const LocationContext *LCtx = (*I)->getLocationContext(); 2022 Expr *BaseExpr = M->getBase(); 2023 2024 // Handle C++ method calls. 2025 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) { 2026 if (MD->isInstance()) 2027 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr); 2028 2029 SVal MDVal = svalBuilder.getFunctionPointer(MD); 2030 state = state->BindExpr(M, LCtx, MDVal); 2031 2032 Bldr.generateNode(M, *I, state); 2033 continue; 2034 } 2035 2036 // Handle regular struct fields / member variables. 2037 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr); 2038 SVal baseExprVal = state->getSVal(BaseExpr, LCtx); 2039 2040 FieldDecl *field = cast<FieldDecl>(Member); 2041 SVal L = state->getLValue(field, baseExprVal); 2042 2043 if (M->isGLValue() || M->getType()->isArrayType()) { 2044 // We special-case rvalues of array type because the analyzer cannot 2045 // reason about them, since we expect all regions to be wrapped in Locs. 2046 // We instead treat these as lvalues and assume that they will decay to 2047 // pointers as soon as they are used. 2048 if (!M->isGLValue()) { 2049 assert(M->getType()->isArrayType()); 2050 const ImplicitCastExpr *PE = 2051 dyn_cast<ImplicitCastExpr>((*I)->getParentMap().getParentIgnoreParens(M)); 2052 if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) { 2053 llvm_unreachable("should always be wrapped in ArrayToPointerDecay"); 2054 } 2055 } 2056 2057 if (field->getType()->isReferenceType()) { 2058 if (const MemRegion *R = L.getAsRegion()) 2059 L = state->getSVal(R); 2060 else 2061 L = UnknownVal(); 2062 } 2063 2064 Bldr.generateNode(M, *I, state->BindExpr(M, LCtx, L), nullptr, 2065 ProgramPoint::PostLValueKind); 2066 } else { 2067 Bldr.takeNodes(*I); 2068 evalLoad(Tmp, M, M, *I, state, L); 2069 Bldr.addNodes(Tmp); 2070 } 2071 } 2072 } 2073 2074 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this); 2075 } 2076 2077 void ExprEngine::VisitAtomicExpr(const AtomicExpr *AE, ExplodedNode *Pred, 2078 ExplodedNodeSet &Dst) { 2079 ExplodedNodeSet AfterPreSet; 2080 getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this); 2081 2082 // For now, treat all the arguments to C11 atomics as escaping. 2083 // FIXME: Ideally we should model the behavior of the atomics precisely here. 2084 2085 ExplodedNodeSet AfterInvalidateSet; 2086 StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx); 2087 2088 for (ExplodedNodeSet::iterator I = AfterPreSet.begin(), E = AfterPreSet.end(); 2089 I != E; ++I) { 2090 ProgramStateRef State = (*I)->getState(); 2091 const LocationContext *LCtx = (*I)->getLocationContext(); 2092 2093 SmallVector<SVal, 8> ValuesToInvalidate; 2094 for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) { 2095 const Expr *SubExpr = AE->getSubExprs()[SI]; 2096 SVal SubExprVal = State->getSVal(SubExpr, LCtx); 2097 ValuesToInvalidate.push_back(SubExprVal); 2098 } 2099 2100 State = State->invalidateRegions(ValuesToInvalidate, AE, 2101 currBldrCtx->blockCount(), 2102 LCtx, 2103 /*CausedByPointerEscape*/true, 2104 /*Symbols=*/nullptr); 2105 2106 SVal ResultVal = UnknownVal(); 2107 State = State->BindExpr(AE, LCtx, ResultVal); 2108 Bldr.generateNode(AE, *I, State, nullptr, 2109 ProgramPoint::PostStmtKind); 2110 } 2111 2112 getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this); 2113 } 2114 2115 namespace { 2116 class CollectReachableSymbolsCallback final : public SymbolVisitor { 2117 InvalidatedSymbols Symbols; 2118 2119 public: 2120 CollectReachableSymbolsCallback(ProgramStateRef State) {} 2121 const InvalidatedSymbols &getSymbols() const { return Symbols; } 2122 2123 bool VisitSymbol(SymbolRef Sym) override { 2124 Symbols.insert(Sym); 2125 return true; 2126 } 2127 }; 2128 } // end anonymous namespace 2129 2130 // A value escapes in three possible cases: 2131 // (1) We are binding to something that is not a memory region. 2132 // (2) We are binding to a MemrRegion that does not have stack storage. 2133 // (3) We are binding to a MemRegion with stack storage that the store 2134 // does not understand. 2135 ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State, 2136 SVal Loc, SVal Val) { 2137 // Are we storing to something that causes the value to "escape"? 2138 bool escapes = true; 2139 2140 // TODO: Move to StoreManager. 2141 if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) { 2142 escapes = !regionLoc->getRegion()->hasStackStorage(); 2143 2144 if (!escapes) { 2145 // To test (3), generate a new state with the binding added. If it is 2146 // the same state, then it escapes (since the store cannot represent 2147 // the binding). 2148 // Do this only if we know that the store is not supposed to generate the 2149 // same state. 2150 SVal StoredVal = State->getSVal(regionLoc->getRegion()); 2151 if (StoredVal != Val) 2152 escapes = (State == (State->bindLoc(*regionLoc, Val))); 2153 } 2154 } 2155 2156 // If our store can represent the binding and we aren't storing to something 2157 // that doesn't have local storage then just return and have the simulation 2158 // state continue as is. 2159 if (!escapes) 2160 return State; 2161 2162 // Otherwise, find all symbols referenced by 'val' that we are tracking 2163 // and stop tracking them. 2164 CollectReachableSymbolsCallback Scanner = 2165 State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val); 2166 const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols(); 2167 State = getCheckerManager().runCheckersForPointerEscape(State, 2168 EscapedSymbols, 2169 /*CallEvent*/ nullptr, 2170 PSK_EscapeOnBind, 2171 nullptr); 2172 2173 return State; 2174 } 2175 2176 ProgramStateRef 2177 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State, 2178 const InvalidatedSymbols *Invalidated, 2179 ArrayRef<const MemRegion *> ExplicitRegions, 2180 ArrayRef<const MemRegion *> Regions, 2181 const CallEvent *Call, 2182 RegionAndSymbolInvalidationTraits &ITraits) { 2183 2184 if (!Invalidated || Invalidated->empty()) 2185 return State; 2186 2187 if (!Call) 2188 return getCheckerManager().runCheckersForPointerEscape(State, 2189 *Invalidated, 2190 nullptr, 2191 PSK_EscapeOther, 2192 &ITraits); 2193 2194 // If the symbols were invalidated by a call, we want to find out which ones 2195 // were invalidated directly due to being arguments to the call. 2196 InvalidatedSymbols SymbolsDirectlyInvalidated; 2197 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(), 2198 E = ExplicitRegions.end(); I != E; ++I) { 2199 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>()) 2200 SymbolsDirectlyInvalidated.insert(R->getSymbol()); 2201 } 2202 2203 InvalidatedSymbols SymbolsIndirectlyInvalidated; 2204 for (InvalidatedSymbols::const_iterator I=Invalidated->begin(), 2205 E = Invalidated->end(); I!=E; ++I) { 2206 SymbolRef sym = *I; 2207 if (SymbolsDirectlyInvalidated.count(sym)) 2208 continue; 2209 SymbolsIndirectlyInvalidated.insert(sym); 2210 } 2211 2212 if (!SymbolsDirectlyInvalidated.empty()) 2213 State = getCheckerManager().runCheckersForPointerEscape(State, 2214 SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits); 2215 2216 // Notify about the symbols that get indirectly invalidated by the call. 2217 if (!SymbolsIndirectlyInvalidated.empty()) 2218 State = getCheckerManager().runCheckersForPointerEscape(State, 2219 SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits); 2220 2221 return State; 2222 } 2223 2224 /// evalBind - Handle the semantics of binding a value to a specific location. 2225 /// This method is used by evalStore and (soon) VisitDeclStmt, and others. 2226 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, 2227 ExplodedNode *Pred, 2228 SVal location, SVal Val, 2229 bool atDeclInit, const ProgramPoint *PP) { 2230 2231 const LocationContext *LC = Pred->getLocationContext(); 2232 PostStmt PS(StoreE, LC); 2233 if (!PP) 2234 PP = &PS; 2235 2236 // Do a previsit of the bind. 2237 ExplodedNodeSet CheckedSet; 2238 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val, 2239 StoreE, *this, *PP); 2240 2241 StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx); 2242 2243 // If the location is not a 'Loc', it will already be handled by 2244 // the checkers. There is nothing left to do. 2245 if (!location.getAs<Loc>()) { 2246 const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr, 2247 /*tag*/nullptr); 2248 ProgramStateRef state = Pred->getState(); 2249 state = processPointerEscapedOnBind(state, location, Val); 2250 Bldr.generateNode(L, state, Pred); 2251 return; 2252 } 2253 2254 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 2255 I!=E; ++I) { 2256 ExplodedNode *PredI = *I; 2257 ProgramStateRef state = PredI->getState(); 2258 2259 state = processPointerEscapedOnBind(state, location, Val); 2260 2261 // When binding the value, pass on the hint that this is a initialization. 2262 // For initializations, we do not need to inform clients of region 2263 // changes. 2264 state = state->bindLoc(location.castAs<Loc>(), 2265 Val, /* notifyChanges = */ !atDeclInit); 2266 2267 const MemRegion *LocReg = nullptr; 2268 if (Optional<loc::MemRegionVal> LocRegVal = 2269 location.getAs<loc::MemRegionVal>()) { 2270 LocReg = LocRegVal->getRegion(); 2271 } 2272 2273 const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr); 2274 Bldr.generateNode(L, state, PredI); 2275 } 2276 } 2277 2278 /// evalStore - Handle the semantics of a store via an assignment. 2279 /// @param Dst The node set to store generated state nodes 2280 /// @param AssignE The assignment expression if the store happens in an 2281 /// assignment. 2282 /// @param LocationE The location expression that is stored to. 2283 /// @param state The current simulation state 2284 /// @param location The location to store the value 2285 /// @param Val The value to be stored 2286 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, 2287 const Expr *LocationE, 2288 ExplodedNode *Pred, 2289 ProgramStateRef state, SVal location, SVal Val, 2290 const ProgramPointTag *tag) { 2291 // Proceed with the store. We use AssignE as the anchor for the PostStore 2292 // ProgramPoint if it is non-NULL, and LocationE otherwise. 2293 const Expr *StoreE = AssignE ? AssignE : LocationE; 2294 2295 // Evaluate the location (checks for bad dereferences). 2296 ExplodedNodeSet Tmp; 2297 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false); 2298 2299 if (Tmp.empty()) 2300 return; 2301 2302 if (location.isUndef()) 2303 return; 2304 2305 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) 2306 evalBind(Dst, StoreE, *NI, location, Val, false); 2307 } 2308 2309 void ExprEngine::evalLoad(ExplodedNodeSet &Dst, 2310 const Expr *NodeEx, 2311 const Expr *BoundEx, 2312 ExplodedNode *Pred, 2313 ProgramStateRef state, 2314 SVal location, 2315 const ProgramPointTag *tag, 2316 QualType LoadTy) 2317 { 2318 assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc."); 2319 2320 // Are we loading from a region? This actually results in two loads; one 2321 // to fetch the address of the referenced value and one to fetch the 2322 // referenced value. 2323 if (const TypedValueRegion *TR = 2324 dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) { 2325 2326 QualType ValTy = TR->getValueType(); 2327 if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) { 2328 static SimpleProgramPointTag 2329 loadReferenceTag(TagProviderName, "Load Reference"); 2330 ExplodedNodeSet Tmp; 2331 evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state, 2332 location, &loadReferenceTag, 2333 getContext().getPointerType(RT->getPointeeType())); 2334 2335 // Perform the load from the referenced value. 2336 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) { 2337 state = (*I)->getState(); 2338 location = state->getSVal(BoundEx, (*I)->getLocationContext()); 2339 evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy); 2340 } 2341 return; 2342 } 2343 } 2344 2345 evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy); 2346 } 2347 2348 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst, 2349 const Expr *NodeEx, 2350 const Expr *BoundEx, 2351 ExplodedNode *Pred, 2352 ProgramStateRef state, 2353 SVal location, 2354 const ProgramPointTag *tag, 2355 QualType LoadTy) { 2356 assert(NodeEx); 2357 assert(BoundEx); 2358 // Evaluate the location (checks for bad dereferences). 2359 ExplodedNodeSet Tmp; 2360 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true); 2361 if (Tmp.empty()) 2362 return; 2363 2364 StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx); 2365 if (location.isUndef()) 2366 return; 2367 2368 // Proceed with the load. 2369 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) { 2370 state = (*NI)->getState(); 2371 const LocationContext *LCtx = (*NI)->getLocationContext(); 2372 2373 SVal V = UnknownVal(); 2374 if (location.isValid()) { 2375 if (LoadTy.isNull()) 2376 LoadTy = BoundEx->getType(); 2377 V = state->getSVal(location.castAs<Loc>(), LoadTy); 2378 } 2379 2380 Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag, 2381 ProgramPoint::PostLoadKind); 2382 } 2383 } 2384 2385 void ExprEngine::evalLocation(ExplodedNodeSet &Dst, 2386 const Stmt *NodeEx, 2387 const Stmt *BoundEx, 2388 ExplodedNode *Pred, 2389 ProgramStateRef state, 2390 SVal location, 2391 const ProgramPointTag *tag, 2392 bool isLoad) { 2393 StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx); 2394 // Early checks for performance reason. 2395 if (location.isUnknown()) { 2396 return; 2397 } 2398 2399 ExplodedNodeSet Src; 2400 BldrTop.takeNodes(Pred); 2401 StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx); 2402 if (Pred->getState() != state) { 2403 // Associate this new state with an ExplodedNode. 2404 // FIXME: If I pass null tag, the graph is incorrect, e.g for 2405 // int *p; 2406 // p = 0; 2407 // *p = 0xDEADBEEF; 2408 // "p = 0" is not noted as "Null pointer value stored to 'p'" but 2409 // instead "int *p" is noted as 2410 // "Variable 'p' initialized to a null pointer value" 2411 2412 static SimpleProgramPointTag tag(TagProviderName, "Location"); 2413 Bldr.generateNode(NodeEx, Pred, state, &tag); 2414 } 2415 ExplodedNodeSet Tmp; 2416 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad, 2417 NodeEx, BoundEx, *this); 2418 BldrTop.addNodes(Tmp); 2419 } 2420 2421 std::pair<const ProgramPointTag *, const ProgramPointTag*> 2422 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() { 2423 static SimpleProgramPointTag 2424 eagerlyAssumeBinOpBifurcationTrue(TagProviderName, 2425 "Eagerly Assume True"), 2426 eagerlyAssumeBinOpBifurcationFalse(TagProviderName, 2427 "Eagerly Assume False"); 2428 return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue, 2429 &eagerlyAssumeBinOpBifurcationFalse); 2430 } 2431 2432 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, 2433 ExplodedNodeSet &Src, 2434 const Expr *Ex) { 2435 StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx); 2436 2437 for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) { 2438 ExplodedNode *Pred = *I; 2439 // Test if the previous node was as the same expression. This can happen 2440 // when the expression fails to evaluate to anything meaningful and 2441 // (as an optimization) we don't generate a node. 2442 ProgramPoint P = Pred->getLocation(); 2443 if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) { 2444 continue; 2445 } 2446 2447 ProgramStateRef state = Pred->getState(); 2448 SVal V = state->getSVal(Ex, Pred->getLocationContext()); 2449 Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>(); 2450 if (SEV && SEV->isExpression()) { 2451 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags = 2452 geteagerlyAssumeBinOpBifurcationTags(); 2453 2454 ProgramStateRef StateTrue, StateFalse; 2455 std::tie(StateTrue, StateFalse) = state->assume(*SEV); 2456 2457 // First assume that the condition is true. 2458 if (StateTrue) { 2459 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType()); 2460 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val); 2461 Bldr.generateNode(Ex, Pred, StateTrue, tags.first); 2462 } 2463 2464 // Next, assume that the condition is false. 2465 if (StateFalse) { 2466 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType()); 2467 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val); 2468 Bldr.generateNode(Ex, Pred, StateFalse, tags.second); 2469 } 2470 } 2471 } 2472 } 2473 2474 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, 2475 ExplodedNodeSet &Dst) { 2476 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 2477 // We have processed both the inputs and the outputs. All of the outputs 2478 // should evaluate to Locs. Nuke all of their values. 2479 2480 // FIXME: Some day in the future it would be nice to allow a "plug-in" 2481 // which interprets the inline asm and stores proper results in the 2482 // outputs. 2483 2484 ProgramStateRef state = Pred->getState(); 2485 2486 for (const Expr *O : A->outputs()) { 2487 SVal X = state->getSVal(O, Pred->getLocationContext()); 2488 assert (!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef. 2489 2490 if (Optional<Loc> LV = X.getAs<Loc>()) 2491 state = state->bindLoc(*LV, UnknownVal()); 2492 } 2493 2494 Bldr.generateNode(A, Pred, state); 2495 } 2496 2497 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred, 2498 ExplodedNodeSet &Dst) { 2499 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 2500 Bldr.generateNode(A, Pred, Pred->getState()); 2501 } 2502 2503 //===----------------------------------------------------------------------===// 2504 // Visualization. 2505 //===----------------------------------------------------------------------===// 2506 2507 #ifndef NDEBUG 2508 static ExprEngine* GraphPrintCheckerState; 2509 static SourceManager* GraphPrintSourceManager; 2510 2511 namespace llvm { 2512 template<> 2513 struct DOTGraphTraits<ExplodedNode*> : 2514 public DefaultDOTGraphTraits { 2515 2516 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 2517 2518 // FIXME: Since we do not cache error nodes in ExprEngine now, this does not 2519 // work. 2520 static std::string getNodeAttributes(const ExplodedNode *N, void*) { 2521 return ""; 2522 } 2523 2524 // De-duplicate some source location pretty-printing. 2525 static void printLocation(raw_ostream &Out, SourceLocation SLoc) { 2526 if (SLoc.isFileID()) { 2527 Out << "\\lline=" 2528 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 2529 << " col=" 2530 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc) 2531 << "\\l"; 2532 } 2533 } 2534 static void printLocation2(raw_ostream &Out, SourceLocation SLoc) { 2535 if (SLoc.isFileID() && GraphPrintSourceManager->isInMainFile(SLoc)) 2536 Out << "line " << GraphPrintSourceManager->getExpansionLineNumber(SLoc); 2537 else 2538 SLoc.print(Out, *GraphPrintSourceManager); 2539 } 2540 2541 static std::string getNodeLabel(const ExplodedNode *N, void*){ 2542 2543 std::string sbuf; 2544 llvm::raw_string_ostream Out(sbuf); 2545 2546 // Program Location. 2547 ProgramPoint Loc = N->getLocation(); 2548 2549 switch (Loc.getKind()) { 2550 case ProgramPoint::BlockEntranceKind: { 2551 Out << "Block Entrance: B" 2552 << Loc.castAs<BlockEntrance>().getBlock()->getBlockID(); 2553 break; 2554 } 2555 2556 case ProgramPoint::BlockExitKind: 2557 assert (false); 2558 break; 2559 2560 case ProgramPoint::CallEnterKind: 2561 Out << "CallEnter"; 2562 break; 2563 2564 case ProgramPoint::CallExitBeginKind: 2565 Out << "CallExitBegin"; 2566 break; 2567 2568 case ProgramPoint::CallExitEndKind: 2569 Out << "CallExitEnd"; 2570 break; 2571 2572 case ProgramPoint::PostStmtPurgeDeadSymbolsKind: 2573 Out << "PostStmtPurgeDeadSymbols"; 2574 break; 2575 2576 case ProgramPoint::PreStmtPurgeDeadSymbolsKind: 2577 Out << "PreStmtPurgeDeadSymbols"; 2578 break; 2579 2580 case ProgramPoint::EpsilonKind: 2581 Out << "Epsilon Point"; 2582 break; 2583 2584 case ProgramPoint::PreImplicitCallKind: { 2585 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>(); 2586 Out << "PreCall: "; 2587 2588 // FIXME: Get proper printing options. 2589 PC.getDecl()->print(Out, LangOptions()); 2590 printLocation(Out, PC.getLocation()); 2591 break; 2592 } 2593 2594 case ProgramPoint::PostImplicitCallKind: { 2595 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>(); 2596 Out << "PostCall: "; 2597 2598 // FIXME: Get proper printing options. 2599 PC.getDecl()->print(Out, LangOptions()); 2600 printLocation(Out, PC.getLocation()); 2601 break; 2602 } 2603 2604 case ProgramPoint::PostInitializerKind: { 2605 Out << "PostInitializer: "; 2606 const CXXCtorInitializer *Init = 2607 Loc.castAs<PostInitializer>().getInitializer(); 2608 if (const FieldDecl *FD = Init->getAnyMember()) 2609 Out << *FD; 2610 else { 2611 QualType Ty = Init->getTypeSourceInfo()->getType(); 2612 Ty = Ty.getLocalUnqualifiedType(); 2613 LangOptions LO; // FIXME. 2614 Ty.print(Out, LO); 2615 } 2616 break; 2617 } 2618 2619 case ProgramPoint::BlockEdgeKind: { 2620 const BlockEdge &E = Loc.castAs<BlockEdge>(); 2621 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B" 2622 << E.getDst()->getBlockID() << ')'; 2623 2624 if (const Stmt *T = E.getSrc()->getTerminator()) { 2625 SourceLocation SLoc = T->getLocStart(); 2626 2627 Out << "\\|Terminator: "; 2628 LangOptions LO; // FIXME. 2629 E.getSrc()->printTerminator(Out, LO); 2630 2631 if (SLoc.isFileID()) { 2632 Out << "\\lline=" 2633 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 2634 << " col=" 2635 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc); 2636 } 2637 2638 if (isa<SwitchStmt>(T)) { 2639 const Stmt *Label = E.getDst()->getLabel(); 2640 2641 if (Label) { 2642 if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) { 2643 Out << "\\lcase "; 2644 LangOptions LO; // FIXME. 2645 if (C->getLHS()) 2646 C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO)); 2647 2648 if (const Stmt *RHS = C->getRHS()) { 2649 Out << " .. "; 2650 RHS->printPretty(Out, nullptr, PrintingPolicy(LO)); 2651 } 2652 2653 Out << ":"; 2654 } 2655 else { 2656 assert (isa<DefaultStmt>(Label)); 2657 Out << "\\ldefault:"; 2658 } 2659 } 2660 else 2661 Out << "\\l(implicit) default:"; 2662 } 2663 else if (isa<IndirectGotoStmt>(T)) { 2664 // FIXME 2665 } 2666 else { 2667 Out << "\\lCondition: "; 2668 if (*E.getSrc()->succ_begin() == E.getDst()) 2669 Out << "true"; 2670 else 2671 Out << "false"; 2672 } 2673 2674 Out << "\\l"; 2675 } 2676 2677 break; 2678 } 2679 2680 default: { 2681 const Stmt *S = Loc.castAs<StmtPoint>().getStmt(); 2682 assert(S != nullptr && "Expecting non-null Stmt"); 2683 2684 Out << S->getStmtClassName() << ' ' << (const void*) S << ' '; 2685 LangOptions LO; // FIXME. 2686 S->printPretty(Out, nullptr, PrintingPolicy(LO)); 2687 printLocation(Out, S->getLocStart()); 2688 2689 if (Loc.getAs<PreStmt>()) 2690 Out << "\\lPreStmt\\l;"; 2691 else if (Loc.getAs<PostLoad>()) 2692 Out << "\\lPostLoad\\l;"; 2693 else if (Loc.getAs<PostStore>()) 2694 Out << "\\lPostStore\\l"; 2695 else if (Loc.getAs<PostLValue>()) 2696 Out << "\\lPostLValue\\l"; 2697 2698 break; 2699 } 2700 } 2701 2702 ProgramStateRef state = N->getState(); 2703 Out << "\\|StateID: " << (const void*) state.get() 2704 << " NodeID: " << (const void*) N << "\\|"; 2705 2706 // Analysis stack backtrace. 2707 Out << "Location context stack (from current to outer):\\l"; 2708 const LocationContext *LC = Loc.getLocationContext(); 2709 unsigned Idx = 0; 2710 for (; LC; LC = LC->getParent(), ++Idx) { 2711 Out << Idx << ". (" << (const void *)LC << ") "; 2712 switch (LC->getKind()) { 2713 case LocationContext::StackFrame: 2714 if (const NamedDecl *D = dyn_cast<NamedDecl>(LC->getDecl())) 2715 Out << "Calling " << D->getQualifiedNameAsString(); 2716 else 2717 Out << "Calling anonymous code"; 2718 if (const Stmt *S = cast<StackFrameContext>(LC)->getCallSite()) { 2719 Out << " at "; 2720 printLocation2(Out, S->getLocStart()); 2721 } 2722 break; 2723 case LocationContext::Block: 2724 Out << "Invoking block"; 2725 if (const Decl *D = cast<BlockInvocationContext>(LC)->getBlockDecl()) { 2726 Out << " defined at "; 2727 printLocation2(Out, D->getLocStart()); 2728 } 2729 break; 2730 case LocationContext::Scope: 2731 Out << "Entering scope"; 2732 // FIXME: Add more info once ScopeContext is activated. 2733 break; 2734 } 2735 Out << "\\l"; 2736 } 2737 Out << "\\l"; 2738 2739 state->printDOT(Out); 2740 2741 Out << "\\l"; 2742 2743 if (const ProgramPointTag *tag = Loc.getTag()) { 2744 Out << "\\|Tag: " << tag->getTagDescription(); 2745 Out << "\\l"; 2746 } 2747 return Out.str(); 2748 } 2749 }; 2750 } // end llvm namespace 2751 #endif 2752 2753 void ExprEngine::ViewGraph(bool trim) { 2754 #ifndef NDEBUG 2755 if (trim) { 2756 std::vector<const ExplodedNode*> Src; 2757 2758 // Flush any outstanding reports to make sure we cover all the nodes. 2759 // This does not cause them to get displayed. 2760 for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I) 2761 const_cast<BugType*>(*I)->FlushReports(BR); 2762 2763 // Iterate through the reports and get their nodes. 2764 for (BugReporter::EQClasses_iterator 2765 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) { 2766 ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode()); 2767 if (N) Src.push_back(N); 2768 } 2769 2770 ViewGraph(Src); 2771 } 2772 else { 2773 GraphPrintCheckerState = this; 2774 GraphPrintSourceManager = &getContext().getSourceManager(); 2775 2776 llvm::ViewGraph(*G.roots_begin(), "ExprEngine"); 2777 2778 GraphPrintCheckerState = nullptr; 2779 GraphPrintSourceManager = nullptr; 2780 } 2781 #endif 2782 } 2783 2784 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) { 2785 #ifndef NDEBUG 2786 GraphPrintCheckerState = this; 2787 GraphPrintSourceManager = &getContext().getSourceManager(); 2788 2789 std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes)); 2790 2791 if (!TrimmedG.get()) 2792 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n"; 2793 else 2794 llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine"); 2795 2796 GraphPrintCheckerState = nullptr; 2797 GraphPrintSourceManager = nullptr; 2798 #endif 2799 } 2800