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