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