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