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