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