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