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