1 //===- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ----------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines a meta-engine for path-sensitive dataflow analysis that 10 // is built on GREngine, but provides the boilerplate to execute transfer 11 // functions and build the ExplodedGraph at the expression level. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 16 #include "PrettyStackTraceLocationContext.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclBase.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/ExprObjC.h" 25 #include "clang/AST/ParentMap.h" 26 #include "clang/AST/PrettyPrinter.h" 27 #include "clang/AST/Stmt.h" 28 #include "clang/AST/StmtCXX.h" 29 #include "clang/AST/StmtObjC.h" 30 #include "clang/AST/Type.h" 31 #include "clang/Analysis/AnalysisDeclContext.h" 32 #include "clang/Analysis/CFG.h" 33 #include "clang/Analysis/ConstructionContext.h" 34 #include "clang/Analysis/ProgramPoint.h" 35 #include "clang/Basic/IdentifierTable.h" 36 #include "clang/Basic/LLVM.h" 37 #include "clang/Basic/LangOptions.h" 38 #include "clang/Basic/PrettyStackTrace.h" 39 #include "clang/Basic/SourceLocation.h" 40 #include "clang/Basic/SourceManager.h" 41 #include "clang/Basic/Specifiers.h" 42 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" 43 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 44 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 45 #include "clang/StaticAnalyzer/Core/CheckerManager.h" 46 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 47 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 48 #include "clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h" 49 #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h" 50 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h" 51 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h" 52 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h" 53 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h" 54 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 55 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" 56 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h" 57 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h" 58 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" 59 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h" 60 #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h" 61 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h" 62 #include "llvm/ADT/APSInt.h" 63 #include "llvm/ADT/DenseMap.h" 64 #include "llvm/ADT/ImmutableMap.h" 65 #include "llvm/ADT/ImmutableSet.h" 66 #include "llvm/ADT/Optional.h" 67 #include "llvm/ADT/SmallVector.h" 68 #include "llvm/ADT/Statistic.h" 69 #include "llvm/Support/Casting.h" 70 #include "llvm/Support/Compiler.h" 71 #include "llvm/Support/DOTGraphTraits.h" 72 #include "llvm/Support/ErrorHandling.h" 73 #include "llvm/Support/GraphWriter.h" 74 #include "llvm/Support/SaveAndRestore.h" 75 #include "llvm/Support/raw_ostream.h" 76 #include <cassert> 77 #include <cstdint> 78 #include <memory> 79 #include <string> 80 #include <tuple> 81 #include <utility> 82 #include <vector> 83 84 using namespace clang; 85 using namespace ento; 86 87 #define DEBUG_TYPE "ExprEngine" 88 89 STATISTIC(NumRemoveDeadBindings, 90 "The # of times RemoveDeadBindings is called"); 91 STATISTIC(NumMaxBlockCountReached, 92 "The # of aborted paths due to reaching the maximum block count in " 93 "a top level function"); 94 STATISTIC(NumMaxBlockCountReachedInInlined, 95 "The # of aborted paths due to reaching the maximum block count in " 96 "an inlined function"); 97 STATISTIC(NumTimesRetriedWithoutInlining, 98 "The # of times we re-evaluated a call without inlining"); 99 100 //===----------------------------------------------------------------------===// 101 // Internal program state traits. 102 //===----------------------------------------------------------------------===// 103 104 namespace { 105 106 // When modeling a C++ constructor, for a variety of reasons we need to track 107 // the location of the object for the duration of its ConstructionContext. 108 // ObjectsUnderConstruction maps statements within the construction context 109 // to the object's location, so that on every such statement the location 110 // could have been retrieved. 111 112 /// ConstructedObjectKey is used for being able to find the path-sensitive 113 /// memory region of a freshly constructed object while modeling the AST node 114 /// that syntactically represents the object that is being constructed. 115 /// Semantics of such nodes may sometimes require access to the region that's 116 /// not otherwise present in the program state, or to the very fact that 117 /// the construction context was present and contained references to these 118 /// AST nodes. 119 class ConstructedObjectKey { 120 typedef std::pair<ConstructionContextItem, const LocationContext *> 121 ConstructedObjectKeyImpl; 122 123 const ConstructedObjectKeyImpl Impl; 124 125 const void *getAnyASTNodePtr() const { 126 if (const Stmt *S = getItem().getStmtOrNull()) 127 return S; 128 else 129 return getItem().getCXXCtorInitializer(); 130 } 131 132 public: 133 explicit ConstructedObjectKey(const ConstructionContextItem &Item, 134 const LocationContext *LC) 135 : Impl(Item, LC) {} 136 137 const ConstructionContextItem &getItem() const { return Impl.first; } 138 const LocationContext *getLocationContext() const { return Impl.second; } 139 140 ASTContext &getASTContext() const { 141 return getLocationContext()->getDecl()->getASTContext(); 142 } 143 144 void print(llvm::raw_ostream &OS, PrinterHelper *Helper, PrintingPolicy &PP) { 145 OS << "(LC" << getLocationContext()->getID() << ','; 146 if (const Stmt *S = getItem().getStmtOrNull()) 147 OS << 'S' << S->getID(getASTContext()); 148 else 149 OS << 'I' << getItem().getCXXCtorInitializer()->getID(getASTContext()); 150 OS << ',' << getItem().getKindAsString(); 151 if (getItem().getKind() == ConstructionContextItem::ArgumentKind) 152 OS << " #" << getItem().getIndex(); 153 OS << ") "; 154 if (const Stmt *S = getItem().getStmtOrNull()) { 155 S->printPretty(OS, Helper, PP); 156 } else { 157 const CXXCtorInitializer *I = getItem().getCXXCtorInitializer(); 158 OS << I->getAnyMember()->getNameAsString(); 159 } 160 } 161 162 void Profile(llvm::FoldingSetNodeID &ID) const { 163 ID.Add(Impl.first); 164 ID.AddPointer(Impl.second); 165 } 166 167 bool operator==(const ConstructedObjectKey &RHS) const { 168 return Impl == RHS.Impl; 169 } 170 171 bool operator<(const ConstructedObjectKey &RHS) const { 172 return Impl < RHS.Impl; 173 } 174 }; 175 } // namespace 176 177 typedef llvm::ImmutableMap<ConstructedObjectKey, SVal> 178 ObjectsUnderConstructionMap; 179 REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction, 180 ObjectsUnderConstructionMap) 181 182 //===----------------------------------------------------------------------===// 183 // Engine construction and deletion. 184 //===----------------------------------------------------------------------===// 185 186 static const char* TagProviderName = "ExprEngine"; 187 188 ExprEngine::ExprEngine(cross_tu::CrossTranslationUnitContext &CTU, 189 AnalysisManager &mgr, 190 SetOfConstDecls *VisitedCalleesIn, 191 FunctionSummariesTy *FS, 192 InliningModes HowToInlineIn) 193 : CTU(CTU), AMgr(mgr), 194 AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()), 195 Engine(*this, FS, mgr.getAnalyzerOptions()), G(Engine.getGraph()), 196 StateMgr(getContext(), mgr.getStoreManagerCreator(), 197 mgr.getConstraintManagerCreator(), G.getAllocator(), 198 this), 199 SymMgr(StateMgr.getSymbolManager()), 200 MRMgr(StateMgr.getRegionManager()), 201 svalBuilder(StateMgr.getSValBuilder()), 202 ObjCNoRet(mgr.getASTContext()), 203 BR(mgr, *this), 204 VisitedCallees(VisitedCalleesIn), 205 HowToInline(HowToInlineIn) 206 { 207 unsigned TrimInterval = mgr.options.GraphTrimInterval; 208 if (TrimInterval != 0) { 209 // Enable eager node reclamation when constructing the ExplodedGraph. 210 G.enableNodeReclamation(TrimInterval); 211 } 212 } 213 214 ExprEngine::~ExprEngine() { 215 BR.FlushReports(); 216 } 217 218 //===----------------------------------------------------------------------===// 219 // Utility methods. 220 //===----------------------------------------------------------------------===// 221 222 ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) { 223 ProgramStateRef state = StateMgr.getInitialState(InitLoc); 224 const Decl *D = InitLoc->getDecl(); 225 226 // Preconditions. 227 // FIXME: It would be nice if we had a more general mechanism to add 228 // such preconditions. Some day. 229 do { 230 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 231 // Precondition: the first argument of 'main' is an integer guaranteed 232 // to be > 0. 233 const IdentifierInfo *II = FD->getIdentifier(); 234 if (!II || !(II->getName() == "main" && FD->getNumParams() > 0)) 235 break; 236 237 const ParmVarDecl *PD = FD->getParamDecl(0); 238 QualType T = PD->getType(); 239 const auto *BT = dyn_cast<BuiltinType>(T); 240 if (!BT || !BT->isInteger()) 241 break; 242 243 const MemRegion *R = state->getRegion(PD, InitLoc); 244 if (!R) 245 break; 246 247 SVal V = state->getSVal(loc::MemRegionVal(R)); 248 SVal Constraint_untested = evalBinOp(state, BO_GT, V, 249 svalBuilder.makeZeroVal(T), 250 svalBuilder.getConditionType()); 251 252 Optional<DefinedOrUnknownSVal> Constraint = 253 Constraint_untested.getAs<DefinedOrUnknownSVal>(); 254 255 if (!Constraint) 256 break; 257 258 if (ProgramStateRef newState = state->assume(*Constraint, true)) 259 state = newState; 260 } 261 break; 262 } 263 while (false); 264 265 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) { 266 // Precondition: 'self' is always non-null upon entry to an Objective-C 267 // method. 268 const ImplicitParamDecl *SelfD = MD->getSelfDecl(); 269 const MemRegion *R = state->getRegion(SelfD, InitLoc); 270 SVal V = state->getSVal(loc::MemRegionVal(R)); 271 272 if (Optional<Loc> LV = V.getAs<Loc>()) { 273 // Assume that the pointer value in 'self' is non-null. 274 state = state->assume(*LV, true); 275 assert(state && "'self' cannot be null"); 276 } 277 } 278 279 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) { 280 if (!MD->isStatic()) { 281 // Precondition: 'this' is always non-null upon entry to the 282 // top-level function. This is our starting assumption for 283 // analyzing an "open" program. 284 const StackFrameContext *SFC = InitLoc->getStackFrame(); 285 if (SFC->getParent() == nullptr) { 286 loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC); 287 SVal V = state->getSVal(L); 288 if (Optional<Loc> LV = V.getAs<Loc>()) { 289 state = state->assume(*LV, true); 290 assert(state && "'this' cannot be null"); 291 } 292 } 293 } 294 } 295 296 return state; 297 } 298 299 ProgramStateRef ExprEngine::createTemporaryRegionIfNeeded( 300 ProgramStateRef State, const LocationContext *LC, 301 const Expr *InitWithAdjustments, const Expr *Result, 302 const SubRegion **OutRegionWithAdjustments) { 303 // FIXME: This function is a hack that works around the quirky AST 304 // we're often having with respect to C++ temporaries. If only we modelled 305 // the actual execution order of statements properly in the CFG, 306 // all the hassle with adjustments would not be necessary, 307 // and perhaps the whole function would be removed. 308 SVal InitValWithAdjustments = State->getSVal(InitWithAdjustments, LC); 309 if (!Result) { 310 // If we don't have an explicit result expression, we're in "if needed" 311 // mode. Only create a region if the current value is a NonLoc. 312 if (!InitValWithAdjustments.getAs<NonLoc>()) { 313 if (OutRegionWithAdjustments) 314 *OutRegionWithAdjustments = nullptr; 315 return State; 316 } 317 Result = InitWithAdjustments; 318 } else { 319 // We need to create a region no matter what. For sanity, make sure we don't 320 // try to stuff a Loc into a non-pointer temporary region. 321 assert(!InitValWithAdjustments.getAs<Loc>() || 322 Loc::isLocType(Result->getType()) || 323 Result->getType()->isMemberPointerType()); 324 } 325 326 ProgramStateManager &StateMgr = State->getStateManager(); 327 MemRegionManager &MRMgr = StateMgr.getRegionManager(); 328 StoreManager &StoreMgr = StateMgr.getStoreManager(); 329 330 // MaterializeTemporaryExpr may appear out of place, after a few field and 331 // base-class accesses have been made to the object, even though semantically 332 // it is the whole object that gets materialized and lifetime-extended. 333 // 334 // For example: 335 // 336 // `-MaterializeTemporaryExpr 337 // `-MemberExpr 338 // `-CXXTemporaryObjectExpr 339 // 340 // instead of the more natural 341 // 342 // `-MemberExpr 343 // `-MaterializeTemporaryExpr 344 // `-CXXTemporaryObjectExpr 345 // 346 // Use the usual methods for obtaining the expression of the base object, 347 // and record the adjustments that we need to make to obtain the sub-object 348 // that the whole expression 'Ex' refers to. This trick is usual, 349 // in the sense that CodeGen takes a similar route. 350 351 SmallVector<const Expr *, 2> CommaLHSs; 352 SmallVector<SubobjectAdjustment, 2> Adjustments; 353 354 const Expr *Init = InitWithAdjustments->skipRValueSubobjectAdjustments( 355 CommaLHSs, Adjustments); 356 357 // Take the region for Init, i.e. for the whole object. If we do not remember 358 // the region in which the object originally was constructed, come up with 359 // a new temporary region out of thin air and copy the contents of the object 360 // (which are currently present in the Environment, because Init is an rvalue) 361 // into that region. This is not correct, but it is better than nothing. 362 const TypedValueRegion *TR = nullptr; 363 if (const auto *MT = dyn_cast<MaterializeTemporaryExpr>(Result)) { 364 if (Optional<SVal> V = getObjectUnderConstruction(State, MT, LC)) { 365 State = finishObjectConstruction(State, MT, LC); 366 State = State->BindExpr(Result, LC, *V); 367 return State; 368 } else { 369 StorageDuration SD = MT->getStorageDuration(); 370 // If this object is bound to a reference with static storage duration, we 371 // put it in a different region to prevent "address leakage" warnings. 372 if (SD == SD_Static || SD == SD_Thread) { 373 TR = MRMgr.getCXXStaticTempObjectRegion(Init); 374 } else { 375 TR = MRMgr.getCXXTempObjectRegion(Init, LC); 376 } 377 } 378 } else { 379 TR = MRMgr.getCXXTempObjectRegion(Init, LC); 380 } 381 382 SVal Reg = loc::MemRegionVal(TR); 383 SVal BaseReg = Reg; 384 385 // Make the necessary adjustments to obtain the sub-object. 386 for (auto I = Adjustments.rbegin(), E = Adjustments.rend(); I != E; ++I) { 387 const SubobjectAdjustment &Adj = *I; 388 switch (Adj.Kind) { 389 case SubobjectAdjustment::DerivedToBaseAdjustment: 390 Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath); 391 break; 392 case SubobjectAdjustment::FieldAdjustment: 393 Reg = StoreMgr.getLValueField(Adj.Field, Reg); 394 break; 395 case SubobjectAdjustment::MemberPointerAdjustment: 396 // FIXME: Unimplemented. 397 State = State->invalidateRegions(Reg, InitWithAdjustments, 398 currBldrCtx->blockCount(), LC, true, 399 nullptr, nullptr, nullptr); 400 return State; 401 } 402 } 403 404 // What remains is to copy the value of the object to the new region. 405 // FIXME: In other words, what we should always do is copy value of the 406 // Init expression (which corresponds to the bigger object) to the whole 407 // temporary region TR. However, this value is often no longer present 408 // in the Environment. If it has disappeared, we instead invalidate TR. 409 // Still, what we can do is assign the value of expression Ex (which 410 // corresponds to the sub-object) to the TR's sub-region Reg. At least, 411 // values inside Reg would be correct. 412 SVal InitVal = State->getSVal(Init, LC); 413 if (InitVal.isUnknown()) { 414 InitVal = getSValBuilder().conjureSymbolVal(Result, LC, Init->getType(), 415 currBldrCtx->blockCount()); 416 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false); 417 418 // Then we'd need to take the value that certainly exists and bind it 419 // over. 420 if (InitValWithAdjustments.isUnknown()) { 421 // Try to recover some path sensitivity in case we couldn't 422 // compute the value. 423 InitValWithAdjustments = getSValBuilder().conjureSymbolVal( 424 Result, LC, InitWithAdjustments->getType(), 425 currBldrCtx->blockCount()); 426 } 427 State = 428 State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, LC, false); 429 } else { 430 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false); 431 } 432 433 // The result expression would now point to the correct sub-region of the 434 // newly created temporary region. Do this last in order to getSVal of Init 435 // correctly in case (Result == Init). 436 if (Result->isGLValue()) { 437 State = State->BindExpr(Result, LC, Reg); 438 } else { 439 State = State->BindExpr(Result, LC, InitValWithAdjustments); 440 } 441 442 // Notify checkers once for two bindLoc()s. 443 State = processRegionChange(State, TR, LC); 444 445 if (OutRegionWithAdjustments) 446 *OutRegionWithAdjustments = cast<SubRegion>(Reg.getAsRegion()); 447 return State; 448 } 449 450 ProgramStateRef 451 ExprEngine::addObjectUnderConstruction(ProgramStateRef State, 452 const ConstructionContextItem &Item, 453 const LocationContext *LC, SVal V) { 454 ConstructedObjectKey Key(Item, LC->getStackFrame()); 455 // FIXME: Currently the state might already contain the marker due to 456 // incorrect handling of temporaries bound to default parameters. 457 assert(!State->get<ObjectsUnderConstruction>(Key) || 458 Key.getItem().getKind() == 459 ConstructionContextItem::TemporaryDestructorKind); 460 return State->set<ObjectsUnderConstruction>(Key, V); 461 } 462 463 Optional<SVal> 464 ExprEngine::getObjectUnderConstruction(ProgramStateRef State, 465 const ConstructionContextItem &Item, 466 const LocationContext *LC) { 467 ConstructedObjectKey Key(Item, LC->getStackFrame()); 468 return Optional<SVal>::create(State->get<ObjectsUnderConstruction>(Key)); 469 } 470 471 ProgramStateRef 472 ExprEngine::finishObjectConstruction(ProgramStateRef State, 473 const ConstructionContextItem &Item, 474 const LocationContext *LC) { 475 ConstructedObjectKey Key(Item, LC->getStackFrame()); 476 assert(State->contains<ObjectsUnderConstruction>(Key)); 477 return State->remove<ObjectsUnderConstruction>(Key); 478 } 479 480 ProgramStateRef ExprEngine::elideDestructor(ProgramStateRef State, 481 const CXXBindTemporaryExpr *BTE, 482 const LocationContext *LC) { 483 ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC); 484 // FIXME: Currently the state might already contain the marker due to 485 // incorrect handling of temporaries bound to default parameters. 486 return State->set<ObjectsUnderConstruction>(Key, UnknownVal()); 487 } 488 489 ProgramStateRef 490 ExprEngine::cleanupElidedDestructor(ProgramStateRef State, 491 const CXXBindTemporaryExpr *BTE, 492 const LocationContext *LC) { 493 ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC); 494 assert(State->contains<ObjectsUnderConstruction>(Key)); 495 return State->remove<ObjectsUnderConstruction>(Key); 496 } 497 498 bool ExprEngine::isDestructorElided(ProgramStateRef State, 499 const CXXBindTemporaryExpr *BTE, 500 const LocationContext *LC) { 501 ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC); 502 return State->contains<ObjectsUnderConstruction>(Key); 503 } 504 505 bool ExprEngine::areAllObjectsFullyConstructed(ProgramStateRef State, 506 const LocationContext *FromLC, 507 const LocationContext *ToLC) { 508 const LocationContext *LC = FromLC; 509 while (LC != ToLC) { 510 assert(LC && "ToLC must be a parent of FromLC!"); 511 for (auto I : State->get<ObjectsUnderConstruction>()) 512 if (I.first.getLocationContext() == LC) 513 return false; 514 515 LC = LC->getParent(); 516 } 517 return true; 518 } 519 520 521 //===----------------------------------------------------------------------===// 522 // Top-level transfer function logic (Dispatcher). 523 //===----------------------------------------------------------------------===// 524 525 /// evalAssume - Called by ConstraintManager. Used to call checker-specific 526 /// logic for handling assumptions on symbolic values. 527 ProgramStateRef ExprEngine::processAssume(ProgramStateRef state, 528 SVal cond, bool assumption) { 529 return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption); 530 } 531 532 ProgramStateRef 533 ExprEngine::processRegionChanges(ProgramStateRef state, 534 const InvalidatedSymbols *invalidated, 535 ArrayRef<const MemRegion *> Explicits, 536 ArrayRef<const MemRegion *> Regions, 537 const LocationContext *LCtx, 538 const CallEvent *Call) { 539 return getCheckerManager().runCheckersForRegionChanges(state, invalidated, 540 Explicits, Regions, 541 LCtx, Call); 542 } 543 544 static void printObjectsUnderConstructionForContext(raw_ostream &Out, 545 ProgramStateRef State, 546 const char *NL, 547 const LocationContext *LC) { 548 PrintingPolicy PP = 549 LC->getAnalysisDeclContext()->getASTContext().getPrintingPolicy(); 550 for (auto I : State->get<ObjectsUnderConstruction>()) { 551 ConstructedObjectKey Key = I.first; 552 SVal Value = I.second; 553 if (Key.getLocationContext() != LC) 554 continue; 555 Key.print(Out, nullptr, PP); 556 Out << " : " << Value << NL; 557 } 558 } 559 560 void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State, 561 const char *NL, const char *Sep, 562 const LocationContext *LCtx) { 563 if (LCtx) { 564 if (!State->get<ObjectsUnderConstruction>().isEmpty()) { 565 Out << Sep << "Objects under construction:" << NL; 566 567 LCtx->dumpStack(Out, "", NL, Sep, [&](const LocationContext *LC) { 568 printObjectsUnderConstructionForContext(Out, State, NL, LC); 569 }); 570 } 571 } 572 573 getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep); 574 } 575 576 void ExprEngine::processEndWorklist() { 577 getCheckerManager().runCheckersForEndAnalysis(G, BR, *this); 578 } 579 580 void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred, 581 unsigned StmtIdx, NodeBuilderContext *Ctx) { 582 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 583 currStmtIdx = StmtIdx; 584 currBldrCtx = Ctx; 585 586 switch (E.getKind()) { 587 case CFGElement::Statement: 588 case CFGElement::Constructor: 589 case CFGElement::CXXRecordTypedCall: 590 ProcessStmt(E.castAs<CFGStmt>().getStmt(), Pred); 591 return; 592 case CFGElement::Initializer: 593 ProcessInitializer(E.castAs<CFGInitializer>(), Pred); 594 return; 595 case CFGElement::NewAllocator: 596 ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(), 597 Pred); 598 return; 599 case CFGElement::AutomaticObjectDtor: 600 case CFGElement::DeleteDtor: 601 case CFGElement::BaseDtor: 602 case CFGElement::MemberDtor: 603 case CFGElement::TemporaryDtor: 604 ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred); 605 return; 606 case CFGElement::LoopExit: 607 ProcessLoopExit(E.castAs<CFGLoopExit>().getLoopStmt(), Pred); 608 return; 609 case CFGElement::LifetimeEnds: 610 case CFGElement::ScopeBegin: 611 case CFGElement::ScopeEnd: 612 return; 613 } 614 } 615 616 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr, 617 const Stmt *S, 618 const ExplodedNode *Pred, 619 const LocationContext *LC) { 620 // Are we never purging state values? 621 if (AMgr.options.AnalysisPurgeOpt == PurgeNone) 622 return false; 623 624 // Is this the beginning of a basic block? 625 if (Pred->getLocation().getAs<BlockEntrance>()) 626 return true; 627 628 // Is this on a non-expression? 629 if (!isa<Expr>(S)) 630 return true; 631 632 // Run before processing a call. 633 if (CallEvent::isCallStmt(S)) 634 return true; 635 636 // Is this an expression that is consumed by another expression? If so, 637 // postpone cleaning out the state. 638 ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap(); 639 return !PM.isConsumedExpr(cast<Expr>(S)); 640 } 641 642 void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out, 643 const Stmt *ReferenceStmt, 644 const LocationContext *LC, 645 const Stmt *DiagnosticStmt, 646 ProgramPoint::Kind K) { 647 assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind || 648 ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt)) 649 && "PostStmt is not generally supported by the SymbolReaper yet"); 650 assert(LC && "Must pass the current (or expiring) LocationContext"); 651 652 if (!DiagnosticStmt) { 653 DiagnosticStmt = ReferenceStmt; 654 assert(DiagnosticStmt && "Required for clearing a LocationContext"); 655 } 656 657 NumRemoveDeadBindings++; 658 ProgramStateRef CleanedState = Pred->getState(); 659 660 // LC is the location context being destroyed, but SymbolReaper wants a 661 // location context that is still live. (If this is the top-level stack 662 // frame, this will be null.) 663 if (!ReferenceStmt) { 664 assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind && 665 "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext"); 666 LC = LC->getParent(); 667 } 668 669 const StackFrameContext *SFC = LC ? LC->getStackFrame() : nullptr; 670 SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager()); 671 672 for (auto I : CleanedState->get<ObjectsUnderConstruction>()) { 673 if (SymbolRef Sym = I.second.getAsSymbol()) 674 SymReaper.markLive(Sym); 675 if (const MemRegion *MR = I.second.getAsRegion()) 676 SymReaper.markLive(MR); 677 } 678 679 getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper); 680 681 // Create a state in which dead bindings are removed from the environment 682 // and the store. TODO: The function should just return new env and store, 683 // not a new state. 684 CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper); 685 686 // Process any special transfer function for dead symbols. 687 // A tag to track convenience transitions, which can be removed at cleanup. 688 static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node"); 689 // Call checkers with the non-cleaned state so that they could query the 690 // values of the soon to be dead symbols. 691 ExplodedNodeSet CheckedSet; 692 getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper, 693 DiagnosticStmt, *this, K); 694 695 // For each node in CheckedSet, generate CleanedNodes that have the 696 // environment, the store, and the constraints cleaned up but have the 697 // user-supplied states as the predecessors. 698 StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx); 699 for (const auto I : CheckedSet) { 700 ProgramStateRef CheckerState = I->getState(); 701 702 // The constraint manager has not been cleaned up yet, so clean up now. 703 CheckerState = 704 getConstraintManager().removeDeadBindings(CheckerState, SymReaper); 705 706 assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) && 707 "Checkers are not allowed to modify the Environment as a part of " 708 "checkDeadSymbols processing."); 709 assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) && 710 "Checkers are not allowed to modify the Store as a part of " 711 "checkDeadSymbols processing."); 712 713 // Create a state based on CleanedState with CheckerState GDM and 714 // generate a transition to that state. 715 ProgramStateRef CleanedCheckerSt = 716 StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState); 717 Bldr.generateNode(DiagnosticStmt, I, CleanedCheckerSt, &cleanupTag, K); 718 } 719 } 720 721 void ExprEngine::ProcessStmt(const Stmt *currStmt, ExplodedNode *Pred) { 722 // Reclaim any unnecessary nodes in the ExplodedGraph. 723 G.reclaimRecentlyAllocatedNodes(); 724 725 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 726 currStmt->getBeginLoc(), 727 "Error evaluating statement"); 728 729 // Remove dead bindings and symbols. 730 ExplodedNodeSet CleanedStates; 731 if (shouldRemoveDeadBindings(AMgr, currStmt, Pred, 732 Pred->getLocationContext())) { 733 removeDead(Pred, CleanedStates, currStmt, 734 Pred->getLocationContext()); 735 } else 736 CleanedStates.Add(Pred); 737 738 // Visit the statement. 739 ExplodedNodeSet Dst; 740 for (const auto I : CleanedStates) { 741 ExplodedNodeSet DstI; 742 // Visit the statement. 743 Visit(currStmt, I, DstI); 744 Dst.insert(DstI); 745 } 746 747 // Enqueue the new nodes onto the work list. 748 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 749 } 750 751 void ExprEngine::ProcessLoopExit(const Stmt* S, ExplodedNode *Pred) { 752 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 753 S->getBeginLoc(), 754 "Error evaluating end of the loop"); 755 ExplodedNodeSet Dst; 756 Dst.Add(Pred); 757 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 758 ProgramStateRef NewState = Pred->getState(); 759 760 if(AMgr.options.ShouldUnrollLoops) 761 NewState = processLoopEnd(S, NewState); 762 763 LoopExit PP(S, Pred->getLocationContext()); 764 Bldr.generateNode(PP, NewState, Pred); 765 // Enqueue the new nodes onto the work list. 766 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 767 } 768 769 void ExprEngine::ProcessInitializer(const CFGInitializer CFGInit, 770 ExplodedNode *Pred) { 771 const CXXCtorInitializer *BMI = CFGInit.getInitializer(); 772 const Expr *Init = BMI->getInit()->IgnoreImplicit(); 773 const LocationContext *LC = Pred->getLocationContext(); 774 775 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 776 BMI->getSourceLocation(), 777 "Error evaluating initializer"); 778 779 // We don't clean up dead bindings here. 780 const auto *stackFrame = cast<StackFrameContext>(Pred->getLocationContext()); 781 const auto *decl = cast<CXXConstructorDecl>(stackFrame->getDecl()); 782 783 ProgramStateRef State = Pred->getState(); 784 SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame)); 785 786 ExplodedNodeSet Tmp; 787 SVal FieldLoc; 788 789 // Evaluate the initializer, if necessary 790 if (BMI->isAnyMemberInitializer()) { 791 // Constructors build the object directly in the field, 792 // but non-objects must be copied in from the initializer. 793 if (getObjectUnderConstruction(State, BMI, LC)) { 794 // The field was directly constructed, so there is no need to bind. 795 // But we still need to stop tracking the object under construction. 796 State = finishObjectConstruction(State, BMI, LC); 797 NodeBuilder Bldr(Pred, Tmp, *currBldrCtx); 798 PostStore PS(Init, LC, /*Loc*/ nullptr, /*tag*/ nullptr); 799 Bldr.generateNode(PS, State, Pred); 800 } else { 801 const ValueDecl *Field; 802 if (BMI->isIndirectMemberInitializer()) { 803 Field = BMI->getIndirectMember(); 804 FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal); 805 } else { 806 Field = BMI->getMember(); 807 FieldLoc = State->getLValue(BMI->getMember(), thisVal); 808 } 809 810 SVal InitVal; 811 if (Init->getType()->isArrayType()) { 812 // Handle arrays of trivial type. We can represent this with a 813 // primitive load/copy from the base array region. 814 const ArraySubscriptExpr *ASE; 815 while ((ASE = dyn_cast<ArraySubscriptExpr>(Init))) 816 Init = ASE->getBase()->IgnoreImplicit(); 817 818 SVal LValue = State->getSVal(Init, stackFrame); 819 if (!Field->getType()->isReferenceType()) 820 if (Optional<Loc> LValueLoc = LValue.getAs<Loc>()) 821 InitVal = State->getSVal(*LValueLoc); 822 823 // If we fail to get the value for some reason, use a symbolic value. 824 if (InitVal.isUnknownOrUndef()) { 825 SValBuilder &SVB = getSValBuilder(); 826 InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame, 827 Field->getType(), 828 currBldrCtx->blockCount()); 829 } 830 } else { 831 InitVal = State->getSVal(BMI->getInit(), stackFrame); 832 } 833 834 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame); 835 evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP); 836 } 837 } else { 838 assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer()); 839 Tmp.insert(Pred); 840 // We already did all the work when visiting the CXXConstructExpr. 841 } 842 843 // Construct PostInitializer nodes whether the state changed or not, 844 // so that the diagnostics don't get confused. 845 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame); 846 ExplodedNodeSet Dst; 847 NodeBuilder Bldr(Tmp, Dst, *currBldrCtx); 848 for (const auto I : Tmp) { 849 ProgramStateRef State = I->getState(); 850 Bldr.generateNode(PP, State, I); 851 } 852 853 // Enqueue the new nodes onto the work list. 854 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 855 } 856 857 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D, 858 ExplodedNode *Pred) { 859 ExplodedNodeSet Dst; 860 switch (D.getKind()) { 861 case CFGElement::AutomaticObjectDtor: 862 ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst); 863 break; 864 case CFGElement::BaseDtor: 865 ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst); 866 break; 867 case CFGElement::MemberDtor: 868 ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst); 869 break; 870 case CFGElement::TemporaryDtor: 871 ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst); 872 break; 873 case CFGElement::DeleteDtor: 874 ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst); 875 break; 876 default: 877 llvm_unreachable("Unexpected dtor kind."); 878 } 879 880 // Enqueue the new nodes onto the work list. 881 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 882 } 883 884 void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE, 885 ExplodedNode *Pred) { 886 ExplodedNodeSet Dst; 887 AnalysisManager &AMgr = getAnalysisManager(); 888 AnalyzerOptions &Opts = AMgr.options; 889 // TODO: We're not evaluating allocators for all cases just yet as 890 // we're not handling the return value correctly, which causes false 891 // positives when the alpha.cplusplus.NewDeleteLeaks check is on. 892 if (Opts.MayInlineCXXAllocator) 893 VisitCXXNewAllocatorCall(NE, Pred, Dst); 894 else { 895 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 896 const LocationContext *LCtx = Pred->getLocationContext(); 897 PostImplicitCall PP(NE->getOperatorNew(), NE->getBeginLoc(), LCtx); 898 Bldr.generateNode(PP, Pred->getState(), Pred); 899 } 900 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 901 } 902 903 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor, 904 ExplodedNode *Pred, 905 ExplodedNodeSet &Dst) { 906 const VarDecl *varDecl = Dtor.getVarDecl(); 907 QualType varType = varDecl->getType(); 908 909 ProgramStateRef state = Pred->getState(); 910 SVal dest = state->getLValue(varDecl, Pred->getLocationContext()); 911 const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion(); 912 913 if (varType->isReferenceType()) { 914 const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion(); 915 if (!ValueRegion) { 916 // FIXME: This should not happen. The language guarantees a presence 917 // of a valid initializer here, so the reference shall not be undefined. 918 // It seems that we're calling destructors over variables that 919 // were not initialized yet. 920 return; 921 } 922 Region = ValueRegion->getBaseRegion(); 923 varType = cast<TypedValueRegion>(Region)->getValueType(); 924 } 925 926 // FIXME: We need to run the same destructor on every element of the array. 927 // This workaround will just run the first destructor (which will still 928 // invalidate the entire array). 929 EvalCallOptions CallOpts; 930 Region = makeZeroElementRegion(state, loc::MemRegionVal(Region), varType, 931 CallOpts.IsArrayCtorOrDtor).getAsRegion(); 932 933 VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false, 934 Pred, Dst, CallOpts); 935 } 936 937 void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor, 938 ExplodedNode *Pred, 939 ExplodedNodeSet &Dst) { 940 ProgramStateRef State = Pred->getState(); 941 const LocationContext *LCtx = Pred->getLocationContext(); 942 const CXXDeleteExpr *DE = Dtor.getDeleteExpr(); 943 const Stmt *Arg = DE->getArgument(); 944 QualType DTy = DE->getDestroyedType(); 945 SVal ArgVal = State->getSVal(Arg, LCtx); 946 947 // If the argument to delete is known to be a null value, 948 // don't run destructor. 949 if (State->isNull(ArgVal).isConstrainedTrue()) { 950 QualType BTy = getContext().getBaseElementType(DTy); 951 const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl(); 952 const CXXDestructorDecl *Dtor = RD->getDestructor(); 953 954 PostImplicitCall PP(Dtor, DE->getBeginLoc(), LCtx); 955 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 956 Bldr.generateNode(PP, Pred->getState(), Pred); 957 return; 958 } 959 960 EvalCallOptions CallOpts; 961 const MemRegion *ArgR = ArgVal.getAsRegion(); 962 if (DE->isArrayForm()) { 963 // FIXME: We need to run the same destructor on every element of the array. 964 // This workaround will just run the first destructor (which will still 965 // invalidate the entire array). 966 CallOpts.IsArrayCtorOrDtor = true; 967 // Yes, it may even be a multi-dimensional array. 968 while (const auto *AT = getContext().getAsArrayType(DTy)) 969 DTy = AT->getElementType(); 970 if (ArgR) 971 ArgR = getStoreManager().GetElementZeroRegion(cast<SubRegion>(ArgR), DTy); 972 } 973 974 VisitCXXDestructor(DTy, ArgR, DE, /*IsBase=*/false, Pred, Dst, CallOpts); 975 } 976 977 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D, 978 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 979 const LocationContext *LCtx = Pred->getLocationContext(); 980 981 const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl()); 982 Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor, 983 LCtx->getStackFrame()); 984 SVal ThisVal = Pred->getState()->getSVal(ThisPtr); 985 986 // Create the base object region. 987 const CXXBaseSpecifier *Base = D.getBaseSpecifier(); 988 QualType BaseTy = Base->getType(); 989 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy, 990 Base->isVirtual()); 991 992 VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(), 993 CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst, {}); 994 } 995 996 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D, 997 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 998 const FieldDecl *Member = D.getFieldDecl(); 999 QualType T = Member->getType(); 1000 ProgramStateRef State = Pred->getState(); 1001 const LocationContext *LCtx = Pred->getLocationContext(); 1002 1003 const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl()); 1004 Loc ThisVal = getSValBuilder().getCXXThis(CurDtor, 1005 LCtx->getStackFrame()); 1006 SVal FieldVal = 1007 State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>()); 1008 1009 // FIXME: We need to run the same destructor on every element of the array. 1010 // This workaround will just run the first destructor (which will still 1011 // invalidate the entire array). 1012 EvalCallOptions CallOpts; 1013 FieldVal = makeZeroElementRegion(State, FieldVal, T, 1014 CallOpts.IsArrayCtorOrDtor); 1015 1016 VisitCXXDestructor(T, FieldVal.castAs<loc::MemRegionVal>().getRegion(), 1017 CurDtor->getBody(), /*IsBase=*/false, Pred, Dst, CallOpts); 1018 } 1019 1020 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D, 1021 ExplodedNode *Pred, 1022 ExplodedNodeSet &Dst) { 1023 const CXXBindTemporaryExpr *BTE = D.getBindTemporaryExpr(); 1024 ProgramStateRef State = Pred->getState(); 1025 const LocationContext *LC = Pred->getLocationContext(); 1026 const MemRegion *MR = nullptr; 1027 1028 if (Optional<SVal> V = 1029 getObjectUnderConstruction(State, D.getBindTemporaryExpr(), 1030 Pred->getLocationContext())) { 1031 // FIXME: Currently we insert temporary destructors for default parameters, 1032 // but we don't insert the constructors, so the entry in 1033 // ObjectsUnderConstruction may be missing. 1034 State = finishObjectConstruction(State, D.getBindTemporaryExpr(), 1035 Pred->getLocationContext()); 1036 MR = V->getAsRegion(); 1037 } 1038 1039 // If copy elision has occurred, and the constructor corresponding to the 1040 // destructor was elided, we need to skip the destructor as well. 1041 if (isDestructorElided(State, BTE, LC)) { 1042 State = cleanupElidedDestructor(State, BTE, LC); 1043 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1044 PostImplicitCall PP(D.getDestructorDecl(getContext()), 1045 D.getBindTemporaryExpr()->getBeginLoc(), 1046 Pred->getLocationContext()); 1047 Bldr.generateNode(PP, State, Pred); 1048 return; 1049 } 1050 1051 ExplodedNodeSet CleanDtorState; 1052 StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx); 1053 StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State); 1054 1055 QualType T = D.getBindTemporaryExpr()->getSubExpr()->getType(); 1056 // FIXME: Currently CleanDtorState can be empty here due to temporaries being 1057 // bound to default parameters. 1058 assert(CleanDtorState.size() <= 1); 1059 ExplodedNode *CleanPred = 1060 CleanDtorState.empty() ? Pred : *CleanDtorState.begin(); 1061 1062 EvalCallOptions CallOpts; 1063 CallOpts.IsTemporaryCtorOrDtor = true; 1064 if (!MR) { 1065 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true; 1066 1067 // If we have no MR, we still need to unwrap the array to avoid destroying 1068 // the whole array at once. Regardless, we'd eventually need to model array 1069 // destructors properly, element-by-element. 1070 while (const ArrayType *AT = getContext().getAsArrayType(T)) { 1071 T = AT->getElementType(); 1072 CallOpts.IsArrayCtorOrDtor = true; 1073 } 1074 } else { 1075 // We'd eventually need to makeZeroElementRegion() trick here, 1076 // but for now we don't have the respective construction contexts, 1077 // so MR would always be null in this case. Do nothing for now. 1078 } 1079 VisitCXXDestructor(T, MR, D.getBindTemporaryExpr(), 1080 /*IsBase=*/false, CleanPred, Dst, CallOpts); 1081 } 1082 1083 void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE, 1084 NodeBuilderContext &BldCtx, 1085 ExplodedNode *Pred, 1086 ExplodedNodeSet &Dst, 1087 const CFGBlock *DstT, 1088 const CFGBlock *DstF) { 1089 BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF); 1090 ProgramStateRef State = Pred->getState(); 1091 const LocationContext *LC = Pred->getLocationContext(); 1092 if (getObjectUnderConstruction(State, BTE, LC)) { 1093 TempDtorBuilder.markInfeasible(false); 1094 TempDtorBuilder.generateNode(State, true, Pred); 1095 } else { 1096 TempDtorBuilder.markInfeasible(true); 1097 TempDtorBuilder.generateNode(State, false, Pred); 1098 } 1099 } 1100 1101 void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE, 1102 ExplodedNodeSet &PreVisit, 1103 ExplodedNodeSet &Dst) { 1104 // This is a fallback solution in case we didn't have a construction 1105 // context when we were constructing the temporary. Otherwise the map should 1106 // have been populated there. 1107 if (!getAnalysisManager().options.ShouldIncludeTemporaryDtorsInCFG) { 1108 // In case we don't have temporary destructors in the CFG, do not mark 1109 // the initialization - we would otherwise never clean it up. 1110 Dst = PreVisit; 1111 return; 1112 } 1113 StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx); 1114 for (ExplodedNode *Node : PreVisit) { 1115 ProgramStateRef State = Node->getState(); 1116 const LocationContext *LC = Node->getLocationContext(); 1117 if (!getObjectUnderConstruction(State, BTE, LC)) { 1118 // FIXME: Currently the state might also already contain the marker due to 1119 // incorrect handling of temporaries bound to default parameters; for 1120 // those, we currently skip the CXXBindTemporaryExpr but rely on adding 1121 // temporary destructor nodes. 1122 State = addObjectUnderConstruction(State, BTE, LC, UnknownVal()); 1123 } 1124 StmtBldr.generateNode(BTE, Node, State); 1125 } 1126 } 1127 1128 ProgramStateRef ExprEngine::escapeValue(ProgramStateRef State, SVal V, 1129 PointerEscapeKind K) const { 1130 class CollectReachableSymbolsCallback final : public SymbolVisitor { 1131 InvalidatedSymbols Symbols; 1132 1133 public: 1134 explicit CollectReachableSymbolsCallback(ProgramStateRef) {} 1135 1136 const InvalidatedSymbols &getSymbols() const { return Symbols; } 1137 1138 bool VisitSymbol(SymbolRef Sym) override { 1139 Symbols.insert(Sym); 1140 return true; 1141 } 1142 }; 1143 1144 const CollectReachableSymbolsCallback &Scanner = 1145 State->scanReachableSymbols<CollectReachableSymbolsCallback>(V); 1146 return getCheckerManager().runCheckersForPointerEscape( 1147 State, Scanner.getSymbols(), /*CallEvent*/ nullptr, K, nullptr); 1148 } 1149 1150 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred, 1151 ExplodedNodeSet &DstTop) { 1152 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 1153 S->getBeginLoc(), "Error evaluating statement"); 1154 ExplodedNodeSet Dst; 1155 StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx); 1156 1157 assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens()); 1158 1159 switch (S->getStmtClass()) { 1160 // C++, OpenMP and ARC stuff we don't support yet. 1161 case Expr::ObjCIndirectCopyRestoreExprClass: 1162 case Stmt::CXXDependentScopeMemberExprClass: 1163 case Stmt::CXXInheritedCtorInitExprClass: 1164 case Stmt::CXXTryStmtClass: 1165 case Stmt::CXXTypeidExprClass: 1166 case Stmt::CXXUuidofExprClass: 1167 case Stmt::CXXFoldExprClass: 1168 case Stmt::MSPropertyRefExprClass: 1169 case Stmt::MSPropertySubscriptExprClass: 1170 case Stmt::CXXUnresolvedConstructExprClass: 1171 case Stmt::DependentScopeDeclRefExprClass: 1172 case Stmt::ArrayTypeTraitExprClass: 1173 case Stmt::ExpressionTraitExprClass: 1174 case Stmt::UnresolvedLookupExprClass: 1175 case Stmt::UnresolvedMemberExprClass: 1176 case Stmt::TypoExprClass: 1177 case Stmt::CXXNoexceptExprClass: 1178 case Stmt::PackExpansionExprClass: 1179 case Stmt::SubstNonTypeTemplateParmPackExprClass: 1180 case Stmt::FunctionParmPackExprClass: 1181 case Stmt::CoroutineBodyStmtClass: 1182 case Stmt::CoawaitExprClass: 1183 case Stmt::DependentCoawaitExprClass: 1184 case Stmt::CoreturnStmtClass: 1185 case Stmt::CoyieldExprClass: 1186 case Stmt::SEHTryStmtClass: 1187 case Stmt::SEHExceptStmtClass: 1188 case Stmt::SEHLeaveStmtClass: 1189 case Stmt::SEHFinallyStmtClass: 1190 case Stmt::OMPParallelDirectiveClass: 1191 case Stmt::OMPSimdDirectiveClass: 1192 case Stmt::OMPForDirectiveClass: 1193 case Stmt::OMPForSimdDirectiveClass: 1194 case Stmt::OMPSectionsDirectiveClass: 1195 case Stmt::OMPSectionDirectiveClass: 1196 case Stmt::OMPSingleDirectiveClass: 1197 case Stmt::OMPMasterDirectiveClass: 1198 case Stmt::OMPCriticalDirectiveClass: 1199 case Stmt::OMPParallelForDirectiveClass: 1200 case Stmt::OMPParallelForSimdDirectiveClass: 1201 case Stmt::OMPParallelSectionsDirectiveClass: 1202 case Stmt::OMPTaskDirectiveClass: 1203 case Stmt::OMPTaskyieldDirectiveClass: 1204 case Stmt::OMPBarrierDirectiveClass: 1205 case Stmt::OMPTaskwaitDirectiveClass: 1206 case Stmt::OMPTaskgroupDirectiveClass: 1207 case Stmt::OMPFlushDirectiveClass: 1208 case Stmt::OMPOrderedDirectiveClass: 1209 case Stmt::OMPAtomicDirectiveClass: 1210 case Stmt::OMPTargetDirectiveClass: 1211 case Stmt::OMPTargetDataDirectiveClass: 1212 case Stmt::OMPTargetEnterDataDirectiveClass: 1213 case Stmt::OMPTargetExitDataDirectiveClass: 1214 case Stmt::OMPTargetParallelDirectiveClass: 1215 case Stmt::OMPTargetParallelForDirectiveClass: 1216 case Stmt::OMPTargetUpdateDirectiveClass: 1217 case Stmt::OMPTeamsDirectiveClass: 1218 case Stmt::OMPCancellationPointDirectiveClass: 1219 case Stmt::OMPCancelDirectiveClass: 1220 case Stmt::OMPTaskLoopDirectiveClass: 1221 case Stmt::OMPTaskLoopSimdDirectiveClass: 1222 case Stmt::OMPDistributeDirectiveClass: 1223 case Stmt::OMPDistributeParallelForDirectiveClass: 1224 case Stmt::OMPDistributeParallelForSimdDirectiveClass: 1225 case Stmt::OMPDistributeSimdDirectiveClass: 1226 case Stmt::OMPTargetParallelForSimdDirectiveClass: 1227 case Stmt::OMPTargetSimdDirectiveClass: 1228 case Stmt::OMPTeamsDistributeDirectiveClass: 1229 case Stmt::OMPTeamsDistributeSimdDirectiveClass: 1230 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass: 1231 case Stmt::OMPTeamsDistributeParallelForDirectiveClass: 1232 case Stmt::OMPTargetTeamsDirectiveClass: 1233 case Stmt::OMPTargetTeamsDistributeDirectiveClass: 1234 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass: 1235 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass: 1236 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass: 1237 case Stmt::CapturedStmtClass: { 1238 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState()); 1239 Engine.addAbortedBlock(node, currBldrCtx->getBlock()); 1240 break; 1241 } 1242 1243 case Stmt::ParenExprClass: 1244 llvm_unreachable("ParenExprs already handled."); 1245 case Stmt::GenericSelectionExprClass: 1246 llvm_unreachable("GenericSelectionExprs already handled."); 1247 // Cases that should never be evaluated simply because they shouldn't 1248 // appear in the CFG. 1249 case Stmt::BreakStmtClass: 1250 case Stmt::CaseStmtClass: 1251 case Stmt::CompoundStmtClass: 1252 case Stmt::ContinueStmtClass: 1253 case Stmt::CXXForRangeStmtClass: 1254 case Stmt::DefaultStmtClass: 1255 case Stmt::DoStmtClass: 1256 case Stmt::ForStmtClass: 1257 case Stmt::GotoStmtClass: 1258 case Stmt::IfStmtClass: 1259 case Stmt::IndirectGotoStmtClass: 1260 case Stmt::LabelStmtClass: 1261 case Stmt::NoStmtClass: 1262 case Stmt::NullStmtClass: 1263 case Stmt::SwitchStmtClass: 1264 case Stmt::WhileStmtClass: 1265 case Expr::MSDependentExistsStmtClass: 1266 llvm_unreachable("Stmt should not be in analyzer evaluation loop"); 1267 1268 case Stmt::ObjCSubscriptRefExprClass: 1269 case Stmt::ObjCPropertyRefExprClass: 1270 llvm_unreachable("These are handled by PseudoObjectExpr"); 1271 1272 case Stmt::GNUNullExprClass: { 1273 // GNU __null is a pointer-width integer, not an actual pointer. 1274 ProgramStateRef state = Pred->getState(); 1275 state = state->BindExpr(S, Pred->getLocationContext(), 1276 svalBuilder.makeIntValWithPtrWidth(0, false)); 1277 Bldr.generateNode(S, Pred, state); 1278 break; 1279 } 1280 1281 case Stmt::ObjCAtSynchronizedStmtClass: 1282 Bldr.takeNodes(Pred); 1283 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst); 1284 Bldr.addNodes(Dst); 1285 break; 1286 1287 case Expr::ConstantExprClass: 1288 case Stmt::ExprWithCleanupsClass: 1289 // Handled due to fully linearised CFG. 1290 break; 1291 1292 case Stmt::CXXBindTemporaryExprClass: { 1293 Bldr.takeNodes(Pred); 1294 ExplodedNodeSet PreVisit; 1295 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 1296 ExplodedNodeSet Next; 1297 VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next); 1298 getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this); 1299 Bldr.addNodes(Dst); 1300 break; 1301 } 1302 1303 // Cases not handled yet; but will handle some day. 1304 case Stmt::DesignatedInitExprClass: 1305 case Stmt::DesignatedInitUpdateExprClass: 1306 case Stmt::ArrayInitLoopExprClass: 1307 case Stmt::ArrayInitIndexExprClass: 1308 case Stmt::ExtVectorElementExprClass: 1309 case Stmt::ImaginaryLiteralClass: 1310 case Stmt::ObjCAtCatchStmtClass: 1311 case Stmt::ObjCAtFinallyStmtClass: 1312 case Stmt::ObjCAtTryStmtClass: 1313 case Stmt::ObjCAutoreleasePoolStmtClass: 1314 case Stmt::ObjCEncodeExprClass: 1315 case Stmt::ObjCIsaExprClass: 1316 case Stmt::ObjCProtocolExprClass: 1317 case Stmt::ObjCSelectorExprClass: 1318 case Stmt::ParenListExprClass: 1319 case Stmt::ShuffleVectorExprClass: 1320 case Stmt::ConvertVectorExprClass: 1321 case Stmt::VAArgExprClass: 1322 case Stmt::CUDAKernelCallExprClass: 1323 case Stmt::OpaqueValueExprClass: 1324 case Stmt::AsTypeExprClass: 1325 // Fall through. 1326 1327 // Cases we intentionally don't evaluate, since they don't need 1328 // to be explicitly evaluated. 1329 case Stmt::PredefinedExprClass: 1330 case Stmt::AddrLabelExprClass: 1331 case Stmt::AttributedStmtClass: 1332 case Stmt::IntegerLiteralClass: 1333 case Stmt::FixedPointLiteralClass: 1334 case Stmt::CharacterLiteralClass: 1335 case Stmt::ImplicitValueInitExprClass: 1336 case Stmt::CXXScalarValueInitExprClass: 1337 case Stmt::CXXBoolLiteralExprClass: 1338 case Stmt::ObjCBoolLiteralExprClass: 1339 case Stmt::ObjCAvailabilityCheckExprClass: 1340 case Stmt::FloatingLiteralClass: 1341 case Stmt::NoInitExprClass: 1342 case Stmt::SizeOfPackExprClass: 1343 case Stmt::StringLiteralClass: 1344 case Stmt::SourceLocExprClass: 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()->getTerminatorStmt(); 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()->getTerminatorStmt(); 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().isStmtBranch() && 2012 "Other kinds of branches are handled separately!"); 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 four possible cases: 2628 // (1) We are binding to something that is not a memory region. 2629 // (2) We are binding to a MemRegion that does not have stack storage. 2630 // (3) We are binding to a top-level parameter region with a non-trivial 2631 // destructor. We won't see the destructor during analysis, but it's there. 2632 // (4) We are binding to a MemRegion with stack storage that the store 2633 // does not understand. 2634 ProgramStateRef 2635 ExprEngine::processPointerEscapedOnBind(ProgramStateRef State, SVal Loc, 2636 SVal Val, const LocationContext *LCtx) { 2637 2638 // Cases (1) and (2). 2639 const MemRegion *MR = Loc.getAsRegion(); 2640 if (!MR || !MR->hasStackStorage()) 2641 return escapeValue(State, Val, PSK_EscapeOnBind); 2642 2643 // Case (3). 2644 if (const auto *VR = dyn_cast<VarRegion>(MR->getBaseRegion())) 2645 if (VR->hasStackParametersStorage() && VR->getStackFrame()->inTopFrame()) 2646 if (const auto *RD = VR->getValueType()->getAsCXXRecordDecl()) 2647 if (!RD->hasTrivialDestructor()) 2648 return escapeValue(State, Val, PSK_EscapeOnBind); 2649 2650 // Case (4): in order to test that, generate a new state with the binding 2651 // added. If it is the same state, then it escapes (since the store cannot 2652 // represent the binding). 2653 // Do this only if we know that the store is not supposed to generate the 2654 // same state. 2655 SVal StoredVal = State->getSVal(MR); 2656 if (StoredVal != Val) 2657 if (State == (State->bindLoc(loc::MemRegionVal(MR), Val, LCtx))) 2658 return escapeValue(State, Val, PSK_EscapeOnBind); 2659 2660 return State; 2661 } 2662 2663 ProgramStateRef 2664 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State, 2665 const InvalidatedSymbols *Invalidated, 2666 ArrayRef<const MemRegion *> ExplicitRegions, 2667 const CallEvent *Call, 2668 RegionAndSymbolInvalidationTraits &ITraits) { 2669 if (!Invalidated || Invalidated->empty()) 2670 return State; 2671 2672 if (!Call) 2673 return getCheckerManager().runCheckersForPointerEscape(State, 2674 *Invalidated, 2675 nullptr, 2676 PSK_EscapeOther, 2677 &ITraits); 2678 2679 // If the symbols were invalidated by a call, we want to find out which ones 2680 // were invalidated directly due to being arguments to the call. 2681 InvalidatedSymbols SymbolsDirectlyInvalidated; 2682 for (const auto I : ExplicitRegions) { 2683 if (const SymbolicRegion *R = I->StripCasts()->getAs<SymbolicRegion>()) 2684 SymbolsDirectlyInvalidated.insert(R->getSymbol()); 2685 } 2686 2687 InvalidatedSymbols SymbolsIndirectlyInvalidated; 2688 for (const auto &sym : *Invalidated) { 2689 if (SymbolsDirectlyInvalidated.count(sym)) 2690 continue; 2691 SymbolsIndirectlyInvalidated.insert(sym); 2692 } 2693 2694 if (!SymbolsDirectlyInvalidated.empty()) 2695 State = getCheckerManager().runCheckersForPointerEscape(State, 2696 SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits); 2697 2698 // Notify about the symbols that get indirectly invalidated by the call. 2699 if (!SymbolsIndirectlyInvalidated.empty()) 2700 State = getCheckerManager().runCheckersForPointerEscape(State, 2701 SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits); 2702 2703 return State; 2704 } 2705 2706 /// evalBind - Handle the semantics of binding a value to a specific location. 2707 /// This method is used by evalStore and (soon) VisitDeclStmt, and others. 2708 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, 2709 ExplodedNode *Pred, 2710 SVal location, SVal Val, 2711 bool atDeclInit, const ProgramPoint *PP) { 2712 const LocationContext *LC = Pred->getLocationContext(); 2713 PostStmt PS(StoreE, LC); 2714 if (!PP) 2715 PP = &PS; 2716 2717 // Do a previsit of the bind. 2718 ExplodedNodeSet CheckedSet; 2719 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val, 2720 StoreE, *this, *PP); 2721 2722 StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx); 2723 2724 // If the location is not a 'Loc', it will already be handled by 2725 // the checkers. There is nothing left to do. 2726 if (!location.getAs<Loc>()) { 2727 const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr, 2728 /*tag*/nullptr); 2729 ProgramStateRef state = Pred->getState(); 2730 state = processPointerEscapedOnBind(state, location, Val, LC); 2731 Bldr.generateNode(L, state, Pred); 2732 return; 2733 } 2734 2735 for (const auto PredI : CheckedSet) { 2736 ProgramStateRef state = PredI->getState(); 2737 2738 state = processPointerEscapedOnBind(state, location, Val, LC); 2739 2740 // When binding the value, pass on the hint that this is a initialization. 2741 // For initializations, we do not need to inform clients of region 2742 // changes. 2743 state = state->bindLoc(location.castAs<Loc>(), 2744 Val, LC, /* notifyChanges = */ !atDeclInit); 2745 2746 const MemRegion *LocReg = nullptr; 2747 if (Optional<loc::MemRegionVal> LocRegVal = 2748 location.getAs<loc::MemRegionVal>()) { 2749 LocReg = LocRegVal->getRegion(); 2750 } 2751 2752 const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr); 2753 Bldr.generateNode(L, state, PredI); 2754 } 2755 } 2756 2757 /// evalStore - Handle the semantics of a store via an assignment. 2758 /// @param Dst The node set to store generated state nodes 2759 /// @param AssignE The assignment expression if the store happens in an 2760 /// assignment. 2761 /// @param LocationE The location expression that is stored to. 2762 /// @param state The current simulation state 2763 /// @param location The location to store the value 2764 /// @param Val The value to be stored 2765 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, 2766 const Expr *LocationE, 2767 ExplodedNode *Pred, 2768 ProgramStateRef state, SVal location, SVal Val, 2769 const ProgramPointTag *tag) { 2770 // Proceed with the store. We use AssignE as the anchor for the PostStore 2771 // ProgramPoint if it is non-NULL, and LocationE otherwise. 2772 const Expr *StoreE = AssignE ? AssignE : LocationE; 2773 2774 // Evaluate the location (checks for bad dereferences). 2775 ExplodedNodeSet Tmp; 2776 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, false); 2777 2778 if (Tmp.empty()) 2779 return; 2780 2781 if (location.isUndef()) 2782 return; 2783 2784 for (const auto I : Tmp) 2785 evalBind(Dst, StoreE, I, location, Val, false); 2786 } 2787 2788 void ExprEngine::evalLoad(ExplodedNodeSet &Dst, 2789 const Expr *NodeEx, 2790 const Expr *BoundEx, 2791 ExplodedNode *Pred, 2792 ProgramStateRef state, 2793 SVal location, 2794 const ProgramPointTag *tag, 2795 QualType LoadTy) { 2796 assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc."); 2797 assert(NodeEx); 2798 assert(BoundEx); 2799 // Evaluate the location (checks for bad dereferences). 2800 ExplodedNodeSet Tmp; 2801 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, true); 2802 if (Tmp.empty()) 2803 return; 2804 2805 StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx); 2806 if (location.isUndef()) 2807 return; 2808 2809 // Proceed with the load. 2810 for (const auto I : Tmp) { 2811 state = I->getState(); 2812 const LocationContext *LCtx = I->getLocationContext(); 2813 2814 SVal V = UnknownVal(); 2815 if (location.isValid()) { 2816 if (LoadTy.isNull()) 2817 LoadTy = BoundEx->getType(); 2818 V = state->getSVal(location.castAs<Loc>(), LoadTy); 2819 } 2820 2821 Bldr.generateNode(NodeEx, I, state->BindExpr(BoundEx, LCtx, V), tag, 2822 ProgramPoint::PostLoadKind); 2823 } 2824 } 2825 2826 void ExprEngine::evalLocation(ExplodedNodeSet &Dst, 2827 const Stmt *NodeEx, 2828 const Stmt *BoundEx, 2829 ExplodedNode *Pred, 2830 ProgramStateRef state, 2831 SVal location, 2832 bool isLoad) { 2833 StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx); 2834 // Early checks for performance reason. 2835 if (location.isUnknown()) { 2836 return; 2837 } 2838 2839 ExplodedNodeSet Src; 2840 BldrTop.takeNodes(Pred); 2841 StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx); 2842 if (Pred->getState() != state) { 2843 // Associate this new state with an ExplodedNode. 2844 // FIXME: If I pass null tag, the graph is incorrect, e.g for 2845 // int *p; 2846 // p = 0; 2847 // *p = 0xDEADBEEF; 2848 // "p = 0" is not noted as "Null pointer value stored to 'p'" but 2849 // instead "int *p" is noted as 2850 // "Variable 'p' initialized to a null pointer value" 2851 2852 static SimpleProgramPointTag tag(TagProviderName, "Location"); 2853 Bldr.generateNode(NodeEx, Pred, state, &tag); 2854 } 2855 ExplodedNodeSet Tmp; 2856 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad, 2857 NodeEx, BoundEx, *this); 2858 BldrTop.addNodes(Tmp); 2859 } 2860 2861 std::pair<const ProgramPointTag *, const ProgramPointTag*> 2862 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() { 2863 static SimpleProgramPointTag 2864 eagerlyAssumeBinOpBifurcationTrue(TagProviderName, 2865 "Eagerly Assume True"), 2866 eagerlyAssumeBinOpBifurcationFalse(TagProviderName, 2867 "Eagerly Assume False"); 2868 return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue, 2869 &eagerlyAssumeBinOpBifurcationFalse); 2870 } 2871 2872 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, 2873 ExplodedNodeSet &Src, 2874 const Expr *Ex) { 2875 StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx); 2876 2877 for (const auto Pred : Src) { 2878 // Test if the previous node was as the same expression. This can happen 2879 // when the expression fails to evaluate to anything meaningful and 2880 // (as an optimization) we don't generate a node. 2881 ProgramPoint P = Pred->getLocation(); 2882 if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) { 2883 continue; 2884 } 2885 2886 ProgramStateRef state = Pred->getState(); 2887 SVal V = state->getSVal(Ex, Pred->getLocationContext()); 2888 Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>(); 2889 if (SEV && SEV->isExpression()) { 2890 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags = 2891 geteagerlyAssumeBinOpBifurcationTags(); 2892 2893 ProgramStateRef StateTrue, StateFalse; 2894 std::tie(StateTrue, StateFalse) = state->assume(*SEV); 2895 2896 // First assume that the condition is true. 2897 if (StateTrue) { 2898 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType()); 2899 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val); 2900 Bldr.generateNode(Ex, Pred, StateTrue, tags.first); 2901 } 2902 2903 // Next, assume that the condition is false. 2904 if (StateFalse) { 2905 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType()); 2906 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val); 2907 Bldr.generateNode(Ex, Pred, StateFalse, tags.second); 2908 } 2909 } 2910 } 2911 } 2912 2913 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, 2914 ExplodedNodeSet &Dst) { 2915 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 2916 // We have processed both the inputs and the outputs. All of the outputs 2917 // should evaluate to Locs. Nuke all of their values. 2918 2919 // FIXME: Some day in the future it would be nice to allow a "plug-in" 2920 // which interprets the inline asm and stores proper results in the 2921 // outputs. 2922 2923 ProgramStateRef state = Pred->getState(); 2924 2925 for (const Expr *O : A->outputs()) { 2926 SVal X = state->getSVal(O, Pred->getLocationContext()); 2927 assert(!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef. 2928 2929 if (Optional<Loc> LV = X.getAs<Loc>()) 2930 state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext()); 2931 } 2932 2933 Bldr.generateNode(A, Pred, state); 2934 } 2935 2936 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred, 2937 ExplodedNodeSet &Dst) { 2938 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 2939 Bldr.generateNode(A, Pred, Pred->getState()); 2940 } 2941 2942 //===----------------------------------------------------------------------===// 2943 // Visualization. 2944 //===----------------------------------------------------------------------===// 2945 2946 #ifndef NDEBUG 2947 namespace llvm { 2948 2949 template<> 2950 struct DOTGraphTraits<ExplodedGraph*> : public DefaultDOTGraphTraits { 2951 DOTGraphTraits (bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 2952 2953 static bool nodeHasBugReport(const ExplodedNode *N) { 2954 BugReporter &BR = static_cast<ExprEngine &>( 2955 N->getState()->getStateManager().getOwningEngine()).getBugReporter(); 2956 2957 const auto EQClasses = 2958 llvm::make_range(BR.EQClasses_begin(), BR.EQClasses_end()); 2959 2960 for (const auto &EQ : EQClasses) { 2961 for (const BugReport &Report : EQ) { 2962 if (Report.getErrorNode() == N) 2963 return true; 2964 } 2965 } 2966 return false; 2967 } 2968 2969 /// \p PreCallback: callback before break. 2970 /// \p PostCallback: callback after break. 2971 /// \p Stop: stop iteration if returns {@code true} 2972 /// \return Whether {@code Stop} ever returned {@code true}. 2973 static bool traverseHiddenNodes( 2974 const ExplodedNode *N, 2975 llvm::function_ref<void(const ExplodedNode *)> PreCallback, 2976 llvm::function_ref<void(const ExplodedNode *)> PostCallback, 2977 llvm::function_ref<bool(const ExplodedNode *)> Stop) { 2978 const ExplodedNode *FirstHiddenNode = N; 2979 while (FirstHiddenNode->pred_size() == 1 && 2980 isNodeHidden(*FirstHiddenNode->pred_begin())) { 2981 FirstHiddenNode = *FirstHiddenNode->pred_begin(); 2982 } 2983 const ExplodedNode *OtherNode = FirstHiddenNode; 2984 while (true) { 2985 PreCallback(OtherNode); 2986 if (Stop(OtherNode)) 2987 return true; 2988 2989 if (OtherNode == N) 2990 break; 2991 PostCallback(OtherNode); 2992 2993 OtherNode = *OtherNode->succ_begin(); 2994 } 2995 return false; 2996 } 2997 2998 static std::string getNodeAttributes(const ExplodedNode *N, 2999 ExplodedGraph *) { 3000 SmallVector<StringRef, 10> Out; 3001 auto Noop = [](const ExplodedNode*){}; 3002 if (traverseHiddenNodes(N, Noop, Noop, &nodeHasBugReport)) { 3003 Out.push_back("style=filled"); 3004 Out.push_back("fillcolor=red"); 3005 } 3006 3007 if (traverseHiddenNodes(N, Noop, Noop, 3008 [](const ExplodedNode *C) { return C->isSink(); })) 3009 Out.push_back("color=blue"); 3010 return llvm::join(Out, ","); 3011 } 3012 3013 static bool isNodeHidden(const ExplodedNode *N) { 3014 return N->isTrivial(); 3015 } 3016 3017 static std::string getNodeLabel(const ExplodedNode *N, ExplodedGraph *G){ 3018 std::string sbuf; 3019 llvm::raw_string_ostream Out(sbuf); 3020 3021 ProgramStateRef State = N->getState(); 3022 3023 // Dump program point for all the previously skipped nodes. 3024 traverseHiddenNodes( 3025 N, 3026 [&](const ExplodedNode *OtherNode) { 3027 OtherNode->getLocation().print(/*CR=*/"\\l", Out); 3028 if (const ProgramPointTag *Tag = OtherNode->getLocation().getTag()) 3029 Out << "\\lTag:" << Tag->getTagDescription(); 3030 if (N->isSink()) 3031 Out << "\\lNode is sink\\l"; 3032 if (nodeHasBugReport(N)) 3033 Out << "\\lBug report attached\\l"; 3034 }, 3035 [&](const ExplodedNode *) { Out << "\\l--------\\l"; }, 3036 [&](const ExplodedNode *) { return false; }); 3037 3038 Out << "\\l\\|"; 3039 3040 Out << "StateID: ST" << State->getID() << ", NodeID: N" << N->getID(G) 3041 << " <" << (const void *)N << ">\\|"; 3042 3043 bool SameAsAllPredecessors = 3044 std::all_of(N->pred_begin(), N->pred_end(), [&](const ExplodedNode *P) { 3045 return P->getState() == State; 3046 }); 3047 if (!SameAsAllPredecessors) 3048 State->printDOT(Out, N->getLocationContext()); 3049 return Out.str(); 3050 } 3051 }; 3052 3053 } // namespace llvm 3054 #endif 3055 3056 void ExprEngine::ViewGraph(bool trim) { 3057 #ifndef NDEBUG 3058 std::string Filename = DumpGraph(trim); 3059 llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT); 3060 #endif 3061 llvm::errs() << "Warning: viewing graph requires assertions" << "\n"; 3062 } 3063 3064 3065 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) { 3066 #ifndef NDEBUG 3067 std::string Filename = DumpGraph(Nodes); 3068 llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT); 3069 #endif 3070 llvm::errs() << "Warning: viewing graph requires assertions" << "\n"; 3071 } 3072 3073 std::string ExprEngine::DumpGraph(bool trim, StringRef Filename) { 3074 #ifndef NDEBUG 3075 if (trim) { 3076 std::vector<const ExplodedNode *> Src; 3077 3078 // Iterate through the reports and get their nodes. 3079 for (BugReporter::EQClasses_iterator 3080 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) { 3081 const auto *N = const_cast<ExplodedNode *>(EI->begin()->getErrorNode()); 3082 if (N) Src.push_back(N); 3083 } 3084 return DumpGraph(Src, Filename); 3085 } else { 3086 return llvm::WriteGraph(&G, "ExprEngine", /*ShortNames=*/false, 3087 /*Title=*/"Exploded Graph", /*Filename=*/Filename); 3088 } 3089 #endif 3090 llvm::errs() << "Warning: dumping graph requires assertions" << "\n"; 3091 return ""; 3092 } 3093 3094 std::string ExprEngine::DumpGraph(ArrayRef<const ExplodedNode*> Nodes, 3095 StringRef Filename) { 3096 #ifndef NDEBUG 3097 std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes)); 3098 3099 if (!TrimmedG.get()) { 3100 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n"; 3101 } else { 3102 return llvm::WriteGraph(TrimmedG.get(), "TrimmedExprEngine", 3103 /*ShortNames=*/false, 3104 /*Title=*/"Trimmed Exploded Graph", 3105 /*Filename=*/Filename); 3106 } 3107 #endif 3108 llvm::errs() << "Warning: dumping graph requires assertions" << "\n"; 3109 return ""; 3110 } 3111 3112 void *ProgramStateTrait<ReplayWithoutInlining>::GDMIndex() { 3113 static int index = 0; 3114 return &index; 3115 } 3116