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