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