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 llvm_unreachable("Stmt should not be in analyzer evaluation loop"); 871 872 case Stmt::ObjCSubscriptRefExprClass: 873 case Stmt::ObjCPropertyRefExprClass: 874 llvm_unreachable("These are handled by PseudoObjectExpr"); 875 876 case Stmt::GNUNullExprClass: { 877 // GNU __null is a pointer-width integer, not an actual pointer. 878 ProgramStateRef state = Pred->getState(); 879 state = state->BindExpr(S, Pred->getLocationContext(), 880 svalBuilder.makeIntValWithPtrWidth(0, false)); 881 Bldr.generateNode(S, Pred, state); 882 break; 883 } 884 885 case Stmt::ObjCAtSynchronizedStmtClass: 886 Bldr.takeNodes(Pred); 887 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst); 888 Bldr.addNodes(Dst); 889 break; 890 891 case Stmt::ExprWithCleanupsClass: 892 // Handled due to fully linearised CFG. 893 break; 894 895 case Stmt::CXXBindTemporaryExprClass: { 896 Bldr.takeNodes(Pred); 897 ExplodedNodeSet PreVisit; 898 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 899 ExplodedNodeSet Next; 900 VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next); 901 getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this); 902 Bldr.addNodes(Dst); 903 break; 904 } 905 906 // Cases not handled yet; but will handle some day. 907 case Stmt::DesignatedInitExprClass: 908 case Stmt::DesignatedInitUpdateExprClass: 909 case Stmt::ArrayInitLoopExprClass: 910 case Stmt::ArrayInitIndexExprClass: 911 case Stmt::ExtVectorElementExprClass: 912 case Stmt::ImaginaryLiteralClass: 913 case Stmt::ObjCAtCatchStmtClass: 914 case Stmt::ObjCAtFinallyStmtClass: 915 case Stmt::ObjCAtTryStmtClass: 916 case Stmt::ObjCAutoreleasePoolStmtClass: 917 case Stmt::ObjCEncodeExprClass: 918 case Stmt::ObjCIsaExprClass: 919 case Stmt::ObjCProtocolExprClass: 920 case Stmt::ObjCSelectorExprClass: 921 case Stmt::ParenListExprClass: 922 case Stmt::ShuffleVectorExprClass: 923 case Stmt::ConvertVectorExprClass: 924 case Stmt::VAArgExprClass: 925 case Stmt::CUDAKernelCallExprClass: 926 case Stmt::OpaqueValueExprClass: 927 case Stmt::AsTypeExprClass: 928 // Fall through. 929 930 // Cases we intentionally don't evaluate, since they don't need 931 // to be explicitly evaluated. 932 case Stmt::PredefinedExprClass: 933 case Stmt::AddrLabelExprClass: 934 case Stmt::AttributedStmtClass: 935 case Stmt::IntegerLiteralClass: 936 case Stmt::CharacterLiteralClass: 937 case Stmt::ImplicitValueInitExprClass: 938 case Stmt::CXXScalarValueInitExprClass: 939 case Stmt::CXXBoolLiteralExprClass: 940 case Stmt::ObjCBoolLiteralExprClass: 941 case Stmt::ObjCAvailabilityCheckExprClass: 942 case Stmt::FloatingLiteralClass: 943 case Stmt::NoInitExprClass: 944 case Stmt::SizeOfPackExprClass: 945 case Stmt::StringLiteralClass: 946 case Stmt::ObjCStringLiteralClass: 947 case Stmt::CXXPseudoDestructorExprClass: 948 case Stmt::SubstNonTypeTemplateParmExprClass: 949 case Stmt::CXXNullPtrLiteralExprClass: 950 case Stmt::OMPArraySectionExprClass: 951 case Stmt::TypeTraitExprClass: { 952 Bldr.takeNodes(Pred); 953 ExplodedNodeSet preVisit; 954 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this); 955 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this); 956 Bldr.addNodes(Dst); 957 break; 958 } 959 960 case Stmt::CXXDefaultArgExprClass: 961 case Stmt::CXXDefaultInitExprClass: { 962 Bldr.takeNodes(Pred); 963 ExplodedNodeSet PreVisit; 964 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 965 966 ExplodedNodeSet Tmp; 967 StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx); 968 969 const Expr *ArgE; 970 if (const CXXDefaultArgExpr *DefE = dyn_cast<CXXDefaultArgExpr>(S)) 971 ArgE = DefE->getExpr(); 972 else if (const CXXDefaultInitExpr *DefE = dyn_cast<CXXDefaultInitExpr>(S)) 973 ArgE = DefE->getExpr(); 974 else 975 llvm_unreachable("unknown constant wrapper kind"); 976 977 bool IsTemporary = false; 978 if (const MaterializeTemporaryExpr *MTE = 979 dyn_cast<MaterializeTemporaryExpr>(ArgE)) { 980 ArgE = MTE->GetTemporaryExpr(); 981 IsTemporary = true; 982 } 983 984 Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE); 985 if (!ConstantVal) 986 ConstantVal = UnknownVal(); 987 988 const LocationContext *LCtx = Pred->getLocationContext(); 989 for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end(); 990 I != E; ++I) { 991 ProgramStateRef State = (*I)->getState(); 992 State = State->BindExpr(S, LCtx, *ConstantVal); 993 if (IsTemporary) 994 State = createTemporaryRegionIfNeeded(State, LCtx, 995 cast<Expr>(S), 996 cast<Expr>(S)); 997 Bldr2.generateNode(S, *I, State); 998 } 999 1000 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this); 1001 Bldr.addNodes(Dst); 1002 break; 1003 } 1004 1005 // Cases we evaluate as opaque expressions, conjuring a symbol. 1006 case Stmt::CXXStdInitializerListExprClass: 1007 case Expr::ObjCArrayLiteralClass: 1008 case Expr::ObjCDictionaryLiteralClass: 1009 case Expr::ObjCBoxedExprClass: { 1010 Bldr.takeNodes(Pred); 1011 1012 ExplodedNodeSet preVisit; 1013 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this); 1014 1015 ExplodedNodeSet Tmp; 1016 StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx); 1017 1018 const Expr *Ex = cast<Expr>(S); 1019 QualType resultType = Ex->getType(); 1020 1021 for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end(); 1022 it != et; ++it) { 1023 ExplodedNode *N = *it; 1024 const LocationContext *LCtx = N->getLocationContext(); 1025 SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx, 1026 resultType, 1027 currBldrCtx->blockCount()); 1028 ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result); 1029 Bldr2.generateNode(S, N, state); 1030 } 1031 1032 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this); 1033 Bldr.addNodes(Dst); 1034 break; 1035 } 1036 1037 case Stmt::ArraySubscriptExprClass: 1038 Bldr.takeNodes(Pred); 1039 VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst); 1040 Bldr.addNodes(Dst); 1041 break; 1042 1043 case Stmt::GCCAsmStmtClass: 1044 Bldr.takeNodes(Pred); 1045 VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst); 1046 Bldr.addNodes(Dst); 1047 break; 1048 1049 case Stmt::MSAsmStmtClass: 1050 Bldr.takeNodes(Pred); 1051 VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst); 1052 Bldr.addNodes(Dst); 1053 break; 1054 1055 case Stmt::BlockExprClass: 1056 Bldr.takeNodes(Pred); 1057 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst); 1058 Bldr.addNodes(Dst); 1059 break; 1060 1061 case Stmt::LambdaExprClass: 1062 if (AMgr.options.shouldInlineLambdas()) { 1063 Bldr.takeNodes(Pred); 1064 VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst); 1065 Bldr.addNodes(Dst); 1066 } else { 1067 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState()); 1068 Engine.addAbortedBlock(node, currBldrCtx->getBlock()); 1069 } 1070 break; 1071 1072 case Stmt::BinaryOperatorClass: { 1073 const BinaryOperator* B = cast<BinaryOperator>(S); 1074 if (B->isLogicalOp()) { 1075 Bldr.takeNodes(Pred); 1076 VisitLogicalExpr(B, Pred, Dst); 1077 Bldr.addNodes(Dst); 1078 break; 1079 } 1080 else if (B->getOpcode() == BO_Comma) { 1081 ProgramStateRef state = Pred->getState(); 1082 Bldr.generateNode(B, Pred, 1083 state->BindExpr(B, Pred->getLocationContext(), 1084 state->getSVal(B->getRHS(), 1085 Pred->getLocationContext()))); 1086 break; 1087 } 1088 1089 Bldr.takeNodes(Pred); 1090 1091 if (AMgr.options.eagerlyAssumeBinOpBifurcation && 1092 (B->isRelationalOp() || B->isEqualityOp())) { 1093 ExplodedNodeSet Tmp; 1094 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp); 1095 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S)); 1096 } 1097 else 1098 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 1099 1100 Bldr.addNodes(Dst); 1101 break; 1102 } 1103 1104 case Stmt::CXXOperatorCallExprClass: { 1105 const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S); 1106 1107 // For instance method operators, make sure the 'this' argument has a 1108 // valid region. 1109 const Decl *Callee = OCE->getCalleeDecl(); 1110 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) { 1111 if (MD->isInstance()) { 1112 ProgramStateRef State = Pred->getState(); 1113 const LocationContext *LCtx = Pred->getLocationContext(); 1114 ProgramStateRef NewState = 1115 createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0)); 1116 if (NewState != State) { 1117 Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr, 1118 ProgramPoint::PreStmtKind); 1119 // Did we cache out? 1120 if (!Pred) 1121 break; 1122 } 1123 } 1124 } 1125 // FALLTHROUGH 1126 } 1127 case Stmt::CallExprClass: 1128 case Stmt::CXXMemberCallExprClass: 1129 case Stmt::UserDefinedLiteralClass: { 1130 Bldr.takeNodes(Pred); 1131 VisitCallExpr(cast<CallExpr>(S), Pred, Dst); 1132 Bldr.addNodes(Dst); 1133 break; 1134 } 1135 1136 case Stmt::CXXCatchStmtClass: { 1137 Bldr.takeNodes(Pred); 1138 VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst); 1139 Bldr.addNodes(Dst); 1140 break; 1141 } 1142 1143 case Stmt::CXXTemporaryObjectExprClass: 1144 case Stmt::CXXConstructExprClass: { 1145 Bldr.takeNodes(Pred); 1146 VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst); 1147 Bldr.addNodes(Dst); 1148 break; 1149 } 1150 1151 case Stmt::CXXNewExprClass: { 1152 Bldr.takeNodes(Pred); 1153 ExplodedNodeSet PostVisit; 1154 VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit); 1155 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this); 1156 Bldr.addNodes(Dst); 1157 break; 1158 } 1159 1160 case Stmt::CXXDeleteExprClass: { 1161 Bldr.takeNodes(Pred); 1162 ExplodedNodeSet PreVisit; 1163 const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S); 1164 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 1165 1166 for (ExplodedNodeSet::iterator i = PreVisit.begin(), 1167 e = PreVisit.end(); i != e ; ++i) 1168 VisitCXXDeleteExpr(CDE, *i, Dst); 1169 1170 Bldr.addNodes(Dst); 1171 break; 1172 } 1173 // FIXME: ChooseExpr is really a constant. We need to fix 1174 // the CFG do not model them as explicit control-flow. 1175 1176 case Stmt::ChooseExprClass: { // __builtin_choose_expr 1177 Bldr.takeNodes(Pred); 1178 const ChooseExpr *C = cast<ChooseExpr>(S); 1179 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst); 1180 Bldr.addNodes(Dst); 1181 break; 1182 } 1183 1184 case Stmt::CompoundAssignOperatorClass: 1185 Bldr.takeNodes(Pred); 1186 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 1187 Bldr.addNodes(Dst); 1188 break; 1189 1190 case Stmt::CompoundLiteralExprClass: 1191 Bldr.takeNodes(Pred); 1192 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst); 1193 Bldr.addNodes(Dst); 1194 break; 1195 1196 case Stmt::BinaryConditionalOperatorClass: 1197 case Stmt::ConditionalOperatorClass: { // '?' operator 1198 Bldr.takeNodes(Pred); 1199 const AbstractConditionalOperator *C 1200 = cast<AbstractConditionalOperator>(S); 1201 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst); 1202 Bldr.addNodes(Dst); 1203 break; 1204 } 1205 1206 case Stmt::CXXThisExprClass: 1207 Bldr.takeNodes(Pred); 1208 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst); 1209 Bldr.addNodes(Dst); 1210 break; 1211 1212 case Stmt::DeclRefExprClass: { 1213 Bldr.takeNodes(Pred); 1214 const DeclRefExpr *DE = cast<DeclRefExpr>(S); 1215 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst); 1216 Bldr.addNodes(Dst); 1217 break; 1218 } 1219 1220 case Stmt::DeclStmtClass: 1221 Bldr.takeNodes(Pred); 1222 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst); 1223 Bldr.addNodes(Dst); 1224 break; 1225 1226 case Stmt::ImplicitCastExprClass: 1227 case Stmt::CStyleCastExprClass: 1228 case Stmt::CXXStaticCastExprClass: 1229 case Stmt::CXXDynamicCastExprClass: 1230 case Stmt::CXXReinterpretCastExprClass: 1231 case Stmt::CXXConstCastExprClass: 1232 case Stmt::CXXFunctionalCastExprClass: 1233 case Stmt::ObjCBridgedCastExprClass: { 1234 Bldr.takeNodes(Pred); 1235 const CastExpr *C = cast<CastExpr>(S); 1236 ExplodedNodeSet dstExpr; 1237 VisitCast(C, C->getSubExpr(), Pred, dstExpr); 1238 1239 // Handle the postvisit checks. 1240 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this); 1241 Bldr.addNodes(Dst); 1242 break; 1243 } 1244 1245 case Expr::MaterializeTemporaryExprClass: { 1246 Bldr.takeNodes(Pred); 1247 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S); 1248 CreateCXXTemporaryObject(MTE, Pred, Dst); 1249 Bldr.addNodes(Dst); 1250 break; 1251 } 1252 1253 case Stmt::InitListExprClass: 1254 Bldr.takeNodes(Pred); 1255 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst); 1256 Bldr.addNodes(Dst); 1257 break; 1258 1259 case Stmt::MemberExprClass: 1260 Bldr.takeNodes(Pred); 1261 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst); 1262 Bldr.addNodes(Dst); 1263 break; 1264 1265 case Stmt::AtomicExprClass: 1266 Bldr.takeNodes(Pred); 1267 VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst); 1268 Bldr.addNodes(Dst); 1269 break; 1270 1271 case Stmt::ObjCIvarRefExprClass: 1272 Bldr.takeNodes(Pred); 1273 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst); 1274 Bldr.addNodes(Dst); 1275 break; 1276 1277 case Stmt::ObjCForCollectionStmtClass: 1278 Bldr.takeNodes(Pred); 1279 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst); 1280 Bldr.addNodes(Dst); 1281 break; 1282 1283 case Stmt::ObjCMessageExprClass: 1284 Bldr.takeNodes(Pred); 1285 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst); 1286 Bldr.addNodes(Dst); 1287 break; 1288 1289 case Stmt::ObjCAtThrowStmtClass: 1290 case Stmt::CXXThrowExprClass: 1291 // FIXME: This is not complete. We basically treat @throw as 1292 // an abort. 1293 Bldr.generateSink(S, Pred, Pred->getState()); 1294 break; 1295 1296 case Stmt::ReturnStmtClass: 1297 Bldr.takeNodes(Pred); 1298 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst); 1299 Bldr.addNodes(Dst); 1300 break; 1301 1302 case Stmt::OffsetOfExprClass: 1303 Bldr.takeNodes(Pred); 1304 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst); 1305 Bldr.addNodes(Dst); 1306 break; 1307 1308 case Stmt::UnaryExprOrTypeTraitExprClass: 1309 Bldr.takeNodes(Pred); 1310 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S), 1311 Pred, Dst); 1312 Bldr.addNodes(Dst); 1313 break; 1314 1315 case Stmt::StmtExprClass: { 1316 const StmtExpr *SE = cast<StmtExpr>(S); 1317 1318 if (SE->getSubStmt()->body_empty()) { 1319 // Empty statement expression. 1320 assert(SE->getType() == getContext().VoidTy 1321 && "Empty statement expression must have void type."); 1322 break; 1323 } 1324 1325 if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) { 1326 ProgramStateRef state = Pred->getState(); 1327 Bldr.generateNode(SE, Pred, 1328 state->BindExpr(SE, Pred->getLocationContext(), 1329 state->getSVal(LastExpr, 1330 Pred->getLocationContext()))); 1331 } 1332 break; 1333 } 1334 1335 case Stmt::UnaryOperatorClass: { 1336 Bldr.takeNodes(Pred); 1337 const UnaryOperator *U = cast<UnaryOperator>(S); 1338 if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) { 1339 ExplodedNodeSet Tmp; 1340 VisitUnaryOperator(U, Pred, Tmp); 1341 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U); 1342 } 1343 else 1344 VisitUnaryOperator(U, Pred, Dst); 1345 Bldr.addNodes(Dst); 1346 break; 1347 } 1348 1349 case Stmt::PseudoObjectExprClass: { 1350 Bldr.takeNodes(Pred); 1351 ProgramStateRef state = Pred->getState(); 1352 const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S); 1353 if (const Expr *Result = PE->getResultExpr()) { 1354 SVal V = state->getSVal(Result, Pred->getLocationContext()); 1355 Bldr.generateNode(S, Pred, 1356 state->BindExpr(S, Pred->getLocationContext(), V)); 1357 } 1358 else 1359 Bldr.generateNode(S, Pred, 1360 state->BindExpr(S, Pred->getLocationContext(), 1361 UnknownVal())); 1362 1363 Bldr.addNodes(Dst); 1364 break; 1365 } 1366 } 1367 } 1368 1369 bool ExprEngine::replayWithoutInlining(ExplodedNode *N, 1370 const LocationContext *CalleeLC) { 1371 const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame(); 1372 const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame(); 1373 assert(CalleeSF && CallerSF); 1374 ExplodedNode *BeforeProcessingCall = nullptr; 1375 const Stmt *CE = CalleeSF->getCallSite(); 1376 1377 // Find the first node before we started processing the call expression. 1378 while (N) { 1379 ProgramPoint L = N->getLocation(); 1380 BeforeProcessingCall = N; 1381 N = N->pred_empty() ? nullptr : *(N->pred_begin()); 1382 1383 // Skip the nodes corresponding to the inlined code. 1384 if (L.getLocationContext()->getCurrentStackFrame() != CallerSF) 1385 continue; 1386 // We reached the caller. Find the node right before we started 1387 // processing the call. 1388 if (L.isPurgeKind()) 1389 continue; 1390 if (L.getAs<PreImplicitCall>()) 1391 continue; 1392 if (L.getAs<CallEnter>()) 1393 continue; 1394 if (Optional<StmtPoint> SP = L.getAs<StmtPoint>()) 1395 if (SP->getStmt() == CE) 1396 continue; 1397 break; 1398 } 1399 1400 if (!BeforeProcessingCall) 1401 return false; 1402 1403 // TODO: Clean up the unneeded nodes. 1404 1405 // Build an Epsilon node from which we will restart the analyzes. 1406 // Note that CE is permitted to be NULL! 1407 ProgramPoint NewNodeLoc = 1408 EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE); 1409 // Add the special flag to GDM to signal retrying with no inlining. 1410 // Note, changing the state ensures that we are not going to cache out. 1411 ProgramStateRef NewNodeState = BeforeProcessingCall->getState(); 1412 NewNodeState = 1413 NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE)); 1414 1415 // Make the new node a successor of BeforeProcessingCall. 1416 bool IsNew = false; 1417 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew); 1418 // We cached out at this point. Caching out is common due to us backtracking 1419 // from the inlined function, which might spawn several paths. 1420 if (!IsNew) 1421 return true; 1422 1423 NewNode->addPredecessor(BeforeProcessingCall, G); 1424 1425 // Add the new node to the work list. 1426 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(), 1427 CalleeSF->getIndex()); 1428 NumTimesRetriedWithoutInlining++; 1429 return true; 1430 } 1431 1432 /// Block entrance. (Update counters). 1433 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L, 1434 NodeBuilderWithSinks &nodeBuilder, 1435 ExplodedNode *Pred) { 1436 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 1437 1438 // If this block is terminated by a loop and it has already been visited the 1439 // maximum number of times, widen the loop. 1440 unsigned int BlockCount = nodeBuilder.getContext().blockCount(); 1441 if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 && 1442 AMgr.options.shouldWidenLoops()) { 1443 const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator(); 1444 if (!(Term && 1445 (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term)))) 1446 return; 1447 // Widen. 1448 const LocationContext *LCtx = Pred->getLocationContext(); 1449 ProgramStateRef WidenedState = 1450 getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term); 1451 nodeBuilder.generateNode(WidenedState, Pred); 1452 return; 1453 } 1454 1455 // FIXME: Refactor this into a checker. 1456 if (BlockCount >= AMgr.options.maxBlockVisitOnPath) { 1457 static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded"); 1458 const ExplodedNode *Sink = 1459 nodeBuilder.generateSink(Pred->getState(), Pred, &tag); 1460 1461 // Check if we stopped at the top level function or not. 1462 // Root node should have the location context of the top most function. 1463 const LocationContext *CalleeLC = Pred->getLocation().getLocationContext(); 1464 const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame(); 1465 const LocationContext *RootLC = 1466 (*G.roots_begin())->getLocation().getLocationContext(); 1467 if (RootLC->getCurrentStackFrame() != CalleeSF) { 1468 Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl()); 1469 1470 // Re-run the call evaluation without inlining it, by storing the 1471 // no-inlining policy in the state and enqueuing the new work item on 1472 // the list. Replay should almost never fail. Use the stats to catch it 1473 // if it does. 1474 if ((!AMgr.options.NoRetryExhausted && 1475 replayWithoutInlining(Pred, CalleeLC))) 1476 return; 1477 NumMaxBlockCountReachedInInlined++; 1478 } else 1479 NumMaxBlockCountReached++; 1480 1481 // Make sink nodes as exhausted(for stats) only if retry failed. 1482 Engine.blocksExhausted.push_back(std::make_pair(L, Sink)); 1483 } 1484 } 1485 1486 //===----------------------------------------------------------------------===// 1487 // Branch processing. 1488 //===----------------------------------------------------------------------===// 1489 1490 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used 1491 /// to try to recover some path-sensitivity for casts of symbolic 1492 /// integers that promote their values (which are currently not tracked well). 1493 /// This function returns the SVal bound to Condition->IgnoreCasts if all the 1494 // cast(s) did was sign-extend the original value. 1495 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr, 1496 ProgramStateRef state, 1497 const Stmt *Condition, 1498 const LocationContext *LCtx, 1499 ASTContext &Ctx) { 1500 1501 const Expr *Ex = dyn_cast<Expr>(Condition); 1502 if (!Ex) 1503 return UnknownVal(); 1504 1505 uint64_t bits = 0; 1506 bool bitsInit = false; 1507 1508 while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) { 1509 QualType T = CE->getType(); 1510 1511 if (!T->isIntegralOrEnumerationType()) 1512 return UnknownVal(); 1513 1514 uint64_t newBits = Ctx.getTypeSize(T); 1515 if (!bitsInit || newBits < bits) { 1516 bitsInit = true; 1517 bits = newBits; 1518 } 1519 1520 Ex = CE->getSubExpr(); 1521 } 1522 1523 // We reached a non-cast. Is it a symbolic value? 1524 QualType T = Ex->getType(); 1525 1526 if (!bitsInit || !T->isIntegralOrEnumerationType() || 1527 Ctx.getTypeSize(T) > bits) 1528 return UnknownVal(); 1529 1530 return state->getSVal(Ex, LCtx); 1531 } 1532 1533 #ifndef NDEBUG 1534 static const Stmt *getRightmostLeaf(const Stmt *Condition) { 1535 while (Condition) { 1536 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition); 1537 if (!BO || !BO->isLogicalOp()) { 1538 return Condition; 1539 } 1540 Condition = BO->getRHS()->IgnoreParens(); 1541 } 1542 return nullptr; 1543 } 1544 #endif 1545 1546 // Returns the condition the branch at the end of 'B' depends on and whose value 1547 // has been evaluated within 'B'. 1548 // In most cases, the terminator condition of 'B' will be evaluated fully in 1549 // the last statement of 'B'; in those cases, the resolved condition is the 1550 // given 'Condition'. 1551 // If the condition of the branch is a logical binary operator tree, the CFG is 1552 // optimized: in that case, we know that the expression formed by all but the 1553 // rightmost leaf of the logical binary operator tree must be true, and thus 1554 // the branch condition is at this point equivalent to the truth value of that 1555 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf 1556 // expression in its final statement. As the full condition in that case was 1557 // not evaluated, and is thus not in the SVal cache, we need to use that leaf 1558 // expression to evaluate the truth value of the condition in the current state 1559 // space. 1560 static const Stmt *ResolveCondition(const Stmt *Condition, 1561 const CFGBlock *B) { 1562 if (const Expr *Ex = dyn_cast<Expr>(Condition)) 1563 Condition = Ex->IgnoreParens(); 1564 1565 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition); 1566 if (!BO || !BO->isLogicalOp()) 1567 return Condition; 1568 1569 assert(!B->getTerminator().isTemporaryDtorsBranch() && 1570 "Temporary destructor branches handled by processBindTemporary."); 1571 1572 // For logical operations, we still have the case where some branches 1573 // use the traditional "merge" approach and others sink the branch 1574 // directly into the basic blocks representing the logical operation. 1575 // We need to distinguish between those two cases here. 1576 1577 // The invariants are still shifting, but it is possible that the 1578 // last element in a CFGBlock is not a CFGStmt. Look for the last 1579 // CFGStmt as the value of the condition. 1580 CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend(); 1581 for (; I != E; ++I) { 1582 CFGElement Elem = *I; 1583 Optional<CFGStmt> CS = Elem.getAs<CFGStmt>(); 1584 if (!CS) 1585 continue; 1586 const Stmt *LastStmt = CS->getStmt(); 1587 assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition)); 1588 return LastStmt; 1589 } 1590 llvm_unreachable("could not resolve condition"); 1591 } 1592 1593 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term, 1594 NodeBuilderContext& BldCtx, 1595 ExplodedNode *Pred, 1596 ExplodedNodeSet &Dst, 1597 const CFGBlock *DstT, 1598 const CFGBlock *DstF) { 1599 assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) && 1600 "CXXBindTemporaryExprs are handled by processBindTemporary."); 1601 const LocationContext *LCtx = Pred->getLocationContext(); 1602 PrettyStackTraceLocationContext StackCrashInfo(LCtx); 1603 currBldrCtx = &BldCtx; 1604 1605 // Check for NULL conditions; e.g. "for(;;)" 1606 if (!Condition) { 1607 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF); 1608 NullCondBldr.markInfeasible(false); 1609 NullCondBldr.generateNode(Pred->getState(), true, Pred); 1610 return; 1611 } 1612 1613 if (const Expr *Ex = dyn_cast<Expr>(Condition)) 1614 Condition = Ex->IgnoreParens(); 1615 1616 Condition = ResolveCondition(Condition, BldCtx.getBlock()); 1617 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 1618 Condition->getLocStart(), 1619 "Error evaluating branch"); 1620 1621 ExplodedNodeSet CheckersOutSet; 1622 getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet, 1623 Pred, *this); 1624 // We generated only sinks. 1625 if (CheckersOutSet.empty()) 1626 return; 1627 1628 BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF); 1629 for (NodeBuilder::iterator I = CheckersOutSet.begin(), 1630 E = CheckersOutSet.end(); E != I; ++I) { 1631 ExplodedNode *PredI = *I; 1632 1633 if (PredI->isSink()) 1634 continue; 1635 1636 ProgramStateRef PrevState = PredI->getState(); 1637 SVal X = PrevState->getSVal(Condition, PredI->getLocationContext()); 1638 1639 if (X.isUnknownOrUndef()) { 1640 // Give it a chance to recover from unknown. 1641 if (const Expr *Ex = dyn_cast<Expr>(Condition)) { 1642 if (Ex->getType()->isIntegralOrEnumerationType()) { 1643 // Try to recover some path-sensitivity. Right now casts of symbolic 1644 // integers that promote their values are currently not tracked well. 1645 // If 'Condition' is such an expression, try and recover the 1646 // underlying value and use that instead. 1647 SVal recovered = RecoverCastedSymbol(getStateManager(), 1648 PrevState, Condition, 1649 PredI->getLocationContext(), 1650 getContext()); 1651 1652 if (!recovered.isUnknown()) { 1653 X = recovered; 1654 } 1655 } 1656 } 1657 } 1658 1659 // If the condition is still unknown, give up. 1660 if (X.isUnknownOrUndef()) { 1661 builder.generateNode(PrevState, true, PredI); 1662 builder.generateNode(PrevState, false, PredI); 1663 continue; 1664 } 1665 1666 DefinedSVal V = X.castAs<DefinedSVal>(); 1667 1668 ProgramStateRef StTrue, StFalse; 1669 std::tie(StTrue, StFalse) = PrevState->assume(V); 1670 1671 // Process the true branch. 1672 if (builder.isFeasible(true)) { 1673 if (StTrue) 1674 builder.generateNode(StTrue, true, PredI); 1675 else 1676 builder.markInfeasible(true); 1677 } 1678 1679 // Process the false branch. 1680 if (builder.isFeasible(false)) { 1681 if (StFalse) 1682 builder.generateNode(StFalse, false, PredI); 1683 else 1684 builder.markInfeasible(false); 1685 } 1686 } 1687 currBldrCtx = nullptr; 1688 } 1689 1690 /// The GDM component containing the set of global variables which have been 1691 /// previously initialized with explicit initializers. 1692 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet, 1693 llvm::ImmutableSet<const VarDecl *>) 1694 1695 void ExprEngine::processStaticInitializer(const DeclStmt *DS, 1696 NodeBuilderContext &BuilderCtx, 1697 ExplodedNode *Pred, 1698 clang::ento::ExplodedNodeSet &Dst, 1699 const CFGBlock *DstT, 1700 const CFGBlock *DstF) { 1701 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 1702 currBldrCtx = &BuilderCtx; 1703 1704 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl()); 1705 ProgramStateRef state = Pred->getState(); 1706 bool initHasRun = state->contains<InitializedGlobalsSet>(VD); 1707 BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF); 1708 1709 if (!initHasRun) { 1710 state = state->add<InitializedGlobalsSet>(VD); 1711 } 1712 1713 builder.generateNode(state, initHasRun, Pred); 1714 builder.markInfeasible(!initHasRun); 1715 1716 currBldrCtx = nullptr; 1717 } 1718 1719 /// processIndirectGoto - Called by CoreEngine. Used to generate successor 1720 /// nodes by processing the 'effects' of a computed goto jump. 1721 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) { 1722 1723 ProgramStateRef state = builder.getState(); 1724 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext()); 1725 1726 // Three possibilities: 1727 // 1728 // (1) We know the computed label. 1729 // (2) The label is NULL (or some other constant), or Undefined. 1730 // (3) We have no clue about the label. Dispatch to all targets. 1731 // 1732 1733 typedef IndirectGotoNodeBuilder::iterator iterator; 1734 1735 if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) { 1736 const LabelDecl *L = LV->getLabel(); 1737 1738 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) { 1739 if (I.getLabel() == L) { 1740 builder.generateNode(I, state); 1741 return; 1742 } 1743 } 1744 1745 llvm_unreachable("No block with label."); 1746 } 1747 1748 if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) { 1749 // Dispatch to the first target and mark it as a sink. 1750 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true); 1751 // FIXME: add checker visit. 1752 // UndefBranches.insert(N); 1753 return; 1754 } 1755 1756 // This is really a catch-all. We don't support symbolics yet. 1757 // FIXME: Implement dispatch for symbolic pointers. 1758 1759 for (iterator I=builder.begin(), E=builder.end(); I != E; ++I) 1760 builder.generateNode(I, state); 1761 } 1762 1763 #if 0 1764 static bool stackFrameDoesNotContainInitializedTemporaries(ExplodedNode &Pred) { 1765 const StackFrameContext* Frame = Pred.getStackFrame(); 1766 const llvm::ImmutableSet<CXXBindTemporaryContext> &Set = 1767 Pred.getState()->get<InitializedTemporariesSet>(); 1768 return std::find_if(Set.begin(), Set.end(), 1769 [&](const CXXBindTemporaryContext &Ctx) { 1770 if (Ctx.second == Frame) { 1771 Ctx.first->dump(); 1772 llvm::errs() << "\n"; 1773 } 1774 return Ctx.second == Frame; 1775 }) == Set.end(); 1776 } 1777 #endif 1778 1779 void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC, 1780 ExplodedNode *Pred, 1781 ExplodedNodeSet &Dst, 1782 const BlockEdge &L) { 1783 SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC); 1784 getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this); 1785 } 1786 1787 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path 1788 /// nodes when the control reaches the end of a function. 1789 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC, 1790 ExplodedNode *Pred, 1791 const ReturnStmt *RS) { 1792 // FIXME: Assert that stackFrameDoesNotContainInitializedTemporaries(*Pred)). 1793 // We currently cannot enable this assert, as lifetime extended temporaries 1794 // are not modelled correctly. 1795 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 1796 StateMgr.EndPath(Pred->getState()); 1797 1798 ExplodedNodeSet Dst; 1799 if (Pred->getLocationContext()->inTopFrame()) { 1800 // Remove dead symbols. 1801 ExplodedNodeSet AfterRemovedDead; 1802 removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead); 1803 1804 // Notify checkers. 1805 for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(), 1806 E = AfterRemovedDead.end(); I != E; ++I) { 1807 getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this); 1808 } 1809 } else { 1810 getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this); 1811 } 1812 1813 Engine.enqueueEndOfFunction(Dst, RS); 1814 } 1815 1816 /// ProcessSwitch - Called by CoreEngine. Used to generate successor 1817 /// nodes by processing the 'effects' of a switch statement. 1818 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) { 1819 typedef SwitchNodeBuilder::iterator iterator; 1820 ProgramStateRef state = builder.getState(); 1821 const Expr *CondE = builder.getCondition(); 1822 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext()); 1823 1824 if (CondV_untested.isUndef()) { 1825 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true); 1826 // FIXME: add checker 1827 //UndefBranches.insert(N); 1828 1829 return; 1830 } 1831 DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>(); 1832 1833 ProgramStateRef DefaultSt = state; 1834 1835 iterator I = builder.begin(), EI = builder.end(); 1836 bool defaultIsFeasible = I == EI; 1837 1838 for ( ; I != EI; ++I) { 1839 // Successor may be pruned out during CFG construction. 1840 if (!I.getBlock()) 1841 continue; 1842 1843 const CaseStmt *Case = I.getCase(); 1844 1845 // Evaluate the LHS of the case value. 1846 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext()); 1847 assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType())); 1848 1849 // Get the RHS of the case, if it exists. 1850 llvm::APSInt V2; 1851 if (const Expr *E = Case->getRHS()) 1852 V2 = E->EvaluateKnownConstInt(getContext()); 1853 else 1854 V2 = V1; 1855 1856 ProgramStateRef StateCase; 1857 if (Optional<NonLoc> NL = CondV.getAs<NonLoc>()) 1858 std::tie(StateCase, DefaultSt) = 1859 DefaultSt->assumeInclusiveRange(*NL, V1, V2); 1860 else // UnknownVal 1861 StateCase = DefaultSt; 1862 1863 if (StateCase) 1864 builder.generateCaseStmtNode(I, StateCase); 1865 1866 // Now "assume" that the case doesn't match. Add this state 1867 // to the default state (if it is feasible). 1868 if (DefaultSt) 1869 defaultIsFeasible = true; 1870 else { 1871 defaultIsFeasible = false; 1872 break; 1873 } 1874 } 1875 1876 if (!defaultIsFeasible) 1877 return; 1878 1879 // If we have switch(enum value), the default branch is not 1880 // feasible if all of the enum constants not covered by 'case:' statements 1881 // are not feasible values for the switch condition. 1882 // 1883 // Note that this isn't as accurate as it could be. Even if there isn't 1884 // a case for a particular enum value as long as that enum value isn't 1885 // feasible then it shouldn't be considered for making 'default:' reachable. 1886 const SwitchStmt *SS = builder.getSwitch(); 1887 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts(); 1888 if (CondExpr->getType()->getAs<EnumType>()) { 1889 if (SS->isAllEnumCasesCovered()) 1890 return; 1891 } 1892 1893 builder.generateDefaultCaseNode(DefaultSt); 1894 } 1895 1896 //===----------------------------------------------------------------------===// 1897 // Transfer functions: Loads and stores. 1898 //===----------------------------------------------------------------------===// 1899 1900 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D, 1901 ExplodedNode *Pred, 1902 ExplodedNodeSet &Dst) { 1903 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1904 1905 ProgramStateRef state = Pred->getState(); 1906 const LocationContext *LCtx = Pred->getLocationContext(); 1907 1908 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1909 // C permits "extern void v", and if you cast the address to a valid type, 1910 // you can even do things with it. We simply pretend 1911 assert(Ex->isGLValue() || VD->getType()->isVoidType()); 1912 const LocationContext *LocCtxt = Pred->getLocationContext(); 1913 const Decl *D = LocCtxt->getDecl(); 1914 const auto *MD = D ? dyn_cast<CXXMethodDecl>(D) : nullptr; 1915 const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex); 1916 SVal V; 1917 bool IsReference; 1918 if (AMgr.options.shouldInlineLambdas() && DeclRefEx && 1919 DeclRefEx->refersToEnclosingVariableOrCapture() && MD && 1920 MD->getParent()->isLambda()) { 1921 // Lookup the field of the lambda. 1922 const CXXRecordDecl *CXXRec = MD->getParent(); 1923 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 1924 FieldDecl *LambdaThisCaptureField; 1925 CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField); 1926 const FieldDecl *FD = LambdaCaptureFields[VD]; 1927 if (!FD) { 1928 // When a constant is captured, sometimes no corresponding field is 1929 // created in the lambda object. 1930 assert(VD->getType().isConstQualified()); 1931 V = state->getLValue(VD, LocCtxt); 1932 IsReference = false; 1933 } else { 1934 Loc CXXThis = 1935 svalBuilder.getCXXThis(MD, LocCtxt->getCurrentStackFrame()); 1936 SVal CXXThisVal = state->getSVal(CXXThis); 1937 V = state->getLValue(FD, CXXThisVal); 1938 IsReference = FD->getType()->isReferenceType(); 1939 } 1940 } else { 1941 V = state->getLValue(VD, LocCtxt); 1942 IsReference = VD->getType()->isReferenceType(); 1943 } 1944 1945 // For references, the 'lvalue' is the pointer address stored in the 1946 // reference region. 1947 if (IsReference) { 1948 if (const MemRegion *R = V.getAsRegion()) 1949 V = state->getSVal(R); 1950 else 1951 V = UnknownVal(); 1952 } 1953 1954 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr, 1955 ProgramPoint::PostLValueKind); 1956 return; 1957 } 1958 if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 1959 assert(!Ex->isGLValue()); 1960 SVal V = svalBuilder.makeIntVal(ED->getInitVal()); 1961 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V)); 1962 return; 1963 } 1964 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1965 SVal V = svalBuilder.getFunctionPointer(FD); 1966 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr, 1967 ProgramPoint::PostLValueKind); 1968 return; 1969 } 1970 if (isa<FieldDecl>(D)) { 1971 // FIXME: Compute lvalue of field pointers-to-member. 1972 // Right now we just use a non-null void pointer, so that it gives proper 1973 // results in boolean contexts. 1974 SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy, 1975 currBldrCtx->blockCount()); 1976 state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true); 1977 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr, 1978 ProgramPoint::PostLValueKind); 1979 return; 1980 } 1981 1982 llvm_unreachable("Support for this Decl not implemented."); 1983 } 1984 1985 /// VisitArraySubscriptExpr - Transfer function for array accesses 1986 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A, 1987 ExplodedNode *Pred, 1988 ExplodedNodeSet &Dst){ 1989 1990 const Expr *Base = A->getBase()->IgnoreParens(); 1991 const Expr *Idx = A->getIdx()->IgnoreParens(); 1992 1993 ExplodedNodeSet CheckerPreStmt; 1994 getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this); 1995 1996 ExplodedNodeSet EvalSet; 1997 StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx); 1998 assert(A->isGLValue() || 1999 (!AMgr.getLangOpts().CPlusPlus && 2000 A->getType().isCForbiddenLValueType())); 2001 2002 for (auto *Node : CheckerPreStmt) { 2003 const LocationContext *LCtx = Node->getLocationContext(); 2004 ProgramStateRef state = Node->getState(); 2005 SVal V = state->getLValue(A->getType(), 2006 state->getSVal(Idx, LCtx), 2007 state->getSVal(Base, LCtx)); 2008 Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr, 2009 ProgramPoint::PostLValueKind); 2010 } 2011 2012 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this); 2013 } 2014 2015 /// VisitMemberExpr - Transfer function for member expressions. 2016 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, 2017 ExplodedNodeSet &Dst) { 2018 2019 // FIXME: Prechecks eventually go in ::Visit(). 2020 ExplodedNodeSet CheckedSet; 2021 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this); 2022 2023 ExplodedNodeSet EvalSet; 2024 ValueDecl *Member = M->getMemberDecl(); 2025 2026 // Handle static member variables and enum constants accessed via 2027 // member syntax. 2028 if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) { 2029 ExplodedNodeSet Dst; 2030 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 2031 I != E; ++I) { 2032 VisitCommonDeclRefExpr(M, Member, Pred, EvalSet); 2033 } 2034 } else { 2035 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx); 2036 ExplodedNodeSet Tmp; 2037 2038 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 2039 I != E; ++I) { 2040 ProgramStateRef state = (*I)->getState(); 2041 const LocationContext *LCtx = (*I)->getLocationContext(); 2042 Expr *BaseExpr = M->getBase(); 2043 2044 // Handle C++ method calls. 2045 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) { 2046 if (MD->isInstance()) 2047 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr); 2048 2049 SVal MDVal = svalBuilder.getFunctionPointer(MD); 2050 state = state->BindExpr(M, LCtx, MDVal); 2051 2052 Bldr.generateNode(M, *I, state); 2053 continue; 2054 } 2055 2056 // Handle regular struct fields / member variables. 2057 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr); 2058 SVal baseExprVal = state->getSVal(BaseExpr, LCtx); 2059 2060 FieldDecl *field = cast<FieldDecl>(Member); 2061 SVal L = state->getLValue(field, baseExprVal); 2062 2063 if (M->isGLValue() || M->getType()->isArrayType()) { 2064 // We special-case rvalues of array type because the analyzer cannot 2065 // reason about them, since we expect all regions to be wrapped in Locs. 2066 // We instead treat these as lvalues and assume that they will decay to 2067 // pointers as soon as they are used. 2068 if (!M->isGLValue()) { 2069 assert(M->getType()->isArrayType()); 2070 const ImplicitCastExpr *PE = 2071 dyn_cast<ImplicitCastExpr>((*I)->getParentMap().getParentIgnoreParens(M)); 2072 if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) { 2073 llvm_unreachable("should always be wrapped in ArrayToPointerDecay"); 2074 } 2075 } 2076 2077 if (field->getType()->isReferenceType()) { 2078 if (const MemRegion *R = L.getAsRegion()) 2079 L = state->getSVal(R); 2080 else 2081 L = UnknownVal(); 2082 } 2083 2084 Bldr.generateNode(M, *I, state->BindExpr(M, LCtx, L), nullptr, 2085 ProgramPoint::PostLValueKind); 2086 } else { 2087 Bldr.takeNodes(*I); 2088 evalLoad(Tmp, M, M, *I, state, L); 2089 Bldr.addNodes(Tmp); 2090 } 2091 } 2092 } 2093 2094 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this); 2095 } 2096 2097 void ExprEngine::VisitAtomicExpr(const AtomicExpr *AE, ExplodedNode *Pred, 2098 ExplodedNodeSet &Dst) { 2099 ExplodedNodeSet AfterPreSet; 2100 getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this); 2101 2102 // For now, treat all the arguments to C11 atomics as escaping. 2103 // FIXME: Ideally we should model the behavior of the atomics precisely here. 2104 2105 ExplodedNodeSet AfterInvalidateSet; 2106 StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx); 2107 2108 for (ExplodedNodeSet::iterator I = AfterPreSet.begin(), E = AfterPreSet.end(); 2109 I != E; ++I) { 2110 ProgramStateRef State = (*I)->getState(); 2111 const LocationContext *LCtx = (*I)->getLocationContext(); 2112 2113 SmallVector<SVal, 8> ValuesToInvalidate; 2114 for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) { 2115 const Expr *SubExpr = AE->getSubExprs()[SI]; 2116 SVal SubExprVal = State->getSVal(SubExpr, LCtx); 2117 ValuesToInvalidate.push_back(SubExprVal); 2118 } 2119 2120 State = State->invalidateRegions(ValuesToInvalidate, AE, 2121 currBldrCtx->blockCount(), 2122 LCtx, 2123 /*CausedByPointerEscape*/true, 2124 /*Symbols=*/nullptr); 2125 2126 SVal ResultVal = UnknownVal(); 2127 State = State->BindExpr(AE, LCtx, ResultVal); 2128 Bldr.generateNode(AE, *I, State, nullptr, 2129 ProgramPoint::PostStmtKind); 2130 } 2131 2132 getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this); 2133 } 2134 2135 namespace { 2136 class CollectReachableSymbolsCallback final : public SymbolVisitor { 2137 InvalidatedSymbols Symbols; 2138 2139 public: 2140 CollectReachableSymbolsCallback(ProgramStateRef State) {} 2141 const InvalidatedSymbols &getSymbols() const { return Symbols; } 2142 2143 bool VisitSymbol(SymbolRef Sym) override { 2144 Symbols.insert(Sym); 2145 return true; 2146 } 2147 }; 2148 } // end anonymous namespace 2149 2150 // A value escapes in three possible cases: 2151 // (1) We are binding to something that is not a memory region. 2152 // (2) We are binding to a MemrRegion that does not have stack storage. 2153 // (3) We are binding to a MemRegion with stack storage that the store 2154 // does not understand. 2155 ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State, 2156 SVal Loc, SVal Val) { 2157 // Are we storing to something that causes the value to "escape"? 2158 bool escapes = true; 2159 2160 // TODO: Move to StoreManager. 2161 if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) { 2162 escapes = !regionLoc->getRegion()->hasStackStorage(); 2163 2164 if (!escapes) { 2165 // To test (3), generate a new state with the binding added. If it is 2166 // the same state, then it escapes (since the store cannot represent 2167 // the binding). 2168 // Do this only if we know that the store is not supposed to generate the 2169 // same state. 2170 SVal StoredVal = State->getSVal(regionLoc->getRegion()); 2171 if (StoredVal != Val) 2172 escapes = (State == (State->bindLoc(*regionLoc, Val))); 2173 } 2174 } 2175 2176 // If our store can represent the binding and we aren't storing to something 2177 // that doesn't have local storage then just return and have the simulation 2178 // state continue as is. 2179 if (!escapes) 2180 return State; 2181 2182 // Otherwise, find all symbols referenced by 'val' that we are tracking 2183 // and stop tracking them. 2184 CollectReachableSymbolsCallback Scanner = 2185 State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val); 2186 const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols(); 2187 State = getCheckerManager().runCheckersForPointerEscape(State, 2188 EscapedSymbols, 2189 /*CallEvent*/ nullptr, 2190 PSK_EscapeOnBind, 2191 nullptr); 2192 2193 return State; 2194 } 2195 2196 ProgramStateRef 2197 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State, 2198 const InvalidatedSymbols *Invalidated, 2199 ArrayRef<const MemRegion *> ExplicitRegions, 2200 ArrayRef<const MemRegion *> Regions, 2201 const CallEvent *Call, 2202 RegionAndSymbolInvalidationTraits &ITraits) { 2203 2204 if (!Invalidated || Invalidated->empty()) 2205 return State; 2206 2207 if (!Call) 2208 return getCheckerManager().runCheckersForPointerEscape(State, 2209 *Invalidated, 2210 nullptr, 2211 PSK_EscapeOther, 2212 &ITraits); 2213 2214 // If the symbols were invalidated by a call, we want to find out which ones 2215 // were invalidated directly due to being arguments to the call. 2216 InvalidatedSymbols SymbolsDirectlyInvalidated; 2217 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(), 2218 E = ExplicitRegions.end(); I != E; ++I) { 2219 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>()) 2220 SymbolsDirectlyInvalidated.insert(R->getSymbol()); 2221 } 2222 2223 InvalidatedSymbols SymbolsIndirectlyInvalidated; 2224 for (InvalidatedSymbols::const_iterator I=Invalidated->begin(), 2225 E = Invalidated->end(); I!=E; ++I) { 2226 SymbolRef sym = *I; 2227 if (SymbolsDirectlyInvalidated.count(sym)) 2228 continue; 2229 SymbolsIndirectlyInvalidated.insert(sym); 2230 } 2231 2232 if (!SymbolsDirectlyInvalidated.empty()) 2233 State = getCheckerManager().runCheckersForPointerEscape(State, 2234 SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits); 2235 2236 // Notify about the symbols that get indirectly invalidated by the call. 2237 if (!SymbolsIndirectlyInvalidated.empty()) 2238 State = getCheckerManager().runCheckersForPointerEscape(State, 2239 SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits); 2240 2241 return State; 2242 } 2243 2244 /// evalBind - Handle the semantics of binding a value to a specific location. 2245 /// This method is used by evalStore and (soon) VisitDeclStmt, and others. 2246 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, 2247 ExplodedNode *Pred, 2248 SVal location, SVal Val, 2249 bool atDeclInit, const ProgramPoint *PP) { 2250 2251 const LocationContext *LC = Pred->getLocationContext(); 2252 PostStmt PS(StoreE, LC); 2253 if (!PP) 2254 PP = &PS; 2255 2256 // Do a previsit of the bind. 2257 ExplodedNodeSet CheckedSet; 2258 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val, 2259 StoreE, *this, *PP); 2260 2261 StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx); 2262 2263 // If the location is not a 'Loc', it will already be handled by 2264 // the checkers. There is nothing left to do. 2265 if (!location.getAs<Loc>()) { 2266 const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr, 2267 /*tag*/nullptr); 2268 ProgramStateRef state = Pred->getState(); 2269 state = processPointerEscapedOnBind(state, location, Val); 2270 Bldr.generateNode(L, state, Pred); 2271 return; 2272 } 2273 2274 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 2275 I!=E; ++I) { 2276 ExplodedNode *PredI = *I; 2277 ProgramStateRef state = PredI->getState(); 2278 2279 state = processPointerEscapedOnBind(state, location, Val); 2280 2281 // When binding the value, pass on the hint that this is a initialization. 2282 // For initializations, we do not need to inform clients of region 2283 // changes. 2284 state = state->bindLoc(location.castAs<Loc>(), 2285 Val, /* notifyChanges = */ !atDeclInit); 2286 2287 const MemRegion *LocReg = nullptr; 2288 if (Optional<loc::MemRegionVal> LocRegVal = 2289 location.getAs<loc::MemRegionVal>()) { 2290 LocReg = LocRegVal->getRegion(); 2291 } 2292 2293 const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr); 2294 Bldr.generateNode(L, state, PredI); 2295 } 2296 } 2297 2298 /// evalStore - Handle the semantics of a store via an assignment. 2299 /// @param Dst The node set to store generated state nodes 2300 /// @param AssignE The assignment expression if the store happens in an 2301 /// assignment. 2302 /// @param LocationE The location expression that is stored to. 2303 /// @param state The current simulation state 2304 /// @param location The location to store the value 2305 /// @param Val The value to be stored 2306 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, 2307 const Expr *LocationE, 2308 ExplodedNode *Pred, 2309 ProgramStateRef state, SVal location, SVal Val, 2310 const ProgramPointTag *tag) { 2311 // Proceed with the store. We use AssignE as the anchor for the PostStore 2312 // ProgramPoint if it is non-NULL, and LocationE otherwise. 2313 const Expr *StoreE = AssignE ? AssignE : LocationE; 2314 2315 // Evaluate the location (checks for bad dereferences). 2316 ExplodedNodeSet Tmp; 2317 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false); 2318 2319 if (Tmp.empty()) 2320 return; 2321 2322 if (location.isUndef()) 2323 return; 2324 2325 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) 2326 evalBind(Dst, StoreE, *NI, location, Val, false); 2327 } 2328 2329 void ExprEngine::evalLoad(ExplodedNodeSet &Dst, 2330 const Expr *NodeEx, 2331 const Expr *BoundEx, 2332 ExplodedNode *Pred, 2333 ProgramStateRef state, 2334 SVal location, 2335 const ProgramPointTag *tag, 2336 QualType LoadTy) 2337 { 2338 assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc."); 2339 2340 // Are we loading from a region? This actually results in two loads; one 2341 // to fetch the address of the referenced value and one to fetch the 2342 // referenced value. 2343 if (const TypedValueRegion *TR = 2344 dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) { 2345 2346 QualType ValTy = TR->getValueType(); 2347 if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) { 2348 static SimpleProgramPointTag 2349 loadReferenceTag(TagProviderName, "Load Reference"); 2350 ExplodedNodeSet Tmp; 2351 evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state, 2352 location, &loadReferenceTag, 2353 getContext().getPointerType(RT->getPointeeType())); 2354 2355 // Perform the load from the referenced value. 2356 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) { 2357 state = (*I)->getState(); 2358 location = state->getSVal(BoundEx, (*I)->getLocationContext()); 2359 evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy); 2360 } 2361 return; 2362 } 2363 } 2364 2365 evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy); 2366 } 2367 2368 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst, 2369 const Expr *NodeEx, 2370 const Expr *BoundEx, 2371 ExplodedNode *Pred, 2372 ProgramStateRef state, 2373 SVal location, 2374 const ProgramPointTag *tag, 2375 QualType LoadTy) { 2376 assert(NodeEx); 2377 assert(BoundEx); 2378 // Evaluate the location (checks for bad dereferences). 2379 ExplodedNodeSet Tmp; 2380 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true); 2381 if (Tmp.empty()) 2382 return; 2383 2384 StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx); 2385 if (location.isUndef()) 2386 return; 2387 2388 // Proceed with the load. 2389 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) { 2390 state = (*NI)->getState(); 2391 const LocationContext *LCtx = (*NI)->getLocationContext(); 2392 2393 SVal V = UnknownVal(); 2394 if (location.isValid()) { 2395 if (LoadTy.isNull()) 2396 LoadTy = BoundEx->getType(); 2397 V = state->getSVal(location.castAs<Loc>(), LoadTy); 2398 } 2399 2400 Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag, 2401 ProgramPoint::PostLoadKind); 2402 } 2403 } 2404 2405 void ExprEngine::evalLocation(ExplodedNodeSet &Dst, 2406 const Stmt *NodeEx, 2407 const Stmt *BoundEx, 2408 ExplodedNode *Pred, 2409 ProgramStateRef state, 2410 SVal location, 2411 const ProgramPointTag *tag, 2412 bool isLoad) { 2413 StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx); 2414 // Early checks for performance reason. 2415 if (location.isUnknown()) { 2416 return; 2417 } 2418 2419 ExplodedNodeSet Src; 2420 BldrTop.takeNodes(Pred); 2421 StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx); 2422 if (Pred->getState() != state) { 2423 // Associate this new state with an ExplodedNode. 2424 // FIXME: If I pass null tag, the graph is incorrect, e.g for 2425 // int *p; 2426 // p = 0; 2427 // *p = 0xDEADBEEF; 2428 // "p = 0" is not noted as "Null pointer value stored to 'p'" but 2429 // instead "int *p" is noted as 2430 // "Variable 'p' initialized to a null pointer value" 2431 2432 static SimpleProgramPointTag tag(TagProviderName, "Location"); 2433 Bldr.generateNode(NodeEx, Pred, state, &tag); 2434 } 2435 ExplodedNodeSet Tmp; 2436 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad, 2437 NodeEx, BoundEx, *this); 2438 BldrTop.addNodes(Tmp); 2439 } 2440 2441 std::pair<const ProgramPointTag *, const ProgramPointTag*> 2442 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() { 2443 static SimpleProgramPointTag 2444 eagerlyAssumeBinOpBifurcationTrue(TagProviderName, 2445 "Eagerly Assume True"), 2446 eagerlyAssumeBinOpBifurcationFalse(TagProviderName, 2447 "Eagerly Assume False"); 2448 return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue, 2449 &eagerlyAssumeBinOpBifurcationFalse); 2450 } 2451 2452 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, 2453 ExplodedNodeSet &Src, 2454 const Expr *Ex) { 2455 StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx); 2456 2457 for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) { 2458 ExplodedNode *Pred = *I; 2459 // Test if the previous node was as the same expression. This can happen 2460 // when the expression fails to evaluate to anything meaningful and 2461 // (as an optimization) we don't generate a node. 2462 ProgramPoint P = Pred->getLocation(); 2463 if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) { 2464 continue; 2465 } 2466 2467 ProgramStateRef state = Pred->getState(); 2468 SVal V = state->getSVal(Ex, Pred->getLocationContext()); 2469 Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>(); 2470 if (SEV && SEV->isExpression()) { 2471 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags = 2472 geteagerlyAssumeBinOpBifurcationTags(); 2473 2474 ProgramStateRef StateTrue, StateFalse; 2475 std::tie(StateTrue, StateFalse) = state->assume(*SEV); 2476 2477 // First assume that the condition is true. 2478 if (StateTrue) { 2479 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType()); 2480 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val); 2481 Bldr.generateNode(Ex, Pred, StateTrue, tags.first); 2482 } 2483 2484 // Next, assume that the condition is false. 2485 if (StateFalse) { 2486 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType()); 2487 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val); 2488 Bldr.generateNode(Ex, Pred, StateFalse, tags.second); 2489 } 2490 } 2491 } 2492 } 2493 2494 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, 2495 ExplodedNodeSet &Dst) { 2496 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 2497 // We have processed both the inputs and the outputs. All of the outputs 2498 // should evaluate to Locs. Nuke all of their values. 2499 2500 // FIXME: Some day in the future it would be nice to allow a "plug-in" 2501 // which interprets the inline asm and stores proper results in the 2502 // outputs. 2503 2504 ProgramStateRef state = Pred->getState(); 2505 2506 for (const Expr *O : A->outputs()) { 2507 SVal X = state->getSVal(O, Pred->getLocationContext()); 2508 assert (!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef. 2509 2510 if (Optional<Loc> LV = X.getAs<Loc>()) 2511 state = state->bindLoc(*LV, UnknownVal()); 2512 } 2513 2514 Bldr.generateNode(A, Pred, state); 2515 } 2516 2517 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred, 2518 ExplodedNodeSet &Dst) { 2519 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 2520 Bldr.generateNode(A, Pred, Pred->getState()); 2521 } 2522 2523 //===----------------------------------------------------------------------===// 2524 // Visualization. 2525 //===----------------------------------------------------------------------===// 2526 2527 #ifndef NDEBUG 2528 static ExprEngine* GraphPrintCheckerState; 2529 static SourceManager* GraphPrintSourceManager; 2530 2531 namespace llvm { 2532 template<> 2533 struct DOTGraphTraits<ExplodedNode*> : 2534 public DefaultDOTGraphTraits { 2535 2536 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 2537 2538 // FIXME: Since we do not cache error nodes in ExprEngine now, this does not 2539 // work. 2540 static std::string getNodeAttributes(const ExplodedNode *N, void*) { 2541 return ""; 2542 } 2543 2544 // De-duplicate some source location pretty-printing. 2545 static void printLocation(raw_ostream &Out, SourceLocation SLoc) { 2546 if (SLoc.isFileID()) { 2547 Out << "\\lline=" 2548 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 2549 << " col=" 2550 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc) 2551 << "\\l"; 2552 } 2553 } 2554 static void printLocation2(raw_ostream &Out, SourceLocation SLoc) { 2555 if (SLoc.isFileID() && GraphPrintSourceManager->isInMainFile(SLoc)) 2556 Out << "line " << GraphPrintSourceManager->getExpansionLineNumber(SLoc); 2557 else 2558 SLoc.print(Out, *GraphPrintSourceManager); 2559 } 2560 2561 static std::string getNodeLabel(const ExplodedNode *N, void*){ 2562 2563 std::string sbuf; 2564 llvm::raw_string_ostream Out(sbuf); 2565 2566 // Program Location. 2567 ProgramPoint Loc = N->getLocation(); 2568 2569 switch (Loc.getKind()) { 2570 case ProgramPoint::BlockEntranceKind: { 2571 Out << "Block Entrance: B" 2572 << Loc.castAs<BlockEntrance>().getBlock()->getBlockID(); 2573 break; 2574 } 2575 2576 case ProgramPoint::BlockExitKind: 2577 assert (false); 2578 break; 2579 2580 case ProgramPoint::CallEnterKind: 2581 Out << "CallEnter"; 2582 break; 2583 2584 case ProgramPoint::CallExitBeginKind: 2585 Out << "CallExitBegin"; 2586 break; 2587 2588 case ProgramPoint::CallExitEndKind: 2589 Out << "CallExitEnd"; 2590 break; 2591 2592 case ProgramPoint::PostStmtPurgeDeadSymbolsKind: 2593 Out << "PostStmtPurgeDeadSymbols"; 2594 break; 2595 2596 case ProgramPoint::PreStmtPurgeDeadSymbolsKind: 2597 Out << "PreStmtPurgeDeadSymbols"; 2598 break; 2599 2600 case ProgramPoint::EpsilonKind: 2601 Out << "Epsilon Point"; 2602 break; 2603 2604 case ProgramPoint::PreImplicitCallKind: { 2605 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>(); 2606 Out << "PreCall: "; 2607 2608 // FIXME: Get proper printing options. 2609 PC.getDecl()->print(Out, LangOptions()); 2610 printLocation(Out, PC.getLocation()); 2611 break; 2612 } 2613 2614 case ProgramPoint::PostImplicitCallKind: { 2615 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>(); 2616 Out << "PostCall: "; 2617 2618 // FIXME: Get proper printing options. 2619 PC.getDecl()->print(Out, LangOptions()); 2620 printLocation(Out, PC.getLocation()); 2621 break; 2622 } 2623 2624 case ProgramPoint::PostInitializerKind: { 2625 Out << "PostInitializer: "; 2626 const CXXCtorInitializer *Init = 2627 Loc.castAs<PostInitializer>().getInitializer(); 2628 if (const FieldDecl *FD = Init->getAnyMember()) 2629 Out << *FD; 2630 else { 2631 QualType Ty = Init->getTypeSourceInfo()->getType(); 2632 Ty = Ty.getLocalUnqualifiedType(); 2633 LangOptions LO; // FIXME. 2634 Ty.print(Out, LO); 2635 } 2636 break; 2637 } 2638 2639 case ProgramPoint::BlockEdgeKind: { 2640 const BlockEdge &E = Loc.castAs<BlockEdge>(); 2641 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B" 2642 << E.getDst()->getBlockID() << ')'; 2643 2644 if (const Stmt *T = E.getSrc()->getTerminator()) { 2645 SourceLocation SLoc = T->getLocStart(); 2646 2647 Out << "\\|Terminator: "; 2648 LangOptions LO; // FIXME. 2649 E.getSrc()->printTerminator(Out, LO); 2650 2651 if (SLoc.isFileID()) { 2652 Out << "\\lline=" 2653 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 2654 << " col=" 2655 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc); 2656 } 2657 2658 if (isa<SwitchStmt>(T)) { 2659 const Stmt *Label = E.getDst()->getLabel(); 2660 2661 if (Label) { 2662 if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) { 2663 Out << "\\lcase "; 2664 LangOptions LO; // FIXME. 2665 if (C->getLHS()) 2666 C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO)); 2667 2668 if (const Stmt *RHS = C->getRHS()) { 2669 Out << " .. "; 2670 RHS->printPretty(Out, nullptr, PrintingPolicy(LO)); 2671 } 2672 2673 Out << ":"; 2674 } 2675 else { 2676 assert (isa<DefaultStmt>(Label)); 2677 Out << "\\ldefault:"; 2678 } 2679 } 2680 else 2681 Out << "\\l(implicit) default:"; 2682 } 2683 else if (isa<IndirectGotoStmt>(T)) { 2684 // FIXME 2685 } 2686 else { 2687 Out << "\\lCondition: "; 2688 if (*E.getSrc()->succ_begin() == E.getDst()) 2689 Out << "true"; 2690 else 2691 Out << "false"; 2692 } 2693 2694 Out << "\\l"; 2695 } 2696 2697 break; 2698 } 2699 2700 default: { 2701 const Stmt *S = Loc.castAs<StmtPoint>().getStmt(); 2702 assert(S != nullptr && "Expecting non-null Stmt"); 2703 2704 Out << S->getStmtClassName() << ' ' << (const void*) S << ' '; 2705 LangOptions LO; // FIXME. 2706 S->printPretty(Out, nullptr, PrintingPolicy(LO)); 2707 printLocation(Out, S->getLocStart()); 2708 2709 if (Loc.getAs<PreStmt>()) 2710 Out << "\\lPreStmt\\l;"; 2711 else if (Loc.getAs<PostLoad>()) 2712 Out << "\\lPostLoad\\l;"; 2713 else if (Loc.getAs<PostStore>()) 2714 Out << "\\lPostStore\\l"; 2715 else if (Loc.getAs<PostLValue>()) 2716 Out << "\\lPostLValue\\l"; 2717 2718 break; 2719 } 2720 } 2721 2722 ProgramStateRef state = N->getState(); 2723 Out << "\\|StateID: " << (const void*) state.get() 2724 << " NodeID: " << (const void*) N << "\\|"; 2725 2726 // Analysis stack backtrace. 2727 Out << "Location context stack (from current to outer):\\l"; 2728 const LocationContext *LC = Loc.getLocationContext(); 2729 unsigned Idx = 0; 2730 for (; LC; LC = LC->getParent(), ++Idx) { 2731 Out << Idx << ". (" << (const void *)LC << ") "; 2732 switch (LC->getKind()) { 2733 case LocationContext::StackFrame: 2734 if (const NamedDecl *D = dyn_cast<NamedDecl>(LC->getDecl())) 2735 Out << "Calling " << D->getQualifiedNameAsString(); 2736 else 2737 Out << "Calling anonymous code"; 2738 if (const Stmt *S = cast<StackFrameContext>(LC)->getCallSite()) { 2739 Out << " at "; 2740 printLocation2(Out, S->getLocStart()); 2741 } 2742 break; 2743 case LocationContext::Block: 2744 Out << "Invoking block"; 2745 if (const Decl *D = cast<BlockInvocationContext>(LC)->getBlockDecl()) { 2746 Out << " defined at "; 2747 printLocation2(Out, D->getLocStart()); 2748 } 2749 break; 2750 case LocationContext::Scope: 2751 Out << "Entering scope"; 2752 // FIXME: Add more info once ScopeContext is activated. 2753 break; 2754 } 2755 Out << "\\l"; 2756 } 2757 Out << "\\l"; 2758 2759 state->printDOT(Out); 2760 2761 Out << "\\l"; 2762 2763 if (const ProgramPointTag *tag = Loc.getTag()) { 2764 Out << "\\|Tag: " << tag->getTagDescription(); 2765 Out << "\\l"; 2766 } 2767 return Out.str(); 2768 } 2769 }; 2770 } // end llvm namespace 2771 #endif 2772 2773 void ExprEngine::ViewGraph(bool trim) { 2774 #ifndef NDEBUG 2775 if (trim) { 2776 std::vector<const ExplodedNode*> Src; 2777 2778 // Flush any outstanding reports to make sure we cover all the nodes. 2779 // This does not cause them to get displayed. 2780 for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I) 2781 const_cast<BugType*>(*I)->FlushReports(BR); 2782 2783 // Iterate through the reports and get their nodes. 2784 for (BugReporter::EQClasses_iterator 2785 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) { 2786 ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode()); 2787 if (N) Src.push_back(N); 2788 } 2789 2790 ViewGraph(Src); 2791 } 2792 else { 2793 GraphPrintCheckerState = this; 2794 GraphPrintSourceManager = &getContext().getSourceManager(); 2795 2796 llvm::ViewGraph(*G.roots_begin(), "ExprEngine"); 2797 2798 GraphPrintCheckerState = nullptr; 2799 GraphPrintSourceManager = nullptr; 2800 } 2801 #endif 2802 } 2803 2804 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) { 2805 #ifndef NDEBUG 2806 GraphPrintCheckerState = this; 2807 GraphPrintSourceManager = &getContext().getSourceManager(); 2808 2809 std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes)); 2810 2811 if (!TrimmedG.get()) 2812 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n"; 2813 else 2814 llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine"); 2815 2816 GraphPrintCheckerState = nullptr; 2817 GraphPrintSourceManager = nullptr; 2818 #endif 2819 } 2820