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