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