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