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