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