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