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