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