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