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.removeDeadBindingsFromEnvironmentAndStore( 732 CleanedState, SFC, SymReaper); 733 734 // Process any special transfer function for dead symbols. 735 // A tag to track convenience transitions, which can be removed at cleanup. 736 static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node"); 737 // Call checkers with the non-cleaned state so that they could query the 738 // values of the soon to be dead symbols. 739 ExplodedNodeSet CheckedSet; 740 getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper, 741 DiagnosticStmt, *this, K); 742 743 // For each node in CheckedSet, generate CleanedNodes that have the 744 // environment, the store, and the constraints cleaned up but have the 745 // user-supplied states as the predecessors. 746 StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx); 747 for (const auto I : CheckedSet) { 748 ProgramStateRef CheckerState = I->getState(); 749 750 // The constraint manager has not been cleaned up yet, so clean up now. 751 CheckerState = 752 getConstraintManager().removeDeadBindings(CheckerState, SymReaper); 753 754 assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) && 755 "Checkers are not allowed to modify the Environment as a part of " 756 "checkDeadSymbols processing."); 757 assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) && 758 "Checkers are not allowed to modify the Store as a part of " 759 "checkDeadSymbols processing."); 760 761 // Create a state based on CleanedState with CheckerState GDM and 762 // generate a transition to that state. 763 ProgramStateRef CleanedCheckerSt = 764 StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState); 765 Bldr.generateNode(DiagnosticStmt, I, CleanedCheckerSt, &cleanupTag, K); 766 } 767 } 768 769 void ExprEngine::ProcessStmt(const Stmt *currStmt, ExplodedNode *Pred) { 770 // Reclaim any unnecessary nodes in the ExplodedGraph. 771 G.reclaimRecentlyAllocatedNodes(); 772 773 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 774 currStmt->getBeginLoc(), 775 "Error evaluating statement"); 776 777 // Remove dead bindings and symbols. 778 ExplodedNodeSet CleanedStates; 779 if (shouldRemoveDeadBindings(AMgr, currStmt, Pred, 780 Pred->getLocationContext())) { 781 removeDead(Pred, CleanedStates, currStmt, 782 Pred->getLocationContext()); 783 } else 784 CleanedStates.Add(Pred); 785 786 // Visit the statement. 787 ExplodedNodeSet Dst; 788 for (const auto I : CleanedStates) { 789 ExplodedNodeSet DstI; 790 // Visit the statement. 791 Visit(currStmt, I, DstI); 792 Dst.insert(DstI); 793 } 794 795 // Enqueue the new nodes onto the work list. 796 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 797 } 798 799 void ExprEngine::ProcessLoopExit(const Stmt* S, ExplodedNode *Pred) { 800 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 801 S->getBeginLoc(), 802 "Error evaluating end of the loop"); 803 ExplodedNodeSet Dst; 804 Dst.Add(Pred); 805 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 806 ProgramStateRef NewState = Pred->getState(); 807 808 if(AMgr.options.ShouldUnrollLoops) 809 NewState = processLoopEnd(S, NewState); 810 811 LoopExit PP(S, Pred->getLocationContext()); 812 Bldr.generateNode(PP, NewState, Pred); 813 // Enqueue the new nodes onto the work list. 814 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 815 } 816 817 void ExprEngine::ProcessInitializer(const CFGInitializer CFGInit, 818 ExplodedNode *Pred) { 819 const CXXCtorInitializer *BMI = CFGInit.getInitializer(); 820 const Expr *Init = BMI->getInit()->IgnoreImplicit(); 821 const LocationContext *LC = Pred->getLocationContext(); 822 823 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 824 BMI->getSourceLocation(), 825 "Error evaluating initializer"); 826 827 // We don't clean up dead bindings here. 828 const auto *stackFrame = cast<StackFrameContext>(Pred->getLocationContext()); 829 const auto *decl = cast<CXXConstructorDecl>(stackFrame->getDecl()); 830 831 ProgramStateRef State = Pred->getState(); 832 SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame)); 833 834 ExplodedNodeSet Tmp; 835 SVal FieldLoc; 836 837 // Evaluate the initializer, if necessary 838 if (BMI->isAnyMemberInitializer()) { 839 // Constructors build the object directly in the field, 840 // but non-objects must be copied in from the initializer. 841 if (getObjectUnderConstruction(State, BMI, LC)) { 842 // The field was directly constructed, so there is no need to bind. 843 // But we still need to stop tracking the object under construction. 844 State = finishObjectConstruction(State, BMI, LC); 845 NodeBuilder Bldr(Pred, Tmp, *currBldrCtx); 846 PostStore PS(Init, LC, /*Loc*/ nullptr, /*tag*/ nullptr); 847 Bldr.generateNode(PS, State, Pred); 848 } else { 849 const ValueDecl *Field; 850 if (BMI->isIndirectMemberInitializer()) { 851 Field = BMI->getIndirectMember(); 852 FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal); 853 } else { 854 Field = BMI->getMember(); 855 FieldLoc = State->getLValue(BMI->getMember(), thisVal); 856 } 857 858 SVal InitVal; 859 if (Init->getType()->isArrayType()) { 860 // Handle arrays of trivial type. We can represent this with a 861 // primitive load/copy from the base array region. 862 const ArraySubscriptExpr *ASE; 863 while ((ASE = dyn_cast<ArraySubscriptExpr>(Init))) 864 Init = ASE->getBase()->IgnoreImplicit(); 865 866 SVal LValue = State->getSVal(Init, stackFrame); 867 if (!Field->getType()->isReferenceType()) 868 if (Optional<Loc> LValueLoc = LValue.getAs<Loc>()) 869 InitVal = State->getSVal(*LValueLoc); 870 871 // If we fail to get the value for some reason, use a symbolic value. 872 if (InitVal.isUnknownOrUndef()) { 873 SValBuilder &SVB = getSValBuilder(); 874 InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame, 875 Field->getType(), 876 currBldrCtx->blockCount()); 877 } 878 } else { 879 InitVal = State->getSVal(BMI->getInit(), stackFrame); 880 } 881 882 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame); 883 evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP); 884 } 885 } else { 886 assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer()); 887 Tmp.insert(Pred); 888 // We already did all the work when visiting the CXXConstructExpr. 889 } 890 891 // Construct PostInitializer nodes whether the state changed or not, 892 // so that the diagnostics don't get confused. 893 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame); 894 ExplodedNodeSet Dst; 895 NodeBuilder Bldr(Tmp, Dst, *currBldrCtx); 896 for (const auto I : Tmp) { 897 ProgramStateRef State = I->getState(); 898 Bldr.generateNode(PP, State, I); 899 } 900 901 // Enqueue the new nodes onto the work list. 902 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 903 } 904 905 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D, 906 ExplodedNode *Pred) { 907 ExplodedNodeSet Dst; 908 switch (D.getKind()) { 909 case CFGElement::AutomaticObjectDtor: 910 ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst); 911 break; 912 case CFGElement::BaseDtor: 913 ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst); 914 break; 915 case CFGElement::MemberDtor: 916 ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst); 917 break; 918 case CFGElement::TemporaryDtor: 919 ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst); 920 break; 921 case CFGElement::DeleteDtor: 922 ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst); 923 break; 924 default: 925 llvm_unreachable("Unexpected dtor kind."); 926 } 927 928 // Enqueue the new nodes onto the work list. 929 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 930 } 931 932 void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE, 933 ExplodedNode *Pred) { 934 ExplodedNodeSet Dst; 935 AnalysisManager &AMgr = getAnalysisManager(); 936 AnalyzerOptions &Opts = AMgr.options; 937 // TODO: We're not evaluating allocators for all cases just yet as 938 // we're not handling the return value correctly, which causes false 939 // positives when the alpha.cplusplus.NewDeleteLeaks check is on. 940 if (Opts.MayInlineCXXAllocator) 941 VisitCXXNewAllocatorCall(NE, Pred, Dst); 942 else { 943 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 944 const LocationContext *LCtx = Pred->getLocationContext(); 945 PostImplicitCall PP(NE->getOperatorNew(), NE->getBeginLoc(), LCtx); 946 Bldr.generateNode(PP, Pred->getState(), Pred); 947 } 948 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 949 } 950 951 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor, 952 ExplodedNode *Pred, 953 ExplodedNodeSet &Dst) { 954 const VarDecl *varDecl = Dtor.getVarDecl(); 955 QualType varType = varDecl->getType(); 956 957 ProgramStateRef state = Pred->getState(); 958 SVal dest = state->getLValue(varDecl, Pred->getLocationContext()); 959 const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion(); 960 961 if (varType->isReferenceType()) { 962 const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion(); 963 if (!ValueRegion) { 964 // FIXME: This should not happen. The language guarantees a presence 965 // of a valid initializer here, so the reference shall not be undefined. 966 // It seems that we're calling destructors over variables that 967 // were not initialized yet. 968 return; 969 } 970 Region = ValueRegion->getBaseRegion(); 971 varType = cast<TypedValueRegion>(Region)->getValueType(); 972 } 973 974 // FIXME: We need to run the same destructor on every element of the array. 975 // This workaround will just run the first destructor (which will still 976 // invalidate the entire array). 977 EvalCallOptions CallOpts; 978 Region = makeZeroElementRegion(state, loc::MemRegionVal(Region), varType, 979 CallOpts.IsArrayCtorOrDtor).getAsRegion(); 980 981 VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), 982 /*IsBase=*/false, Pred, Dst, CallOpts); 983 } 984 985 void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor, 986 ExplodedNode *Pred, 987 ExplodedNodeSet &Dst) { 988 ProgramStateRef State = Pred->getState(); 989 const LocationContext *LCtx = Pred->getLocationContext(); 990 const CXXDeleteExpr *DE = Dtor.getDeleteExpr(); 991 const Stmt *Arg = DE->getArgument(); 992 QualType DTy = DE->getDestroyedType(); 993 SVal ArgVal = State->getSVal(Arg, LCtx); 994 995 // If the argument to delete is known to be a null value, 996 // don't run destructor. 997 if (State->isNull(ArgVal).isConstrainedTrue()) { 998 QualType BTy = getContext().getBaseElementType(DTy); 999 const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl(); 1000 const CXXDestructorDecl *Dtor = RD->getDestructor(); 1001 1002 PostImplicitCall PP(Dtor, DE->getBeginLoc(), LCtx); 1003 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1004 Bldr.generateNode(PP, Pred->getState(), Pred); 1005 return; 1006 } 1007 1008 EvalCallOptions CallOpts; 1009 const MemRegion *ArgR = ArgVal.getAsRegion(); 1010 if (DE->isArrayForm()) { 1011 // FIXME: We need to run the same destructor on every element of the array. 1012 // This workaround will just run the first destructor (which will still 1013 // invalidate the entire array). 1014 CallOpts.IsArrayCtorOrDtor = true; 1015 // Yes, it may even be a multi-dimensional array. 1016 while (const auto *AT = getContext().getAsArrayType(DTy)) 1017 DTy = AT->getElementType(); 1018 if (ArgR) 1019 ArgR = getStoreManager().GetElementZeroRegion(cast<SubRegion>(ArgR), DTy); 1020 } 1021 1022 VisitCXXDestructor(DTy, ArgR, DE, /*IsBase=*/false, Pred, Dst, CallOpts); 1023 } 1024 1025 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D, 1026 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 1027 const LocationContext *LCtx = Pred->getLocationContext(); 1028 1029 const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl()); 1030 Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor, 1031 LCtx->getStackFrame()); 1032 SVal ThisVal = Pred->getState()->getSVal(ThisPtr); 1033 1034 // Create the base object region. 1035 const CXXBaseSpecifier *Base = D.getBaseSpecifier(); 1036 QualType BaseTy = Base->getType(); 1037 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy, 1038 Base->isVirtual()); 1039 1040 EvalCallOptions CallOpts; 1041 VisitCXXDestructor(BaseTy, BaseVal.getAsRegion(), CurDtor->getBody(), 1042 /*IsBase=*/true, Pred, Dst, CallOpts); 1043 } 1044 1045 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D, 1046 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 1047 const FieldDecl *Member = D.getFieldDecl(); 1048 QualType T = Member->getType(); 1049 ProgramStateRef State = Pred->getState(); 1050 const LocationContext *LCtx = Pred->getLocationContext(); 1051 1052 const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl()); 1053 Loc ThisStorageLoc = 1054 getSValBuilder().getCXXThis(CurDtor, LCtx->getStackFrame()); 1055 Loc ThisLoc = State->getSVal(ThisStorageLoc).castAs<Loc>(); 1056 SVal FieldVal = State->getLValue(Member, ThisLoc); 1057 1058 // FIXME: We need to run the same destructor on every element of the array. 1059 // This workaround will just run the first destructor (which will still 1060 // invalidate the entire array). 1061 EvalCallOptions CallOpts; 1062 FieldVal = makeZeroElementRegion(State, FieldVal, T, 1063 CallOpts.IsArrayCtorOrDtor); 1064 1065 VisitCXXDestructor(T, FieldVal.getAsRegion(), CurDtor->getBody(), 1066 /*IsBase=*/false, Pred, Dst, CallOpts); 1067 } 1068 1069 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D, 1070 ExplodedNode *Pred, 1071 ExplodedNodeSet &Dst) { 1072 const CXXBindTemporaryExpr *BTE = D.getBindTemporaryExpr(); 1073 ProgramStateRef State = Pred->getState(); 1074 const LocationContext *LC = Pred->getLocationContext(); 1075 const MemRegion *MR = nullptr; 1076 1077 if (Optional<SVal> V = 1078 getObjectUnderConstruction(State, D.getBindTemporaryExpr(), 1079 Pred->getLocationContext())) { 1080 // FIXME: Currently we insert temporary destructors for default parameters, 1081 // but we don't insert the constructors, so the entry in 1082 // ObjectsUnderConstruction may be missing. 1083 State = finishObjectConstruction(State, D.getBindTemporaryExpr(), 1084 Pred->getLocationContext()); 1085 MR = V->getAsRegion(); 1086 } 1087 1088 // If copy elision has occurred, and the constructor corresponding to the 1089 // destructor was elided, we need to skip the destructor as well. 1090 if (isDestructorElided(State, BTE, LC)) { 1091 State = cleanupElidedDestructor(State, BTE, LC); 1092 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1093 PostImplicitCall PP(D.getDestructorDecl(getContext()), 1094 D.getBindTemporaryExpr()->getBeginLoc(), 1095 Pred->getLocationContext()); 1096 Bldr.generateNode(PP, State, Pred); 1097 return; 1098 } 1099 1100 ExplodedNodeSet CleanDtorState; 1101 StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx); 1102 StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State); 1103 1104 QualType T = D.getBindTemporaryExpr()->getSubExpr()->getType(); 1105 // FIXME: Currently CleanDtorState can be empty here due to temporaries being 1106 // bound to default parameters. 1107 assert(CleanDtorState.size() <= 1); 1108 ExplodedNode *CleanPred = 1109 CleanDtorState.empty() ? Pred : *CleanDtorState.begin(); 1110 1111 EvalCallOptions CallOpts; 1112 CallOpts.IsTemporaryCtorOrDtor = true; 1113 if (!MR) { 1114 // If we have no MR, we still need to unwrap the array to avoid destroying 1115 // the whole array at once. Regardless, we'd eventually need to model array 1116 // destructors properly, element-by-element. 1117 while (const ArrayType *AT = getContext().getAsArrayType(T)) { 1118 T = AT->getElementType(); 1119 CallOpts.IsArrayCtorOrDtor = true; 1120 } 1121 } else { 1122 // We'd eventually need to makeZeroElementRegion() trick here, 1123 // but for now we don't have the respective construction contexts, 1124 // so MR would always be null in this case. Do nothing for now. 1125 } 1126 VisitCXXDestructor(T, MR, D.getBindTemporaryExpr(), 1127 /*IsBase=*/false, CleanPred, Dst, CallOpts); 1128 } 1129 1130 void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE, 1131 NodeBuilderContext &BldCtx, 1132 ExplodedNode *Pred, 1133 ExplodedNodeSet &Dst, 1134 const CFGBlock *DstT, 1135 const CFGBlock *DstF) { 1136 BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF); 1137 ProgramStateRef State = Pred->getState(); 1138 const LocationContext *LC = Pred->getLocationContext(); 1139 if (getObjectUnderConstruction(State, BTE, LC)) { 1140 TempDtorBuilder.markInfeasible(false); 1141 TempDtorBuilder.generateNode(State, true, Pred); 1142 } else { 1143 TempDtorBuilder.markInfeasible(true); 1144 TempDtorBuilder.generateNode(State, false, Pred); 1145 } 1146 } 1147 1148 void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE, 1149 ExplodedNodeSet &PreVisit, 1150 ExplodedNodeSet &Dst) { 1151 // This is a fallback solution in case we didn't have a construction 1152 // context when we were constructing the temporary. Otherwise the map should 1153 // have been populated there. 1154 if (!getAnalysisManager().options.ShouldIncludeTemporaryDtorsInCFG) { 1155 // In case we don't have temporary destructors in the CFG, do not mark 1156 // the initialization - we would otherwise never clean it up. 1157 Dst = PreVisit; 1158 return; 1159 } 1160 StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx); 1161 for (ExplodedNode *Node : PreVisit) { 1162 ProgramStateRef State = Node->getState(); 1163 const LocationContext *LC = Node->getLocationContext(); 1164 if (!getObjectUnderConstruction(State, BTE, LC)) { 1165 // FIXME: Currently the state might also already contain the marker due to 1166 // incorrect handling of temporaries bound to default parameters; for 1167 // those, we currently skip the CXXBindTemporaryExpr but rely on adding 1168 // temporary destructor nodes. 1169 State = addObjectUnderConstruction(State, BTE, LC, UnknownVal()); 1170 } 1171 StmtBldr.generateNode(BTE, Node, State); 1172 } 1173 } 1174 1175 ProgramStateRef ExprEngine::escapeValue(ProgramStateRef State, SVal V, 1176 PointerEscapeKind K) const { 1177 class CollectReachableSymbolsCallback final : public SymbolVisitor { 1178 InvalidatedSymbols Symbols; 1179 1180 public: 1181 explicit CollectReachableSymbolsCallback(ProgramStateRef) {} 1182 1183 const InvalidatedSymbols &getSymbols() const { return Symbols; } 1184 1185 bool VisitSymbol(SymbolRef Sym) override { 1186 Symbols.insert(Sym); 1187 return true; 1188 } 1189 }; 1190 1191 const CollectReachableSymbolsCallback &Scanner = 1192 State->scanReachableSymbols<CollectReachableSymbolsCallback>(V); 1193 return getCheckerManager().runCheckersForPointerEscape( 1194 State, Scanner.getSymbols(), /*CallEvent*/ nullptr, K, nullptr); 1195 } 1196 1197 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred, 1198 ExplodedNodeSet &DstTop) { 1199 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 1200 S->getBeginLoc(), "Error evaluating statement"); 1201 ExplodedNodeSet Dst; 1202 StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx); 1203 1204 assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens()); 1205 1206 switch (S->getStmtClass()) { 1207 // C++, OpenMP and ARC stuff we don't support yet. 1208 case Expr::ObjCIndirectCopyRestoreExprClass: 1209 case Stmt::CXXDependentScopeMemberExprClass: 1210 case Stmt::CXXInheritedCtorInitExprClass: 1211 case Stmt::CXXTryStmtClass: 1212 case Stmt::CXXTypeidExprClass: 1213 case Stmt::CXXUuidofExprClass: 1214 case Stmt::CXXFoldExprClass: 1215 case Stmt::MSPropertyRefExprClass: 1216 case Stmt::MSPropertySubscriptExprClass: 1217 case Stmt::CXXUnresolvedConstructExprClass: 1218 case Stmt::DependentScopeDeclRefExprClass: 1219 case Stmt::ArrayTypeTraitExprClass: 1220 case Stmt::ExpressionTraitExprClass: 1221 case Stmt::UnresolvedLookupExprClass: 1222 case Stmt::UnresolvedMemberExprClass: 1223 case Stmt::TypoExprClass: 1224 case Stmt::CXXNoexceptExprClass: 1225 case Stmt::PackExpansionExprClass: 1226 case Stmt::SubstNonTypeTemplateParmPackExprClass: 1227 case Stmt::FunctionParmPackExprClass: 1228 case Stmt::CoroutineBodyStmtClass: 1229 case Stmt::CoawaitExprClass: 1230 case Stmt::DependentCoawaitExprClass: 1231 case Stmt::CoreturnStmtClass: 1232 case Stmt::CoyieldExprClass: 1233 case Stmt::SEHTryStmtClass: 1234 case Stmt::SEHExceptStmtClass: 1235 case Stmt::SEHLeaveStmtClass: 1236 case Stmt::SEHFinallyStmtClass: 1237 case Stmt::OMPParallelDirectiveClass: 1238 case Stmt::OMPSimdDirectiveClass: 1239 case Stmt::OMPForDirectiveClass: 1240 case Stmt::OMPForSimdDirectiveClass: 1241 case Stmt::OMPSectionsDirectiveClass: 1242 case Stmt::OMPSectionDirectiveClass: 1243 case Stmt::OMPSingleDirectiveClass: 1244 case Stmt::OMPMasterDirectiveClass: 1245 case Stmt::OMPCriticalDirectiveClass: 1246 case Stmt::OMPParallelForDirectiveClass: 1247 case Stmt::OMPParallelForSimdDirectiveClass: 1248 case Stmt::OMPParallelSectionsDirectiveClass: 1249 case Stmt::OMPParallelMasterDirectiveClass: 1250 case Stmt::OMPTaskDirectiveClass: 1251 case Stmt::OMPTaskyieldDirectiveClass: 1252 case Stmt::OMPBarrierDirectiveClass: 1253 case Stmt::OMPTaskwaitDirectiveClass: 1254 case Stmt::OMPTaskgroupDirectiveClass: 1255 case Stmt::OMPFlushDirectiveClass: 1256 case Stmt::OMPOrderedDirectiveClass: 1257 case Stmt::OMPAtomicDirectiveClass: 1258 case Stmt::OMPTargetDirectiveClass: 1259 case Stmt::OMPTargetDataDirectiveClass: 1260 case Stmt::OMPTargetEnterDataDirectiveClass: 1261 case Stmt::OMPTargetExitDataDirectiveClass: 1262 case Stmt::OMPTargetParallelDirectiveClass: 1263 case Stmt::OMPTargetParallelForDirectiveClass: 1264 case Stmt::OMPTargetUpdateDirectiveClass: 1265 case Stmt::OMPTeamsDirectiveClass: 1266 case Stmt::OMPCancellationPointDirectiveClass: 1267 case Stmt::OMPCancelDirectiveClass: 1268 case Stmt::OMPTaskLoopDirectiveClass: 1269 case Stmt::OMPTaskLoopSimdDirectiveClass: 1270 case Stmt::OMPMasterTaskLoopDirectiveClass: 1271 case Stmt::OMPMasterTaskLoopSimdDirectiveClass: 1272 case Stmt::OMPParallelMasterTaskLoopDirectiveClass: 1273 case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass: 1274 case Stmt::OMPDistributeDirectiveClass: 1275 case Stmt::OMPDistributeParallelForDirectiveClass: 1276 case Stmt::OMPDistributeParallelForSimdDirectiveClass: 1277 case Stmt::OMPDistributeSimdDirectiveClass: 1278 case Stmt::OMPTargetParallelForSimdDirectiveClass: 1279 case Stmt::OMPTargetSimdDirectiveClass: 1280 case Stmt::OMPTeamsDistributeDirectiveClass: 1281 case Stmt::OMPTeamsDistributeSimdDirectiveClass: 1282 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass: 1283 case Stmt::OMPTeamsDistributeParallelForDirectiveClass: 1284 case Stmt::OMPTargetTeamsDirectiveClass: 1285 case Stmt::OMPTargetTeamsDistributeDirectiveClass: 1286 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass: 1287 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass: 1288 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass: 1289 case Stmt::CapturedStmtClass: { 1290 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState()); 1291 Engine.addAbortedBlock(node, currBldrCtx->getBlock()); 1292 break; 1293 } 1294 1295 case Stmt::ParenExprClass: 1296 llvm_unreachable("ParenExprs already handled."); 1297 case Stmt::GenericSelectionExprClass: 1298 llvm_unreachable("GenericSelectionExprs already handled."); 1299 // Cases that should never be evaluated simply because they shouldn't 1300 // appear in the CFG. 1301 case Stmt::BreakStmtClass: 1302 case Stmt::CaseStmtClass: 1303 case Stmt::CompoundStmtClass: 1304 case Stmt::ContinueStmtClass: 1305 case Stmt::CXXForRangeStmtClass: 1306 case Stmt::DefaultStmtClass: 1307 case Stmt::DoStmtClass: 1308 case Stmt::ForStmtClass: 1309 case Stmt::GotoStmtClass: 1310 case Stmt::IfStmtClass: 1311 case Stmt::IndirectGotoStmtClass: 1312 case Stmt::LabelStmtClass: 1313 case Stmt::NoStmtClass: 1314 case Stmt::NullStmtClass: 1315 case Stmt::SwitchStmtClass: 1316 case Stmt::WhileStmtClass: 1317 case Expr::MSDependentExistsStmtClass: 1318 llvm_unreachable("Stmt should not be in analyzer evaluation loop"); 1319 1320 case Stmt::ObjCSubscriptRefExprClass: 1321 case Stmt::ObjCPropertyRefExprClass: 1322 llvm_unreachable("These are handled by PseudoObjectExpr"); 1323 1324 case Stmt::GNUNullExprClass: { 1325 // GNU __null is a pointer-width integer, not an actual pointer. 1326 ProgramStateRef state = Pred->getState(); 1327 state = state->BindExpr(S, Pred->getLocationContext(), 1328 svalBuilder.makeIntValWithPtrWidth(0, false)); 1329 Bldr.generateNode(S, Pred, state); 1330 break; 1331 } 1332 1333 case Stmt::ObjCAtSynchronizedStmtClass: 1334 Bldr.takeNodes(Pred); 1335 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst); 1336 Bldr.addNodes(Dst); 1337 break; 1338 1339 case Expr::ConstantExprClass: 1340 case Stmt::ExprWithCleanupsClass: 1341 // Handled due to fully linearised CFG. 1342 break; 1343 1344 case Stmt::CXXBindTemporaryExprClass: { 1345 Bldr.takeNodes(Pred); 1346 ExplodedNodeSet PreVisit; 1347 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 1348 ExplodedNodeSet Next; 1349 VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next); 1350 getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this); 1351 Bldr.addNodes(Dst); 1352 break; 1353 } 1354 1355 // Cases not handled yet; but will handle some day. 1356 case Stmt::DesignatedInitExprClass: 1357 case Stmt::DesignatedInitUpdateExprClass: 1358 case Stmt::ArrayInitLoopExprClass: 1359 case Stmt::ArrayInitIndexExprClass: 1360 case Stmt::ExtVectorElementExprClass: 1361 case Stmt::ImaginaryLiteralClass: 1362 case Stmt::ObjCAtCatchStmtClass: 1363 case Stmt::ObjCAtFinallyStmtClass: 1364 case Stmt::ObjCAtTryStmtClass: 1365 case Stmt::ObjCAutoreleasePoolStmtClass: 1366 case Stmt::ObjCEncodeExprClass: 1367 case Stmt::ObjCIsaExprClass: 1368 case Stmt::ObjCProtocolExprClass: 1369 case Stmt::ObjCSelectorExprClass: 1370 case Stmt::ParenListExprClass: 1371 case Stmt::ShuffleVectorExprClass: 1372 case Stmt::ConvertVectorExprClass: 1373 case Stmt::VAArgExprClass: 1374 case Stmt::CUDAKernelCallExprClass: 1375 case Stmt::OpaqueValueExprClass: 1376 case Stmt::AsTypeExprClass: 1377 case Stmt::ConceptSpecializationExprClass: 1378 case Stmt::CXXRewrittenBinaryOperatorClass: 1379 // Fall through. 1380 1381 // Cases we intentionally don't evaluate, since they don't need 1382 // to be explicitly evaluated. 1383 case Stmt::PredefinedExprClass: 1384 case Stmt::AddrLabelExprClass: 1385 case Stmt::AttributedStmtClass: 1386 case Stmt::IntegerLiteralClass: 1387 case Stmt::FixedPointLiteralClass: 1388 case Stmt::CharacterLiteralClass: 1389 case Stmt::ImplicitValueInitExprClass: 1390 case Stmt::CXXScalarValueInitExprClass: 1391 case Stmt::CXXBoolLiteralExprClass: 1392 case Stmt::ObjCBoolLiteralExprClass: 1393 case Stmt::ObjCAvailabilityCheckExprClass: 1394 case Stmt::FloatingLiteralClass: 1395 case Stmt::NoInitExprClass: 1396 case Stmt::SizeOfPackExprClass: 1397 case Stmt::StringLiteralClass: 1398 case Stmt::SourceLocExprClass: 1399 case Stmt::ObjCStringLiteralClass: 1400 case Stmt::CXXPseudoDestructorExprClass: 1401 case Stmt::SubstNonTypeTemplateParmExprClass: 1402 case Stmt::CXXNullPtrLiteralExprClass: 1403 case Stmt::OMPArraySectionExprClass: 1404 case Stmt::TypeTraitExprClass: { 1405 Bldr.takeNodes(Pred); 1406 ExplodedNodeSet preVisit; 1407 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this); 1408 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this); 1409 Bldr.addNodes(Dst); 1410 break; 1411 } 1412 1413 case Stmt::CXXDefaultArgExprClass: 1414 case Stmt::CXXDefaultInitExprClass: { 1415 Bldr.takeNodes(Pred); 1416 ExplodedNodeSet PreVisit; 1417 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 1418 1419 ExplodedNodeSet Tmp; 1420 StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx); 1421 1422 const Expr *ArgE; 1423 if (const auto *DefE = dyn_cast<CXXDefaultArgExpr>(S)) 1424 ArgE = DefE->getExpr(); 1425 else if (const auto *DefE = dyn_cast<CXXDefaultInitExpr>(S)) 1426 ArgE = DefE->getExpr(); 1427 else 1428 llvm_unreachable("unknown constant wrapper kind"); 1429 1430 bool IsTemporary = false; 1431 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(ArgE)) { 1432 ArgE = MTE->getSubExpr(); 1433 IsTemporary = true; 1434 } 1435 1436 Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE); 1437 if (!ConstantVal) 1438 ConstantVal = UnknownVal(); 1439 1440 const LocationContext *LCtx = Pred->getLocationContext(); 1441 for (const auto I : PreVisit) { 1442 ProgramStateRef State = I->getState(); 1443 State = State->BindExpr(S, LCtx, *ConstantVal); 1444 if (IsTemporary) 1445 State = createTemporaryRegionIfNeeded(State, LCtx, 1446 cast<Expr>(S), 1447 cast<Expr>(S)); 1448 Bldr2.generateNode(S, I, State); 1449 } 1450 1451 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this); 1452 Bldr.addNodes(Dst); 1453 break; 1454 } 1455 1456 // Cases we evaluate as opaque expressions, conjuring a symbol. 1457 case Stmt::CXXStdInitializerListExprClass: 1458 case Expr::ObjCArrayLiteralClass: 1459 case Expr::ObjCDictionaryLiteralClass: 1460 case Expr::ObjCBoxedExprClass: { 1461 Bldr.takeNodes(Pred); 1462 1463 ExplodedNodeSet preVisit; 1464 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this); 1465 1466 ExplodedNodeSet Tmp; 1467 StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx); 1468 1469 const auto *Ex = cast<Expr>(S); 1470 QualType resultType = Ex->getType(); 1471 1472 for (const auto N : preVisit) { 1473 const LocationContext *LCtx = N->getLocationContext(); 1474 SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx, 1475 resultType, 1476 currBldrCtx->blockCount()); 1477 ProgramStateRef State = N->getState()->BindExpr(Ex, LCtx, result); 1478 1479 // Escape pointers passed into the list, unless it's an ObjC boxed 1480 // expression which is not a boxable C structure. 1481 if (!(isa<ObjCBoxedExpr>(Ex) && 1482 !cast<ObjCBoxedExpr>(Ex)->getSubExpr() 1483 ->getType()->isRecordType())) 1484 for (auto Child : Ex->children()) { 1485 assert(Child); 1486 SVal Val = State->getSVal(Child, LCtx); 1487 State = escapeValue(State, Val, PSK_EscapeOther); 1488 } 1489 1490 Bldr2.generateNode(S, N, State); 1491 } 1492 1493 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this); 1494 Bldr.addNodes(Dst); 1495 break; 1496 } 1497 1498 case Stmt::ArraySubscriptExprClass: 1499 Bldr.takeNodes(Pred); 1500 VisitArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst); 1501 Bldr.addNodes(Dst); 1502 break; 1503 1504 case Stmt::GCCAsmStmtClass: 1505 Bldr.takeNodes(Pred); 1506 VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst); 1507 Bldr.addNodes(Dst); 1508 break; 1509 1510 case Stmt::MSAsmStmtClass: 1511 Bldr.takeNodes(Pred); 1512 VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst); 1513 Bldr.addNodes(Dst); 1514 break; 1515 1516 case Stmt::BlockExprClass: 1517 Bldr.takeNodes(Pred); 1518 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst); 1519 Bldr.addNodes(Dst); 1520 break; 1521 1522 case Stmt::LambdaExprClass: 1523 if (AMgr.options.ShouldInlineLambdas) { 1524 Bldr.takeNodes(Pred); 1525 VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst); 1526 Bldr.addNodes(Dst); 1527 } else { 1528 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState()); 1529 Engine.addAbortedBlock(node, currBldrCtx->getBlock()); 1530 } 1531 break; 1532 1533 case Stmt::BinaryOperatorClass: { 1534 const auto *B = cast<BinaryOperator>(S); 1535 if (B->isLogicalOp()) { 1536 Bldr.takeNodes(Pred); 1537 VisitLogicalExpr(B, Pred, Dst); 1538 Bldr.addNodes(Dst); 1539 break; 1540 } 1541 else if (B->getOpcode() == BO_Comma) { 1542 ProgramStateRef state = Pred->getState(); 1543 Bldr.generateNode(B, Pred, 1544 state->BindExpr(B, Pred->getLocationContext(), 1545 state->getSVal(B->getRHS(), 1546 Pred->getLocationContext()))); 1547 break; 1548 } 1549 1550 Bldr.takeNodes(Pred); 1551 1552 if (AMgr.options.ShouldEagerlyAssume && 1553 (B->isRelationalOp() || B->isEqualityOp())) { 1554 ExplodedNodeSet Tmp; 1555 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp); 1556 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S)); 1557 } 1558 else 1559 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 1560 1561 Bldr.addNodes(Dst); 1562 break; 1563 } 1564 1565 case Stmt::CXXOperatorCallExprClass: { 1566 const auto *OCE = cast<CXXOperatorCallExpr>(S); 1567 1568 // For instance method operators, make sure the 'this' argument has a 1569 // valid region. 1570 const Decl *Callee = OCE->getCalleeDecl(); 1571 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) { 1572 if (MD->isInstance()) { 1573 ProgramStateRef State = Pred->getState(); 1574 const LocationContext *LCtx = Pred->getLocationContext(); 1575 ProgramStateRef NewState = 1576 createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0)); 1577 if (NewState != State) { 1578 Pred = Bldr.generateNode(OCE, Pred, NewState, /*tag=*/nullptr, 1579 ProgramPoint::PreStmtKind); 1580 // Did we cache out? 1581 if (!Pred) 1582 break; 1583 } 1584 } 1585 } 1586 // FALLTHROUGH 1587 LLVM_FALLTHROUGH; 1588 } 1589 1590 case Stmt::CallExprClass: 1591 case Stmt::CXXMemberCallExprClass: 1592 case Stmt::UserDefinedLiteralClass: 1593 Bldr.takeNodes(Pred); 1594 VisitCallExpr(cast<CallExpr>(S), Pred, Dst); 1595 Bldr.addNodes(Dst); 1596 break; 1597 1598 case Stmt::CXXCatchStmtClass: 1599 Bldr.takeNodes(Pred); 1600 VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst); 1601 Bldr.addNodes(Dst); 1602 break; 1603 1604 case Stmt::CXXTemporaryObjectExprClass: 1605 case Stmt::CXXConstructExprClass: 1606 Bldr.takeNodes(Pred); 1607 VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst); 1608 Bldr.addNodes(Dst); 1609 break; 1610 1611 case Stmt::CXXNewExprClass: { 1612 Bldr.takeNodes(Pred); 1613 1614 ExplodedNodeSet PreVisit; 1615 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 1616 1617 ExplodedNodeSet PostVisit; 1618 for (const auto i : PreVisit) 1619 VisitCXXNewExpr(cast<CXXNewExpr>(S), i, PostVisit); 1620 1621 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this); 1622 Bldr.addNodes(Dst); 1623 break; 1624 } 1625 1626 case Stmt::CXXDeleteExprClass: { 1627 Bldr.takeNodes(Pred); 1628 ExplodedNodeSet PreVisit; 1629 const auto *CDE = cast<CXXDeleteExpr>(S); 1630 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 1631 1632 for (const auto i : PreVisit) 1633 VisitCXXDeleteExpr(CDE, i, Dst); 1634 1635 Bldr.addNodes(Dst); 1636 break; 1637 } 1638 // FIXME: ChooseExpr is really a constant. We need to fix 1639 // the CFG do not model them as explicit control-flow. 1640 1641 case Stmt::ChooseExprClass: { // __builtin_choose_expr 1642 Bldr.takeNodes(Pred); 1643 const auto *C = cast<ChooseExpr>(S); 1644 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst); 1645 Bldr.addNodes(Dst); 1646 break; 1647 } 1648 1649 case Stmt::CompoundAssignOperatorClass: 1650 Bldr.takeNodes(Pred); 1651 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 1652 Bldr.addNodes(Dst); 1653 break; 1654 1655 case Stmt::CompoundLiteralExprClass: 1656 Bldr.takeNodes(Pred); 1657 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst); 1658 Bldr.addNodes(Dst); 1659 break; 1660 1661 case Stmt::BinaryConditionalOperatorClass: 1662 case Stmt::ConditionalOperatorClass: { // '?' operator 1663 Bldr.takeNodes(Pred); 1664 const auto *C = cast<AbstractConditionalOperator>(S); 1665 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst); 1666 Bldr.addNodes(Dst); 1667 break; 1668 } 1669 1670 case Stmt::CXXThisExprClass: 1671 Bldr.takeNodes(Pred); 1672 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst); 1673 Bldr.addNodes(Dst); 1674 break; 1675 1676 case Stmt::DeclRefExprClass: { 1677 Bldr.takeNodes(Pred); 1678 const auto *DE = cast<DeclRefExpr>(S); 1679 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst); 1680 Bldr.addNodes(Dst); 1681 break; 1682 } 1683 1684 case Stmt::DeclStmtClass: 1685 Bldr.takeNodes(Pred); 1686 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst); 1687 Bldr.addNodes(Dst); 1688 break; 1689 1690 case Stmt::ImplicitCastExprClass: 1691 case Stmt::CStyleCastExprClass: 1692 case Stmt::CXXStaticCastExprClass: 1693 case Stmt::CXXDynamicCastExprClass: 1694 case Stmt::CXXReinterpretCastExprClass: 1695 case Stmt::CXXConstCastExprClass: 1696 case Stmt::CXXFunctionalCastExprClass: 1697 case Stmt::BuiltinBitCastExprClass: 1698 case Stmt::ObjCBridgedCastExprClass: { 1699 Bldr.takeNodes(Pred); 1700 const auto *C = cast<CastExpr>(S); 1701 ExplodedNodeSet dstExpr; 1702 VisitCast(C, C->getSubExpr(), Pred, dstExpr); 1703 1704 // Handle the postvisit checks. 1705 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this); 1706 Bldr.addNodes(Dst); 1707 break; 1708 } 1709 1710 case Expr::MaterializeTemporaryExprClass: { 1711 Bldr.takeNodes(Pred); 1712 const auto *MTE = cast<MaterializeTemporaryExpr>(S); 1713 ExplodedNodeSet dstPrevisit; 1714 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this); 1715 ExplodedNodeSet dstExpr; 1716 for (const auto i : dstPrevisit) 1717 CreateCXXTemporaryObject(MTE, i, dstExpr); 1718 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this); 1719 Bldr.addNodes(Dst); 1720 break; 1721 } 1722 1723 case Stmt::InitListExprClass: 1724 Bldr.takeNodes(Pred); 1725 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst); 1726 Bldr.addNodes(Dst); 1727 break; 1728 1729 case Stmt::MemberExprClass: 1730 Bldr.takeNodes(Pred); 1731 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst); 1732 Bldr.addNodes(Dst); 1733 break; 1734 1735 case Stmt::AtomicExprClass: 1736 Bldr.takeNodes(Pred); 1737 VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst); 1738 Bldr.addNodes(Dst); 1739 break; 1740 1741 case Stmt::ObjCIvarRefExprClass: 1742 Bldr.takeNodes(Pred); 1743 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst); 1744 Bldr.addNodes(Dst); 1745 break; 1746 1747 case Stmt::ObjCForCollectionStmtClass: 1748 Bldr.takeNodes(Pred); 1749 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst); 1750 Bldr.addNodes(Dst); 1751 break; 1752 1753 case Stmt::ObjCMessageExprClass: 1754 Bldr.takeNodes(Pred); 1755 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst); 1756 Bldr.addNodes(Dst); 1757 break; 1758 1759 case Stmt::ObjCAtThrowStmtClass: 1760 case Stmt::CXXThrowExprClass: 1761 // FIXME: This is not complete. We basically treat @throw as 1762 // an abort. 1763 Bldr.generateSink(S, Pred, Pred->getState()); 1764 break; 1765 1766 case Stmt::ReturnStmtClass: 1767 Bldr.takeNodes(Pred); 1768 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst); 1769 Bldr.addNodes(Dst); 1770 break; 1771 1772 case Stmt::OffsetOfExprClass: { 1773 Bldr.takeNodes(Pred); 1774 ExplodedNodeSet PreVisit; 1775 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 1776 1777 ExplodedNodeSet PostVisit; 1778 for (const auto Node : PreVisit) 1779 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Node, PostVisit); 1780 1781 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this); 1782 Bldr.addNodes(Dst); 1783 break; 1784 } 1785 1786 case Stmt::UnaryExprOrTypeTraitExprClass: 1787 Bldr.takeNodes(Pred); 1788 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S), 1789 Pred, Dst); 1790 Bldr.addNodes(Dst); 1791 break; 1792 1793 case Stmt::StmtExprClass: { 1794 const auto *SE = cast<StmtExpr>(S); 1795 1796 if (SE->getSubStmt()->body_empty()) { 1797 // Empty statement expression. 1798 assert(SE->getType() == getContext().VoidTy 1799 && "Empty statement expression must have void type."); 1800 break; 1801 } 1802 1803 if (const auto *LastExpr = 1804 dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) { 1805 ProgramStateRef state = Pred->getState(); 1806 Bldr.generateNode(SE, Pred, 1807 state->BindExpr(SE, Pred->getLocationContext(), 1808 state->getSVal(LastExpr, 1809 Pred->getLocationContext()))); 1810 } 1811 break; 1812 } 1813 1814 case Stmt::UnaryOperatorClass: { 1815 Bldr.takeNodes(Pred); 1816 const auto *U = cast<UnaryOperator>(S); 1817 if (AMgr.options.ShouldEagerlyAssume && (U->getOpcode() == UO_LNot)) { 1818 ExplodedNodeSet Tmp; 1819 VisitUnaryOperator(U, Pred, Tmp); 1820 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U); 1821 } 1822 else 1823 VisitUnaryOperator(U, Pred, Dst); 1824 Bldr.addNodes(Dst); 1825 break; 1826 } 1827 1828 case Stmt::PseudoObjectExprClass: { 1829 Bldr.takeNodes(Pred); 1830 ProgramStateRef state = Pred->getState(); 1831 const auto *PE = cast<PseudoObjectExpr>(S); 1832 if (const Expr *Result = PE->getResultExpr()) { 1833 SVal V = state->getSVal(Result, Pred->getLocationContext()); 1834 Bldr.generateNode(S, Pred, 1835 state->BindExpr(S, Pred->getLocationContext(), V)); 1836 } 1837 else 1838 Bldr.generateNode(S, Pred, 1839 state->BindExpr(S, Pred->getLocationContext(), 1840 UnknownVal())); 1841 1842 Bldr.addNodes(Dst); 1843 break; 1844 } 1845 } 1846 } 1847 1848 bool ExprEngine::replayWithoutInlining(ExplodedNode *N, 1849 const LocationContext *CalleeLC) { 1850 const StackFrameContext *CalleeSF = CalleeLC->getStackFrame(); 1851 const StackFrameContext *CallerSF = CalleeSF->getParent()->getStackFrame(); 1852 assert(CalleeSF && CallerSF); 1853 ExplodedNode *BeforeProcessingCall = nullptr; 1854 const Stmt *CE = CalleeSF->getCallSite(); 1855 1856 // Find the first node before we started processing the call expression. 1857 while (N) { 1858 ProgramPoint L = N->getLocation(); 1859 BeforeProcessingCall = N; 1860 N = N->pred_empty() ? nullptr : *(N->pred_begin()); 1861 1862 // Skip the nodes corresponding to the inlined code. 1863 if (L.getStackFrame() != CallerSF) 1864 continue; 1865 // We reached the caller. Find the node right before we started 1866 // processing the call. 1867 if (L.isPurgeKind()) 1868 continue; 1869 if (L.getAs<PreImplicitCall>()) 1870 continue; 1871 if (L.getAs<CallEnter>()) 1872 continue; 1873 if (Optional<StmtPoint> SP = L.getAs<StmtPoint>()) 1874 if (SP->getStmt() == CE) 1875 continue; 1876 break; 1877 } 1878 1879 if (!BeforeProcessingCall) 1880 return false; 1881 1882 // TODO: Clean up the unneeded nodes. 1883 1884 // Build an Epsilon node from which we will restart the analyzes. 1885 // Note that CE is permitted to be NULL! 1886 ProgramPoint NewNodeLoc = 1887 EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE); 1888 // Add the special flag to GDM to signal retrying with no inlining. 1889 // Note, changing the state ensures that we are not going to cache out. 1890 ProgramStateRef NewNodeState = BeforeProcessingCall->getState(); 1891 NewNodeState = 1892 NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE)); 1893 1894 // Make the new node a successor of BeforeProcessingCall. 1895 bool IsNew = false; 1896 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew); 1897 // We cached out at this point. Caching out is common due to us backtracking 1898 // from the inlined function, which might spawn several paths. 1899 if (!IsNew) 1900 return true; 1901 1902 NewNode->addPredecessor(BeforeProcessingCall, G); 1903 1904 // Add the new node to the work list. 1905 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(), 1906 CalleeSF->getIndex()); 1907 NumTimesRetriedWithoutInlining++; 1908 return true; 1909 } 1910 1911 /// Block entrance. (Update counters). 1912 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L, 1913 NodeBuilderWithSinks &nodeBuilder, 1914 ExplodedNode *Pred) { 1915 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 1916 // If we reach a loop which has a known bound (and meets 1917 // other constraints) then consider completely unrolling it. 1918 if(AMgr.options.ShouldUnrollLoops) { 1919 unsigned maxBlockVisitOnPath = AMgr.options.maxBlockVisitOnPath; 1920 const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminatorStmt(); 1921 if (Term) { 1922 ProgramStateRef NewState = updateLoopStack(Term, AMgr.getASTContext(), 1923 Pred, maxBlockVisitOnPath); 1924 if (NewState != Pred->getState()) { 1925 ExplodedNode *UpdatedNode = nodeBuilder.generateNode(NewState, Pred); 1926 if (!UpdatedNode) 1927 return; 1928 Pred = UpdatedNode; 1929 } 1930 } 1931 // Is we are inside an unrolled loop then no need the check the counters. 1932 if(isUnrolledState(Pred->getState())) 1933 return; 1934 } 1935 1936 // If this block is terminated by a loop and it has already been visited the 1937 // maximum number of times, widen the loop. 1938 unsigned int BlockCount = nodeBuilder.getContext().blockCount(); 1939 if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 && 1940 AMgr.options.ShouldWidenLoops) { 1941 const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminatorStmt(); 1942 if (!(Term && 1943 (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term)))) 1944 return; 1945 // Widen. 1946 const LocationContext *LCtx = Pred->getLocationContext(); 1947 ProgramStateRef WidenedState = 1948 getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term); 1949 nodeBuilder.generateNode(WidenedState, Pred); 1950 return; 1951 } 1952 1953 // FIXME: Refactor this into a checker. 1954 if (BlockCount >= AMgr.options.maxBlockVisitOnPath) { 1955 static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded"); 1956 const ExplodedNode *Sink = 1957 nodeBuilder.generateSink(Pred->getState(), Pred, &tag); 1958 1959 // Check if we stopped at the top level function or not. 1960 // Root node should have the location context of the top most function. 1961 const LocationContext *CalleeLC = Pred->getLocation().getLocationContext(); 1962 const LocationContext *CalleeSF = CalleeLC->getStackFrame(); 1963 const LocationContext *RootLC = 1964 (*G.roots_begin())->getLocation().getLocationContext(); 1965 if (RootLC->getStackFrame() != CalleeSF) { 1966 Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl()); 1967 1968 // Re-run the call evaluation without inlining it, by storing the 1969 // no-inlining policy in the state and enqueuing the new work item on 1970 // the list. Replay should almost never fail. Use the stats to catch it 1971 // if it does. 1972 if ((!AMgr.options.NoRetryExhausted && 1973 replayWithoutInlining(Pred, CalleeLC))) 1974 return; 1975 NumMaxBlockCountReachedInInlined++; 1976 } else 1977 NumMaxBlockCountReached++; 1978 1979 // Make sink nodes as exhausted(for stats) only if retry failed. 1980 Engine.blocksExhausted.push_back(std::make_pair(L, Sink)); 1981 } 1982 } 1983 1984 //===----------------------------------------------------------------------===// 1985 // Branch processing. 1986 //===----------------------------------------------------------------------===// 1987 1988 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used 1989 /// to try to recover some path-sensitivity for casts of symbolic 1990 /// integers that promote their values (which are currently not tracked well). 1991 /// This function returns the SVal bound to Condition->IgnoreCasts if all the 1992 // cast(s) did was sign-extend the original value. 1993 static SVal RecoverCastedSymbol(ProgramStateRef state, 1994 const Stmt *Condition, 1995 const LocationContext *LCtx, 1996 ASTContext &Ctx) { 1997 1998 const auto *Ex = dyn_cast<Expr>(Condition); 1999 if (!Ex) 2000 return UnknownVal(); 2001 2002 uint64_t bits = 0; 2003 bool bitsInit = false; 2004 2005 while (const auto *CE = dyn_cast<CastExpr>(Ex)) { 2006 QualType T = CE->getType(); 2007 2008 if (!T->isIntegralOrEnumerationType()) 2009 return UnknownVal(); 2010 2011 uint64_t newBits = Ctx.getTypeSize(T); 2012 if (!bitsInit || newBits < bits) { 2013 bitsInit = true; 2014 bits = newBits; 2015 } 2016 2017 Ex = CE->getSubExpr(); 2018 } 2019 2020 // We reached a non-cast. Is it a symbolic value? 2021 QualType T = Ex->getType(); 2022 2023 if (!bitsInit || !T->isIntegralOrEnumerationType() || 2024 Ctx.getTypeSize(T) > bits) 2025 return UnknownVal(); 2026 2027 return state->getSVal(Ex, LCtx); 2028 } 2029 2030 #ifndef NDEBUG 2031 static const Stmt *getRightmostLeaf(const Stmt *Condition) { 2032 while (Condition) { 2033 const auto *BO = dyn_cast<BinaryOperator>(Condition); 2034 if (!BO || !BO->isLogicalOp()) { 2035 return Condition; 2036 } 2037 Condition = BO->getRHS()->IgnoreParens(); 2038 } 2039 return nullptr; 2040 } 2041 #endif 2042 2043 // Returns the condition the branch at the end of 'B' depends on and whose value 2044 // has been evaluated within 'B'. 2045 // In most cases, the terminator condition of 'B' will be evaluated fully in 2046 // the last statement of 'B'; in those cases, the resolved condition is the 2047 // given 'Condition'. 2048 // If the condition of the branch is a logical binary operator tree, the CFG is 2049 // optimized: in that case, we know that the expression formed by all but the 2050 // rightmost leaf of the logical binary operator tree must be true, and thus 2051 // the branch condition is at this point equivalent to the truth value of that 2052 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf 2053 // expression in its final statement. As the full condition in that case was 2054 // not evaluated, and is thus not in the SVal cache, we need to use that leaf 2055 // expression to evaluate the truth value of the condition in the current state 2056 // space. 2057 static const Stmt *ResolveCondition(const Stmt *Condition, 2058 const CFGBlock *B) { 2059 if (const auto *Ex = dyn_cast<Expr>(Condition)) 2060 Condition = Ex->IgnoreParens(); 2061 2062 const auto *BO = dyn_cast<BinaryOperator>(Condition); 2063 if (!BO || !BO->isLogicalOp()) 2064 return Condition; 2065 2066 assert(B->getTerminator().isStmtBranch() && 2067 "Other kinds of branches are handled separately!"); 2068 2069 // For logical operations, we still have the case where some branches 2070 // use the traditional "merge" approach and others sink the branch 2071 // directly into the basic blocks representing the logical operation. 2072 // We need to distinguish between those two cases here. 2073 2074 // The invariants are still shifting, but it is possible that the 2075 // last element in a CFGBlock is not a CFGStmt. Look for the last 2076 // CFGStmt as the value of the condition. 2077 CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend(); 2078 for (; I != E; ++I) { 2079 CFGElement Elem = *I; 2080 Optional<CFGStmt> CS = Elem.getAs<CFGStmt>(); 2081 if (!CS) 2082 continue; 2083 const Stmt *LastStmt = CS->getStmt(); 2084 assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition)); 2085 return LastStmt; 2086 } 2087 llvm_unreachable("could not resolve condition"); 2088 } 2089 2090 void ExprEngine::processBranch(const Stmt *Condition, 2091 NodeBuilderContext& BldCtx, 2092 ExplodedNode *Pred, 2093 ExplodedNodeSet &Dst, 2094 const CFGBlock *DstT, 2095 const CFGBlock *DstF) { 2096 assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) && 2097 "CXXBindTemporaryExprs are handled by processBindTemporary."); 2098 const LocationContext *LCtx = Pred->getLocationContext(); 2099 PrettyStackTraceLocationContext StackCrashInfo(LCtx); 2100 currBldrCtx = &BldCtx; 2101 2102 // Check for NULL conditions; e.g. "for(;;)" 2103 if (!Condition) { 2104 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF); 2105 NullCondBldr.markInfeasible(false); 2106 NullCondBldr.generateNode(Pred->getState(), true, Pred); 2107 return; 2108 } 2109 2110 if (const auto *Ex = dyn_cast<Expr>(Condition)) 2111 Condition = Ex->IgnoreParens(); 2112 2113 Condition = ResolveCondition(Condition, BldCtx.getBlock()); 2114 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 2115 Condition->getBeginLoc(), 2116 "Error evaluating branch"); 2117 2118 ExplodedNodeSet CheckersOutSet; 2119 getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet, 2120 Pred, *this); 2121 // We generated only sinks. 2122 if (CheckersOutSet.empty()) 2123 return; 2124 2125 BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF); 2126 for (const auto PredI : CheckersOutSet) { 2127 if (PredI->isSink()) 2128 continue; 2129 2130 ProgramStateRef PrevState = PredI->getState(); 2131 SVal X = PrevState->getSVal(Condition, PredI->getLocationContext()); 2132 2133 if (X.isUnknownOrUndef()) { 2134 // Give it a chance to recover from unknown. 2135 if (const auto *Ex = dyn_cast<Expr>(Condition)) { 2136 if (Ex->getType()->isIntegralOrEnumerationType()) { 2137 // Try to recover some path-sensitivity. Right now casts of symbolic 2138 // integers that promote their values are currently not tracked well. 2139 // If 'Condition' is such an expression, try and recover the 2140 // underlying value and use that instead. 2141 SVal recovered = RecoverCastedSymbol(PrevState, Condition, 2142 PredI->getLocationContext(), 2143 getContext()); 2144 2145 if (!recovered.isUnknown()) { 2146 X = recovered; 2147 } 2148 } 2149 } 2150 } 2151 2152 // If the condition is still unknown, give up. 2153 if (X.isUnknownOrUndef()) { 2154 builder.generateNode(PrevState, true, PredI); 2155 builder.generateNode(PrevState, false, PredI); 2156 continue; 2157 } 2158 2159 DefinedSVal V = X.castAs<DefinedSVal>(); 2160 2161 ProgramStateRef StTrue, StFalse; 2162 std::tie(StTrue, StFalse) = PrevState->assume(V); 2163 2164 // Process the true branch. 2165 if (builder.isFeasible(true)) { 2166 if (StTrue) 2167 builder.generateNode(StTrue, true, PredI); 2168 else 2169 builder.markInfeasible(true); 2170 } 2171 2172 // Process the false branch. 2173 if (builder.isFeasible(false)) { 2174 if (StFalse) 2175 builder.generateNode(StFalse, false, PredI); 2176 else 2177 builder.markInfeasible(false); 2178 } 2179 } 2180 currBldrCtx = nullptr; 2181 } 2182 2183 /// The GDM component containing the set of global variables which have been 2184 /// previously initialized with explicit initializers. 2185 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet, 2186 llvm::ImmutableSet<const VarDecl *>) 2187 2188 void ExprEngine::processStaticInitializer(const DeclStmt *DS, 2189 NodeBuilderContext &BuilderCtx, 2190 ExplodedNode *Pred, 2191 ExplodedNodeSet &Dst, 2192 const CFGBlock *DstT, 2193 const CFGBlock *DstF) { 2194 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 2195 currBldrCtx = &BuilderCtx; 2196 2197 const auto *VD = cast<VarDecl>(DS->getSingleDecl()); 2198 ProgramStateRef state = Pred->getState(); 2199 bool initHasRun = state->contains<InitializedGlobalsSet>(VD); 2200 BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF); 2201 2202 if (!initHasRun) { 2203 state = state->add<InitializedGlobalsSet>(VD); 2204 } 2205 2206 builder.generateNode(state, initHasRun, Pred); 2207 builder.markInfeasible(!initHasRun); 2208 2209 currBldrCtx = nullptr; 2210 } 2211 2212 /// processIndirectGoto - Called by CoreEngine. Used to generate successor 2213 /// nodes by processing the 'effects' of a computed goto jump. 2214 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) { 2215 ProgramStateRef state = builder.getState(); 2216 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext()); 2217 2218 // Three possibilities: 2219 // 2220 // (1) We know the computed label. 2221 // (2) The label is NULL (or some other constant), or Undefined. 2222 // (3) We have no clue about the label. Dispatch to all targets. 2223 // 2224 2225 using iterator = IndirectGotoNodeBuilder::iterator; 2226 2227 if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) { 2228 const LabelDecl *L = LV->getLabel(); 2229 2230 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) { 2231 if (I.getLabel() == L) { 2232 builder.generateNode(I, state); 2233 return; 2234 } 2235 } 2236 2237 llvm_unreachable("No block with label."); 2238 } 2239 2240 if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) { 2241 // Dispatch to the first target and mark it as a sink. 2242 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true); 2243 // FIXME: add checker visit. 2244 // UndefBranches.insert(N); 2245 return; 2246 } 2247 2248 // This is really a catch-all. We don't support symbolics yet. 2249 // FIXME: Implement dispatch for symbolic pointers. 2250 2251 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) 2252 builder.generateNode(I, state); 2253 } 2254 2255 void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC, 2256 ExplodedNode *Pred, 2257 ExplodedNodeSet &Dst, 2258 const BlockEdge &L) { 2259 SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC); 2260 getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this); 2261 } 2262 2263 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path 2264 /// nodes when the control reaches the end of a function. 2265 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC, 2266 ExplodedNode *Pred, 2267 const ReturnStmt *RS) { 2268 ProgramStateRef State = Pred->getState(); 2269 2270 if (!Pred->getStackFrame()->inTopFrame()) 2271 State = finishArgumentConstruction( 2272 State, *getStateManager().getCallEventManager().getCaller( 2273 Pred->getStackFrame(), Pred->getState())); 2274 2275 // FIXME: We currently cannot assert that temporaries are clear, because 2276 // lifetime extended temporaries are not always modelled correctly. In some 2277 // cases when we materialize the temporary, we do 2278 // createTemporaryRegionIfNeeded(), and the region changes, and also the 2279 // respective destructor becomes automatic from temporary. So for now clean up 2280 // the state manually before asserting. Ideally, this braced block of code 2281 // should go away. 2282 { 2283 const LocationContext *FromLC = Pred->getLocationContext(); 2284 const LocationContext *ToLC = FromLC->getStackFrame()->getParent(); 2285 const LocationContext *LC = FromLC; 2286 while (LC != ToLC) { 2287 assert(LC && "ToLC must be a parent of FromLC!"); 2288 for (auto I : State->get<ObjectsUnderConstruction>()) 2289 if (I.first.getLocationContext() == LC) { 2290 // The comment above only pardons us for not cleaning up a 2291 // temporary destructor. If any other statements are found here, 2292 // it must be a separate problem. 2293 assert(I.first.getItem().getKind() == 2294 ConstructionContextItem::TemporaryDestructorKind || 2295 I.first.getItem().getKind() == 2296 ConstructionContextItem::ElidedDestructorKind); 2297 State = State->remove<ObjectsUnderConstruction>(I.first); 2298 } 2299 LC = LC->getParent(); 2300 } 2301 } 2302 2303 // Perform the transition with cleanups. 2304 if (State != Pred->getState()) { 2305 ExplodedNodeSet PostCleanup; 2306 NodeBuilder Bldr(Pred, PostCleanup, BC); 2307 Pred = Bldr.generateNode(Pred->getLocation(), State, Pred); 2308 if (!Pred) { 2309 // The node with clean temporaries already exists. We might have reached 2310 // it on a path on which we initialize different temporaries. 2311 return; 2312 } 2313 } 2314 2315 assert(areAllObjectsFullyConstructed(Pred->getState(), 2316 Pred->getLocationContext(), 2317 Pred->getStackFrame()->getParent())); 2318 2319 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 2320 2321 ExplodedNodeSet Dst; 2322 if (Pred->getLocationContext()->inTopFrame()) { 2323 // Remove dead symbols. 2324 ExplodedNodeSet AfterRemovedDead; 2325 removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead); 2326 2327 // Notify checkers. 2328 for (const auto I : AfterRemovedDead) 2329 getCheckerManager().runCheckersForEndFunction(BC, Dst, I, *this, RS); 2330 } else { 2331 getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this, RS); 2332 } 2333 2334 Engine.enqueueEndOfFunction(Dst, RS); 2335 } 2336 2337 /// ProcessSwitch - Called by CoreEngine. Used to generate successor 2338 /// nodes by processing the 'effects' of a switch statement. 2339 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) { 2340 using iterator = SwitchNodeBuilder::iterator; 2341 2342 ProgramStateRef state = builder.getState(); 2343 const Expr *CondE = builder.getCondition(); 2344 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext()); 2345 2346 if (CondV_untested.isUndef()) { 2347 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true); 2348 // FIXME: add checker 2349 //UndefBranches.insert(N); 2350 2351 return; 2352 } 2353 DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>(); 2354 2355 ProgramStateRef DefaultSt = state; 2356 2357 iterator I = builder.begin(), EI = builder.end(); 2358 bool defaultIsFeasible = I == EI; 2359 2360 for ( ; I != EI; ++I) { 2361 // Successor may be pruned out during CFG construction. 2362 if (!I.getBlock()) 2363 continue; 2364 2365 const CaseStmt *Case = I.getCase(); 2366 2367 // Evaluate the LHS of the case value. 2368 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext()); 2369 assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType())); 2370 2371 // Get the RHS of the case, if it exists. 2372 llvm::APSInt V2; 2373 if (const Expr *E = Case->getRHS()) 2374 V2 = E->EvaluateKnownConstInt(getContext()); 2375 else 2376 V2 = V1; 2377 2378 ProgramStateRef StateCase; 2379 if (Optional<NonLoc> NL = CondV.getAs<NonLoc>()) 2380 std::tie(StateCase, DefaultSt) = 2381 DefaultSt->assumeInclusiveRange(*NL, V1, V2); 2382 else // UnknownVal 2383 StateCase = DefaultSt; 2384 2385 if (StateCase) 2386 builder.generateCaseStmtNode(I, StateCase); 2387 2388 // Now "assume" that the case doesn't match. Add this state 2389 // to the default state (if it is feasible). 2390 if (DefaultSt) 2391 defaultIsFeasible = true; 2392 else { 2393 defaultIsFeasible = false; 2394 break; 2395 } 2396 } 2397 2398 if (!defaultIsFeasible) 2399 return; 2400 2401 // If we have switch(enum value), the default branch is not 2402 // feasible if all of the enum constants not covered by 'case:' statements 2403 // are not feasible values for the switch condition. 2404 // 2405 // Note that this isn't as accurate as it could be. Even if there isn't 2406 // a case for a particular enum value as long as that enum value isn't 2407 // feasible then it shouldn't be considered for making 'default:' reachable. 2408 const SwitchStmt *SS = builder.getSwitch(); 2409 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts(); 2410 if (CondExpr->getType()->getAs<EnumType>()) { 2411 if (SS->isAllEnumCasesCovered()) 2412 return; 2413 } 2414 2415 builder.generateDefaultCaseNode(DefaultSt); 2416 } 2417 2418 //===----------------------------------------------------------------------===// 2419 // Transfer functions: Loads and stores. 2420 //===----------------------------------------------------------------------===// 2421 2422 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D, 2423 ExplodedNode *Pred, 2424 ExplodedNodeSet &Dst) { 2425 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 2426 2427 ProgramStateRef state = Pred->getState(); 2428 const LocationContext *LCtx = Pred->getLocationContext(); 2429 2430 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2431 // C permits "extern void v", and if you cast the address to a valid type, 2432 // you can even do things with it. We simply pretend 2433 assert(Ex->isGLValue() || VD->getType()->isVoidType()); 2434 const LocationContext *LocCtxt = Pred->getLocationContext(); 2435 const Decl *D = LocCtxt->getDecl(); 2436 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D); 2437 const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex); 2438 Optional<std::pair<SVal, QualType>> VInfo; 2439 2440 if (AMgr.options.ShouldInlineLambdas && DeclRefEx && 2441 DeclRefEx->refersToEnclosingVariableOrCapture() && MD && 2442 MD->getParent()->isLambda()) { 2443 // Lookup the field of the lambda. 2444 const CXXRecordDecl *CXXRec = MD->getParent(); 2445 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 2446 FieldDecl *LambdaThisCaptureField; 2447 CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField); 2448 2449 // Sema follows a sequence of complex rules to determine whether the 2450 // variable should be captured. 2451 if (const FieldDecl *FD = LambdaCaptureFields[VD]) { 2452 Loc CXXThis = 2453 svalBuilder.getCXXThis(MD, LocCtxt->getStackFrame()); 2454 SVal CXXThisVal = state->getSVal(CXXThis); 2455 VInfo = std::make_pair(state->getLValue(FD, CXXThisVal), FD->getType()); 2456 } 2457 } 2458 2459 if (!VInfo) 2460 VInfo = std::make_pair(state->getLValue(VD, LocCtxt), VD->getType()); 2461 2462 SVal V = VInfo->first; 2463 bool IsReference = VInfo->second->isReferenceType(); 2464 2465 // For references, the 'lvalue' is the pointer address stored in the 2466 // reference region. 2467 if (IsReference) { 2468 if (const MemRegion *R = V.getAsRegion()) 2469 V = state->getSVal(R); 2470 else 2471 V = UnknownVal(); 2472 } 2473 2474 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr, 2475 ProgramPoint::PostLValueKind); 2476 return; 2477 } 2478 if (const auto *ED = dyn_cast<EnumConstantDecl>(D)) { 2479 assert(!Ex->isGLValue()); 2480 SVal V = svalBuilder.makeIntVal(ED->getInitVal()); 2481 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V)); 2482 return; 2483 } 2484 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 2485 SVal V = svalBuilder.getFunctionPointer(FD); 2486 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr, 2487 ProgramPoint::PostLValueKind); 2488 return; 2489 } 2490 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) { 2491 // FIXME: Compute lvalue of field pointers-to-member. 2492 // Right now we just use a non-null void pointer, so that it gives proper 2493 // results in boolean contexts. 2494 // FIXME: Maybe delegate this to the surrounding operator&. 2495 // Note how this expression is lvalue, however pointer-to-member is NonLoc. 2496 SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy, 2497 currBldrCtx->blockCount()); 2498 state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true); 2499 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr, 2500 ProgramPoint::PostLValueKind); 2501 return; 2502 } 2503 if (isa<BindingDecl>(D)) { 2504 // FIXME: proper support for bound declarations. 2505 // For now, let's just prevent crashing. 2506 return; 2507 } 2508 2509 llvm_unreachable("Support for this Decl not implemented."); 2510 } 2511 2512 /// VisitArraySubscriptExpr - Transfer function for array accesses 2513 void ExprEngine::VisitArraySubscriptExpr(const ArraySubscriptExpr *A, 2514 ExplodedNode *Pred, 2515 ExplodedNodeSet &Dst){ 2516 const Expr *Base = A->getBase()->IgnoreParens(); 2517 const Expr *Idx = A->getIdx()->IgnoreParens(); 2518 2519 ExplodedNodeSet CheckerPreStmt; 2520 getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this); 2521 2522 ExplodedNodeSet EvalSet; 2523 StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx); 2524 2525 bool IsVectorType = A->getBase()->getType()->isVectorType(); 2526 2527 // The "like" case is for situations where C standard prohibits the type to 2528 // be an lvalue, e.g. taking the address of a subscript of an expression of 2529 // type "void *". 2530 bool IsGLValueLike = A->isGLValue() || 2531 (A->getType().isCForbiddenLValueType() && !AMgr.getLangOpts().CPlusPlus); 2532 2533 for (auto *Node : CheckerPreStmt) { 2534 const LocationContext *LCtx = Node->getLocationContext(); 2535 ProgramStateRef state = Node->getState(); 2536 2537 if (IsGLValueLike) { 2538 QualType T = A->getType(); 2539 2540 // One of the forbidden LValue types! We still need to have sensible 2541 // symbolic locations to represent this stuff. Note that arithmetic on 2542 // void pointers is a GCC extension. 2543 if (T->isVoidType()) 2544 T = getContext().CharTy; 2545 2546 SVal V = state->getLValue(T, 2547 state->getSVal(Idx, LCtx), 2548 state->getSVal(Base, LCtx)); 2549 Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr, 2550 ProgramPoint::PostLValueKind); 2551 } else if (IsVectorType) { 2552 // FIXME: non-glvalue vector reads are not modelled. 2553 Bldr.generateNode(A, Node, state, nullptr); 2554 } else { 2555 llvm_unreachable("Array subscript should be an lValue when not \ 2556 a vector and not a forbidden lvalue type"); 2557 } 2558 } 2559 2560 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this); 2561 } 2562 2563 /// VisitMemberExpr - Transfer function for member expressions. 2564 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, 2565 ExplodedNodeSet &Dst) { 2566 // FIXME: Prechecks eventually go in ::Visit(). 2567 ExplodedNodeSet CheckedSet; 2568 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this); 2569 2570 ExplodedNodeSet EvalSet; 2571 ValueDecl *Member = M->getMemberDecl(); 2572 2573 // Handle static member variables and enum constants accessed via 2574 // member syntax. 2575 if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) { 2576 for (const auto I : CheckedSet) 2577 VisitCommonDeclRefExpr(M, Member, I, EvalSet); 2578 } else { 2579 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx); 2580 ExplodedNodeSet Tmp; 2581 2582 for (const auto I : CheckedSet) { 2583 ProgramStateRef state = I->getState(); 2584 const LocationContext *LCtx = I->getLocationContext(); 2585 Expr *BaseExpr = M->getBase(); 2586 2587 // Handle C++ method calls. 2588 if (const auto *MD = dyn_cast<CXXMethodDecl>(Member)) { 2589 if (MD->isInstance()) 2590 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr); 2591 2592 SVal MDVal = svalBuilder.getFunctionPointer(MD); 2593 state = state->BindExpr(M, LCtx, MDVal); 2594 2595 Bldr.generateNode(M, I, state); 2596 continue; 2597 } 2598 2599 // Handle regular struct fields / member variables. 2600 const SubRegion *MR = nullptr; 2601 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr, 2602 /*Result=*/nullptr, 2603 /*OutRegionWithAdjustments=*/&MR); 2604 SVal baseExprVal = 2605 MR ? loc::MemRegionVal(MR) : state->getSVal(BaseExpr, LCtx); 2606 2607 const auto *field = cast<FieldDecl>(Member); 2608 SVal L = state->getLValue(field, baseExprVal); 2609 2610 if (M->isGLValue() || M->getType()->isArrayType()) { 2611 // We special-case rvalues of array type because the analyzer cannot 2612 // reason about them, since we expect all regions to be wrapped in Locs. 2613 // We instead treat these as lvalues and assume that they will decay to 2614 // pointers as soon as they are used. 2615 if (!M->isGLValue()) { 2616 assert(M->getType()->isArrayType()); 2617 const auto *PE = 2618 dyn_cast<ImplicitCastExpr>(I->getParentMap().getParentIgnoreParens(M)); 2619 if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) { 2620 llvm_unreachable("should always be wrapped in ArrayToPointerDecay"); 2621 } 2622 } 2623 2624 if (field->getType()->isReferenceType()) { 2625 if (const MemRegion *R = L.getAsRegion()) 2626 L = state->getSVal(R); 2627 else 2628 L = UnknownVal(); 2629 } 2630 2631 Bldr.generateNode(M, I, state->BindExpr(M, LCtx, L), nullptr, 2632 ProgramPoint::PostLValueKind); 2633 } else { 2634 Bldr.takeNodes(I); 2635 evalLoad(Tmp, M, M, I, state, L); 2636 Bldr.addNodes(Tmp); 2637 } 2638 } 2639 } 2640 2641 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this); 2642 } 2643 2644 void ExprEngine::VisitAtomicExpr(const AtomicExpr *AE, ExplodedNode *Pred, 2645 ExplodedNodeSet &Dst) { 2646 ExplodedNodeSet AfterPreSet; 2647 getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this); 2648 2649 // For now, treat all the arguments to C11 atomics as escaping. 2650 // FIXME: Ideally we should model the behavior of the atomics precisely here. 2651 2652 ExplodedNodeSet AfterInvalidateSet; 2653 StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx); 2654 2655 for (const auto I : AfterPreSet) { 2656 ProgramStateRef State = I->getState(); 2657 const LocationContext *LCtx = I->getLocationContext(); 2658 2659 SmallVector<SVal, 8> ValuesToInvalidate; 2660 for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) { 2661 const Expr *SubExpr = AE->getSubExprs()[SI]; 2662 SVal SubExprVal = State->getSVal(SubExpr, LCtx); 2663 ValuesToInvalidate.push_back(SubExprVal); 2664 } 2665 2666 State = State->invalidateRegions(ValuesToInvalidate, AE, 2667 currBldrCtx->blockCount(), 2668 LCtx, 2669 /*CausedByPointerEscape*/true, 2670 /*Symbols=*/nullptr); 2671 2672 SVal ResultVal = UnknownVal(); 2673 State = State->BindExpr(AE, LCtx, ResultVal); 2674 Bldr.generateNode(AE, I, State, nullptr, 2675 ProgramPoint::PostStmtKind); 2676 } 2677 2678 getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this); 2679 } 2680 2681 // A value escapes in four possible cases: 2682 // (1) We are binding to something that is not a memory region. 2683 // (2) We are binding to a MemRegion that does not have stack storage. 2684 // (3) We are binding to a top-level parameter region with a non-trivial 2685 // destructor. We won't see the destructor during analysis, but it's there. 2686 // (4) We are binding to a MemRegion with stack storage that the store 2687 // does not understand. 2688 ProgramStateRef 2689 ExprEngine::processPointerEscapedOnBind(ProgramStateRef State, SVal Loc, 2690 SVal Val, const LocationContext *LCtx) { 2691 2692 // Cases (1) and (2). 2693 const MemRegion *MR = Loc.getAsRegion(); 2694 if (!MR || !MR->hasStackStorage()) 2695 return escapeValue(State, Val, PSK_EscapeOnBind); 2696 2697 // Case (3). 2698 if (const auto *VR = dyn_cast<VarRegion>(MR->getBaseRegion())) 2699 if (VR->hasStackParametersStorage() && VR->getStackFrame()->inTopFrame()) 2700 if (const auto *RD = VR->getValueType()->getAsCXXRecordDecl()) 2701 if (!RD->hasTrivialDestructor()) 2702 return escapeValue(State, Val, PSK_EscapeOnBind); 2703 2704 // Case (4): in order to test that, generate a new state with the binding 2705 // added. If it is the same state, then it escapes (since the store cannot 2706 // represent the binding). 2707 // Do this only if we know that the store is not supposed to generate the 2708 // same state. 2709 SVal StoredVal = State->getSVal(MR); 2710 if (StoredVal != Val) 2711 if (State == (State->bindLoc(loc::MemRegionVal(MR), Val, LCtx))) 2712 return escapeValue(State, Val, PSK_EscapeOnBind); 2713 2714 return State; 2715 } 2716 2717 ProgramStateRef 2718 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State, 2719 const InvalidatedSymbols *Invalidated, 2720 ArrayRef<const MemRegion *> ExplicitRegions, 2721 const CallEvent *Call, 2722 RegionAndSymbolInvalidationTraits &ITraits) { 2723 if (!Invalidated || Invalidated->empty()) 2724 return State; 2725 2726 if (!Call) 2727 return getCheckerManager().runCheckersForPointerEscape(State, 2728 *Invalidated, 2729 nullptr, 2730 PSK_EscapeOther, 2731 &ITraits); 2732 2733 // If the symbols were invalidated by a call, we want to find out which ones 2734 // were invalidated directly due to being arguments to the call. 2735 InvalidatedSymbols SymbolsDirectlyInvalidated; 2736 for (const auto I : ExplicitRegions) { 2737 if (const SymbolicRegion *R = I->StripCasts()->getAs<SymbolicRegion>()) 2738 SymbolsDirectlyInvalidated.insert(R->getSymbol()); 2739 } 2740 2741 InvalidatedSymbols SymbolsIndirectlyInvalidated; 2742 for (const auto &sym : *Invalidated) { 2743 if (SymbolsDirectlyInvalidated.count(sym)) 2744 continue; 2745 SymbolsIndirectlyInvalidated.insert(sym); 2746 } 2747 2748 if (!SymbolsDirectlyInvalidated.empty()) 2749 State = getCheckerManager().runCheckersForPointerEscape(State, 2750 SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits); 2751 2752 // Notify about the symbols that get indirectly invalidated by the call. 2753 if (!SymbolsIndirectlyInvalidated.empty()) 2754 State = getCheckerManager().runCheckersForPointerEscape(State, 2755 SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits); 2756 2757 return State; 2758 } 2759 2760 /// evalBind - Handle the semantics of binding a value to a specific location. 2761 /// This method is used by evalStore and (soon) VisitDeclStmt, and others. 2762 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, 2763 ExplodedNode *Pred, 2764 SVal location, SVal Val, 2765 bool atDeclInit, const ProgramPoint *PP) { 2766 const LocationContext *LC = Pred->getLocationContext(); 2767 PostStmt PS(StoreE, LC); 2768 if (!PP) 2769 PP = &PS; 2770 2771 // Do a previsit of the bind. 2772 ExplodedNodeSet CheckedSet; 2773 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val, 2774 StoreE, *this, *PP); 2775 2776 StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx); 2777 2778 // If the location is not a 'Loc', it will already be handled by 2779 // the checkers. There is nothing left to do. 2780 if (!location.getAs<Loc>()) { 2781 const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr, 2782 /*tag*/nullptr); 2783 ProgramStateRef state = Pred->getState(); 2784 state = processPointerEscapedOnBind(state, location, Val, LC); 2785 Bldr.generateNode(L, state, Pred); 2786 return; 2787 } 2788 2789 for (const auto PredI : CheckedSet) { 2790 ProgramStateRef state = PredI->getState(); 2791 2792 state = processPointerEscapedOnBind(state, location, Val, LC); 2793 2794 // When binding the value, pass on the hint that this is a initialization. 2795 // For initializations, we do not need to inform clients of region 2796 // changes. 2797 state = state->bindLoc(location.castAs<Loc>(), 2798 Val, LC, /* notifyChanges = */ !atDeclInit); 2799 2800 const MemRegion *LocReg = nullptr; 2801 if (Optional<loc::MemRegionVal> LocRegVal = 2802 location.getAs<loc::MemRegionVal>()) { 2803 LocReg = LocRegVal->getRegion(); 2804 } 2805 2806 const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr); 2807 Bldr.generateNode(L, state, PredI); 2808 } 2809 } 2810 2811 /// evalStore - Handle the semantics of a store via an assignment. 2812 /// @param Dst The node set to store generated state nodes 2813 /// @param AssignE The assignment expression if the store happens in an 2814 /// assignment. 2815 /// @param LocationE The location expression that is stored to. 2816 /// @param state The current simulation state 2817 /// @param location The location to store the value 2818 /// @param Val The value to be stored 2819 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, 2820 const Expr *LocationE, 2821 ExplodedNode *Pred, 2822 ProgramStateRef state, SVal location, SVal Val, 2823 const ProgramPointTag *tag) { 2824 // Proceed with the store. We use AssignE as the anchor for the PostStore 2825 // ProgramPoint if it is non-NULL, and LocationE otherwise. 2826 const Expr *StoreE = AssignE ? AssignE : LocationE; 2827 2828 // Evaluate the location (checks for bad dereferences). 2829 ExplodedNodeSet Tmp; 2830 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, false); 2831 2832 if (Tmp.empty()) 2833 return; 2834 2835 if (location.isUndef()) 2836 return; 2837 2838 for (const auto I : Tmp) 2839 evalBind(Dst, StoreE, I, location, Val, false); 2840 } 2841 2842 void ExprEngine::evalLoad(ExplodedNodeSet &Dst, 2843 const Expr *NodeEx, 2844 const Expr *BoundEx, 2845 ExplodedNode *Pred, 2846 ProgramStateRef state, 2847 SVal location, 2848 const ProgramPointTag *tag, 2849 QualType LoadTy) { 2850 assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc."); 2851 assert(NodeEx); 2852 assert(BoundEx); 2853 // Evaluate the location (checks for bad dereferences). 2854 ExplodedNodeSet Tmp; 2855 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, true); 2856 if (Tmp.empty()) 2857 return; 2858 2859 StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx); 2860 if (location.isUndef()) 2861 return; 2862 2863 // Proceed with the load. 2864 for (const auto I : Tmp) { 2865 state = I->getState(); 2866 const LocationContext *LCtx = I->getLocationContext(); 2867 2868 SVal V = UnknownVal(); 2869 if (location.isValid()) { 2870 if (LoadTy.isNull()) 2871 LoadTy = BoundEx->getType(); 2872 V = state->getSVal(location.castAs<Loc>(), LoadTy); 2873 } 2874 2875 Bldr.generateNode(NodeEx, I, state->BindExpr(BoundEx, LCtx, V), tag, 2876 ProgramPoint::PostLoadKind); 2877 } 2878 } 2879 2880 void ExprEngine::evalLocation(ExplodedNodeSet &Dst, 2881 const Stmt *NodeEx, 2882 const Stmt *BoundEx, 2883 ExplodedNode *Pred, 2884 ProgramStateRef state, 2885 SVal location, 2886 bool isLoad) { 2887 StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx); 2888 // Early checks for performance reason. 2889 if (location.isUnknown()) { 2890 return; 2891 } 2892 2893 ExplodedNodeSet Src; 2894 BldrTop.takeNodes(Pred); 2895 StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx); 2896 if (Pred->getState() != state) { 2897 // Associate this new state with an ExplodedNode. 2898 // FIXME: If I pass null tag, the graph is incorrect, e.g for 2899 // int *p; 2900 // p = 0; 2901 // *p = 0xDEADBEEF; 2902 // "p = 0" is not noted as "Null pointer value stored to 'p'" but 2903 // instead "int *p" is noted as 2904 // "Variable 'p' initialized to a null pointer value" 2905 2906 static SimpleProgramPointTag tag(TagProviderName, "Location"); 2907 Bldr.generateNode(NodeEx, Pred, state, &tag); 2908 } 2909 ExplodedNodeSet Tmp; 2910 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad, 2911 NodeEx, BoundEx, *this); 2912 BldrTop.addNodes(Tmp); 2913 } 2914 2915 std::pair<const ProgramPointTag *, const ProgramPointTag*> 2916 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() { 2917 static SimpleProgramPointTag 2918 eagerlyAssumeBinOpBifurcationTrue(TagProviderName, 2919 "Eagerly Assume True"), 2920 eagerlyAssumeBinOpBifurcationFalse(TagProviderName, 2921 "Eagerly Assume False"); 2922 return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue, 2923 &eagerlyAssumeBinOpBifurcationFalse); 2924 } 2925 2926 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, 2927 ExplodedNodeSet &Src, 2928 const Expr *Ex) { 2929 StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx); 2930 2931 for (const auto Pred : Src) { 2932 // Test if the previous node was as the same expression. This can happen 2933 // when the expression fails to evaluate to anything meaningful and 2934 // (as an optimization) we don't generate a node. 2935 ProgramPoint P = Pred->getLocation(); 2936 if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) { 2937 continue; 2938 } 2939 2940 ProgramStateRef state = Pred->getState(); 2941 SVal V = state->getSVal(Ex, Pred->getLocationContext()); 2942 Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>(); 2943 if (SEV && SEV->isExpression()) { 2944 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags = 2945 geteagerlyAssumeBinOpBifurcationTags(); 2946 2947 ProgramStateRef StateTrue, StateFalse; 2948 std::tie(StateTrue, StateFalse) = state->assume(*SEV); 2949 2950 // First assume that the condition is true. 2951 if (StateTrue) { 2952 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType()); 2953 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val); 2954 Bldr.generateNode(Ex, Pred, StateTrue, tags.first); 2955 } 2956 2957 // Next, assume that the condition is false. 2958 if (StateFalse) { 2959 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType()); 2960 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val); 2961 Bldr.generateNode(Ex, Pred, StateFalse, tags.second); 2962 } 2963 } 2964 } 2965 } 2966 2967 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, 2968 ExplodedNodeSet &Dst) { 2969 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 2970 // We have processed both the inputs and the outputs. All of the outputs 2971 // should evaluate to Locs. Nuke all of their values. 2972 2973 // FIXME: Some day in the future it would be nice to allow a "plug-in" 2974 // which interprets the inline asm and stores proper results in the 2975 // outputs. 2976 2977 ProgramStateRef state = Pred->getState(); 2978 2979 for (const Expr *O : A->outputs()) { 2980 SVal X = state->getSVal(O, Pred->getLocationContext()); 2981 assert(!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef. 2982 2983 if (Optional<Loc> LV = X.getAs<Loc>()) 2984 state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext()); 2985 } 2986 2987 Bldr.generateNode(A, Pred, state); 2988 } 2989 2990 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred, 2991 ExplodedNodeSet &Dst) { 2992 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 2993 Bldr.generateNode(A, Pred, Pred->getState()); 2994 } 2995 2996 //===----------------------------------------------------------------------===// 2997 // Visualization. 2998 //===----------------------------------------------------------------------===// 2999 3000 #ifndef NDEBUG 3001 namespace llvm { 3002 3003 template<> 3004 struct DOTGraphTraits<ExplodedGraph*> : public DefaultDOTGraphTraits { 3005 DOTGraphTraits (bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 3006 3007 static bool nodeHasBugReport(const ExplodedNode *N) { 3008 BugReporter &BR = static_cast<ExprEngine &>( 3009 N->getState()->getStateManager().getOwningEngine()).getBugReporter(); 3010 3011 const auto EQClasses = 3012 llvm::make_range(BR.EQClasses_begin(), BR.EQClasses_end()); 3013 3014 for (const auto &EQ : EQClasses) { 3015 for (const auto &I : EQ.getReports()) { 3016 const auto *PR = dyn_cast<PathSensitiveBugReport>(I.get()); 3017 if (!PR) 3018 continue; 3019 const ExplodedNode *EN = PR->getErrorNode(); 3020 if (EN->getState() == N->getState() && 3021 EN->getLocation() == N->getLocation()) 3022 return true; 3023 } 3024 } 3025 return false; 3026 } 3027 3028 /// \p PreCallback: callback before break. 3029 /// \p PostCallback: callback after break. 3030 /// \p Stop: stop iteration if returns {@code true} 3031 /// \return Whether {@code Stop} ever returned {@code true}. 3032 static bool traverseHiddenNodes( 3033 const ExplodedNode *N, 3034 llvm::function_ref<void(const ExplodedNode *)> PreCallback, 3035 llvm::function_ref<void(const ExplodedNode *)> PostCallback, 3036 llvm::function_ref<bool(const ExplodedNode *)> Stop) { 3037 while (true) { 3038 PreCallback(N); 3039 if (Stop(N)) 3040 return true; 3041 3042 if (N->succ_size() != 1 || !isNodeHidden(N->getFirstSucc())) 3043 break; 3044 PostCallback(N); 3045 3046 N = N->getFirstSucc(); 3047 } 3048 return false; 3049 } 3050 3051 static bool isNodeHidden(const ExplodedNode *N) { 3052 return N->isTrivial(); 3053 } 3054 3055 static std::string getNodeLabel(const ExplodedNode *N, ExplodedGraph *G){ 3056 std::string Buf; 3057 llvm::raw_string_ostream Out(Buf); 3058 3059 const bool IsDot = true; 3060 const unsigned int Space = 1; 3061 ProgramStateRef State = N->getState(); 3062 3063 Out << "{ \"state_id\": " << State->getID() 3064 << ",\\l"; 3065 3066 Indent(Out, Space, IsDot) << "\"program_points\": [\\l"; 3067 3068 // Dump program point for all the previously skipped nodes. 3069 traverseHiddenNodes( 3070 N, 3071 [&](const ExplodedNode *OtherNode) { 3072 Indent(Out, Space + 1, IsDot) << "{ "; 3073 OtherNode->getLocation().printJson(Out, /*NL=*/"\\l"); 3074 Out << ", \"tag\": "; 3075 if (const ProgramPointTag *Tag = OtherNode->getLocation().getTag()) 3076 Out << '\"' << Tag->getTagDescription() << "\""; 3077 else 3078 Out << "null"; 3079 Out << ", \"node_id\": " << OtherNode->getID() << 3080 ", \"is_sink\": " << OtherNode->isSink() << 3081 ", \"has_report\": " << nodeHasBugReport(OtherNode) << " }"; 3082 }, 3083 // Adds a comma and a new-line between each program point. 3084 [&](const ExplodedNode *) { Out << ",\\l"; }, 3085 [&](const ExplodedNode *) { return false; }); 3086 3087 Out << "\\l"; // Adds a new-line to the last program point. 3088 Indent(Out, Space, IsDot) << "],\\l"; 3089 3090 State->printDOT(Out, N->getLocationContext(), Space); 3091 3092 Out << "\\l}\\l"; 3093 return Out.str(); 3094 } 3095 }; 3096 3097 } // namespace llvm 3098 #endif 3099 3100 void ExprEngine::ViewGraph(bool trim) { 3101 #ifndef NDEBUG 3102 std::string Filename = DumpGraph(trim); 3103 llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT); 3104 #endif 3105 llvm::errs() << "Warning: viewing graph requires assertions" << "\n"; 3106 } 3107 3108 3109 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) { 3110 #ifndef NDEBUG 3111 std::string Filename = DumpGraph(Nodes); 3112 llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT); 3113 #endif 3114 llvm::errs() << "Warning: viewing graph requires assertions" << "\n"; 3115 } 3116 3117 std::string ExprEngine::DumpGraph(bool trim, StringRef Filename) { 3118 #ifndef NDEBUG 3119 if (trim) { 3120 std::vector<const ExplodedNode *> Src; 3121 3122 // Iterate through the reports and get their nodes. 3123 for (BugReporter::EQClasses_iterator 3124 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) { 3125 const auto *R = 3126 dyn_cast<PathSensitiveBugReport>(EI->getReports()[0].get()); 3127 if (!R) 3128 continue; 3129 const auto *N = const_cast<ExplodedNode *>(R->getErrorNode()); 3130 Src.push_back(N); 3131 } 3132 return DumpGraph(Src, Filename); 3133 } else { 3134 return llvm::WriteGraph(&G, "ExprEngine", /*ShortNames=*/false, 3135 /*Title=*/"Exploded Graph", /*Filename=*/Filename); 3136 } 3137 #endif 3138 llvm::errs() << "Warning: dumping graph requires assertions" << "\n"; 3139 return ""; 3140 } 3141 3142 std::string ExprEngine::DumpGraph(ArrayRef<const ExplodedNode*> Nodes, 3143 StringRef Filename) { 3144 #ifndef NDEBUG 3145 std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes)); 3146 3147 if (!TrimmedG.get()) { 3148 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n"; 3149 } else { 3150 return llvm::WriteGraph(TrimmedG.get(), "TrimmedExprEngine", 3151 /*ShortNames=*/false, 3152 /*Title=*/"Trimmed Exploded Graph", 3153 /*Filename=*/Filename); 3154 } 3155 #endif 3156 llvm::errs() << "Warning: dumping graph requires assertions" << "\n"; 3157 return ""; 3158 } 3159 3160 void *ProgramStateTrait<ReplayWithoutInlining>::GDMIndex() { 3161 static int index = 0; 3162 return &index; 3163 } 3164