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