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