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 // A tag to track convenience transitions, which can be removed at cleanup. 1076 static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node"); 1077 // Call checkers with the non-cleaned state so that they could query the 1078 // values of the soon to be dead symbols. 1079 ExplodedNodeSet CheckedSet; 1080 getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper, 1081 DiagnosticStmt, *this, K); 1082 1083 // For each node in CheckedSet, generate CleanedNodes that have the 1084 // environment, the store, and the constraints cleaned up but have the 1085 // user-supplied states as the predecessors. 1086 StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx); 1087 for (const auto I : CheckedSet) { 1088 ProgramStateRef CheckerState = I->getState(); 1089 1090 // The constraint manager has not been cleaned up yet, so clean up now. 1091 CheckerState = 1092 getConstraintManager().removeDeadBindings(CheckerState, SymReaper); 1093 1094 assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) && 1095 "Checkers are not allowed to modify the Environment as a part of " 1096 "checkDeadSymbols processing."); 1097 assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) && 1098 "Checkers are not allowed to modify the Store as a part of " 1099 "checkDeadSymbols processing."); 1100 1101 // Create a state based on CleanedState with CheckerState GDM and 1102 // generate a transition to that state. 1103 ProgramStateRef CleanedCheckerSt = 1104 StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState); 1105 Bldr.generateNode(DiagnosticStmt, I, CleanedCheckerSt, &cleanupTag, K); 1106 } 1107 } 1108 1109 void ExprEngine::ProcessStmt(const Stmt *currStmt, ExplodedNode *Pred) { 1110 // Reclaim any unnecessary nodes in the ExplodedGraph. 1111 G.reclaimRecentlyAllocatedNodes(); 1112 1113 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 1114 currStmt->getBeginLoc(), 1115 "Error evaluating statement"); 1116 1117 // Remove dead bindings and symbols. 1118 ExplodedNodeSet CleanedStates; 1119 if (shouldRemoveDeadBindings(AMgr, currStmt, Pred, 1120 Pred->getLocationContext())) { 1121 removeDead(Pred, CleanedStates, currStmt, 1122 Pred->getLocationContext()); 1123 } else 1124 CleanedStates.Add(Pred); 1125 1126 // Visit the statement. 1127 ExplodedNodeSet Dst; 1128 for (const auto I : CleanedStates) { 1129 ExplodedNodeSet DstI; 1130 // Visit the statement. 1131 Visit(currStmt, I, DstI); 1132 Dst.insert(DstI); 1133 } 1134 1135 // Enqueue the new nodes onto the work list. 1136 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 1137 } 1138 1139 void ExprEngine::ProcessLoopExit(const Stmt* S, ExplodedNode *Pred) { 1140 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 1141 S->getBeginLoc(), 1142 "Error evaluating end of the loop"); 1143 ExplodedNodeSet Dst; 1144 Dst.Add(Pred); 1145 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1146 ProgramStateRef NewState = Pred->getState(); 1147 1148 if(AMgr.options.ShouldUnrollLoops) 1149 NewState = processLoopEnd(S, NewState); 1150 1151 LoopExit PP(S, Pred->getLocationContext()); 1152 Bldr.generateNode(PP, NewState, Pred); 1153 // Enqueue the new nodes onto the work list. 1154 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 1155 } 1156 1157 void ExprEngine::ProcessInitializer(const CFGInitializer CFGInit, 1158 ExplodedNode *Pred) { 1159 const CXXCtorInitializer *BMI = CFGInit.getInitializer(); 1160 const Expr *Init = BMI->getInit()->IgnoreImplicit(); 1161 const LocationContext *LC = Pred->getLocationContext(); 1162 1163 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 1164 BMI->getSourceLocation(), 1165 "Error evaluating initializer"); 1166 1167 // We don't clean up dead bindings here. 1168 const auto *stackFrame = cast<StackFrameContext>(Pred->getLocationContext()); 1169 const auto *decl = cast<CXXConstructorDecl>(stackFrame->getDecl()); 1170 1171 ProgramStateRef State = Pred->getState(); 1172 SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame)); 1173 1174 ExplodedNodeSet Tmp; 1175 SVal FieldLoc; 1176 1177 // Evaluate the initializer, if necessary 1178 if (BMI->isAnyMemberInitializer()) { 1179 // Constructors build the object directly in the field, 1180 // but non-objects must be copied in from the initializer. 1181 if (getObjectUnderConstruction(State, BMI, LC)) { 1182 // The field was directly constructed, so there is no need to bind. 1183 // But we still need to stop tracking the object under construction. 1184 State = finishObjectConstruction(State, BMI, LC); 1185 NodeBuilder Bldr(Pred, Tmp, *currBldrCtx); 1186 PostStore PS(Init, LC, /*Loc*/ nullptr, /*tag*/ nullptr); 1187 Bldr.generateNode(PS, State, Pred); 1188 } else { 1189 const ValueDecl *Field; 1190 if (BMI->isIndirectMemberInitializer()) { 1191 Field = BMI->getIndirectMember(); 1192 FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal); 1193 } else { 1194 Field = BMI->getMember(); 1195 FieldLoc = State->getLValue(BMI->getMember(), thisVal); 1196 } 1197 1198 SVal InitVal; 1199 if (Init->getType()->isArrayType()) { 1200 // Handle arrays of trivial type. We can represent this with a 1201 // primitive load/copy from the base array region. 1202 const ArraySubscriptExpr *ASE; 1203 while ((ASE = dyn_cast<ArraySubscriptExpr>(Init))) 1204 Init = ASE->getBase()->IgnoreImplicit(); 1205 1206 SVal LValue = State->getSVal(Init, stackFrame); 1207 if (!Field->getType()->isReferenceType()) 1208 if (std::optional<Loc> LValueLoc = LValue.getAs<Loc>()) 1209 InitVal = State->getSVal(*LValueLoc); 1210 1211 // If we fail to get the value for some reason, use a symbolic value. 1212 if (InitVal.isUnknownOrUndef()) { 1213 SValBuilder &SVB = getSValBuilder(); 1214 InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame, 1215 Field->getType(), 1216 currBldrCtx->blockCount()); 1217 } 1218 } else { 1219 InitVal = State->getSVal(BMI->getInit(), stackFrame); 1220 } 1221 1222 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame); 1223 evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP); 1224 } 1225 } else if (BMI->isBaseInitializer() && isa<InitListExpr>(Init)) { 1226 // When the base class is initialized with an initialization list and the 1227 // base class does not have a ctor, there will not be a CXXConstructExpr to 1228 // initialize the base region. Hence, we need to make the bind for it. 1229 SVal BaseLoc = getStoreManager().evalDerivedToBase( 1230 thisVal, QualType(BMI->getBaseClass(), 0), BMI->isBaseVirtual()); 1231 SVal InitVal = State->getSVal(Init, stackFrame); 1232 evalBind(Tmp, Init, Pred, BaseLoc, InitVal, /*isInit=*/true); 1233 } else { 1234 assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer()); 1235 Tmp.insert(Pred); 1236 // We already did all the work when visiting the CXXConstructExpr. 1237 } 1238 1239 // Construct PostInitializer nodes whether the state changed or not, 1240 // so that the diagnostics don't get confused. 1241 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame); 1242 ExplodedNodeSet Dst; 1243 NodeBuilder Bldr(Tmp, Dst, *currBldrCtx); 1244 for (const auto I : Tmp) { 1245 ProgramStateRef State = I->getState(); 1246 Bldr.generateNode(PP, State, I); 1247 } 1248 1249 // Enqueue the new nodes onto the work list. 1250 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 1251 } 1252 1253 std::pair<ProgramStateRef, uint64_t> 1254 ExprEngine::prepareStateForArrayDestruction(const ProgramStateRef State, 1255 const MemRegion *Region, 1256 const QualType &ElementTy, 1257 const LocationContext *LCtx, 1258 SVal *ElementCountVal) { 1259 assert(Region != nullptr && "Not-null region expected"); 1260 1261 QualType Ty = ElementTy.getDesugaredType(getContext()); 1262 while (const auto *NTy = dyn_cast<ArrayType>(Ty)) 1263 Ty = NTy->getElementType().getDesugaredType(getContext()); 1264 1265 auto ElementCount = getDynamicElementCount(State, Region, svalBuilder, Ty); 1266 1267 if (ElementCountVal) 1268 *ElementCountVal = ElementCount; 1269 1270 // Note: the destructors are called in reverse order. 1271 unsigned Idx = 0; 1272 if (auto OptionalIdx = getPendingArrayDestruction(State, LCtx)) { 1273 Idx = *OptionalIdx; 1274 } else { 1275 // The element count is either unknown, or an SVal that's not an integer. 1276 if (!ElementCount.isConstant()) 1277 return {State, 0}; 1278 1279 Idx = ElementCount.getAsInteger()->getLimitedValue(); 1280 } 1281 1282 if (Idx == 0) 1283 return {State, 0}; 1284 1285 --Idx; 1286 1287 return {setPendingArrayDestruction(State, LCtx, Idx), Idx}; 1288 } 1289 1290 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D, 1291 ExplodedNode *Pred) { 1292 ExplodedNodeSet Dst; 1293 switch (D.getKind()) { 1294 case CFGElement::AutomaticObjectDtor: 1295 ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst); 1296 break; 1297 case CFGElement::BaseDtor: 1298 ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst); 1299 break; 1300 case CFGElement::MemberDtor: 1301 ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst); 1302 break; 1303 case CFGElement::TemporaryDtor: 1304 ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst); 1305 break; 1306 case CFGElement::DeleteDtor: 1307 ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst); 1308 break; 1309 default: 1310 llvm_unreachable("Unexpected dtor kind."); 1311 } 1312 1313 // Enqueue the new nodes onto the work list. 1314 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 1315 } 1316 1317 void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE, 1318 ExplodedNode *Pred) { 1319 ExplodedNodeSet Dst; 1320 AnalysisManager &AMgr = getAnalysisManager(); 1321 AnalyzerOptions &Opts = AMgr.options; 1322 // TODO: We're not evaluating allocators for all cases just yet as 1323 // we're not handling the return value correctly, which causes false 1324 // positives when the alpha.cplusplus.NewDeleteLeaks check is on. 1325 if (Opts.MayInlineCXXAllocator) 1326 VisitCXXNewAllocatorCall(NE, Pred, Dst); 1327 else { 1328 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1329 const LocationContext *LCtx = Pred->getLocationContext(); 1330 PostImplicitCall PP(NE->getOperatorNew(), NE->getBeginLoc(), LCtx, 1331 getCFGElementRef()); 1332 Bldr.generateNode(PP, Pred->getState(), Pred); 1333 } 1334 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 1335 } 1336 1337 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor, 1338 ExplodedNode *Pred, 1339 ExplodedNodeSet &Dst) { 1340 const auto *DtorDecl = Dtor.getDestructorDecl(getContext()); 1341 const VarDecl *varDecl = Dtor.getVarDecl(); 1342 QualType varType = varDecl->getType(); 1343 1344 ProgramStateRef state = Pred->getState(); 1345 const LocationContext *LCtx = Pred->getLocationContext(); 1346 1347 SVal dest = state->getLValue(varDecl, LCtx); 1348 const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion(); 1349 1350 if (varType->isReferenceType()) { 1351 const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion(); 1352 if (!ValueRegion) { 1353 // FIXME: This should not happen. The language guarantees a presence 1354 // of a valid initializer here, so the reference shall not be undefined. 1355 // It seems that we're calling destructors over variables that 1356 // were not initialized yet. 1357 return; 1358 } 1359 Region = ValueRegion->getBaseRegion(); 1360 varType = cast<TypedValueRegion>(Region)->getValueType(); 1361 } 1362 1363 unsigned Idx = 0; 1364 if (isa<ArrayType>(varType)) { 1365 SVal ElementCount; 1366 std::tie(state, Idx) = prepareStateForArrayDestruction( 1367 state, Region, varType, LCtx, &ElementCount); 1368 1369 if (ElementCount.isConstant()) { 1370 uint64_t ArrayLength = ElementCount.getAsInteger()->getLimitedValue(); 1371 assert(ArrayLength && 1372 "An automatic dtor for a 0 length array shouldn't be triggered!"); 1373 1374 // Still handle this case if we don't have assertions enabled. 1375 if (!ArrayLength) { 1376 static SimpleProgramPointTag PT( 1377 "ExprEngine", "Skipping automatic 0 length array destruction, " 1378 "which shouldn't be in the CFG."); 1379 PostImplicitCall PP(DtorDecl, varDecl->getLocation(), LCtx, 1380 getCFGElementRef(), &PT); 1381 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1382 Bldr.generateSink(PP, Pred->getState(), Pred); 1383 return; 1384 } 1385 } 1386 } 1387 1388 EvalCallOptions CallOpts; 1389 Region = makeElementRegion(state, loc::MemRegionVal(Region), varType, 1390 CallOpts.IsArrayCtorOrDtor, Idx) 1391 .getAsRegion(); 1392 1393 NodeBuilder Bldr(Pred, Dst, getBuilderContext()); 1394 1395 static SimpleProgramPointTag PT("ExprEngine", 1396 "Prepare for object destruction"); 1397 PreImplicitCall PP(DtorDecl, varDecl->getLocation(), LCtx, getCFGElementRef(), 1398 &PT); 1399 Pred = Bldr.generateNode(PP, state, Pred); 1400 1401 if (!Pred) 1402 return; 1403 Bldr.takeNodes(Pred); 1404 1405 VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), 1406 /*IsBase=*/false, Pred, Dst, CallOpts); 1407 } 1408 1409 void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor, 1410 ExplodedNode *Pred, 1411 ExplodedNodeSet &Dst) { 1412 ProgramStateRef State = Pred->getState(); 1413 const LocationContext *LCtx = Pred->getLocationContext(); 1414 const CXXDeleteExpr *DE = Dtor.getDeleteExpr(); 1415 const Stmt *Arg = DE->getArgument(); 1416 QualType DTy = DE->getDestroyedType(); 1417 SVal ArgVal = State->getSVal(Arg, LCtx); 1418 1419 // If the argument to delete is known to be a null value, 1420 // don't run destructor. 1421 if (State->isNull(ArgVal).isConstrainedTrue()) { 1422 QualType BTy = getContext().getBaseElementType(DTy); 1423 const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl(); 1424 const CXXDestructorDecl *Dtor = RD->getDestructor(); 1425 1426 PostImplicitCall PP(Dtor, DE->getBeginLoc(), LCtx, getCFGElementRef()); 1427 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1428 Bldr.generateNode(PP, Pred->getState(), Pred); 1429 return; 1430 } 1431 1432 auto getDtorDecl = [](const QualType &DTy) { 1433 const CXXRecordDecl *RD = DTy->getAsCXXRecordDecl(); 1434 return RD->getDestructor(); 1435 }; 1436 1437 unsigned Idx = 0; 1438 EvalCallOptions CallOpts; 1439 const MemRegion *ArgR = ArgVal.getAsRegion(); 1440 1441 if (DE->isArrayForm()) { 1442 CallOpts.IsArrayCtorOrDtor = true; 1443 // Yes, it may even be a multi-dimensional array. 1444 while (const auto *AT = getContext().getAsArrayType(DTy)) 1445 DTy = AT->getElementType(); 1446 1447 if (ArgR) { 1448 SVal ElementCount; 1449 std::tie(State, Idx) = prepareStateForArrayDestruction( 1450 State, ArgR, DTy, LCtx, &ElementCount); 1451 1452 // If we're about to destruct a 0 length array, don't run any of the 1453 // destructors. 1454 if (ElementCount.isConstant() && 1455 ElementCount.getAsInteger()->getLimitedValue() == 0) { 1456 1457 static SimpleProgramPointTag PT( 1458 "ExprEngine", "Skipping 0 length array delete destruction"); 1459 PostImplicitCall PP(getDtorDecl(DTy), DE->getBeginLoc(), LCtx, 1460 getCFGElementRef(), &PT); 1461 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1462 Bldr.generateNode(PP, Pred->getState(), Pred); 1463 return; 1464 } 1465 1466 ArgR = State->getLValue(DTy, svalBuilder.makeArrayIndex(Idx), ArgVal) 1467 .getAsRegion(); 1468 } 1469 } 1470 1471 NodeBuilder Bldr(Pred, Dst, getBuilderContext()); 1472 static SimpleProgramPointTag PT("ExprEngine", 1473 "Prepare for object destruction"); 1474 PreImplicitCall PP(getDtorDecl(DTy), DE->getBeginLoc(), LCtx, 1475 getCFGElementRef(), &PT); 1476 Pred = Bldr.generateNode(PP, State, Pred); 1477 1478 if (!Pred) 1479 return; 1480 Bldr.takeNodes(Pred); 1481 1482 VisitCXXDestructor(DTy, ArgR, DE, /*IsBase=*/false, Pred, Dst, CallOpts); 1483 } 1484 1485 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D, 1486 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 1487 const LocationContext *LCtx = Pred->getLocationContext(); 1488 1489 const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl()); 1490 Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor, 1491 LCtx->getStackFrame()); 1492 SVal ThisVal = Pred->getState()->getSVal(ThisPtr); 1493 1494 // Create the base object region. 1495 const CXXBaseSpecifier *Base = D.getBaseSpecifier(); 1496 QualType BaseTy = Base->getType(); 1497 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy, 1498 Base->isVirtual()); 1499 1500 EvalCallOptions CallOpts; 1501 VisitCXXDestructor(BaseTy, BaseVal.getAsRegion(), CurDtor->getBody(), 1502 /*IsBase=*/true, Pred, Dst, CallOpts); 1503 } 1504 1505 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D, 1506 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 1507 const auto *DtorDecl = D.getDestructorDecl(getContext()); 1508 const FieldDecl *Member = D.getFieldDecl(); 1509 QualType T = Member->getType(); 1510 ProgramStateRef State = Pred->getState(); 1511 const LocationContext *LCtx = Pred->getLocationContext(); 1512 1513 const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl()); 1514 Loc ThisStorageLoc = 1515 getSValBuilder().getCXXThis(CurDtor, LCtx->getStackFrame()); 1516 Loc ThisLoc = State->getSVal(ThisStorageLoc).castAs<Loc>(); 1517 SVal FieldVal = State->getLValue(Member, ThisLoc); 1518 1519 unsigned Idx = 0; 1520 if (isa<ArrayType>(T)) { 1521 SVal ElementCount; 1522 std::tie(State, Idx) = prepareStateForArrayDestruction( 1523 State, FieldVal.getAsRegion(), T, LCtx, &ElementCount); 1524 1525 if (ElementCount.isConstant()) { 1526 uint64_t ArrayLength = ElementCount.getAsInteger()->getLimitedValue(); 1527 assert(ArrayLength && 1528 "A member dtor for a 0 length array shouldn't be triggered!"); 1529 1530 // Still handle this case if we don't have assertions enabled. 1531 if (!ArrayLength) { 1532 static SimpleProgramPointTag PT( 1533 "ExprEngine", "Skipping member 0 length array destruction, which " 1534 "shouldn't be in the CFG."); 1535 PostImplicitCall PP(DtorDecl, Member->getLocation(), LCtx, 1536 getCFGElementRef(), &PT); 1537 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1538 Bldr.generateSink(PP, Pred->getState(), Pred); 1539 return; 1540 } 1541 } 1542 } 1543 1544 EvalCallOptions CallOpts; 1545 FieldVal = 1546 makeElementRegion(State, FieldVal, T, CallOpts.IsArrayCtorOrDtor, Idx); 1547 1548 NodeBuilder Bldr(Pred, Dst, getBuilderContext()); 1549 1550 static SimpleProgramPointTag PT("ExprEngine", 1551 "Prepare for object destruction"); 1552 PreImplicitCall PP(DtorDecl, Member->getLocation(), LCtx, getCFGElementRef(), 1553 &PT); 1554 Pred = Bldr.generateNode(PP, State, Pred); 1555 1556 if (!Pred) 1557 return; 1558 Bldr.takeNodes(Pred); 1559 1560 VisitCXXDestructor(T, FieldVal.getAsRegion(), CurDtor->getBody(), 1561 /*IsBase=*/false, Pred, Dst, CallOpts); 1562 } 1563 1564 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D, 1565 ExplodedNode *Pred, 1566 ExplodedNodeSet &Dst) { 1567 const CXXBindTemporaryExpr *BTE = D.getBindTemporaryExpr(); 1568 ProgramStateRef State = Pred->getState(); 1569 const LocationContext *LC = Pred->getLocationContext(); 1570 const MemRegion *MR = nullptr; 1571 1572 if (std::optional<SVal> V = getObjectUnderConstruction( 1573 State, D.getBindTemporaryExpr(), Pred->getLocationContext())) { 1574 // FIXME: Currently we insert temporary destructors for default parameters, 1575 // but we don't insert the constructors, so the entry in 1576 // ObjectsUnderConstruction may be missing. 1577 State = finishObjectConstruction(State, D.getBindTemporaryExpr(), 1578 Pred->getLocationContext()); 1579 MR = V->getAsRegion(); 1580 } 1581 1582 // If copy elision has occurred, and the constructor corresponding to the 1583 // destructor was elided, we need to skip the destructor as well. 1584 if (isDestructorElided(State, BTE, LC)) { 1585 State = cleanupElidedDestructor(State, BTE, LC); 1586 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1587 PostImplicitCall PP(D.getDestructorDecl(getContext()), 1588 D.getBindTemporaryExpr()->getBeginLoc(), 1589 Pred->getLocationContext(), getCFGElementRef()); 1590 Bldr.generateNode(PP, State, Pred); 1591 return; 1592 } 1593 1594 ExplodedNodeSet CleanDtorState; 1595 StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx); 1596 StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State); 1597 1598 QualType T = D.getBindTemporaryExpr()->getSubExpr()->getType(); 1599 // FIXME: Currently CleanDtorState can be empty here due to temporaries being 1600 // bound to default parameters. 1601 assert(CleanDtorState.size() <= 1); 1602 ExplodedNode *CleanPred = 1603 CleanDtorState.empty() ? Pred : *CleanDtorState.begin(); 1604 1605 EvalCallOptions CallOpts; 1606 CallOpts.IsTemporaryCtorOrDtor = true; 1607 if (!MR) { 1608 // FIXME: If we have no MR, we still need to unwrap the array to avoid 1609 // destroying the whole array at once. 1610 // 1611 // For this case there is no universal solution as there is no way to 1612 // directly create an array of temporary objects. There are some expressions 1613 // however which can create temporary objects and have an array type. 1614 // 1615 // E.g.: std::initializer_list<S>{S(), S()}; 1616 // 1617 // The expression above has a type of 'const struct S[2]' but it's a single 1618 // 'std::initializer_list<>'. The destructors of the 2 temporary 'S()' 1619 // objects will be called anyway, because they are 2 separate objects in 2 1620 // separate clusters, i.e.: not an array. 1621 // 1622 // Now the 'std::initializer_list<>' is not an array either even though it 1623 // has the type of an array. The point is, we only want to invoke the 1624 // destructor for the initializer list once not twice or so. 1625 while (const ArrayType *AT = getContext().getAsArrayType(T)) { 1626 T = AT->getElementType(); 1627 1628 // FIXME: Enable this flag once we handle this case properly. 1629 // CallOpts.IsArrayCtorOrDtor = true; 1630 } 1631 } else { 1632 // FIXME: We'd eventually need to makeElementRegion() trick here, 1633 // but for now we don't have the respective construction contexts, 1634 // so MR would always be null in this case. Do nothing for now. 1635 } 1636 VisitCXXDestructor(T, MR, D.getBindTemporaryExpr(), 1637 /*IsBase=*/false, CleanPred, Dst, CallOpts); 1638 } 1639 1640 void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE, 1641 NodeBuilderContext &BldCtx, 1642 ExplodedNode *Pred, 1643 ExplodedNodeSet &Dst, 1644 const CFGBlock *DstT, 1645 const CFGBlock *DstF) { 1646 BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF); 1647 ProgramStateRef State = Pred->getState(); 1648 const LocationContext *LC = Pred->getLocationContext(); 1649 if (getObjectUnderConstruction(State, BTE, LC)) { 1650 TempDtorBuilder.markInfeasible(false); 1651 TempDtorBuilder.generateNode(State, true, Pred); 1652 } else { 1653 TempDtorBuilder.markInfeasible(true); 1654 TempDtorBuilder.generateNode(State, false, Pred); 1655 } 1656 } 1657 1658 void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE, 1659 ExplodedNodeSet &PreVisit, 1660 ExplodedNodeSet &Dst) { 1661 // This is a fallback solution in case we didn't have a construction 1662 // context when we were constructing the temporary. Otherwise the map should 1663 // have been populated there. 1664 if (!getAnalysisManager().options.ShouldIncludeTemporaryDtorsInCFG) { 1665 // In case we don't have temporary destructors in the CFG, do not mark 1666 // the initialization - we would otherwise never clean it up. 1667 Dst = PreVisit; 1668 return; 1669 } 1670 StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx); 1671 for (ExplodedNode *Node : PreVisit) { 1672 ProgramStateRef State = Node->getState(); 1673 const LocationContext *LC = Node->getLocationContext(); 1674 if (!getObjectUnderConstruction(State, BTE, LC)) { 1675 // FIXME: Currently the state might also already contain the marker due to 1676 // incorrect handling of temporaries bound to default parameters; for 1677 // those, we currently skip the CXXBindTemporaryExpr but rely on adding 1678 // temporary destructor nodes. 1679 State = addObjectUnderConstruction(State, BTE, LC, UnknownVal()); 1680 } 1681 StmtBldr.generateNode(BTE, Node, State); 1682 } 1683 } 1684 1685 ProgramStateRef ExprEngine::escapeValues(ProgramStateRef State, 1686 ArrayRef<SVal> Vs, 1687 PointerEscapeKind K, 1688 const CallEvent *Call) const { 1689 class CollectReachableSymbolsCallback final : public SymbolVisitor { 1690 InvalidatedSymbols &Symbols; 1691 1692 public: 1693 explicit CollectReachableSymbolsCallback(InvalidatedSymbols &Symbols) 1694 : Symbols(Symbols) {} 1695 1696 const InvalidatedSymbols &getSymbols() const { return Symbols; } 1697 1698 bool VisitSymbol(SymbolRef Sym) override { 1699 Symbols.insert(Sym); 1700 return true; 1701 } 1702 }; 1703 InvalidatedSymbols Symbols; 1704 CollectReachableSymbolsCallback CallBack(Symbols); 1705 for (SVal V : Vs) 1706 State->scanReachableSymbols(V, CallBack); 1707 1708 return getCheckerManager().runCheckersForPointerEscape( 1709 State, CallBack.getSymbols(), Call, K, nullptr); 1710 } 1711 1712 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred, 1713 ExplodedNodeSet &DstTop) { 1714 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 1715 S->getBeginLoc(), "Error evaluating statement"); 1716 ExplodedNodeSet Dst; 1717 StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx); 1718 1719 assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens()); 1720 1721 switch (S->getStmtClass()) { 1722 // C++, OpenMP and ARC stuff we don't support yet. 1723 case Stmt::CXXDependentScopeMemberExprClass: 1724 case Stmt::CXXTryStmtClass: 1725 case Stmt::CXXTypeidExprClass: 1726 case Stmt::CXXUuidofExprClass: 1727 case Stmt::CXXFoldExprClass: 1728 case Stmt::MSPropertyRefExprClass: 1729 case Stmt::MSPropertySubscriptExprClass: 1730 case Stmt::CXXUnresolvedConstructExprClass: 1731 case Stmt::DependentScopeDeclRefExprClass: 1732 case Stmt::ArrayTypeTraitExprClass: 1733 case Stmt::ExpressionTraitExprClass: 1734 case Stmt::UnresolvedLookupExprClass: 1735 case Stmt::UnresolvedMemberExprClass: 1736 case Stmt::TypoExprClass: 1737 case Stmt::RecoveryExprClass: 1738 case Stmt::CXXNoexceptExprClass: 1739 case Stmt::PackExpansionExprClass: 1740 case Stmt::PackIndexingExprClass: 1741 case Stmt::SubstNonTypeTemplateParmPackExprClass: 1742 case Stmt::FunctionParmPackExprClass: 1743 case Stmt::CoroutineBodyStmtClass: 1744 case Stmt::CoawaitExprClass: 1745 case Stmt::DependentCoawaitExprClass: 1746 case Stmt::CoreturnStmtClass: 1747 case Stmt::CoyieldExprClass: 1748 case Stmt::SEHTryStmtClass: 1749 case Stmt::SEHExceptStmtClass: 1750 case Stmt::SEHLeaveStmtClass: 1751 case Stmt::SEHFinallyStmtClass: 1752 case Stmt::OMPCanonicalLoopClass: 1753 case Stmt::OMPParallelDirectiveClass: 1754 case Stmt::OMPSimdDirectiveClass: 1755 case Stmt::OMPForDirectiveClass: 1756 case Stmt::OMPForSimdDirectiveClass: 1757 case Stmt::OMPSectionsDirectiveClass: 1758 case Stmt::OMPSectionDirectiveClass: 1759 case Stmt::OMPScopeDirectiveClass: 1760 case Stmt::OMPSingleDirectiveClass: 1761 case Stmt::OMPMasterDirectiveClass: 1762 case Stmt::OMPCriticalDirectiveClass: 1763 case Stmt::OMPParallelForDirectiveClass: 1764 case Stmt::OMPParallelForSimdDirectiveClass: 1765 case Stmt::OMPParallelSectionsDirectiveClass: 1766 case Stmt::OMPParallelMasterDirectiveClass: 1767 case Stmt::OMPParallelMaskedDirectiveClass: 1768 case Stmt::OMPTaskDirectiveClass: 1769 case Stmt::OMPTaskyieldDirectiveClass: 1770 case Stmt::OMPBarrierDirectiveClass: 1771 case Stmt::OMPTaskwaitDirectiveClass: 1772 case Stmt::OMPErrorDirectiveClass: 1773 case Stmt::OMPTaskgroupDirectiveClass: 1774 case Stmt::OMPFlushDirectiveClass: 1775 case Stmt::OMPDepobjDirectiveClass: 1776 case Stmt::OMPScanDirectiveClass: 1777 case Stmt::OMPOrderedDirectiveClass: 1778 case Stmt::OMPAtomicDirectiveClass: 1779 case Stmt::OMPTargetDirectiveClass: 1780 case Stmt::OMPTargetDataDirectiveClass: 1781 case Stmt::OMPTargetEnterDataDirectiveClass: 1782 case Stmt::OMPTargetExitDataDirectiveClass: 1783 case Stmt::OMPTargetParallelDirectiveClass: 1784 case Stmt::OMPTargetParallelForDirectiveClass: 1785 case Stmt::OMPTargetUpdateDirectiveClass: 1786 case Stmt::OMPTeamsDirectiveClass: 1787 case Stmt::OMPCancellationPointDirectiveClass: 1788 case Stmt::OMPCancelDirectiveClass: 1789 case Stmt::OMPTaskLoopDirectiveClass: 1790 case Stmt::OMPTaskLoopSimdDirectiveClass: 1791 case Stmt::OMPMasterTaskLoopDirectiveClass: 1792 case Stmt::OMPMaskedTaskLoopDirectiveClass: 1793 case Stmt::OMPMasterTaskLoopSimdDirectiveClass: 1794 case Stmt::OMPMaskedTaskLoopSimdDirectiveClass: 1795 case Stmt::OMPParallelMasterTaskLoopDirectiveClass: 1796 case Stmt::OMPParallelMaskedTaskLoopDirectiveClass: 1797 case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass: 1798 case Stmt::OMPParallelMaskedTaskLoopSimdDirectiveClass: 1799 case Stmt::OMPDistributeDirectiveClass: 1800 case Stmt::OMPDistributeParallelForDirectiveClass: 1801 case Stmt::OMPDistributeParallelForSimdDirectiveClass: 1802 case Stmt::OMPDistributeSimdDirectiveClass: 1803 case Stmt::OMPTargetParallelForSimdDirectiveClass: 1804 case Stmt::OMPTargetSimdDirectiveClass: 1805 case Stmt::OMPTeamsDistributeDirectiveClass: 1806 case Stmt::OMPTeamsDistributeSimdDirectiveClass: 1807 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass: 1808 case Stmt::OMPTeamsDistributeParallelForDirectiveClass: 1809 case Stmt::OMPTargetTeamsDirectiveClass: 1810 case Stmt::OMPTargetTeamsDistributeDirectiveClass: 1811 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass: 1812 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass: 1813 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass: 1814 case Stmt::OMPReverseDirectiveClass: 1815 case Stmt::OMPTileDirectiveClass: 1816 case Stmt::OMPInteropDirectiveClass: 1817 case Stmt::OMPDispatchDirectiveClass: 1818 case Stmt::OMPMaskedDirectiveClass: 1819 case Stmt::OMPGenericLoopDirectiveClass: 1820 case Stmt::OMPTeamsGenericLoopDirectiveClass: 1821 case Stmt::OMPTargetTeamsGenericLoopDirectiveClass: 1822 case Stmt::OMPParallelGenericLoopDirectiveClass: 1823 case Stmt::OMPTargetParallelGenericLoopDirectiveClass: 1824 case Stmt::CapturedStmtClass: 1825 case Stmt::OpenACCComputeConstructClass: 1826 case Stmt::OpenACCLoopConstructClass: 1827 case Stmt::OMPUnrollDirectiveClass: 1828 case Stmt::OMPMetaDirectiveClass: { 1829 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState()); 1830 Engine.addAbortedBlock(node, currBldrCtx->getBlock()); 1831 break; 1832 } 1833 1834 case Stmt::ParenExprClass: 1835 llvm_unreachable("ParenExprs already handled."); 1836 case Stmt::GenericSelectionExprClass: 1837 llvm_unreachable("GenericSelectionExprs already handled."); 1838 // Cases that should never be evaluated simply because they shouldn't 1839 // appear in the CFG. 1840 case Stmt::BreakStmtClass: 1841 case Stmt::CaseStmtClass: 1842 case Stmt::CompoundStmtClass: 1843 case Stmt::ContinueStmtClass: 1844 case Stmt::CXXForRangeStmtClass: 1845 case Stmt::DefaultStmtClass: 1846 case Stmt::DoStmtClass: 1847 case Stmt::ForStmtClass: 1848 case Stmt::GotoStmtClass: 1849 case Stmt::IfStmtClass: 1850 case Stmt::IndirectGotoStmtClass: 1851 case Stmt::LabelStmtClass: 1852 case Stmt::NoStmtClass: 1853 case Stmt::NullStmtClass: 1854 case Stmt::SwitchStmtClass: 1855 case Stmt::WhileStmtClass: 1856 case Expr::MSDependentExistsStmtClass: 1857 llvm_unreachable("Stmt should not be in analyzer evaluation loop"); 1858 case Stmt::ImplicitValueInitExprClass: 1859 // These nodes are shared in the CFG and would case caching out. 1860 // Moreover, no additional evaluation required for them, the 1861 // analyzer can reconstruct these values from the AST. 1862 llvm_unreachable("Should be pruned from CFG"); 1863 1864 case Stmt::ObjCSubscriptRefExprClass: 1865 case Stmt::ObjCPropertyRefExprClass: 1866 llvm_unreachable("These are handled by PseudoObjectExpr"); 1867 1868 case Stmt::GNUNullExprClass: { 1869 // GNU __null is a pointer-width integer, not an actual pointer. 1870 ProgramStateRef state = Pred->getState(); 1871 state = state->BindExpr( 1872 S, Pred->getLocationContext(), 1873 svalBuilder.makeIntValWithWidth(getContext().VoidPtrTy, 0)); 1874 Bldr.generateNode(S, Pred, state); 1875 break; 1876 } 1877 1878 case Stmt::ObjCAtSynchronizedStmtClass: 1879 Bldr.takeNodes(Pred); 1880 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst); 1881 Bldr.addNodes(Dst); 1882 break; 1883 1884 case Expr::ConstantExprClass: 1885 case Stmt::ExprWithCleanupsClass: 1886 // Handled due to fully linearised CFG. 1887 break; 1888 1889 case Stmt::CXXBindTemporaryExprClass: { 1890 Bldr.takeNodes(Pred); 1891 ExplodedNodeSet PreVisit; 1892 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 1893 ExplodedNodeSet Next; 1894 VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next); 1895 getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this); 1896 Bldr.addNodes(Dst); 1897 break; 1898 } 1899 1900 case Stmt::ArrayInitLoopExprClass: 1901 Bldr.takeNodes(Pred); 1902 VisitArrayInitLoopExpr(cast<ArrayInitLoopExpr>(S), Pred, Dst); 1903 Bldr.addNodes(Dst); 1904 break; 1905 // Cases not handled yet; but will handle some day. 1906 case Stmt::DesignatedInitExprClass: 1907 case Stmt::DesignatedInitUpdateExprClass: 1908 case Stmt::ArrayInitIndexExprClass: 1909 case Stmt::ExtVectorElementExprClass: 1910 case Stmt::ImaginaryLiteralClass: 1911 case Stmt::ObjCAtCatchStmtClass: 1912 case Stmt::ObjCAtFinallyStmtClass: 1913 case Stmt::ObjCAtTryStmtClass: 1914 case Stmt::ObjCAutoreleasePoolStmtClass: 1915 case Stmt::ObjCEncodeExprClass: 1916 case Stmt::ObjCIsaExprClass: 1917 case Stmt::ObjCProtocolExprClass: 1918 case Stmt::ObjCSelectorExprClass: 1919 case Stmt::ParenListExprClass: 1920 case Stmt::ShuffleVectorExprClass: 1921 case Stmt::ConvertVectorExprClass: 1922 case Stmt::VAArgExprClass: 1923 case Stmt::CUDAKernelCallExprClass: 1924 case Stmt::OpaqueValueExprClass: 1925 case Stmt::AsTypeExprClass: 1926 case Stmt::ConceptSpecializationExprClass: 1927 case Stmt::CXXRewrittenBinaryOperatorClass: 1928 case Stmt::RequiresExprClass: 1929 case Expr::CXXParenListInitExprClass: 1930 // Fall through. 1931 1932 // Cases we intentionally don't evaluate, since they don't need 1933 // to be explicitly evaluated. 1934 case Stmt::PredefinedExprClass: 1935 case Stmt::AddrLabelExprClass: 1936 case Stmt::AttributedStmtClass: 1937 case Stmt::IntegerLiteralClass: 1938 case Stmt::FixedPointLiteralClass: 1939 case Stmt::CharacterLiteralClass: 1940 case Stmt::CXXScalarValueInitExprClass: 1941 case Stmt::CXXBoolLiteralExprClass: 1942 case Stmt::ObjCBoolLiteralExprClass: 1943 case Stmt::ObjCAvailabilityCheckExprClass: 1944 case Stmt::FloatingLiteralClass: 1945 case Stmt::NoInitExprClass: 1946 case Stmt::SizeOfPackExprClass: 1947 case Stmt::StringLiteralClass: 1948 case Stmt::SourceLocExprClass: 1949 case Stmt::ObjCStringLiteralClass: 1950 case Stmt::CXXPseudoDestructorExprClass: 1951 case Stmt::SubstNonTypeTemplateParmExprClass: 1952 case Stmt::CXXNullPtrLiteralExprClass: 1953 case Stmt::ArraySectionExprClass: 1954 case Stmt::OMPArrayShapingExprClass: 1955 case Stmt::OMPIteratorExprClass: 1956 case Stmt::SYCLUniqueStableNameExprClass: 1957 case Stmt::TypeTraitExprClass: { 1958 Bldr.takeNodes(Pred); 1959 ExplodedNodeSet preVisit; 1960 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this); 1961 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this); 1962 Bldr.addNodes(Dst); 1963 break; 1964 } 1965 1966 case Stmt::CXXDefaultArgExprClass: 1967 case Stmt::CXXDefaultInitExprClass: { 1968 Bldr.takeNodes(Pred); 1969 ExplodedNodeSet PreVisit; 1970 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 1971 1972 ExplodedNodeSet Tmp; 1973 StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx); 1974 1975 const Expr *ArgE; 1976 if (const auto *DefE = dyn_cast<CXXDefaultArgExpr>(S)) 1977 ArgE = DefE->getExpr(); 1978 else if (const auto *DefE = dyn_cast<CXXDefaultInitExpr>(S)) 1979 ArgE = DefE->getExpr(); 1980 else 1981 llvm_unreachable("unknown constant wrapper kind"); 1982 1983 bool IsTemporary = false; 1984 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(ArgE)) { 1985 ArgE = MTE->getSubExpr(); 1986 IsTemporary = true; 1987 } 1988 1989 std::optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE); 1990 if (!ConstantVal) 1991 ConstantVal = UnknownVal(); 1992 1993 const LocationContext *LCtx = Pred->getLocationContext(); 1994 for (const auto I : PreVisit) { 1995 ProgramStateRef State = I->getState(); 1996 State = State->BindExpr(S, LCtx, *ConstantVal); 1997 if (IsTemporary) 1998 State = createTemporaryRegionIfNeeded(State, LCtx, 1999 cast<Expr>(S), 2000 cast<Expr>(S)); 2001 Bldr2.generateNode(S, I, State); 2002 } 2003 2004 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this); 2005 Bldr.addNodes(Dst); 2006 break; 2007 } 2008 2009 // Cases we evaluate as opaque expressions, conjuring a symbol. 2010 case Stmt::CXXStdInitializerListExprClass: 2011 case Expr::ObjCArrayLiteralClass: 2012 case Expr::ObjCDictionaryLiteralClass: 2013 case Expr::ObjCBoxedExprClass: { 2014 Bldr.takeNodes(Pred); 2015 2016 ExplodedNodeSet preVisit; 2017 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this); 2018 2019 ExplodedNodeSet Tmp; 2020 StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx); 2021 2022 const auto *Ex = cast<Expr>(S); 2023 QualType resultType = Ex->getType(); 2024 2025 for (const auto N : preVisit) { 2026 const LocationContext *LCtx = N->getLocationContext(); 2027 SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx, 2028 resultType, 2029 currBldrCtx->blockCount()); 2030 ProgramStateRef State = N->getState()->BindExpr(Ex, LCtx, result); 2031 2032 // Escape pointers passed into the list, unless it's an ObjC boxed 2033 // expression which is not a boxable C structure. 2034 if (!(isa<ObjCBoxedExpr>(Ex) && 2035 !cast<ObjCBoxedExpr>(Ex)->getSubExpr() 2036 ->getType()->isRecordType())) 2037 for (auto Child : Ex->children()) { 2038 assert(Child); 2039 SVal Val = State->getSVal(Child, LCtx); 2040 State = escapeValues(State, Val, PSK_EscapeOther); 2041 } 2042 2043 Bldr2.generateNode(S, N, State); 2044 } 2045 2046 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this); 2047 Bldr.addNodes(Dst); 2048 break; 2049 } 2050 2051 case Stmt::ArraySubscriptExprClass: 2052 Bldr.takeNodes(Pred); 2053 VisitArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst); 2054 Bldr.addNodes(Dst); 2055 break; 2056 2057 case Stmt::MatrixSubscriptExprClass: 2058 llvm_unreachable("Support for MatrixSubscriptExpr is not implemented."); 2059 break; 2060 2061 case Stmt::GCCAsmStmtClass: { 2062 Bldr.takeNodes(Pred); 2063 ExplodedNodeSet PreVisit; 2064 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 2065 ExplodedNodeSet PostVisit; 2066 for (ExplodedNode *const N : PreVisit) 2067 VisitGCCAsmStmt(cast<GCCAsmStmt>(S), N, PostVisit); 2068 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this); 2069 Bldr.addNodes(Dst); 2070 break; 2071 } 2072 2073 case Stmt::MSAsmStmtClass: 2074 Bldr.takeNodes(Pred); 2075 VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst); 2076 Bldr.addNodes(Dst); 2077 break; 2078 2079 case Stmt::BlockExprClass: 2080 Bldr.takeNodes(Pred); 2081 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst); 2082 Bldr.addNodes(Dst); 2083 break; 2084 2085 case Stmt::LambdaExprClass: 2086 if (AMgr.options.ShouldInlineLambdas) { 2087 Bldr.takeNodes(Pred); 2088 VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst); 2089 Bldr.addNodes(Dst); 2090 } else { 2091 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState()); 2092 Engine.addAbortedBlock(node, currBldrCtx->getBlock()); 2093 } 2094 break; 2095 2096 case Stmt::BinaryOperatorClass: { 2097 const auto *B = cast<BinaryOperator>(S); 2098 if (B->isLogicalOp()) { 2099 Bldr.takeNodes(Pred); 2100 VisitLogicalExpr(B, Pred, Dst); 2101 Bldr.addNodes(Dst); 2102 break; 2103 } 2104 else if (B->getOpcode() == BO_Comma) { 2105 ProgramStateRef state = Pred->getState(); 2106 Bldr.generateNode(B, Pred, 2107 state->BindExpr(B, Pred->getLocationContext(), 2108 state->getSVal(B->getRHS(), 2109 Pred->getLocationContext()))); 2110 break; 2111 } 2112 2113 Bldr.takeNodes(Pred); 2114 2115 if (AMgr.options.ShouldEagerlyAssume && 2116 (B->isRelationalOp() || B->isEqualityOp())) { 2117 ExplodedNodeSet Tmp; 2118 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp); 2119 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S)); 2120 } 2121 else 2122 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 2123 2124 Bldr.addNodes(Dst); 2125 break; 2126 } 2127 2128 case Stmt::CXXOperatorCallExprClass: { 2129 const auto *OCE = cast<CXXOperatorCallExpr>(S); 2130 2131 // For instance method operators, make sure the 'this' argument has a 2132 // valid region. 2133 const Decl *Callee = OCE->getCalleeDecl(); 2134 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) { 2135 if (MD->isImplicitObjectMemberFunction()) { 2136 ProgramStateRef State = Pred->getState(); 2137 const LocationContext *LCtx = Pred->getLocationContext(); 2138 ProgramStateRef NewState = 2139 createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0)); 2140 if (NewState != State) { 2141 Pred = Bldr.generateNode(OCE, Pred, NewState, /*tag=*/nullptr, 2142 ProgramPoint::PreStmtKind); 2143 // Did we cache out? 2144 if (!Pred) 2145 break; 2146 } 2147 } 2148 } 2149 [[fallthrough]]; 2150 } 2151 2152 case Stmt::CallExprClass: 2153 case Stmt::CXXMemberCallExprClass: 2154 case Stmt::UserDefinedLiteralClass: 2155 Bldr.takeNodes(Pred); 2156 VisitCallExpr(cast<CallExpr>(S), Pred, Dst); 2157 Bldr.addNodes(Dst); 2158 break; 2159 2160 case Stmt::CXXCatchStmtClass: 2161 Bldr.takeNodes(Pred); 2162 VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst); 2163 Bldr.addNodes(Dst); 2164 break; 2165 2166 case Stmt::CXXTemporaryObjectExprClass: 2167 case Stmt::CXXConstructExprClass: 2168 Bldr.takeNodes(Pred); 2169 VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst); 2170 Bldr.addNodes(Dst); 2171 break; 2172 2173 case Stmt::CXXInheritedCtorInitExprClass: 2174 Bldr.takeNodes(Pred); 2175 VisitCXXInheritedCtorInitExpr(cast<CXXInheritedCtorInitExpr>(S), Pred, 2176 Dst); 2177 Bldr.addNodes(Dst); 2178 break; 2179 2180 case Stmt::CXXNewExprClass: { 2181 Bldr.takeNodes(Pred); 2182 2183 ExplodedNodeSet PreVisit; 2184 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 2185 2186 ExplodedNodeSet PostVisit; 2187 for (const auto i : PreVisit) 2188 VisitCXXNewExpr(cast<CXXNewExpr>(S), i, PostVisit); 2189 2190 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this); 2191 Bldr.addNodes(Dst); 2192 break; 2193 } 2194 2195 case Stmt::CXXDeleteExprClass: { 2196 Bldr.takeNodes(Pred); 2197 ExplodedNodeSet PreVisit; 2198 const auto *CDE = cast<CXXDeleteExpr>(S); 2199 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 2200 ExplodedNodeSet PostVisit; 2201 getCheckerManager().runCheckersForPostStmt(PostVisit, PreVisit, S, *this); 2202 2203 for (const auto i : PostVisit) 2204 VisitCXXDeleteExpr(CDE, i, Dst); 2205 2206 Bldr.addNodes(Dst); 2207 break; 2208 } 2209 // FIXME: ChooseExpr is really a constant. We need to fix 2210 // the CFG do not model them as explicit control-flow. 2211 2212 case Stmt::ChooseExprClass: { // __builtin_choose_expr 2213 Bldr.takeNodes(Pred); 2214 const auto *C = cast<ChooseExpr>(S); 2215 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst); 2216 Bldr.addNodes(Dst); 2217 break; 2218 } 2219 2220 case Stmt::CompoundAssignOperatorClass: 2221 Bldr.takeNodes(Pred); 2222 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 2223 Bldr.addNodes(Dst); 2224 break; 2225 2226 case Stmt::CompoundLiteralExprClass: 2227 Bldr.takeNodes(Pred); 2228 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst); 2229 Bldr.addNodes(Dst); 2230 break; 2231 2232 case Stmt::BinaryConditionalOperatorClass: 2233 case Stmt::ConditionalOperatorClass: { // '?' operator 2234 Bldr.takeNodes(Pred); 2235 const auto *C = cast<AbstractConditionalOperator>(S); 2236 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst); 2237 Bldr.addNodes(Dst); 2238 break; 2239 } 2240 2241 case Stmt::CXXThisExprClass: 2242 Bldr.takeNodes(Pred); 2243 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst); 2244 Bldr.addNodes(Dst); 2245 break; 2246 2247 case Stmt::DeclRefExprClass: { 2248 Bldr.takeNodes(Pred); 2249 const auto *DE = cast<DeclRefExpr>(S); 2250 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst); 2251 Bldr.addNodes(Dst); 2252 break; 2253 } 2254 2255 case Stmt::DeclStmtClass: 2256 Bldr.takeNodes(Pred); 2257 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst); 2258 Bldr.addNodes(Dst); 2259 break; 2260 2261 case Stmt::ImplicitCastExprClass: 2262 case Stmt::CStyleCastExprClass: 2263 case Stmt::CXXStaticCastExprClass: 2264 case Stmt::CXXDynamicCastExprClass: 2265 case Stmt::CXXReinterpretCastExprClass: 2266 case Stmt::CXXConstCastExprClass: 2267 case Stmt::CXXFunctionalCastExprClass: 2268 case Stmt::BuiltinBitCastExprClass: 2269 case Stmt::ObjCBridgedCastExprClass: 2270 case Stmt::CXXAddrspaceCastExprClass: { 2271 Bldr.takeNodes(Pred); 2272 const auto *C = cast<CastExpr>(S); 2273 ExplodedNodeSet dstExpr; 2274 VisitCast(C, C->getSubExpr(), Pred, dstExpr); 2275 2276 // Handle the postvisit checks. 2277 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this); 2278 Bldr.addNodes(Dst); 2279 break; 2280 } 2281 2282 case Expr::MaterializeTemporaryExprClass: { 2283 Bldr.takeNodes(Pred); 2284 const auto *MTE = cast<MaterializeTemporaryExpr>(S); 2285 ExplodedNodeSet dstPrevisit; 2286 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this); 2287 ExplodedNodeSet dstExpr; 2288 for (const auto i : dstPrevisit) 2289 CreateCXXTemporaryObject(MTE, i, dstExpr); 2290 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this); 2291 Bldr.addNodes(Dst); 2292 break; 2293 } 2294 2295 case Stmt::InitListExprClass: 2296 Bldr.takeNodes(Pred); 2297 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst); 2298 Bldr.addNodes(Dst); 2299 break; 2300 2301 case Stmt::MemberExprClass: 2302 Bldr.takeNodes(Pred); 2303 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst); 2304 Bldr.addNodes(Dst); 2305 break; 2306 2307 case Stmt::AtomicExprClass: 2308 Bldr.takeNodes(Pred); 2309 VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst); 2310 Bldr.addNodes(Dst); 2311 break; 2312 2313 case Stmt::ObjCIvarRefExprClass: 2314 Bldr.takeNodes(Pred); 2315 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst); 2316 Bldr.addNodes(Dst); 2317 break; 2318 2319 case Stmt::ObjCForCollectionStmtClass: 2320 Bldr.takeNodes(Pred); 2321 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst); 2322 Bldr.addNodes(Dst); 2323 break; 2324 2325 case Stmt::ObjCMessageExprClass: 2326 Bldr.takeNodes(Pred); 2327 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst); 2328 Bldr.addNodes(Dst); 2329 break; 2330 2331 case Stmt::ObjCAtThrowStmtClass: 2332 case Stmt::CXXThrowExprClass: 2333 // FIXME: This is not complete. We basically treat @throw as 2334 // an abort. 2335 Bldr.generateSink(S, Pred, Pred->getState()); 2336 break; 2337 2338 case Stmt::ReturnStmtClass: 2339 Bldr.takeNodes(Pred); 2340 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst); 2341 Bldr.addNodes(Dst); 2342 break; 2343 2344 case Stmt::OffsetOfExprClass: { 2345 Bldr.takeNodes(Pred); 2346 ExplodedNodeSet PreVisit; 2347 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 2348 2349 ExplodedNodeSet PostVisit; 2350 for (const auto Node : PreVisit) 2351 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Node, PostVisit); 2352 2353 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this); 2354 Bldr.addNodes(Dst); 2355 break; 2356 } 2357 2358 case Stmt::UnaryExprOrTypeTraitExprClass: 2359 Bldr.takeNodes(Pred); 2360 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S), 2361 Pred, Dst); 2362 Bldr.addNodes(Dst); 2363 break; 2364 2365 case Stmt::StmtExprClass: { 2366 const auto *SE = cast<StmtExpr>(S); 2367 2368 if (SE->getSubStmt()->body_empty()) { 2369 // Empty statement expression. 2370 assert(SE->getType() == getContext().VoidTy 2371 && "Empty statement expression must have void type."); 2372 break; 2373 } 2374 2375 if (const auto *LastExpr = 2376 dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) { 2377 ProgramStateRef state = Pred->getState(); 2378 Bldr.generateNode(SE, Pred, 2379 state->BindExpr(SE, Pred->getLocationContext(), 2380 state->getSVal(LastExpr, 2381 Pred->getLocationContext()))); 2382 } 2383 break; 2384 } 2385 2386 case Stmt::UnaryOperatorClass: { 2387 Bldr.takeNodes(Pred); 2388 const auto *U = cast<UnaryOperator>(S); 2389 if (AMgr.options.ShouldEagerlyAssume && (U->getOpcode() == UO_LNot)) { 2390 ExplodedNodeSet Tmp; 2391 VisitUnaryOperator(U, Pred, Tmp); 2392 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U); 2393 } 2394 else 2395 VisitUnaryOperator(U, Pred, Dst); 2396 Bldr.addNodes(Dst); 2397 break; 2398 } 2399 2400 case Stmt::PseudoObjectExprClass: { 2401 Bldr.takeNodes(Pred); 2402 ProgramStateRef state = Pred->getState(); 2403 const auto *PE = cast<PseudoObjectExpr>(S); 2404 if (const Expr *Result = PE->getResultExpr()) { 2405 SVal V = state->getSVal(Result, Pred->getLocationContext()); 2406 Bldr.generateNode(S, Pred, 2407 state->BindExpr(S, Pred->getLocationContext(), V)); 2408 } 2409 else 2410 Bldr.generateNode(S, Pred, 2411 state->BindExpr(S, Pred->getLocationContext(), 2412 UnknownVal())); 2413 2414 Bldr.addNodes(Dst); 2415 break; 2416 } 2417 2418 case Expr::ObjCIndirectCopyRestoreExprClass: { 2419 // ObjCIndirectCopyRestoreExpr implies passing a temporary for 2420 // correctness of lifetime management. Due to limited analysis 2421 // of ARC, this is implemented as direct arg passing. 2422 Bldr.takeNodes(Pred); 2423 ProgramStateRef state = Pred->getState(); 2424 const auto *OIE = cast<ObjCIndirectCopyRestoreExpr>(S); 2425 const Expr *E = OIE->getSubExpr(); 2426 SVal V = state->getSVal(E, Pred->getLocationContext()); 2427 Bldr.generateNode(S, Pred, 2428 state->BindExpr(S, Pred->getLocationContext(), V)); 2429 Bldr.addNodes(Dst); 2430 break; 2431 } 2432 2433 case Stmt::EmbedExprClass: 2434 llvm::report_fatal_error("Support for EmbedExpr is not implemented."); 2435 break; 2436 } 2437 } 2438 2439 bool ExprEngine::replayWithoutInlining(ExplodedNode *N, 2440 const LocationContext *CalleeLC) { 2441 const StackFrameContext *CalleeSF = CalleeLC->getStackFrame(); 2442 const StackFrameContext *CallerSF = CalleeSF->getParent()->getStackFrame(); 2443 assert(CalleeSF && CallerSF); 2444 ExplodedNode *BeforeProcessingCall = nullptr; 2445 const Stmt *CE = CalleeSF->getCallSite(); 2446 2447 // Find the first node before we started processing the call expression. 2448 while (N) { 2449 ProgramPoint L = N->getLocation(); 2450 BeforeProcessingCall = N; 2451 N = N->pred_empty() ? nullptr : *(N->pred_begin()); 2452 2453 // Skip the nodes corresponding to the inlined code. 2454 if (L.getStackFrame() != CallerSF) 2455 continue; 2456 // We reached the caller. Find the node right before we started 2457 // processing the call. 2458 if (L.isPurgeKind()) 2459 continue; 2460 if (L.getAs<PreImplicitCall>()) 2461 continue; 2462 if (L.getAs<CallEnter>()) 2463 continue; 2464 if (std::optional<StmtPoint> SP = L.getAs<StmtPoint>()) 2465 if (SP->getStmt() == CE) 2466 continue; 2467 break; 2468 } 2469 2470 if (!BeforeProcessingCall) 2471 return false; 2472 2473 // TODO: Clean up the unneeded nodes. 2474 2475 // Build an Epsilon node from which we will restart the analyzes. 2476 // Note that CE is permitted to be NULL! 2477 static SimpleProgramPointTag PT("ExprEngine", "Replay without inlining"); 2478 ProgramPoint NewNodeLoc = EpsilonPoint( 2479 BeforeProcessingCall->getLocationContext(), CE, nullptr, &PT); 2480 // Add the special flag to GDM to signal retrying with no inlining. 2481 // Note, changing the state ensures that we are not going to cache out. 2482 ProgramStateRef NewNodeState = BeforeProcessingCall->getState(); 2483 NewNodeState = 2484 NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE)); 2485 2486 // Make the new node a successor of BeforeProcessingCall. 2487 bool IsNew = false; 2488 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew); 2489 // We cached out at this point. Caching out is common due to us backtracking 2490 // from the inlined function, which might spawn several paths. 2491 if (!IsNew) 2492 return true; 2493 2494 NewNode->addPredecessor(BeforeProcessingCall, G); 2495 2496 // Add the new node to the work list. 2497 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(), 2498 CalleeSF->getIndex()); 2499 NumTimesRetriedWithoutInlining++; 2500 return true; 2501 } 2502 2503 /// Block entrance. (Update counters). 2504 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L, 2505 NodeBuilderWithSinks &nodeBuilder, 2506 ExplodedNode *Pred) { 2507 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 2508 // If we reach a loop which has a known bound (and meets 2509 // other constraints) then consider completely unrolling it. 2510 if(AMgr.options.ShouldUnrollLoops) { 2511 unsigned maxBlockVisitOnPath = AMgr.options.maxBlockVisitOnPath; 2512 const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminatorStmt(); 2513 if (Term) { 2514 ProgramStateRef NewState = updateLoopStack(Term, AMgr.getASTContext(), 2515 Pred, maxBlockVisitOnPath); 2516 if (NewState != Pred->getState()) { 2517 ExplodedNode *UpdatedNode = nodeBuilder.generateNode(NewState, Pred); 2518 if (!UpdatedNode) 2519 return; 2520 Pred = UpdatedNode; 2521 } 2522 } 2523 // Is we are inside an unrolled loop then no need the check the counters. 2524 if(isUnrolledState(Pred->getState())) 2525 return; 2526 } 2527 2528 // If this block is terminated by a loop and it has already been visited the 2529 // maximum number of times, widen the loop. 2530 unsigned int BlockCount = nodeBuilder.getContext().blockCount(); 2531 if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 && 2532 AMgr.options.ShouldWidenLoops) { 2533 const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminatorStmt(); 2534 if (!isa_and_nonnull<ForStmt, WhileStmt, DoStmt, CXXForRangeStmt>(Term)) 2535 return; 2536 // Widen. 2537 const LocationContext *LCtx = Pred->getLocationContext(); 2538 ProgramStateRef WidenedState = 2539 getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term); 2540 nodeBuilder.generateNode(WidenedState, Pred); 2541 return; 2542 } 2543 2544 // FIXME: Refactor this into a checker. 2545 if (BlockCount >= AMgr.options.maxBlockVisitOnPath) { 2546 static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded"); 2547 const ExplodedNode *Sink = 2548 nodeBuilder.generateSink(Pred->getState(), Pred, &tag); 2549 2550 // Check if we stopped at the top level function or not. 2551 // Root node should have the location context of the top most function. 2552 const LocationContext *CalleeLC = Pred->getLocation().getLocationContext(); 2553 const LocationContext *CalleeSF = CalleeLC->getStackFrame(); 2554 const LocationContext *RootLC = 2555 (*G.roots_begin())->getLocation().getLocationContext(); 2556 if (RootLC->getStackFrame() != CalleeSF) { 2557 Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl()); 2558 2559 // Re-run the call evaluation without inlining it, by storing the 2560 // no-inlining policy in the state and enqueuing the new work item on 2561 // the list. Replay should almost never fail. Use the stats to catch it 2562 // if it does. 2563 if ((!AMgr.options.NoRetryExhausted && 2564 replayWithoutInlining(Pred, CalleeLC))) 2565 return; 2566 NumMaxBlockCountReachedInInlined++; 2567 } else 2568 NumMaxBlockCountReached++; 2569 2570 // Make sink nodes as exhausted(for stats) only if retry failed. 2571 Engine.blocksExhausted.push_back(std::make_pair(L, Sink)); 2572 } 2573 } 2574 2575 //===----------------------------------------------------------------------===// 2576 // Branch processing. 2577 //===----------------------------------------------------------------------===// 2578 2579 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used 2580 /// to try to recover some path-sensitivity for casts of symbolic 2581 /// integers that promote their values (which are currently not tracked well). 2582 /// This function returns the SVal bound to Condition->IgnoreCasts if all the 2583 // cast(s) did was sign-extend the original value. 2584 static SVal RecoverCastedSymbol(ProgramStateRef state, 2585 const Stmt *Condition, 2586 const LocationContext *LCtx, 2587 ASTContext &Ctx) { 2588 2589 const auto *Ex = dyn_cast<Expr>(Condition); 2590 if (!Ex) 2591 return UnknownVal(); 2592 2593 uint64_t bits = 0; 2594 bool bitsInit = false; 2595 2596 while (const auto *CE = dyn_cast<CastExpr>(Ex)) { 2597 QualType T = CE->getType(); 2598 2599 if (!T->isIntegralOrEnumerationType()) 2600 return UnknownVal(); 2601 2602 uint64_t newBits = Ctx.getTypeSize(T); 2603 if (!bitsInit || newBits < bits) { 2604 bitsInit = true; 2605 bits = newBits; 2606 } 2607 2608 Ex = CE->getSubExpr(); 2609 } 2610 2611 // We reached a non-cast. Is it a symbolic value? 2612 QualType T = Ex->getType(); 2613 2614 if (!bitsInit || !T->isIntegralOrEnumerationType() || 2615 Ctx.getTypeSize(T) > bits) 2616 return UnknownVal(); 2617 2618 return state->getSVal(Ex, LCtx); 2619 } 2620 2621 #ifndef NDEBUG 2622 static const Stmt *getRightmostLeaf(const Stmt *Condition) { 2623 while (Condition) { 2624 const auto *BO = dyn_cast<BinaryOperator>(Condition); 2625 if (!BO || !BO->isLogicalOp()) { 2626 return Condition; 2627 } 2628 Condition = BO->getRHS()->IgnoreParens(); 2629 } 2630 return nullptr; 2631 } 2632 #endif 2633 2634 // Returns the condition the branch at the end of 'B' depends on and whose value 2635 // has been evaluated within 'B'. 2636 // In most cases, the terminator condition of 'B' will be evaluated fully in 2637 // the last statement of 'B'; in those cases, the resolved condition is the 2638 // given 'Condition'. 2639 // If the condition of the branch is a logical binary operator tree, the CFG is 2640 // optimized: in that case, we know that the expression formed by all but the 2641 // rightmost leaf of the logical binary operator tree must be true, and thus 2642 // the branch condition is at this point equivalent to the truth value of that 2643 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf 2644 // expression in its final statement. As the full condition in that case was 2645 // not evaluated, and is thus not in the SVal cache, we need to use that leaf 2646 // expression to evaluate the truth value of the condition in the current state 2647 // space. 2648 static const Stmt *ResolveCondition(const Stmt *Condition, 2649 const CFGBlock *B) { 2650 if (const auto *Ex = dyn_cast<Expr>(Condition)) 2651 Condition = Ex->IgnoreParens(); 2652 2653 const auto *BO = dyn_cast<BinaryOperator>(Condition); 2654 if (!BO || !BO->isLogicalOp()) 2655 return Condition; 2656 2657 assert(B->getTerminator().isStmtBranch() && 2658 "Other kinds of branches are handled separately!"); 2659 2660 // For logical operations, we still have the case where some branches 2661 // use the traditional "merge" approach and others sink the branch 2662 // directly into the basic blocks representing the logical operation. 2663 // We need to distinguish between those two cases here. 2664 2665 // The invariants are still shifting, but it is possible that the 2666 // last element in a CFGBlock is not a CFGStmt. Look for the last 2667 // CFGStmt as the value of the condition. 2668 for (CFGElement Elem : llvm::reverse(*B)) { 2669 std::optional<CFGStmt> CS = Elem.getAs<CFGStmt>(); 2670 if (!CS) 2671 continue; 2672 const Stmt *LastStmt = CS->getStmt(); 2673 assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition)); 2674 return LastStmt; 2675 } 2676 llvm_unreachable("could not resolve condition"); 2677 } 2678 2679 using ObjCForLctxPair = 2680 std::pair<const ObjCForCollectionStmt *, const LocationContext *>; 2681 2682 REGISTER_MAP_WITH_PROGRAMSTATE(ObjCForHasMoreIterations, ObjCForLctxPair, bool) 2683 2684 ProgramStateRef ExprEngine::setWhetherHasMoreIteration( 2685 ProgramStateRef State, const ObjCForCollectionStmt *O, 2686 const LocationContext *LC, bool HasMoreIteraton) { 2687 assert(!State->contains<ObjCForHasMoreIterations>({O, LC})); 2688 return State->set<ObjCForHasMoreIterations>({O, LC}, HasMoreIteraton); 2689 } 2690 2691 ProgramStateRef 2692 ExprEngine::removeIterationState(ProgramStateRef State, 2693 const ObjCForCollectionStmt *O, 2694 const LocationContext *LC) { 2695 assert(State->contains<ObjCForHasMoreIterations>({O, LC})); 2696 return State->remove<ObjCForHasMoreIterations>({O, LC}); 2697 } 2698 2699 bool ExprEngine::hasMoreIteration(ProgramStateRef State, 2700 const ObjCForCollectionStmt *O, 2701 const LocationContext *LC) { 2702 assert(State->contains<ObjCForHasMoreIterations>({O, LC})); 2703 return *State->get<ObjCForHasMoreIterations>({O, LC}); 2704 } 2705 2706 /// Split the state on whether there are any more iterations left for this loop. 2707 /// Returns a (HasMoreIteration, HasNoMoreIteration) pair, or std::nullopt when 2708 /// the acquisition of the loop condition value failed. 2709 static std::optional<std::pair<ProgramStateRef, ProgramStateRef>> 2710 assumeCondition(const Stmt *Condition, ExplodedNode *N) { 2711 ProgramStateRef State = N->getState(); 2712 if (const auto *ObjCFor = dyn_cast<ObjCForCollectionStmt>(Condition)) { 2713 bool HasMoreIteraton = 2714 ExprEngine::hasMoreIteration(State, ObjCFor, N->getLocationContext()); 2715 // Checkers have already ran on branch conditions, so the current 2716 // information as to whether the loop has more iteration becomes outdated 2717 // after this point. 2718 State = ExprEngine::removeIterationState(State, ObjCFor, 2719 N->getLocationContext()); 2720 if (HasMoreIteraton) 2721 return std::pair<ProgramStateRef, ProgramStateRef>{State, nullptr}; 2722 else 2723 return std::pair<ProgramStateRef, ProgramStateRef>{nullptr, State}; 2724 } 2725 SVal X = State->getSVal(Condition, N->getLocationContext()); 2726 2727 if (X.isUnknownOrUndef()) { 2728 // Give it a chance to recover from unknown. 2729 if (const auto *Ex = dyn_cast<Expr>(Condition)) { 2730 if (Ex->getType()->isIntegralOrEnumerationType()) { 2731 // Try to recover some path-sensitivity. Right now casts of symbolic 2732 // integers that promote their values are currently not tracked well. 2733 // If 'Condition' is such an expression, try and recover the 2734 // underlying value and use that instead. 2735 SVal recovered = 2736 RecoverCastedSymbol(State, Condition, N->getLocationContext(), 2737 N->getState()->getStateManager().getContext()); 2738 2739 if (!recovered.isUnknown()) { 2740 X = recovered; 2741 } 2742 } 2743 } 2744 } 2745 2746 // If the condition is still unknown, give up. 2747 if (X.isUnknownOrUndef()) 2748 return std::nullopt; 2749 2750 DefinedSVal V = X.castAs<DefinedSVal>(); 2751 2752 ProgramStateRef StTrue, StFalse; 2753 return State->assume(V); 2754 } 2755 2756 void ExprEngine::processBranch(const Stmt *Condition, 2757 NodeBuilderContext& BldCtx, 2758 ExplodedNode *Pred, 2759 ExplodedNodeSet &Dst, 2760 const CFGBlock *DstT, 2761 const CFGBlock *DstF) { 2762 assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) && 2763 "CXXBindTemporaryExprs are handled by processBindTemporary."); 2764 const LocationContext *LCtx = Pred->getLocationContext(); 2765 PrettyStackTraceLocationContext StackCrashInfo(LCtx); 2766 currBldrCtx = &BldCtx; 2767 2768 // Check for NULL conditions; e.g. "for(;;)" 2769 if (!Condition) { 2770 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF); 2771 NullCondBldr.markInfeasible(false); 2772 NullCondBldr.generateNode(Pred->getState(), true, Pred); 2773 return; 2774 } 2775 2776 if (const auto *Ex = dyn_cast<Expr>(Condition)) 2777 Condition = Ex->IgnoreParens(); 2778 2779 Condition = ResolveCondition(Condition, BldCtx.getBlock()); 2780 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 2781 Condition->getBeginLoc(), 2782 "Error evaluating branch"); 2783 2784 ExplodedNodeSet CheckersOutSet; 2785 getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet, 2786 Pred, *this); 2787 // We generated only sinks. 2788 if (CheckersOutSet.empty()) 2789 return; 2790 2791 BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF); 2792 for (ExplodedNode *PredN : CheckersOutSet) { 2793 if (PredN->isSink()) 2794 continue; 2795 2796 ProgramStateRef PrevState = PredN->getState(); 2797 2798 ProgramStateRef StTrue, StFalse; 2799 if (const auto KnownCondValueAssumption = assumeCondition(Condition, PredN)) 2800 std::tie(StTrue, StFalse) = *KnownCondValueAssumption; 2801 else { 2802 assert(!isa<ObjCForCollectionStmt>(Condition)); 2803 builder.generateNode(PrevState, true, PredN); 2804 builder.generateNode(PrevState, false, PredN); 2805 continue; 2806 } 2807 if (StTrue && StFalse) 2808 assert(!isa<ObjCForCollectionStmt>(Condition)); 2809 2810 // Process the true branch. 2811 if (builder.isFeasible(true)) { 2812 if (StTrue) 2813 builder.generateNode(StTrue, true, PredN); 2814 else 2815 builder.markInfeasible(true); 2816 } 2817 2818 // Process the false branch. 2819 if (builder.isFeasible(false)) { 2820 if (StFalse) 2821 builder.generateNode(StFalse, false, PredN); 2822 else 2823 builder.markInfeasible(false); 2824 } 2825 } 2826 currBldrCtx = nullptr; 2827 } 2828 2829 /// The GDM component containing the set of global variables which have been 2830 /// previously initialized with explicit initializers. 2831 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet, 2832 llvm::ImmutableSet<const VarDecl *>) 2833 2834 void ExprEngine::processStaticInitializer(const DeclStmt *DS, 2835 NodeBuilderContext &BuilderCtx, 2836 ExplodedNode *Pred, 2837 ExplodedNodeSet &Dst, 2838 const CFGBlock *DstT, 2839 const CFGBlock *DstF) { 2840 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 2841 currBldrCtx = &BuilderCtx; 2842 2843 const auto *VD = cast<VarDecl>(DS->getSingleDecl()); 2844 ProgramStateRef state = Pred->getState(); 2845 bool initHasRun = state->contains<InitializedGlobalsSet>(VD); 2846 BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF); 2847 2848 if (!initHasRun) { 2849 state = state->add<InitializedGlobalsSet>(VD); 2850 } 2851 2852 builder.generateNode(state, initHasRun, Pred); 2853 builder.markInfeasible(!initHasRun); 2854 2855 currBldrCtx = nullptr; 2856 } 2857 2858 /// processIndirectGoto - Called by CoreEngine. Used to generate successor 2859 /// nodes by processing the 'effects' of a computed goto jump. 2860 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) { 2861 ProgramStateRef state = builder.getState(); 2862 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext()); 2863 2864 // Three possibilities: 2865 // 2866 // (1) We know the computed label. 2867 // (2) The label is NULL (or some other constant), or Undefined. 2868 // (3) We have no clue about the label. Dispatch to all targets. 2869 // 2870 2871 using iterator = IndirectGotoNodeBuilder::iterator; 2872 2873 if (std::optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) { 2874 const LabelDecl *L = LV->getLabel(); 2875 2876 for (iterator Succ : builder) { 2877 if (Succ.getLabel() == L) { 2878 builder.generateNode(Succ, state); 2879 return; 2880 } 2881 } 2882 2883 llvm_unreachable("No block with label."); 2884 } 2885 2886 if (isa<UndefinedVal, loc::ConcreteInt>(V)) { 2887 // Dispatch to the first target and mark it as a sink. 2888 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true); 2889 // FIXME: add checker visit. 2890 // UndefBranches.insert(N); 2891 return; 2892 } 2893 2894 // This is really a catch-all. We don't support symbolics yet. 2895 // FIXME: Implement dispatch for symbolic pointers. 2896 2897 for (iterator Succ : builder) 2898 builder.generateNode(Succ, state); 2899 } 2900 2901 void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC, 2902 ExplodedNode *Pred, 2903 ExplodedNodeSet &Dst, 2904 const BlockEdge &L) { 2905 SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC); 2906 getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this); 2907 } 2908 2909 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path 2910 /// nodes when the control reaches the end of a function. 2911 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC, 2912 ExplodedNode *Pred, 2913 const ReturnStmt *RS) { 2914 ProgramStateRef State = Pred->getState(); 2915 2916 if (!Pred->getStackFrame()->inTopFrame()) 2917 State = finishArgumentConstruction( 2918 State, *getStateManager().getCallEventManager().getCaller( 2919 Pred->getStackFrame(), Pred->getState())); 2920 2921 // FIXME: We currently cannot assert that temporaries are clear, because 2922 // lifetime extended temporaries are not always modelled correctly. In some 2923 // cases when we materialize the temporary, we do 2924 // createTemporaryRegionIfNeeded(), and the region changes, and also the 2925 // respective destructor becomes automatic from temporary. So for now clean up 2926 // the state manually before asserting. Ideally, this braced block of code 2927 // should go away. 2928 { 2929 const LocationContext *FromLC = Pred->getLocationContext(); 2930 const LocationContext *ToLC = FromLC->getStackFrame()->getParent(); 2931 const LocationContext *LC = FromLC; 2932 while (LC != ToLC) { 2933 assert(LC && "ToLC must be a parent of FromLC!"); 2934 for (auto I : State->get<ObjectsUnderConstruction>()) 2935 if (I.first.getLocationContext() == LC) { 2936 // The comment above only pardons us for not cleaning up a 2937 // temporary destructor. If any other statements are found here, 2938 // it must be a separate problem. 2939 assert(I.first.getItem().getKind() == 2940 ConstructionContextItem::TemporaryDestructorKind || 2941 I.first.getItem().getKind() == 2942 ConstructionContextItem::ElidedDestructorKind); 2943 State = State->remove<ObjectsUnderConstruction>(I.first); 2944 } 2945 LC = LC->getParent(); 2946 } 2947 } 2948 2949 // Perform the transition with cleanups. 2950 if (State != Pred->getState()) { 2951 ExplodedNodeSet PostCleanup; 2952 NodeBuilder Bldr(Pred, PostCleanup, BC); 2953 Pred = Bldr.generateNode(Pred->getLocation(), State, Pred); 2954 if (!Pred) { 2955 // The node with clean temporaries already exists. We might have reached 2956 // it on a path on which we initialize different temporaries. 2957 return; 2958 } 2959 } 2960 2961 assert(areAllObjectsFullyConstructed(Pred->getState(), 2962 Pred->getLocationContext(), 2963 Pred->getStackFrame()->getParent())); 2964 2965 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 2966 2967 ExplodedNodeSet Dst; 2968 if (Pred->getLocationContext()->inTopFrame()) { 2969 // Remove dead symbols. 2970 ExplodedNodeSet AfterRemovedDead; 2971 removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead); 2972 2973 // Notify checkers. 2974 for (const auto I : AfterRemovedDead) 2975 getCheckerManager().runCheckersForEndFunction(BC, Dst, I, *this, RS); 2976 } else { 2977 getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this, RS); 2978 } 2979 2980 Engine.enqueueEndOfFunction(Dst, RS); 2981 } 2982 2983 /// ProcessSwitch - Called by CoreEngine. Used to generate successor 2984 /// nodes by processing the 'effects' of a switch statement. 2985 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) { 2986 using iterator = SwitchNodeBuilder::iterator; 2987 2988 ProgramStateRef state = builder.getState(); 2989 const Expr *CondE = builder.getCondition(); 2990 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext()); 2991 2992 if (CondV_untested.isUndef()) { 2993 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true); 2994 // FIXME: add checker 2995 //UndefBranches.insert(N); 2996 2997 return; 2998 } 2999 DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>(); 3000 3001 ProgramStateRef DefaultSt = state; 3002 3003 iterator I = builder.begin(), EI = builder.end(); 3004 bool defaultIsFeasible = I == EI; 3005 3006 for ( ; I != EI; ++I) { 3007 // Successor may be pruned out during CFG construction. 3008 if (!I.getBlock()) 3009 continue; 3010 3011 const CaseStmt *Case = I.getCase(); 3012 3013 // Evaluate the LHS of the case value. 3014 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext()); 3015 assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType())); 3016 3017 // Get the RHS of the case, if it exists. 3018 llvm::APSInt V2; 3019 if (const Expr *E = Case->getRHS()) 3020 V2 = E->EvaluateKnownConstInt(getContext()); 3021 else 3022 V2 = V1; 3023 3024 ProgramStateRef StateCase; 3025 if (std::optional<NonLoc> NL = CondV.getAs<NonLoc>()) 3026 std::tie(StateCase, DefaultSt) = 3027 DefaultSt->assumeInclusiveRange(*NL, V1, V2); 3028 else // UnknownVal 3029 StateCase = DefaultSt; 3030 3031 if (StateCase) 3032 builder.generateCaseStmtNode(I, StateCase); 3033 3034 // Now "assume" that the case doesn't match. Add this state 3035 // to the default state (if it is feasible). 3036 if (DefaultSt) 3037 defaultIsFeasible = true; 3038 else { 3039 defaultIsFeasible = false; 3040 break; 3041 } 3042 } 3043 3044 if (!defaultIsFeasible) 3045 return; 3046 3047 // If we have switch(enum value), the default branch is not 3048 // feasible if all of the enum constants not covered by 'case:' statements 3049 // are not feasible values for the switch condition. 3050 // 3051 // Note that this isn't as accurate as it could be. Even if there isn't 3052 // a case for a particular enum value as long as that enum value isn't 3053 // feasible then it shouldn't be considered for making 'default:' reachable. 3054 const SwitchStmt *SS = builder.getSwitch(); 3055 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts(); 3056 if (CondExpr->getType()->getAs<EnumType>()) { 3057 if (SS->isAllEnumCasesCovered()) 3058 return; 3059 } 3060 3061 builder.generateDefaultCaseNode(DefaultSt); 3062 } 3063 3064 //===----------------------------------------------------------------------===// 3065 // Transfer functions: Loads and stores. 3066 //===----------------------------------------------------------------------===// 3067 3068 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D, 3069 ExplodedNode *Pred, 3070 ExplodedNodeSet &Dst) { 3071 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 3072 3073 ProgramStateRef state = Pred->getState(); 3074 const LocationContext *LCtx = Pred->getLocationContext(); 3075 3076 if (const auto *VD = dyn_cast<VarDecl>(D)) { 3077 // C permits "extern void v", and if you cast the address to a valid type, 3078 // you can even do things with it. We simply pretend 3079 assert(Ex->isGLValue() || VD->getType()->isVoidType()); 3080 const LocationContext *LocCtxt = Pred->getLocationContext(); 3081 const Decl *D = LocCtxt->getDecl(); 3082 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D); 3083 const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex); 3084 std::optional<std::pair<SVal, QualType>> VInfo; 3085 3086 if (AMgr.options.ShouldInlineLambdas && DeclRefEx && 3087 DeclRefEx->refersToEnclosingVariableOrCapture() && MD && 3088 MD->getParent()->isLambda()) { 3089 // Lookup the field of the lambda. 3090 const CXXRecordDecl *CXXRec = MD->getParent(); 3091 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields; 3092 FieldDecl *LambdaThisCaptureField; 3093 CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField); 3094 3095 // Sema follows a sequence of complex rules to determine whether the 3096 // variable should be captured. 3097 if (const FieldDecl *FD = LambdaCaptureFields[VD]) { 3098 Loc CXXThis = 3099 svalBuilder.getCXXThis(MD, LocCtxt->getStackFrame()); 3100 SVal CXXThisVal = state->getSVal(CXXThis); 3101 VInfo = std::make_pair(state->getLValue(FD, CXXThisVal), FD->getType()); 3102 } 3103 } 3104 3105 if (!VInfo) 3106 VInfo = std::make_pair(state->getLValue(VD, LocCtxt), VD->getType()); 3107 3108 SVal V = VInfo->first; 3109 bool IsReference = VInfo->second->isReferenceType(); 3110 3111 // For references, the 'lvalue' is the pointer address stored in the 3112 // reference region. 3113 if (IsReference) { 3114 if (const MemRegion *R = V.getAsRegion()) 3115 V = state->getSVal(R); 3116 else 3117 V = UnknownVal(); 3118 } 3119 3120 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr, 3121 ProgramPoint::PostLValueKind); 3122 return; 3123 } 3124 if (const auto *ED = dyn_cast<EnumConstantDecl>(D)) { 3125 assert(!Ex->isGLValue()); 3126 SVal V = svalBuilder.makeIntVal(ED->getInitVal()); 3127 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V)); 3128 return; 3129 } 3130 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 3131 SVal V = svalBuilder.getFunctionPointer(FD); 3132 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr, 3133 ProgramPoint::PostLValueKind); 3134 return; 3135 } 3136 if (isa<FieldDecl, IndirectFieldDecl>(D)) { 3137 // Delegate all work related to pointer to members to the surrounding 3138 // operator&. 3139 return; 3140 } 3141 if (const auto *BD = dyn_cast<BindingDecl>(D)) { 3142 const auto *DD = cast<DecompositionDecl>(BD->getDecomposedDecl()); 3143 3144 SVal Base = state->getLValue(DD, LCtx); 3145 if (DD->getType()->isReferenceType()) { 3146 if (const MemRegion *R = Base.getAsRegion()) 3147 Base = state->getSVal(R); 3148 else 3149 Base = UnknownVal(); 3150 } 3151 3152 SVal V = UnknownVal(); 3153 3154 // Handle binding to data members 3155 if (const auto *ME = dyn_cast<MemberExpr>(BD->getBinding())) { 3156 const auto *Field = cast<FieldDecl>(ME->getMemberDecl()); 3157 V = state->getLValue(Field, Base); 3158 } 3159 // Handle binding to arrays 3160 else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BD->getBinding())) { 3161 SVal Idx = state->getSVal(ASE->getIdx(), LCtx); 3162 3163 // Note: the index of an element in a structured binding is automatically 3164 // created and it is a unique identifier of the specific element. Thus it 3165 // cannot be a value that varies at runtime. 3166 assert(Idx.isConstant() && "BindingDecl array index is not a constant!"); 3167 3168 V = state->getLValue(BD->getType(), Idx, Base); 3169 } 3170 // Handle binding to tuple-like structures 3171 else if (const auto *HV = BD->getHoldingVar()) { 3172 V = state->getLValue(HV, LCtx); 3173 3174 if (HV->getType()->isReferenceType()) { 3175 if (const MemRegion *R = V.getAsRegion()) 3176 V = state->getSVal(R); 3177 else 3178 V = UnknownVal(); 3179 } 3180 } else 3181 llvm_unreachable("An unknown case of structured binding encountered!"); 3182 3183 // In case of tuple-like types the references are already handled, so we 3184 // don't want to handle them again. 3185 if (BD->getType()->isReferenceType() && !BD->getHoldingVar()) { 3186 if (const MemRegion *R = V.getAsRegion()) 3187 V = state->getSVal(R); 3188 else 3189 V = UnknownVal(); 3190 } 3191 3192 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr, 3193 ProgramPoint::PostLValueKind); 3194 3195 return; 3196 } 3197 3198 if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 3199 // FIXME: We should meaningfully implement this. 3200 (void)TPO; 3201 return; 3202 } 3203 3204 llvm_unreachable("Support for this Decl not implemented."); 3205 } 3206 3207 /// VisitArrayInitLoopExpr - Transfer function for array init loop. 3208 void ExprEngine::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *Ex, 3209 ExplodedNode *Pred, 3210 ExplodedNodeSet &Dst) { 3211 ExplodedNodeSet CheckerPreStmt; 3212 getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, Ex, *this); 3213 3214 ExplodedNodeSet EvalSet; 3215 StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx); 3216 3217 const Expr *Arr = Ex->getCommonExpr()->getSourceExpr(); 3218 3219 for (auto *Node : CheckerPreStmt) { 3220 3221 // The constructor visitior has already taken care of everything. 3222 if (isa<CXXConstructExpr>(Ex->getSubExpr())) 3223 break; 3224 3225 const LocationContext *LCtx = Node->getLocationContext(); 3226 ProgramStateRef state = Node->getState(); 3227 3228 SVal Base = UnknownVal(); 3229 3230 // As in case of this expression the sub-expressions are not visited by any 3231 // other transfer functions, they are handled by matching their AST. 3232 3233 // Case of implicit copy or move ctor of object with array member 3234 // 3235 // Note: ExprEngine::VisitMemberExpr is not able to bind the array to the 3236 // environment. 3237 // 3238 // struct S { 3239 // int arr[2]; 3240 // }; 3241 // 3242 // 3243 // S a; 3244 // S b = a; 3245 // 3246 // The AST in case of a *copy constructor* looks like this: 3247 // ArrayInitLoopExpr 3248 // |-OpaqueValueExpr 3249 // | `-MemberExpr <-- match this 3250 // | `-DeclRefExpr 3251 // ` ... 3252 // 3253 // 3254 // S c; 3255 // S d = std::move(d); 3256 // 3257 // In case of a *move constructor* the resulting AST looks like: 3258 // ArrayInitLoopExpr 3259 // |-OpaqueValueExpr 3260 // | `-MemberExpr <-- match this first 3261 // | `-CXXStaticCastExpr <-- match this after 3262 // | `-DeclRefExpr 3263 // ` ... 3264 if (const auto *ME = dyn_cast<MemberExpr>(Arr)) { 3265 Expr *MEBase = ME->getBase(); 3266 3267 // Move ctor 3268 if (auto CXXSCE = dyn_cast<CXXStaticCastExpr>(MEBase)) { 3269 MEBase = CXXSCE->getSubExpr(); 3270 } 3271 3272 auto ObjDeclExpr = cast<DeclRefExpr>(MEBase); 3273 SVal Obj = state->getLValue(cast<VarDecl>(ObjDeclExpr->getDecl()), LCtx); 3274 3275 Base = state->getLValue(cast<FieldDecl>(ME->getMemberDecl()), Obj); 3276 } 3277 3278 // Case of lambda capture and decomposition declaration 3279 // 3280 // int arr[2]; 3281 // 3282 // [arr]{ int a = arr[0]; }(); 3283 // auto[a, b] = arr; 3284 // 3285 // In both of these cases the AST looks like the following: 3286 // ArrayInitLoopExpr 3287 // |-OpaqueValueExpr 3288 // | `-DeclRefExpr <-- match this 3289 // ` ... 3290 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arr)) 3291 Base = state->getLValue(cast<VarDecl>(DRE->getDecl()), LCtx); 3292 3293 // Create a lazy compound value to the original array 3294 if (const MemRegion *R = Base.getAsRegion()) 3295 Base = state->getSVal(R); 3296 else 3297 Base = UnknownVal(); 3298 3299 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, Base)); 3300 } 3301 3302 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, Ex, *this); 3303 } 3304 3305 /// VisitArraySubscriptExpr - Transfer function for array accesses 3306 void ExprEngine::VisitArraySubscriptExpr(const ArraySubscriptExpr *A, 3307 ExplodedNode *Pred, 3308 ExplodedNodeSet &Dst){ 3309 const Expr *Base = A->getBase()->IgnoreParens(); 3310 const Expr *Idx = A->getIdx()->IgnoreParens(); 3311 3312 ExplodedNodeSet CheckerPreStmt; 3313 getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this); 3314 3315 ExplodedNodeSet EvalSet; 3316 StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx); 3317 3318 bool IsVectorType = A->getBase()->getType()->isVectorType(); 3319 3320 // The "like" case is for situations where C standard prohibits the type to 3321 // be an lvalue, e.g. taking the address of a subscript of an expression of 3322 // type "void *". 3323 bool IsGLValueLike = A->isGLValue() || 3324 (A->getType().isCForbiddenLValueType() && !AMgr.getLangOpts().CPlusPlus); 3325 3326 for (auto *Node : CheckerPreStmt) { 3327 const LocationContext *LCtx = Node->getLocationContext(); 3328 ProgramStateRef state = Node->getState(); 3329 3330 if (IsGLValueLike) { 3331 QualType T = A->getType(); 3332 3333 // One of the forbidden LValue types! We still need to have sensible 3334 // symbolic locations to represent this stuff. Note that arithmetic on 3335 // void pointers is a GCC extension. 3336 if (T->isVoidType()) 3337 T = getContext().CharTy; 3338 3339 SVal V = state->getLValue(T, 3340 state->getSVal(Idx, LCtx), 3341 state->getSVal(Base, LCtx)); 3342 Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr, 3343 ProgramPoint::PostLValueKind); 3344 } else if (IsVectorType) { 3345 // FIXME: non-glvalue vector reads are not modelled. 3346 Bldr.generateNode(A, Node, state, nullptr); 3347 } else { 3348 llvm_unreachable("Array subscript should be an lValue when not \ 3349 a vector and not a forbidden lvalue type"); 3350 } 3351 } 3352 3353 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this); 3354 } 3355 3356 /// VisitMemberExpr - Transfer function for member expressions. 3357 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, 3358 ExplodedNodeSet &Dst) { 3359 // FIXME: Prechecks eventually go in ::Visit(). 3360 ExplodedNodeSet CheckedSet; 3361 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this); 3362 3363 ExplodedNodeSet EvalSet; 3364 ValueDecl *Member = M->getMemberDecl(); 3365 3366 // Handle static member variables and enum constants accessed via 3367 // member syntax. 3368 if (isa<VarDecl, EnumConstantDecl>(Member)) { 3369 for (const auto I : CheckedSet) 3370 VisitCommonDeclRefExpr(M, Member, I, EvalSet); 3371 } else { 3372 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx); 3373 ExplodedNodeSet Tmp; 3374 3375 for (const auto I : CheckedSet) { 3376 ProgramStateRef state = I->getState(); 3377 const LocationContext *LCtx = I->getLocationContext(); 3378 Expr *BaseExpr = M->getBase(); 3379 3380 // Handle C++ method calls. 3381 if (const auto *MD = dyn_cast<CXXMethodDecl>(Member)) { 3382 if (MD->isImplicitObjectMemberFunction()) 3383 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr); 3384 3385 SVal MDVal = svalBuilder.getFunctionPointer(MD); 3386 state = state->BindExpr(M, LCtx, MDVal); 3387 3388 Bldr.generateNode(M, I, state); 3389 continue; 3390 } 3391 3392 // Handle regular struct fields / member variables. 3393 const SubRegion *MR = nullptr; 3394 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr, 3395 /*Result=*/nullptr, 3396 /*OutRegionWithAdjustments=*/&MR); 3397 SVal baseExprVal = 3398 MR ? loc::MemRegionVal(MR) : state->getSVal(BaseExpr, LCtx); 3399 3400 // FIXME: Copied from RegionStoreManager::bind() 3401 if (const auto *SR = 3402 dyn_cast_or_null<SymbolicRegion>(baseExprVal.getAsRegion())) { 3403 QualType T = SR->getPointeeStaticType(); 3404 baseExprVal = 3405 loc::MemRegionVal(getStoreManager().GetElementZeroRegion(SR, T)); 3406 } 3407 3408 const auto *field = cast<FieldDecl>(Member); 3409 SVal L = state->getLValue(field, baseExprVal); 3410 3411 if (M->isGLValue() || M->getType()->isArrayType()) { 3412 // We special-case rvalues of array type because the analyzer cannot 3413 // reason about them, since we expect all regions to be wrapped in Locs. 3414 // We instead treat these as lvalues and assume that they will decay to 3415 // pointers as soon as they are used. 3416 if (!M->isGLValue()) { 3417 assert(M->getType()->isArrayType()); 3418 const auto *PE = 3419 dyn_cast<ImplicitCastExpr>(I->getParentMap().getParentIgnoreParens(M)); 3420 if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) { 3421 llvm_unreachable("should always be wrapped in ArrayToPointerDecay"); 3422 } 3423 } 3424 3425 if (field->getType()->isReferenceType()) { 3426 if (const MemRegion *R = L.getAsRegion()) 3427 L = state->getSVal(R); 3428 else 3429 L = UnknownVal(); 3430 } 3431 3432 Bldr.generateNode(M, I, state->BindExpr(M, LCtx, L), nullptr, 3433 ProgramPoint::PostLValueKind); 3434 } else { 3435 Bldr.takeNodes(I); 3436 evalLoad(Tmp, M, M, I, state, L); 3437 Bldr.addNodes(Tmp); 3438 } 3439 } 3440 } 3441 3442 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this); 3443 } 3444 3445 void ExprEngine::VisitAtomicExpr(const AtomicExpr *AE, ExplodedNode *Pred, 3446 ExplodedNodeSet &Dst) { 3447 ExplodedNodeSet AfterPreSet; 3448 getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this); 3449 3450 // For now, treat all the arguments to C11 atomics as escaping. 3451 // FIXME: Ideally we should model the behavior of the atomics precisely here. 3452 3453 ExplodedNodeSet AfterInvalidateSet; 3454 StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx); 3455 3456 for (const auto I : AfterPreSet) { 3457 ProgramStateRef State = I->getState(); 3458 const LocationContext *LCtx = I->getLocationContext(); 3459 3460 SmallVector<SVal, 8> ValuesToInvalidate; 3461 for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) { 3462 const Expr *SubExpr = AE->getSubExprs()[SI]; 3463 SVal SubExprVal = State->getSVal(SubExpr, LCtx); 3464 ValuesToInvalidate.push_back(SubExprVal); 3465 } 3466 3467 State = State->invalidateRegions(ValuesToInvalidate, AE, 3468 currBldrCtx->blockCount(), 3469 LCtx, 3470 /*CausedByPointerEscape*/true, 3471 /*Symbols=*/nullptr); 3472 3473 SVal ResultVal = UnknownVal(); 3474 State = State->BindExpr(AE, LCtx, ResultVal); 3475 Bldr.generateNode(AE, I, State, nullptr, 3476 ProgramPoint::PostStmtKind); 3477 } 3478 3479 getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this); 3480 } 3481 3482 // A value escapes in four possible cases: 3483 // (1) We are binding to something that is not a memory region. 3484 // (2) We are binding to a MemRegion that does not have stack storage. 3485 // (3) We are binding to a top-level parameter region with a non-trivial 3486 // destructor. We won't see the destructor during analysis, but it's there. 3487 // (4) We are binding to a MemRegion with stack storage that the store 3488 // does not understand. 3489 ProgramStateRef ExprEngine::processPointerEscapedOnBind( 3490 ProgramStateRef State, ArrayRef<std::pair<SVal, SVal>> LocAndVals, 3491 const LocationContext *LCtx, PointerEscapeKind Kind, 3492 const CallEvent *Call) { 3493 SmallVector<SVal, 8> Escaped; 3494 for (const std::pair<SVal, SVal> &LocAndVal : LocAndVals) { 3495 // Cases (1) and (2). 3496 const MemRegion *MR = LocAndVal.first.getAsRegion(); 3497 if (!MR || 3498 !isa<StackSpaceRegion, StaticGlobalSpaceRegion>(MR->getMemorySpace())) { 3499 Escaped.push_back(LocAndVal.second); 3500 continue; 3501 } 3502 3503 // Case (3). 3504 if (const auto *VR = dyn_cast<VarRegion>(MR->getBaseRegion())) 3505 if (VR->hasStackParametersStorage() && VR->getStackFrame()->inTopFrame()) 3506 if (const auto *RD = VR->getValueType()->getAsCXXRecordDecl()) 3507 if (!RD->hasTrivialDestructor()) { 3508 Escaped.push_back(LocAndVal.second); 3509 continue; 3510 } 3511 3512 // Case (4): in order to test that, generate a new state with the binding 3513 // added. If it is the same state, then it escapes (since the store cannot 3514 // represent the binding). 3515 // Do this only if we know that the store is not supposed to generate the 3516 // same state. 3517 SVal StoredVal = State->getSVal(MR); 3518 if (StoredVal != LocAndVal.second) 3519 if (State == 3520 (State->bindLoc(loc::MemRegionVal(MR), LocAndVal.second, LCtx))) 3521 Escaped.push_back(LocAndVal.second); 3522 } 3523 3524 if (Escaped.empty()) 3525 return State; 3526 3527 return escapeValues(State, Escaped, Kind, Call); 3528 } 3529 3530 ProgramStateRef 3531 ExprEngine::processPointerEscapedOnBind(ProgramStateRef State, SVal Loc, 3532 SVal Val, const LocationContext *LCtx) { 3533 std::pair<SVal, SVal> LocAndVal(Loc, Val); 3534 return processPointerEscapedOnBind(State, LocAndVal, LCtx, PSK_EscapeOnBind, 3535 nullptr); 3536 } 3537 3538 ProgramStateRef 3539 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State, 3540 const InvalidatedSymbols *Invalidated, 3541 ArrayRef<const MemRegion *> ExplicitRegions, 3542 const CallEvent *Call, 3543 RegionAndSymbolInvalidationTraits &ITraits) { 3544 if (!Invalidated || Invalidated->empty()) 3545 return State; 3546 3547 if (!Call) 3548 return getCheckerManager().runCheckersForPointerEscape(State, 3549 *Invalidated, 3550 nullptr, 3551 PSK_EscapeOther, 3552 &ITraits); 3553 3554 // If the symbols were invalidated by a call, we want to find out which ones 3555 // were invalidated directly due to being arguments to the call. 3556 InvalidatedSymbols SymbolsDirectlyInvalidated; 3557 for (const auto I : ExplicitRegions) { 3558 if (const SymbolicRegion *R = I->StripCasts()->getAs<SymbolicRegion>()) 3559 SymbolsDirectlyInvalidated.insert(R->getSymbol()); 3560 } 3561 3562 InvalidatedSymbols SymbolsIndirectlyInvalidated; 3563 for (const auto &sym : *Invalidated) { 3564 if (SymbolsDirectlyInvalidated.count(sym)) 3565 continue; 3566 SymbolsIndirectlyInvalidated.insert(sym); 3567 } 3568 3569 if (!SymbolsDirectlyInvalidated.empty()) 3570 State = getCheckerManager().runCheckersForPointerEscape(State, 3571 SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits); 3572 3573 // Notify about the symbols that get indirectly invalidated by the call. 3574 if (!SymbolsIndirectlyInvalidated.empty()) 3575 State = getCheckerManager().runCheckersForPointerEscape(State, 3576 SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits); 3577 3578 return State; 3579 } 3580 3581 /// evalBind - Handle the semantics of binding a value to a specific location. 3582 /// This method is used by evalStore and (soon) VisitDeclStmt, and others. 3583 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, 3584 ExplodedNode *Pred, 3585 SVal location, SVal Val, 3586 bool atDeclInit, const ProgramPoint *PP) { 3587 const LocationContext *LC = Pred->getLocationContext(); 3588 PostStmt PS(StoreE, LC); 3589 if (!PP) 3590 PP = &PS; 3591 3592 // Do a previsit of the bind. 3593 ExplodedNodeSet CheckedSet; 3594 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val, 3595 StoreE, *this, *PP); 3596 3597 StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx); 3598 3599 // If the location is not a 'Loc', it will already be handled by 3600 // the checkers. There is nothing left to do. 3601 if (!isa<Loc>(location)) { 3602 const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr, 3603 /*tag*/nullptr); 3604 ProgramStateRef state = Pred->getState(); 3605 state = processPointerEscapedOnBind(state, location, Val, LC); 3606 Bldr.generateNode(L, state, Pred); 3607 return; 3608 } 3609 3610 for (const auto PredI : CheckedSet) { 3611 ProgramStateRef state = PredI->getState(); 3612 3613 state = processPointerEscapedOnBind(state, location, Val, LC); 3614 3615 // When binding the value, pass on the hint that this is a initialization. 3616 // For initializations, we do not need to inform clients of region 3617 // changes. 3618 state = state->bindLoc(location.castAs<Loc>(), 3619 Val, LC, /* notifyChanges = */ !atDeclInit); 3620 3621 const MemRegion *LocReg = nullptr; 3622 if (std::optional<loc::MemRegionVal> LocRegVal = 3623 location.getAs<loc::MemRegionVal>()) { 3624 LocReg = LocRegVal->getRegion(); 3625 } 3626 3627 const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr); 3628 Bldr.generateNode(L, state, PredI); 3629 } 3630 } 3631 3632 /// evalStore - Handle the semantics of a store via an assignment. 3633 /// @param Dst The node set to store generated state nodes 3634 /// @param AssignE The assignment expression if the store happens in an 3635 /// assignment. 3636 /// @param LocationE The location expression that is stored to. 3637 /// @param state The current simulation state 3638 /// @param location The location to store the value 3639 /// @param Val The value to be stored 3640 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, 3641 const Expr *LocationE, 3642 ExplodedNode *Pred, 3643 ProgramStateRef state, SVal location, SVal Val, 3644 const ProgramPointTag *tag) { 3645 // Proceed with the store. We use AssignE as the anchor for the PostStore 3646 // ProgramPoint if it is non-NULL, and LocationE otherwise. 3647 const Expr *StoreE = AssignE ? AssignE : LocationE; 3648 3649 // Evaluate the location (checks for bad dereferences). 3650 ExplodedNodeSet Tmp; 3651 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, false); 3652 3653 if (Tmp.empty()) 3654 return; 3655 3656 if (location.isUndef()) 3657 return; 3658 3659 for (const auto I : Tmp) 3660 evalBind(Dst, StoreE, I, location, Val, false); 3661 } 3662 3663 void ExprEngine::evalLoad(ExplodedNodeSet &Dst, 3664 const Expr *NodeEx, 3665 const Expr *BoundEx, 3666 ExplodedNode *Pred, 3667 ProgramStateRef state, 3668 SVal location, 3669 const ProgramPointTag *tag, 3670 QualType LoadTy) { 3671 assert(!isa<NonLoc>(location) && "location cannot be a NonLoc."); 3672 assert(NodeEx); 3673 assert(BoundEx); 3674 // Evaluate the location (checks for bad dereferences). 3675 ExplodedNodeSet Tmp; 3676 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, true); 3677 if (Tmp.empty()) 3678 return; 3679 3680 StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx); 3681 if (location.isUndef()) 3682 return; 3683 3684 // Proceed with the load. 3685 for (const auto I : Tmp) { 3686 state = I->getState(); 3687 const LocationContext *LCtx = I->getLocationContext(); 3688 3689 SVal V = UnknownVal(); 3690 if (location.isValid()) { 3691 if (LoadTy.isNull()) 3692 LoadTy = BoundEx->getType(); 3693 V = state->getSVal(location.castAs<Loc>(), LoadTy); 3694 } 3695 3696 Bldr.generateNode(NodeEx, I, state->BindExpr(BoundEx, LCtx, V), tag, 3697 ProgramPoint::PostLoadKind); 3698 } 3699 } 3700 3701 void ExprEngine::evalLocation(ExplodedNodeSet &Dst, 3702 const Stmt *NodeEx, 3703 const Stmt *BoundEx, 3704 ExplodedNode *Pred, 3705 ProgramStateRef state, 3706 SVal location, 3707 bool isLoad) { 3708 StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx); 3709 // Early checks for performance reason. 3710 if (location.isUnknown()) { 3711 return; 3712 } 3713 3714 ExplodedNodeSet Src; 3715 BldrTop.takeNodes(Pred); 3716 StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx); 3717 if (Pred->getState() != state) { 3718 // Associate this new state with an ExplodedNode. 3719 // FIXME: If I pass null tag, the graph is incorrect, e.g for 3720 // int *p; 3721 // p = 0; 3722 // *p = 0xDEADBEEF; 3723 // "p = 0" is not noted as "Null pointer value stored to 'p'" but 3724 // instead "int *p" is noted as 3725 // "Variable 'p' initialized to a null pointer value" 3726 3727 static SimpleProgramPointTag tag(TagProviderName, "Location"); 3728 Bldr.generateNode(NodeEx, Pred, state, &tag); 3729 } 3730 ExplodedNodeSet Tmp; 3731 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad, 3732 NodeEx, BoundEx, *this); 3733 BldrTop.addNodes(Tmp); 3734 } 3735 3736 std::pair<const ProgramPointTag *, const ProgramPointTag*> 3737 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() { 3738 static SimpleProgramPointTag 3739 eagerlyAssumeBinOpBifurcationTrue(TagProviderName, 3740 "Eagerly Assume True"), 3741 eagerlyAssumeBinOpBifurcationFalse(TagProviderName, 3742 "Eagerly Assume False"); 3743 return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue, 3744 &eagerlyAssumeBinOpBifurcationFalse); 3745 } 3746 3747 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, 3748 ExplodedNodeSet &Src, 3749 const Expr *Ex) { 3750 StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx); 3751 3752 for (const auto Pred : Src) { 3753 // Test if the previous node was as the same expression. This can happen 3754 // when the expression fails to evaluate to anything meaningful and 3755 // (as an optimization) we don't generate a node. 3756 ProgramPoint P = Pred->getLocation(); 3757 if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) { 3758 continue; 3759 } 3760 3761 ProgramStateRef state = Pred->getState(); 3762 SVal V = state->getSVal(Ex, Pred->getLocationContext()); 3763 std::optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>(); 3764 if (SEV && SEV->isExpression()) { 3765 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags = 3766 geteagerlyAssumeBinOpBifurcationTags(); 3767 3768 ProgramStateRef StateTrue, StateFalse; 3769 std::tie(StateTrue, StateFalse) = state->assume(*SEV); 3770 3771 // First assume that the condition is true. 3772 if (StateTrue) { 3773 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType()); 3774 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val); 3775 Bldr.generateNode(Ex, Pred, StateTrue, tags.first); 3776 } 3777 3778 // Next, assume that the condition is false. 3779 if (StateFalse) { 3780 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType()); 3781 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val); 3782 Bldr.generateNode(Ex, Pred, StateFalse, tags.second); 3783 } 3784 } 3785 } 3786 } 3787 3788 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, 3789 ExplodedNodeSet &Dst) { 3790 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 3791 // We have processed both the inputs and the outputs. All of the outputs 3792 // should evaluate to Locs. Nuke all of their values. 3793 3794 // FIXME: Some day in the future it would be nice to allow a "plug-in" 3795 // which interprets the inline asm and stores proper results in the 3796 // outputs. 3797 3798 ProgramStateRef state = Pred->getState(); 3799 3800 for (const Expr *O : A->outputs()) { 3801 SVal X = state->getSVal(O, Pred->getLocationContext()); 3802 assert(!isa<NonLoc>(X)); // Should be an Lval, or unknown, undef. 3803 3804 if (std::optional<Loc> LV = X.getAs<Loc>()) 3805 state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext()); 3806 } 3807 3808 Bldr.generateNode(A, Pred, state); 3809 } 3810 3811 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred, 3812 ExplodedNodeSet &Dst) { 3813 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 3814 Bldr.generateNode(A, Pred, Pred->getState()); 3815 } 3816 3817 //===----------------------------------------------------------------------===// 3818 // Visualization. 3819 //===----------------------------------------------------------------------===// 3820 3821 namespace llvm { 3822 3823 template<> 3824 struct DOTGraphTraits<ExplodedGraph*> : public DefaultDOTGraphTraits { 3825 DOTGraphTraits (bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 3826 3827 static bool nodeHasBugReport(const ExplodedNode *N) { 3828 BugReporter &BR = static_cast<ExprEngine &>( 3829 N->getState()->getStateManager().getOwningEngine()).getBugReporter(); 3830 3831 for (const auto &Class : BR.equivalenceClasses()) { 3832 for (const auto &Report : Class.getReports()) { 3833 const auto *PR = dyn_cast<PathSensitiveBugReport>(Report.get()); 3834 if (!PR) 3835 continue; 3836 const ExplodedNode *EN = PR->getErrorNode(); 3837 if (EN->getState() == N->getState() && 3838 EN->getLocation() == N->getLocation()) 3839 return true; 3840 } 3841 } 3842 return false; 3843 } 3844 3845 /// \p PreCallback: callback before break. 3846 /// \p PostCallback: callback after break. 3847 /// \p Stop: stop iteration if returns @c true 3848 /// \return Whether @c Stop ever returned @c true. 3849 static bool traverseHiddenNodes( 3850 const ExplodedNode *N, 3851 llvm::function_ref<void(const ExplodedNode *)> PreCallback, 3852 llvm::function_ref<void(const ExplodedNode *)> PostCallback, 3853 llvm::function_ref<bool(const ExplodedNode *)> Stop) { 3854 while (true) { 3855 PreCallback(N); 3856 if (Stop(N)) 3857 return true; 3858 3859 if (N->succ_size() != 1 || !isNodeHidden(N->getFirstSucc(), nullptr)) 3860 break; 3861 PostCallback(N); 3862 3863 N = N->getFirstSucc(); 3864 } 3865 return false; 3866 } 3867 3868 static bool isNodeHidden(const ExplodedNode *N, const ExplodedGraph *G) { 3869 return N->isTrivial(); 3870 } 3871 3872 static std::string getNodeLabel(const ExplodedNode *N, ExplodedGraph *G){ 3873 std::string Buf; 3874 llvm::raw_string_ostream Out(Buf); 3875 3876 const bool IsDot = true; 3877 const unsigned int Space = 1; 3878 ProgramStateRef State = N->getState(); 3879 3880 Out << "{ \"state_id\": " << State->getID() 3881 << ",\\l"; 3882 3883 Indent(Out, Space, IsDot) << "\"program_points\": [\\l"; 3884 3885 // Dump program point for all the previously skipped nodes. 3886 traverseHiddenNodes( 3887 N, 3888 [&](const ExplodedNode *OtherNode) { 3889 Indent(Out, Space + 1, IsDot) << "{ "; 3890 OtherNode->getLocation().printJson(Out, /*NL=*/"\\l"); 3891 Out << ", \"tag\": "; 3892 if (const ProgramPointTag *Tag = OtherNode->getLocation().getTag()) 3893 Out << '\"' << Tag->getTagDescription() << '\"'; 3894 else 3895 Out << "null"; 3896 Out << ", \"node_id\": " << OtherNode->getID() << 3897 ", \"is_sink\": " << OtherNode->isSink() << 3898 ", \"has_report\": " << nodeHasBugReport(OtherNode) << " }"; 3899 }, 3900 // Adds a comma and a new-line between each program point. 3901 [&](const ExplodedNode *) { Out << ",\\l"; }, 3902 [&](const ExplodedNode *) { return false; }); 3903 3904 Out << "\\l"; // Adds a new-line to the last program point. 3905 Indent(Out, Space, IsDot) << "],\\l"; 3906 3907 State->printDOT(Out, N->getLocationContext(), Space); 3908 3909 Out << "\\l}\\l"; 3910 return Buf; 3911 } 3912 }; 3913 3914 } // namespace llvm 3915 3916 void ExprEngine::ViewGraph(bool trim) { 3917 std::string Filename = DumpGraph(trim); 3918 llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT); 3919 } 3920 3921 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode *> Nodes) { 3922 std::string Filename = DumpGraph(Nodes); 3923 llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT); 3924 } 3925 3926 std::string ExprEngine::DumpGraph(bool trim, StringRef Filename) { 3927 if (trim) { 3928 std::vector<const ExplodedNode *> Src; 3929 3930 // Iterate through the reports and get their nodes. 3931 for (const auto &Class : BR.equivalenceClasses()) { 3932 const auto *R = 3933 dyn_cast<PathSensitiveBugReport>(Class.getReports()[0].get()); 3934 if (!R) 3935 continue; 3936 const auto *N = const_cast<ExplodedNode *>(R->getErrorNode()); 3937 Src.push_back(N); 3938 } 3939 return DumpGraph(Src, Filename); 3940 } 3941 3942 return llvm::WriteGraph(&G, "ExprEngine", /*ShortNames=*/false, 3943 /*Title=*/"Exploded Graph", 3944 /*Filename=*/std::string(Filename)); 3945 } 3946 3947 std::string ExprEngine::DumpGraph(ArrayRef<const ExplodedNode *> Nodes, 3948 StringRef Filename) { 3949 std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes)); 3950 3951 if (!TrimmedG.get()) { 3952 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n"; 3953 return ""; 3954 } 3955 3956 return llvm::WriteGraph(TrimmedG.get(), "TrimmedExprEngine", 3957 /*ShortNames=*/false, 3958 /*Title=*/"Trimmed Exploded Graph", 3959 /*Filename=*/std::string(Filename)); 3960 } 3961 3962 void *ProgramStateTrait<ReplayWithoutInlining>::GDMIndex() { 3963 static int index = 0; 3964 return &index; 3965 } 3966 3967 void ExprEngine::anchor() { } 3968