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