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 // FIXME: Currently CleanDtorState can be empty here due to temporaries being 685 // bound to default parameters. 686 assert(CleanDtorState.size() <= 1); 687 ExplodedNode *CleanPred = 688 CleanDtorState.empty() ? Pred : *CleanDtorState.begin(); 689 // FIXME: Inlining of temporary destructors is not supported yet anyway, so 690 // we just put a NULL region for now. This will need to be changed later. 691 VisitCXXDestructor(varType, nullptr, D.getBindTemporaryExpr(), 692 /*IsBase=*/false, CleanPred, Dst); 693 } 694 695 void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE, 696 NodeBuilderContext &BldCtx, 697 ExplodedNode *Pred, 698 ExplodedNodeSet &Dst, 699 const CFGBlock *DstT, 700 const CFGBlock *DstF) { 701 BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF); 702 if (Pred->getState()->contains<InitializedTemporariesSet>( 703 std::make_pair(BTE, Pred->getStackFrame()))) { 704 TempDtorBuilder.markInfeasible(false); 705 TempDtorBuilder.generateNode(Pred->getState(), true, Pred); 706 } else { 707 TempDtorBuilder.markInfeasible(true); 708 TempDtorBuilder.generateNode(Pred->getState(), false, Pred); 709 } 710 } 711 712 void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE, 713 ExplodedNodeSet &PreVisit, 714 ExplodedNodeSet &Dst) { 715 if (!getAnalysisManager().options.includeTemporaryDtorsInCFG()) { 716 // In case we don't have temporary destructors in the CFG, do not mark 717 // the initialization - we would otherwise never clean it up. 718 Dst = PreVisit; 719 return; 720 } 721 StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx); 722 for (ExplodedNode *Node : PreVisit) { 723 ProgramStateRef State = Node->getState(); 724 725 if (!State->contains<InitializedTemporariesSet>( 726 std::make_pair(BTE, Node->getStackFrame()))) { 727 // FIXME: Currently the state might already contain the marker due to 728 // incorrect handling of temporaries bound to default parameters; for 729 // those, we currently skip the CXXBindTemporaryExpr but rely on adding 730 // temporary destructor nodes. 731 State = State->add<InitializedTemporariesSet>( 732 std::make_pair(BTE, Node->getStackFrame())); 733 } 734 StmtBldr.generateNode(BTE, Node, State); 735 } 736 } 737 738 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred, 739 ExplodedNodeSet &DstTop) { 740 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 741 S->getLocStart(), 742 "Error evaluating statement"); 743 ExplodedNodeSet Dst; 744 StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx); 745 746 assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens()); 747 748 switch (S->getStmtClass()) { 749 // C++ and ARC stuff we don't support yet. 750 case Expr::ObjCIndirectCopyRestoreExprClass: 751 case Stmt::CXXDependentScopeMemberExprClass: 752 case Stmt::CXXTryStmtClass: 753 case Stmt::CXXTypeidExprClass: 754 case Stmt::CXXUuidofExprClass: 755 case Stmt::MSPropertyRefExprClass: 756 case Stmt::CXXUnresolvedConstructExprClass: 757 case Stmt::DependentScopeDeclRefExprClass: 758 case Stmt::TypeTraitExprClass: 759 case Stmt::ArrayTypeTraitExprClass: 760 case Stmt::ExpressionTraitExprClass: 761 case Stmt::UnresolvedLookupExprClass: 762 case Stmt::UnresolvedMemberExprClass: 763 case Stmt::CXXNoexceptExprClass: 764 case Stmt::PackExpansionExprClass: 765 case Stmt::SubstNonTypeTemplateParmPackExprClass: 766 case Stmt::FunctionParmPackExprClass: 767 case Stmt::SEHTryStmtClass: 768 case Stmt::SEHExceptStmtClass: 769 case Stmt::SEHLeaveStmtClass: 770 case Stmt::LambdaExprClass: 771 case Stmt::SEHFinallyStmtClass: { 772 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState()); 773 Engine.addAbortedBlock(node, currBldrCtx->getBlock()); 774 break; 775 } 776 777 case Stmt::ParenExprClass: 778 llvm_unreachable("ParenExprs already handled."); 779 case Stmt::GenericSelectionExprClass: 780 llvm_unreachable("GenericSelectionExprs already handled."); 781 // Cases that should never be evaluated simply because they shouldn't 782 // appear in the CFG. 783 case Stmt::BreakStmtClass: 784 case Stmt::CaseStmtClass: 785 case Stmt::CompoundStmtClass: 786 case Stmt::ContinueStmtClass: 787 case Stmt::CXXForRangeStmtClass: 788 case Stmt::DefaultStmtClass: 789 case Stmt::DoStmtClass: 790 case Stmt::ForStmtClass: 791 case Stmt::GotoStmtClass: 792 case Stmt::IfStmtClass: 793 case Stmt::IndirectGotoStmtClass: 794 case Stmt::LabelStmtClass: 795 case Stmt::NoStmtClass: 796 case Stmt::NullStmtClass: 797 case Stmt::SwitchStmtClass: 798 case Stmt::WhileStmtClass: 799 case Expr::MSDependentExistsStmtClass: 800 case Stmt::CapturedStmtClass: 801 case Stmt::OMPParallelDirectiveClass: 802 case Stmt::OMPSimdDirectiveClass: 803 case Stmt::OMPForDirectiveClass: 804 case Stmt::OMPForSimdDirectiveClass: 805 case Stmt::OMPSectionsDirectiveClass: 806 case Stmt::OMPSectionDirectiveClass: 807 case Stmt::OMPSingleDirectiveClass: 808 case Stmt::OMPMasterDirectiveClass: 809 case Stmt::OMPCriticalDirectiveClass: 810 case Stmt::OMPParallelForDirectiveClass: 811 case Stmt::OMPParallelForSimdDirectiveClass: 812 case Stmt::OMPParallelSectionsDirectiveClass: 813 case Stmt::OMPTaskDirectiveClass: 814 case Stmt::OMPTaskyieldDirectiveClass: 815 case Stmt::OMPBarrierDirectiveClass: 816 case Stmt::OMPTaskwaitDirectiveClass: 817 case Stmt::OMPFlushDirectiveClass: 818 case Stmt::OMPOrderedDirectiveClass: 819 case Stmt::OMPAtomicDirectiveClass: 820 case Stmt::OMPTargetDirectiveClass: 821 llvm_unreachable("Stmt should not be in analyzer evaluation loop"); 822 823 case Stmt::ObjCSubscriptRefExprClass: 824 case Stmt::ObjCPropertyRefExprClass: 825 llvm_unreachable("These are handled by PseudoObjectExpr"); 826 827 case Stmt::GNUNullExprClass: { 828 // GNU __null is a pointer-width integer, not an actual pointer. 829 ProgramStateRef state = Pred->getState(); 830 state = state->BindExpr(S, Pred->getLocationContext(), 831 svalBuilder.makeIntValWithPtrWidth(0, false)); 832 Bldr.generateNode(S, Pred, state); 833 break; 834 } 835 836 case Stmt::ObjCAtSynchronizedStmtClass: 837 Bldr.takeNodes(Pred); 838 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst); 839 Bldr.addNodes(Dst); 840 break; 841 842 case Stmt::ExprWithCleanupsClass: 843 // Handled due to fully linearised CFG. 844 break; 845 846 case Stmt::CXXBindTemporaryExprClass: { 847 Bldr.takeNodes(Pred); 848 ExplodedNodeSet PreVisit; 849 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 850 ExplodedNodeSet Next; 851 VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next); 852 getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this); 853 Bldr.addNodes(Dst); 854 break; 855 } 856 857 // Cases not handled yet; but will handle some day. 858 case Stmt::DesignatedInitExprClass: 859 case Stmt::ExtVectorElementExprClass: 860 case Stmt::ImaginaryLiteralClass: 861 case Stmt::ObjCAtCatchStmtClass: 862 case Stmt::ObjCAtFinallyStmtClass: 863 case Stmt::ObjCAtTryStmtClass: 864 case Stmt::ObjCAutoreleasePoolStmtClass: 865 case Stmt::ObjCEncodeExprClass: 866 case Stmt::ObjCIsaExprClass: 867 case Stmt::ObjCProtocolExprClass: 868 case Stmt::ObjCSelectorExprClass: 869 case Stmt::ParenListExprClass: 870 case Stmt::PredefinedExprClass: 871 case Stmt::ShuffleVectorExprClass: 872 case Stmt::ConvertVectorExprClass: 873 case Stmt::VAArgExprClass: 874 case Stmt::CUDAKernelCallExprClass: 875 case Stmt::OpaqueValueExprClass: 876 case Stmt::AsTypeExprClass: 877 case Stmt::AtomicExprClass: 878 // Fall through. 879 880 // Cases we intentionally don't evaluate, since they don't need 881 // to be explicitly evaluated. 882 case Stmt::AddrLabelExprClass: 883 case Stmt::AttributedStmtClass: 884 case Stmt::IntegerLiteralClass: 885 case Stmt::CharacterLiteralClass: 886 case Stmt::ImplicitValueInitExprClass: 887 case Stmt::CXXScalarValueInitExprClass: 888 case Stmt::CXXBoolLiteralExprClass: 889 case Stmt::ObjCBoolLiteralExprClass: 890 case Stmt::FloatingLiteralClass: 891 case Stmt::SizeOfPackExprClass: 892 case Stmt::StringLiteralClass: 893 case Stmt::ObjCStringLiteralClass: 894 case Stmt::CXXPseudoDestructorExprClass: 895 case Stmt::SubstNonTypeTemplateParmExprClass: 896 case Stmt::CXXNullPtrLiteralExprClass: { 897 Bldr.takeNodes(Pred); 898 ExplodedNodeSet preVisit; 899 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this); 900 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this); 901 Bldr.addNodes(Dst); 902 break; 903 } 904 905 case Stmt::CXXDefaultArgExprClass: 906 case Stmt::CXXDefaultInitExprClass: { 907 Bldr.takeNodes(Pred); 908 ExplodedNodeSet PreVisit; 909 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 910 911 ExplodedNodeSet Tmp; 912 StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx); 913 914 const Expr *ArgE; 915 if (const CXXDefaultArgExpr *DefE = dyn_cast<CXXDefaultArgExpr>(S)) 916 ArgE = DefE->getExpr(); 917 else if (const CXXDefaultInitExpr *DefE = dyn_cast<CXXDefaultInitExpr>(S)) 918 ArgE = DefE->getExpr(); 919 else 920 llvm_unreachable("unknown constant wrapper kind"); 921 922 bool IsTemporary = false; 923 if (const MaterializeTemporaryExpr *MTE = 924 dyn_cast<MaterializeTemporaryExpr>(ArgE)) { 925 ArgE = MTE->GetTemporaryExpr(); 926 IsTemporary = true; 927 } 928 929 Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE); 930 if (!ConstantVal) 931 ConstantVal = UnknownVal(); 932 933 const LocationContext *LCtx = Pred->getLocationContext(); 934 for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end(); 935 I != E; ++I) { 936 ProgramStateRef State = (*I)->getState(); 937 State = State->BindExpr(S, LCtx, *ConstantVal); 938 if (IsTemporary) 939 State = createTemporaryRegionIfNeeded(State, LCtx, 940 cast<Expr>(S), 941 cast<Expr>(S)); 942 Bldr2.generateNode(S, *I, State); 943 } 944 945 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this); 946 Bldr.addNodes(Dst); 947 break; 948 } 949 950 // Cases we evaluate as opaque expressions, conjuring a symbol. 951 case Stmt::CXXStdInitializerListExprClass: 952 case Expr::ObjCArrayLiteralClass: 953 case Expr::ObjCDictionaryLiteralClass: 954 case Expr::ObjCBoxedExprClass: { 955 Bldr.takeNodes(Pred); 956 957 ExplodedNodeSet preVisit; 958 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this); 959 960 ExplodedNodeSet Tmp; 961 StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx); 962 963 const Expr *Ex = cast<Expr>(S); 964 QualType resultType = Ex->getType(); 965 966 for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end(); 967 it != et; ++it) { 968 ExplodedNode *N = *it; 969 const LocationContext *LCtx = N->getLocationContext(); 970 SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx, 971 resultType, 972 currBldrCtx->blockCount()); 973 ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result); 974 Bldr2.generateNode(S, N, state); 975 } 976 977 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this); 978 Bldr.addNodes(Dst); 979 break; 980 } 981 982 case Stmt::ArraySubscriptExprClass: 983 Bldr.takeNodes(Pred); 984 VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst); 985 Bldr.addNodes(Dst); 986 break; 987 988 case Stmt::GCCAsmStmtClass: 989 Bldr.takeNodes(Pred); 990 VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst); 991 Bldr.addNodes(Dst); 992 break; 993 994 case Stmt::MSAsmStmtClass: 995 Bldr.takeNodes(Pred); 996 VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst); 997 Bldr.addNodes(Dst); 998 break; 999 1000 case Stmt::BlockExprClass: 1001 Bldr.takeNodes(Pred); 1002 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst); 1003 Bldr.addNodes(Dst); 1004 break; 1005 1006 case Stmt::BinaryOperatorClass: { 1007 const BinaryOperator* B = cast<BinaryOperator>(S); 1008 if (B->isLogicalOp()) { 1009 Bldr.takeNodes(Pred); 1010 VisitLogicalExpr(B, Pred, Dst); 1011 Bldr.addNodes(Dst); 1012 break; 1013 } 1014 else if (B->getOpcode() == BO_Comma) { 1015 ProgramStateRef state = Pred->getState(); 1016 Bldr.generateNode(B, Pred, 1017 state->BindExpr(B, Pred->getLocationContext(), 1018 state->getSVal(B->getRHS(), 1019 Pred->getLocationContext()))); 1020 break; 1021 } 1022 1023 Bldr.takeNodes(Pred); 1024 1025 if (AMgr.options.eagerlyAssumeBinOpBifurcation && 1026 (B->isRelationalOp() || B->isEqualityOp())) { 1027 ExplodedNodeSet Tmp; 1028 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp); 1029 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S)); 1030 } 1031 else 1032 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 1033 1034 Bldr.addNodes(Dst); 1035 break; 1036 } 1037 1038 case Stmt::CXXOperatorCallExprClass: { 1039 const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S); 1040 1041 // For instance method operators, make sure the 'this' argument has a 1042 // valid region. 1043 const Decl *Callee = OCE->getCalleeDecl(); 1044 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) { 1045 if (MD->isInstance()) { 1046 ProgramStateRef State = Pred->getState(); 1047 const LocationContext *LCtx = Pred->getLocationContext(); 1048 ProgramStateRef NewState = 1049 createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0)); 1050 if (NewState != State) { 1051 Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr, 1052 ProgramPoint::PreStmtKind); 1053 // Did we cache out? 1054 if (!Pred) 1055 break; 1056 } 1057 } 1058 } 1059 // FALLTHROUGH 1060 } 1061 case Stmt::CallExprClass: 1062 case Stmt::CXXMemberCallExprClass: 1063 case Stmt::UserDefinedLiteralClass: { 1064 Bldr.takeNodes(Pred); 1065 VisitCallExpr(cast<CallExpr>(S), Pred, Dst); 1066 Bldr.addNodes(Dst); 1067 break; 1068 } 1069 1070 case Stmt::CXXCatchStmtClass: { 1071 Bldr.takeNodes(Pred); 1072 VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst); 1073 Bldr.addNodes(Dst); 1074 break; 1075 } 1076 1077 case Stmt::CXXTemporaryObjectExprClass: 1078 case Stmt::CXXConstructExprClass: { 1079 Bldr.takeNodes(Pred); 1080 VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst); 1081 Bldr.addNodes(Dst); 1082 break; 1083 } 1084 1085 case Stmt::CXXNewExprClass: { 1086 Bldr.takeNodes(Pred); 1087 ExplodedNodeSet PostVisit; 1088 VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit); 1089 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this); 1090 Bldr.addNodes(Dst); 1091 break; 1092 } 1093 1094 case Stmt::CXXDeleteExprClass: { 1095 Bldr.takeNodes(Pred); 1096 ExplodedNodeSet PreVisit; 1097 const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S); 1098 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 1099 1100 for (ExplodedNodeSet::iterator i = PreVisit.begin(), 1101 e = PreVisit.end(); i != e ; ++i) 1102 VisitCXXDeleteExpr(CDE, *i, Dst); 1103 1104 Bldr.addNodes(Dst); 1105 break; 1106 } 1107 // FIXME: ChooseExpr is really a constant. We need to fix 1108 // the CFG do not model them as explicit control-flow. 1109 1110 case Stmt::ChooseExprClass: { // __builtin_choose_expr 1111 Bldr.takeNodes(Pred); 1112 const ChooseExpr *C = cast<ChooseExpr>(S); 1113 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst); 1114 Bldr.addNodes(Dst); 1115 break; 1116 } 1117 1118 case Stmt::CompoundAssignOperatorClass: 1119 Bldr.takeNodes(Pred); 1120 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 1121 Bldr.addNodes(Dst); 1122 break; 1123 1124 case Stmt::CompoundLiteralExprClass: 1125 Bldr.takeNodes(Pred); 1126 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst); 1127 Bldr.addNodes(Dst); 1128 break; 1129 1130 case Stmt::BinaryConditionalOperatorClass: 1131 case Stmt::ConditionalOperatorClass: { // '?' operator 1132 Bldr.takeNodes(Pred); 1133 const AbstractConditionalOperator *C 1134 = cast<AbstractConditionalOperator>(S); 1135 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst); 1136 Bldr.addNodes(Dst); 1137 break; 1138 } 1139 1140 case Stmt::CXXThisExprClass: 1141 Bldr.takeNodes(Pred); 1142 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst); 1143 Bldr.addNodes(Dst); 1144 break; 1145 1146 case Stmt::DeclRefExprClass: { 1147 Bldr.takeNodes(Pred); 1148 const DeclRefExpr *DE = cast<DeclRefExpr>(S); 1149 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst); 1150 Bldr.addNodes(Dst); 1151 break; 1152 } 1153 1154 case Stmt::DeclStmtClass: 1155 Bldr.takeNodes(Pred); 1156 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst); 1157 Bldr.addNodes(Dst); 1158 break; 1159 1160 case Stmt::ImplicitCastExprClass: 1161 case Stmt::CStyleCastExprClass: 1162 case Stmt::CXXStaticCastExprClass: 1163 case Stmt::CXXDynamicCastExprClass: 1164 case Stmt::CXXReinterpretCastExprClass: 1165 case Stmt::CXXConstCastExprClass: 1166 case Stmt::CXXFunctionalCastExprClass: 1167 case Stmt::ObjCBridgedCastExprClass: { 1168 Bldr.takeNodes(Pred); 1169 const CastExpr *C = cast<CastExpr>(S); 1170 // Handle the previsit checks. 1171 ExplodedNodeSet dstPrevisit; 1172 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this); 1173 1174 // Handle the expression itself. 1175 ExplodedNodeSet dstExpr; 1176 for (ExplodedNodeSet::iterator i = dstPrevisit.begin(), 1177 e = dstPrevisit.end(); i != e ; ++i) { 1178 VisitCast(C, C->getSubExpr(), *i, dstExpr); 1179 } 1180 1181 // Handle the postvisit checks. 1182 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this); 1183 Bldr.addNodes(Dst); 1184 break; 1185 } 1186 1187 case Expr::MaterializeTemporaryExprClass: { 1188 Bldr.takeNodes(Pred); 1189 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S); 1190 CreateCXXTemporaryObject(MTE, Pred, Dst); 1191 Bldr.addNodes(Dst); 1192 break; 1193 } 1194 1195 case Stmt::InitListExprClass: 1196 Bldr.takeNodes(Pred); 1197 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst); 1198 Bldr.addNodes(Dst); 1199 break; 1200 1201 case Stmt::MemberExprClass: 1202 Bldr.takeNodes(Pred); 1203 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst); 1204 Bldr.addNodes(Dst); 1205 break; 1206 1207 case Stmt::ObjCIvarRefExprClass: 1208 Bldr.takeNodes(Pred); 1209 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst); 1210 Bldr.addNodes(Dst); 1211 break; 1212 1213 case Stmt::ObjCForCollectionStmtClass: 1214 Bldr.takeNodes(Pred); 1215 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst); 1216 Bldr.addNodes(Dst); 1217 break; 1218 1219 case Stmt::ObjCMessageExprClass: 1220 Bldr.takeNodes(Pred); 1221 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst); 1222 Bldr.addNodes(Dst); 1223 break; 1224 1225 case Stmt::ObjCAtThrowStmtClass: 1226 case Stmt::CXXThrowExprClass: 1227 // FIXME: This is not complete. We basically treat @throw as 1228 // an abort. 1229 Bldr.generateSink(S, Pred, Pred->getState()); 1230 break; 1231 1232 case Stmt::ReturnStmtClass: 1233 Bldr.takeNodes(Pred); 1234 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst); 1235 Bldr.addNodes(Dst); 1236 break; 1237 1238 case Stmt::OffsetOfExprClass: 1239 Bldr.takeNodes(Pred); 1240 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst); 1241 Bldr.addNodes(Dst); 1242 break; 1243 1244 case Stmt::UnaryExprOrTypeTraitExprClass: 1245 Bldr.takeNodes(Pred); 1246 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S), 1247 Pred, Dst); 1248 Bldr.addNodes(Dst); 1249 break; 1250 1251 case Stmt::StmtExprClass: { 1252 const StmtExpr *SE = cast<StmtExpr>(S); 1253 1254 if (SE->getSubStmt()->body_empty()) { 1255 // Empty statement expression. 1256 assert(SE->getType() == getContext().VoidTy 1257 && "Empty statement expression must have void type."); 1258 break; 1259 } 1260 1261 if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) { 1262 ProgramStateRef state = Pred->getState(); 1263 Bldr.generateNode(SE, Pred, 1264 state->BindExpr(SE, Pred->getLocationContext(), 1265 state->getSVal(LastExpr, 1266 Pred->getLocationContext()))); 1267 } 1268 break; 1269 } 1270 1271 case Stmt::UnaryOperatorClass: { 1272 Bldr.takeNodes(Pred); 1273 const UnaryOperator *U = cast<UnaryOperator>(S); 1274 if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) { 1275 ExplodedNodeSet Tmp; 1276 VisitUnaryOperator(U, Pred, Tmp); 1277 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U); 1278 } 1279 else 1280 VisitUnaryOperator(U, Pred, Dst); 1281 Bldr.addNodes(Dst); 1282 break; 1283 } 1284 1285 case Stmt::PseudoObjectExprClass: { 1286 Bldr.takeNodes(Pred); 1287 ProgramStateRef state = Pred->getState(); 1288 const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S); 1289 if (const Expr *Result = PE->getResultExpr()) { 1290 SVal V = state->getSVal(Result, Pred->getLocationContext()); 1291 Bldr.generateNode(S, Pred, 1292 state->BindExpr(S, Pred->getLocationContext(), V)); 1293 } 1294 else 1295 Bldr.generateNode(S, Pred, 1296 state->BindExpr(S, Pred->getLocationContext(), 1297 UnknownVal())); 1298 1299 Bldr.addNodes(Dst); 1300 break; 1301 } 1302 } 1303 } 1304 1305 bool ExprEngine::replayWithoutInlining(ExplodedNode *N, 1306 const LocationContext *CalleeLC) { 1307 const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame(); 1308 const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame(); 1309 assert(CalleeSF && CallerSF); 1310 ExplodedNode *BeforeProcessingCall = nullptr; 1311 const Stmt *CE = CalleeSF->getCallSite(); 1312 1313 // Find the first node before we started processing the call expression. 1314 while (N) { 1315 ProgramPoint L = N->getLocation(); 1316 BeforeProcessingCall = N; 1317 N = N->pred_empty() ? nullptr : *(N->pred_begin()); 1318 1319 // Skip the nodes corresponding to the inlined code. 1320 if (L.getLocationContext()->getCurrentStackFrame() != CallerSF) 1321 continue; 1322 // We reached the caller. Find the node right before we started 1323 // processing the call. 1324 if (L.isPurgeKind()) 1325 continue; 1326 if (L.getAs<PreImplicitCall>()) 1327 continue; 1328 if (L.getAs<CallEnter>()) 1329 continue; 1330 if (Optional<StmtPoint> SP = L.getAs<StmtPoint>()) 1331 if (SP->getStmt() == CE) 1332 continue; 1333 break; 1334 } 1335 1336 if (!BeforeProcessingCall) 1337 return false; 1338 1339 // TODO: Clean up the unneeded nodes. 1340 1341 // Build an Epsilon node from which we will restart the analyzes. 1342 // Note that CE is permitted to be NULL! 1343 ProgramPoint NewNodeLoc = 1344 EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE); 1345 // Add the special flag to GDM to signal retrying with no inlining. 1346 // Note, changing the state ensures that we are not going to cache out. 1347 ProgramStateRef NewNodeState = BeforeProcessingCall->getState(); 1348 NewNodeState = 1349 NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE)); 1350 1351 // Make the new node a successor of BeforeProcessingCall. 1352 bool IsNew = false; 1353 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew); 1354 // We cached out at this point. Caching out is common due to us backtracking 1355 // from the inlined function, which might spawn several paths. 1356 if (!IsNew) 1357 return true; 1358 1359 NewNode->addPredecessor(BeforeProcessingCall, G); 1360 1361 // Add the new node to the work list. 1362 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(), 1363 CalleeSF->getIndex()); 1364 NumTimesRetriedWithoutInlining++; 1365 return true; 1366 } 1367 1368 /// Block entrance. (Update counters). 1369 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L, 1370 NodeBuilderWithSinks &nodeBuilder, 1371 ExplodedNode *Pred) { 1372 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 1373 1374 // FIXME: Refactor this into a checker. 1375 if (nodeBuilder.getContext().blockCount() >= AMgr.options.maxBlockVisitOnPath) { 1376 static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded"); 1377 const ExplodedNode *Sink = 1378 nodeBuilder.generateSink(Pred->getState(), Pred, &tag); 1379 1380 // Check if we stopped at the top level function or not. 1381 // Root node should have the location context of the top most function. 1382 const LocationContext *CalleeLC = Pred->getLocation().getLocationContext(); 1383 const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame(); 1384 const LocationContext *RootLC = 1385 (*G.roots_begin())->getLocation().getLocationContext(); 1386 if (RootLC->getCurrentStackFrame() != CalleeSF) { 1387 Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl()); 1388 1389 // Re-run the call evaluation without inlining it, by storing the 1390 // no-inlining policy in the state and enqueuing the new work item on 1391 // the list. Replay should almost never fail. Use the stats to catch it 1392 // if it does. 1393 if ((!AMgr.options.NoRetryExhausted && 1394 replayWithoutInlining(Pred, CalleeLC))) 1395 return; 1396 NumMaxBlockCountReachedInInlined++; 1397 } else 1398 NumMaxBlockCountReached++; 1399 1400 // Make sink nodes as exhausted(for stats) only if retry failed. 1401 Engine.blocksExhausted.push_back(std::make_pair(L, Sink)); 1402 } 1403 } 1404 1405 //===----------------------------------------------------------------------===// 1406 // Branch processing. 1407 //===----------------------------------------------------------------------===// 1408 1409 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used 1410 /// to try to recover some path-sensitivity for casts of symbolic 1411 /// integers that promote their values (which are currently not tracked well). 1412 /// This function returns the SVal bound to Condition->IgnoreCasts if all the 1413 // cast(s) did was sign-extend the original value. 1414 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr, 1415 ProgramStateRef state, 1416 const Stmt *Condition, 1417 const LocationContext *LCtx, 1418 ASTContext &Ctx) { 1419 1420 const Expr *Ex = dyn_cast<Expr>(Condition); 1421 if (!Ex) 1422 return UnknownVal(); 1423 1424 uint64_t bits = 0; 1425 bool bitsInit = false; 1426 1427 while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) { 1428 QualType T = CE->getType(); 1429 1430 if (!T->isIntegralOrEnumerationType()) 1431 return UnknownVal(); 1432 1433 uint64_t newBits = Ctx.getTypeSize(T); 1434 if (!bitsInit || newBits < bits) { 1435 bitsInit = true; 1436 bits = newBits; 1437 } 1438 1439 Ex = CE->getSubExpr(); 1440 } 1441 1442 // We reached a non-cast. Is it a symbolic value? 1443 QualType T = Ex->getType(); 1444 1445 if (!bitsInit || !T->isIntegralOrEnumerationType() || 1446 Ctx.getTypeSize(T) > bits) 1447 return UnknownVal(); 1448 1449 return state->getSVal(Ex, LCtx); 1450 } 1451 1452 #ifndef NDEBUG 1453 static const Stmt *getRightmostLeaf(const Stmt *Condition) { 1454 while (Condition) { 1455 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition); 1456 if (!BO || !BO->isLogicalOp()) { 1457 return Condition; 1458 } 1459 Condition = BO->getRHS()->IgnoreParens(); 1460 } 1461 return nullptr; 1462 } 1463 #endif 1464 1465 // Returns the condition the branch at the end of 'B' depends on and whose value 1466 // has been evaluated within 'B'. 1467 // In most cases, the terminator condition of 'B' will be evaluated fully in 1468 // the last statement of 'B'; in those cases, the resolved condition is the 1469 // given 'Condition'. 1470 // If the condition of the branch is a logical binary operator tree, the CFG is 1471 // optimized: in that case, we know that the expression formed by all but the 1472 // rightmost leaf of the logical binary operator tree must be true, and thus 1473 // the branch condition is at this point equivalent to the truth value of that 1474 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf 1475 // expression in its final statement. As the full condition in that case was 1476 // not evaluated, and is thus not in the SVal cache, we need to use that leaf 1477 // expression to evaluate the truth value of the condition in the current state 1478 // space. 1479 static const Stmt *ResolveCondition(const Stmt *Condition, 1480 const CFGBlock *B) { 1481 if (const Expr *Ex = dyn_cast<Expr>(Condition)) 1482 Condition = Ex->IgnoreParens(); 1483 1484 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition); 1485 if (!BO || !BO->isLogicalOp()) 1486 return Condition; 1487 1488 assert(!B->getTerminator().isTemporaryDtorsBranch() && 1489 "Temporary destructor branches handled by processBindTemporary."); 1490 1491 // For logical operations, we still have the case where some branches 1492 // use the traditional "merge" approach and others sink the branch 1493 // directly into the basic blocks representing the logical operation. 1494 // We need to distinguish between those two cases here. 1495 1496 // The invariants are still shifting, but it is possible that the 1497 // last element in a CFGBlock is not a CFGStmt. Look for the last 1498 // CFGStmt as the value of the condition. 1499 CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend(); 1500 for (; I != E; ++I) { 1501 CFGElement Elem = *I; 1502 Optional<CFGStmt> CS = Elem.getAs<CFGStmt>(); 1503 if (!CS) 1504 continue; 1505 const Stmt *LastStmt = CS->getStmt(); 1506 assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition)); 1507 return LastStmt; 1508 } 1509 llvm_unreachable("could not resolve condition"); 1510 } 1511 1512 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term, 1513 NodeBuilderContext& BldCtx, 1514 ExplodedNode *Pred, 1515 ExplodedNodeSet &Dst, 1516 const CFGBlock *DstT, 1517 const CFGBlock *DstF) { 1518 assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) && 1519 "CXXBindTemporaryExprs are handled by processBindTemporary."); 1520 const LocationContext *LCtx = Pred->getLocationContext(); 1521 PrettyStackTraceLocationContext StackCrashInfo(LCtx); 1522 currBldrCtx = &BldCtx; 1523 1524 // Check for NULL conditions; e.g. "for(;;)" 1525 if (!Condition) { 1526 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF); 1527 NullCondBldr.markInfeasible(false); 1528 NullCondBldr.generateNode(Pred->getState(), true, Pred); 1529 return; 1530 } 1531 1532 1533 if (const Expr *Ex = dyn_cast<Expr>(Condition)) 1534 Condition = Ex->IgnoreParens(); 1535 1536 Condition = ResolveCondition(Condition, BldCtx.getBlock()); 1537 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 1538 Condition->getLocStart(), 1539 "Error evaluating branch"); 1540 1541 ExplodedNodeSet CheckersOutSet; 1542 getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet, 1543 Pred, *this); 1544 // We generated only sinks. 1545 if (CheckersOutSet.empty()) 1546 return; 1547 1548 BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF); 1549 for (NodeBuilder::iterator I = CheckersOutSet.begin(), 1550 E = CheckersOutSet.end(); E != I; ++I) { 1551 ExplodedNode *PredI = *I; 1552 1553 if (PredI->isSink()) 1554 continue; 1555 1556 ProgramStateRef PrevState = PredI->getState(); 1557 SVal X = PrevState->getSVal(Condition, PredI->getLocationContext()); 1558 1559 if (X.isUnknownOrUndef()) { 1560 // Give it a chance to recover from unknown. 1561 if (const Expr *Ex = dyn_cast<Expr>(Condition)) { 1562 if (Ex->getType()->isIntegralOrEnumerationType()) { 1563 // Try to recover some path-sensitivity. Right now casts of symbolic 1564 // integers that promote their values are currently not tracked well. 1565 // If 'Condition' is such an expression, try and recover the 1566 // underlying value and use that instead. 1567 SVal recovered = RecoverCastedSymbol(getStateManager(), 1568 PrevState, Condition, 1569 PredI->getLocationContext(), 1570 getContext()); 1571 1572 if (!recovered.isUnknown()) { 1573 X = recovered; 1574 } 1575 } 1576 } 1577 } 1578 1579 // If the condition is still unknown, give up. 1580 if (X.isUnknownOrUndef()) { 1581 builder.generateNode(PrevState, true, PredI); 1582 builder.generateNode(PrevState, false, PredI); 1583 continue; 1584 } 1585 1586 DefinedSVal V = X.castAs<DefinedSVal>(); 1587 1588 ProgramStateRef StTrue, StFalse; 1589 std::tie(StTrue, StFalse) = PrevState->assume(V); 1590 1591 // Process the true branch. 1592 if (builder.isFeasible(true)) { 1593 if (StTrue) 1594 builder.generateNode(StTrue, true, PredI); 1595 else 1596 builder.markInfeasible(true); 1597 } 1598 1599 // Process the false branch. 1600 if (builder.isFeasible(false)) { 1601 if (StFalse) 1602 builder.generateNode(StFalse, false, PredI); 1603 else 1604 builder.markInfeasible(false); 1605 } 1606 } 1607 currBldrCtx = nullptr; 1608 } 1609 1610 /// The GDM component containing the set of global variables which have been 1611 /// previously initialized with explicit initializers. 1612 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet, 1613 llvm::ImmutableSet<const VarDecl *>) 1614 1615 void ExprEngine::processStaticInitializer(const DeclStmt *DS, 1616 NodeBuilderContext &BuilderCtx, 1617 ExplodedNode *Pred, 1618 clang::ento::ExplodedNodeSet &Dst, 1619 const CFGBlock *DstT, 1620 const CFGBlock *DstF) { 1621 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 1622 currBldrCtx = &BuilderCtx; 1623 1624 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl()); 1625 ProgramStateRef state = Pred->getState(); 1626 bool initHasRun = state->contains<InitializedGlobalsSet>(VD); 1627 BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF); 1628 1629 if (!initHasRun) { 1630 state = state->add<InitializedGlobalsSet>(VD); 1631 } 1632 1633 builder.generateNode(state, initHasRun, Pred); 1634 builder.markInfeasible(!initHasRun); 1635 1636 currBldrCtx = nullptr; 1637 } 1638 1639 /// processIndirectGoto - Called by CoreEngine. Used to generate successor 1640 /// nodes by processing the 'effects' of a computed goto jump. 1641 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) { 1642 1643 ProgramStateRef state = builder.getState(); 1644 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext()); 1645 1646 // Three possibilities: 1647 // 1648 // (1) We know the computed label. 1649 // (2) The label is NULL (or some other constant), or Undefined. 1650 // (3) We have no clue about the label. Dispatch to all targets. 1651 // 1652 1653 typedef IndirectGotoNodeBuilder::iterator iterator; 1654 1655 if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) { 1656 const LabelDecl *L = LV->getLabel(); 1657 1658 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) { 1659 if (I.getLabel() == L) { 1660 builder.generateNode(I, state); 1661 return; 1662 } 1663 } 1664 1665 llvm_unreachable("No block with label."); 1666 } 1667 1668 if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) { 1669 // Dispatch to the first target and mark it as a sink. 1670 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true); 1671 // FIXME: add checker visit. 1672 // UndefBranches.insert(N); 1673 return; 1674 } 1675 1676 // This is really a catch-all. We don't support symbolics yet. 1677 // FIXME: Implement dispatch for symbolic pointers. 1678 1679 for (iterator I=builder.begin(), E=builder.end(); I != E; ++I) 1680 builder.generateNode(I, state); 1681 } 1682 1683 #if 0 1684 static bool stackFrameDoesNotContainInitializedTemporaries(ExplodedNode &Pred) { 1685 const StackFrameContext* Frame = Pred.getStackFrame(); 1686 const llvm::ImmutableSet<CXXBindTemporaryContext> &Set = 1687 Pred.getState()->get<InitializedTemporariesSet>(); 1688 return std::find_if(Set.begin(), Set.end(), 1689 [&](const CXXBindTemporaryContext &Ctx) { 1690 if (Ctx.second == Frame) { 1691 Ctx.first->dump(); 1692 llvm::errs() << "\n"; 1693 } 1694 return Ctx.second == Frame; 1695 }) == Set.end(); 1696 } 1697 #endif 1698 1699 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path 1700 /// nodes when the control reaches the end of a function. 1701 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC, 1702 ExplodedNode *Pred) { 1703 // FIXME: Assert that stackFrameDoesNotContainInitializedTemporaries(*Pred)). 1704 // We currently cannot enable this assert, as lifetime extended temporaries 1705 // are not modelled correctly. 1706 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext()); 1707 StateMgr.EndPath(Pred->getState()); 1708 1709 ExplodedNodeSet Dst; 1710 if (Pred->getLocationContext()->inTopFrame()) { 1711 // Remove dead symbols. 1712 ExplodedNodeSet AfterRemovedDead; 1713 removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead); 1714 1715 // Notify checkers. 1716 for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(), 1717 E = AfterRemovedDead.end(); I != E; ++I) { 1718 getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this); 1719 } 1720 } else { 1721 getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this); 1722 } 1723 1724 Engine.enqueueEndOfFunction(Dst); 1725 } 1726 1727 /// ProcessSwitch - Called by CoreEngine. Used to generate successor 1728 /// nodes by processing the 'effects' of a switch statement. 1729 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) { 1730 typedef SwitchNodeBuilder::iterator iterator; 1731 ProgramStateRef state = builder.getState(); 1732 const Expr *CondE = builder.getCondition(); 1733 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext()); 1734 1735 if (CondV_untested.isUndef()) { 1736 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true); 1737 // FIXME: add checker 1738 //UndefBranches.insert(N); 1739 1740 return; 1741 } 1742 DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>(); 1743 1744 ProgramStateRef DefaultSt = state; 1745 1746 iterator I = builder.begin(), EI = builder.end(); 1747 bool defaultIsFeasible = I == EI; 1748 1749 for ( ; I != EI; ++I) { 1750 // Successor may be pruned out during CFG construction. 1751 if (!I.getBlock()) 1752 continue; 1753 1754 const CaseStmt *Case = I.getCase(); 1755 1756 // Evaluate the LHS of the case value. 1757 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext()); 1758 assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType())); 1759 1760 // Get the RHS of the case, if it exists. 1761 llvm::APSInt V2; 1762 if (const Expr *E = Case->getRHS()) 1763 V2 = E->EvaluateKnownConstInt(getContext()); 1764 else 1765 V2 = V1; 1766 1767 // FIXME: Eventually we should replace the logic below with a range 1768 // comparison, rather than concretize the values within the range. 1769 // This should be easy once we have "ranges" for NonLVals. 1770 1771 do { 1772 nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1)); 1773 DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state, 1774 CondV, CaseVal); 1775 1776 // Now "assume" that the case matches. 1777 if (ProgramStateRef stateNew = state->assume(Res, true)) { 1778 builder.generateCaseStmtNode(I, stateNew); 1779 1780 // If CondV evaluates to a constant, then we know that this 1781 // is the *only* case that we can take, so stop evaluating the 1782 // others. 1783 if (CondV.getAs<nonloc::ConcreteInt>()) 1784 return; 1785 } 1786 1787 // Now "assume" that the case doesn't match. Add this state 1788 // to the default state (if it is feasible). 1789 if (DefaultSt) { 1790 if (ProgramStateRef stateNew = DefaultSt->assume(Res, false)) { 1791 defaultIsFeasible = true; 1792 DefaultSt = stateNew; 1793 } 1794 else { 1795 defaultIsFeasible = false; 1796 DefaultSt = nullptr; 1797 } 1798 } 1799 1800 // Concretize the next value in the range. 1801 if (V1 == V2) 1802 break; 1803 1804 ++V1; 1805 assert (V1 <= V2); 1806 1807 } while (true); 1808 } 1809 1810 if (!defaultIsFeasible) 1811 return; 1812 1813 // If we have switch(enum value), the default branch is not 1814 // feasible if all of the enum constants not covered by 'case:' statements 1815 // are not feasible values for the switch condition. 1816 // 1817 // Note that this isn't as accurate as it could be. Even if there isn't 1818 // a case for a particular enum value as long as that enum value isn't 1819 // feasible then it shouldn't be considered for making 'default:' reachable. 1820 const SwitchStmt *SS = builder.getSwitch(); 1821 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts(); 1822 if (CondExpr->getType()->getAs<EnumType>()) { 1823 if (SS->isAllEnumCasesCovered()) 1824 return; 1825 } 1826 1827 builder.generateDefaultCaseNode(DefaultSt); 1828 } 1829 1830 //===----------------------------------------------------------------------===// 1831 // Transfer functions: Loads and stores. 1832 //===----------------------------------------------------------------------===// 1833 1834 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D, 1835 ExplodedNode *Pred, 1836 ExplodedNodeSet &Dst) { 1837 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1838 1839 ProgramStateRef state = Pred->getState(); 1840 const LocationContext *LCtx = Pred->getLocationContext(); 1841 1842 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1843 // C permits "extern void v", and if you cast the address to a valid type, 1844 // you can even do things with it. We simply pretend 1845 assert(Ex->isGLValue() || VD->getType()->isVoidType()); 1846 SVal V = state->getLValue(VD, Pred->getLocationContext()); 1847 1848 // For references, the 'lvalue' is the pointer address stored in the 1849 // reference region. 1850 if (VD->getType()->isReferenceType()) { 1851 if (const MemRegion *R = V.getAsRegion()) 1852 V = state->getSVal(R); 1853 else 1854 V = UnknownVal(); 1855 } 1856 1857 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr, 1858 ProgramPoint::PostLValueKind); 1859 return; 1860 } 1861 if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 1862 assert(!Ex->isGLValue()); 1863 SVal V = svalBuilder.makeIntVal(ED->getInitVal()); 1864 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V)); 1865 return; 1866 } 1867 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1868 SVal V = svalBuilder.getFunctionPointer(FD); 1869 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr, 1870 ProgramPoint::PostLValueKind); 1871 return; 1872 } 1873 if (isa<FieldDecl>(D)) { 1874 // FIXME: Compute lvalue of field pointers-to-member. 1875 // Right now we just use a non-null void pointer, so that it gives proper 1876 // results in boolean contexts. 1877 SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy, 1878 currBldrCtx->blockCount()); 1879 state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true); 1880 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr, 1881 ProgramPoint::PostLValueKind); 1882 return; 1883 } 1884 1885 llvm_unreachable("Support for this Decl not implemented."); 1886 } 1887 1888 /// VisitArraySubscriptExpr - Transfer function for array accesses 1889 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A, 1890 ExplodedNode *Pred, 1891 ExplodedNodeSet &Dst){ 1892 1893 const Expr *Base = A->getBase()->IgnoreParens(); 1894 const Expr *Idx = A->getIdx()->IgnoreParens(); 1895 1896 1897 ExplodedNodeSet checkerPreStmt; 1898 getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this); 1899 1900 StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currBldrCtx); 1901 1902 for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(), 1903 ei = checkerPreStmt.end(); it != ei; ++it) { 1904 const LocationContext *LCtx = (*it)->getLocationContext(); 1905 ProgramStateRef state = (*it)->getState(); 1906 SVal V = state->getLValue(A->getType(), 1907 state->getSVal(Idx, LCtx), 1908 state->getSVal(Base, LCtx)); 1909 assert(A->isGLValue()); 1910 Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V), nullptr, 1911 ProgramPoint::PostLValueKind); 1912 } 1913 } 1914 1915 /// VisitMemberExpr - Transfer function for member expressions. 1916 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, 1917 ExplodedNodeSet &Dst) { 1918 1919 // FIXME: Prechecks eventually go in ::Visit(). 1920 ExplodedNodeSet CheckedSet; 1921 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this); 1922 1923 ExplodedNodeSet EvalSet; 1924 ValueDecl *Member = M->getMemberDecl(); 1925 1926 // Handle static member variables and enum constants accessed via 1927 // member syntax. 1928 if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) { 1929 ExplodedNodeSet Dst; 1930 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 1931 I != E; ++I) { 1932 VisitCommonDeclRefExpr(M, Member, Pred, EvalSet); 1933 } 1934 } else { 1935 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx); 1936 ExplodedNodeSet Tmp; 1937 1938 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 1939 I != E; ++I) { 1940 ProgramStateRef state = (*I)->getState(); 1941 const LocationContext *LCtx = (*I)->getLocationContext(); 1942 Expr *BaseExpr = M->getBase(); 1943 1944 // Handle C++ method calls. 1945 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) { 1946 if (MD->isInstance()) 1947 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr); 1948 1949 SVal MDVal = svalBuilder.getFunctionPointer(MD); 1950 state = state->BindExpr(M, LCtx, MDVal); 1951 1952 Bldr.generateNode(M, *I, state); 1953 continue; 1954 } 1955 1956 // Handle regular struct fields / member variables. 1957 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr); 1958 SVal baseExprVal = state->getSVal(BaseExpr, LCtx); 1959 1960 FieldDecl *field = cast<FieldDecl>(Member); 1961 SVal L = state->getLValue(field, baseExprVal); 1962 1963 if (M->isGLValue() || M->getType()->isArrayType()) { 1964 // We special-case rvalues of array type because the analyzer cannot 1965 // reason about them, since we expect all regions to be wrapped in Locs. 1966 // We instead treat these as lvalues and assume that they will decay to 1967 // pointers as soon as they are used. 1968 if (!M->isGLValue()) { 1969 assert(M->getType()->isArrayType()); 1970 const ImplicitCastExpr *PE = 1971 dyn_cast<ImplicitCastExpr>((*I)->getParentMap().getParent(M)); 1972 if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) { 1973 llvm_unreachable("should always be wrapped in ArrayToPointerDecay"); 1974 } 1975 } 1976 1977 if (field->getType()->isReferenceType()) { 1978 if (const MemRegion *R = L.getAsRegion()) 1979 L = state->getSVal(R); 1980 else 1981 L = UnknownVal(); 1982 } 1983 1984 Bldr.generateNode(M, *I, state->BindExpr(M, LCtx, L), nullptr, 1985 ProgramPoint::PostLValueKind); 1986 } else { 1987 Bldr.takeNodes(*I); 1988 evalLoad(Tmp, M, M, *I, state, L); 1989 Bldr.addNodes(Tmp); 1990 } 1991 } 1992 } 1993 1994 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this); 1995 } 1996 1997 namespace { 1998 class CollectReachableSymbolsCallback : public SymbolVisitor { 1999 InvalidatedSymbols Symbols; 2000 public: 2001 CollectReachableSymbolsCallback(ProgramStateRef State) {} 2002 const InvalidatedSymbols &getSymbols() const { return Symbols; } 2003 2004 bool VisitSymbol(SymbolRef Sym) override { 2005 Symbols.insert(Sym); 2006 return true; 2007 } 2008 }; 2009 } // end anonymous namespace 2010 2011 // A value escapes in three possible cases: 2012 // (1) We are binding to something that is not a memory region. 2013 // (2) We are binding to a MemrRegion that does not have stack storage. 2014 // (3) We are binding to a MemRegion with stack storage that the store 2015 // does not understand. 2016 ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State, 2017 SVal Loc, SVal Val) { 2018 // Are we storing to something that causes the value to "escape"? 2019 bool escapes = true; 2020 2021 // TODO: Move to StoreManager. 2022 if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) { 2023 escapes = !regionLoc->getRegion()->hasStackStorage(); 2024 2025 if (!escapes) { 2026 // To test (3), generate a new state with the binding added. If it is 2027 // the same state, then it escapes (since the store cannot represent 2028 // the binding). 2029 // Do this only if we know that the store is not supposed to generate the 2030 // same state. 2031 SVal StoredVal = State->getSVal(regionLoc->getRegion()); 2032 if (StoredVal != Val) 2033 escapes = (State == (State->bindLoc(*regionLoc, Val))); 2034 } 2035 } 2036 2037 // If our store can represent the binding and we aren't storing to something 2038 // that doesn't have local storage then just return and have the simulation 2039 // state continue as is. 2040 if (!escapes) 2041 return State; 2042 2043 // Otherwise, find all symbols referenced by 'val' that we are tracking 2044 // and stop tracking them. 2045 CollectReachableSymbolsCallback Scanner = 2046 State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val); 2047 const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols(); 2048 State = getCheckerManager().runCheckersForPointerEscape(State, 2049 EscapedSymbols, 2050 /*CallEvent*/ nullptr, 2051 PSK_EscapeOnBind, 2052 nullptr); 2053 2054 return State; 2055 } 2056 2057 ProgramStateRef 2058 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State, 2059 const InvalidatedSymbols *Invalidated, 2060 ArrayRef<const MemRegion *> ExplicitRegions, 2061 ArrayRef<const MemRegion *> Regions, 2062 const CallEvent *Call, 2063 RegionAndSymbolInvalidationTraits &ITraits) { 2064 2065 if (!Invalidated || Invalidated->empty()) 2066 return State; 2067 2068 if (!Call) 2069 return getCheckerManager().runCheckersForPointerEscape(State, 2070 *Invalidated, 2071 nullptr, 2072 PSK_EscapeOther, 2073 &ITraits); 2074 2075 // If the symbols were invalidated by a call, we want to find out which ones 2076 // were invalidated directly due to being arguments to the call. 2077 InvalidatedSymbols SymbolsDirectlyInvalidated; 2078 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(), 2079 E = ExplicitRegions.end(); I != E; ++I) { 2080 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>()) 2081 SymbolsDirectlyInvalidated.insert(R->getSymbol()); 2082 } 2083 2084 InvalidatedSymbols SymbolsIndirectlyInvalidated; 2085 for (InvalidatedSymbols::const_iterator I=Invalidated->begin(), 2086 E = Invalidated->end(); I!=E; ++I) { 2087 SymbolRef sym = *I; 2088 if (SymbolsDirectlyInvalidated.count(sym)) 2089 continue; 2090 SymbolsIndirectlyInvalidated.insert(sym); 2091 } 2092 2093 if (!SymbolsDirectlyInvalidated.empty()) 2094 State = getCheckerManager().runCheckersForPointerEscape(State, 2095 SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits); 2096 2097 // Notify about the symbols that get indirectly invalidated by the call. 2098 if (!SymbolsIndirectlyInvalidated.empty()) 2099 State = getCheckerManager().runCheckersForPointerEscape(State, 2100 SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits); 2101 2102 return State; 2103 } 2104 2105 /// evalBind - Handle the semantics of binding a value to a specific location. 2106 /// This method is used by evalStore and (soon) VisitDeclStmt, and others. 2107 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, 2108 ExplodedNode *Pred, 2109 SVal location, SVal Val, 2110 bool atDeclInit, const ProgramPoint *PP) { 2111 2112 const LocationContext *LC = Pred->getLocationContext(); 2113 PostStmt PS(StoreE, LC); 2114 if (!PP) 2115 PP = &PS; 2116 2117 // Do a previsit of the bind. 2118 ExplodedNodeSet CheckedSet; 2119 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val, 2120 StoreE, *this, *PP); 2121 2122 2123 StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx); 2124 2125 // If the location is not a 'Loc', it will already be handled by 2126 // the checkers. There is nothing left to do. 2127 if (!location.getAs<Loc>()) { 2128 const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr, 2129 /*tag*/nullptr); 2130 ProgramStateRef state = Pred->getState(); 2131 state = processPointerEscapedOnBind(state, location, Val); 2132 Bldr.generateNode(L, state, Pred); 2133 return; 2134 } 2135 2136 2137 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 2138 I!=E; ++I) { 2139 ExplodedNode *PredI = *I; 2140 ProgramStateRef state = PredI->getState(); 2141 2142 state = processPointerEscapedOnBind(state, location, Val); 2143 2144 // When binding the value, pass on the hint that this is a initialization. 2145 // For initializations, we do not need to inform clients of region 2146 // changes. 2147 state = state->bindLoc(location.castAs<Loc>(), 2148 Val, /* notifyChanges = */ !atDeclInit); 2149 2150 const MemRegion *LocReg = nullptr; 2151 if (Optional<loc::MemRegionVal> LocRegVal = 2152 location.getAs<loc::MemRegionVal>()) { 2153 LocReg = LocRegVal->getRegion(); 2154 } 2155 2156 const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr); 2157 Bldr.generateNode(L, state, PredI); 2158 } 2159 } 2160 2161 /// evalStore - Handle the semantics of a store via an assignment. 2162 /// @param Dst The node set to store generated state nodes 2163 /// @param AssignE The assignment expression if the store happens in an 2164 /// assignment. 2165 /// @param LocationE The location expression that is stored to. 2166 /// @param state The current simulation state 2167 /// @param location The location to store the value 2168 /// @param Val The value to be stored 2169 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, 2170 const Expr *LocationE, 2171 ExplodedNode *Pred, 2172 ProgramStateRef state, SVal location, SVal Val, 2173 const ProgramPointTag *tag) { 2174 // Proceed with the store. We use AssignE as the anchor for the PostStore 2175 // ProgramPoint if it is non-NULL, and LocationE otherwise. 2176 const Expr *StoreE = AssignE ? AssignE : LocationE; 2177 2178 // Evaluate the location (checks for bad dereferences). 2179 ExplodedNodeSet Tmp; 2180 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false); 2181 2182 if (Tmp.empty()) 2183 return; 2184 2185 if (location.isUndef()) 2186 return; 2187 2188 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) 2189 evalBind(Dst, StoreE, *NI, location, Val, false); 2190 } 2191 2192 void ExprEngine::evalLoad(ExplodedNodeSet &Dst, 2193 const Expr *NodeEx, 2194 const Expr *BoundEx, 2195 ExplodedNode *Pred, 2196 ProgramStateRef state, 2197 SVal location, 2198 const ProgramPointTag *tag, 2199 QualType LoadTy) 2200 { 2201 assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc."); 2202 2203 // Are we loading from a region? This actually results in two loads; one 2204 // to fetch the address of the referenced value and one to fetch the 2205 // referenced value. 2206 if (const TypedValueRegion *TR = 2207 dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) { 2208 2209 QualType ValTy = TR->getValueType(); 2210 if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) { 2211 static SimpleProgramPointTag 2212 loadReferenceTag(TagProviderName, "Load Reference"); 2213 ExplodedNodeSet Tmp; 2214 evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state, 2215 location, &loadReferenceTag, 2216 getContext().getPointerType(RT->getPointeeType())); 2217 2218 // Perform the load from the referenced value. 2219 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) { 2220 state = (*I)->getState(); 2221 location = state->getSVal(BoundEx, (*I)->getLocationContext()); 2222 evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy); 2223 } 2224 return; 2225 } 2226 } 2227 2228 evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy); 2229 } 2230 2231 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst, 2232 const Expr *NodeEx, 2233 const Expr *BoundEx, 2234 ExplodedNode *Pred, 2235 ProgramStateRef state, 2236 SVal location, 2237 const ProgramPointTag *tag, 2238 QualType LoadTy) { 2239 assert(NodeEx); 2240 assert(BoundEx); 2241 // Evaluate the location (checks for bad dereferences). 2242 ExplodedNodeSet Tmp; 2243 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true); 2244 if (Tmp.empty()) 2245 return; 2246 2247 StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx); 2248 if (location.isUndef()) 2249 return; 2250 2251 // Proceed with the load. 2252 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) { 2253 state = (*NI)->getState(); 2254 const LocationContext *LCtx = (*NI)->getLocationContext(); 2255 2256 SVal V = UnknownVal(); 2257 if (location.isValid()) { 2258 if (LoadTy.isNull()) 2259 LoadTy = BoundEx->getType(); 2260 V = state->getSVal(location.castAs<Loc>(), LoadTy); 2261 } 2262 2263 Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag, 2264 ProgramPoint::PostLoadKind); 2265 } 2266 } 2267 2268 void ExprEngine::evalLocation(ExplodedNodeSet &Dst, 2269 const Stmt *NodeEx, 2270 const Stmt *BoundEx, 2271 ExplodedNode *Pred, 2272 ProgramStateRef state, 2273 SVal location, 2274 const ProgramPointTag *tag, 2275 bool isLoad) { 2276 StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx); 2277 // Early checks for performance reason. 2278 if (location.isUnknown()) { 2279 return; 2280 } 2281 2282 ExplodedNodeSet Src; 2283 BldrTop.takeNodes(Pred); 2284 StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx); 2285 if (Pred->getState() != state) { 2286 // Associate this new state with an ExplodedNode. 2287 // FIXME: If I pass null tag, the graph is incorrect, e.g for 2288 // int *p; 2289 // p = 0; 2290 // *p = 0xDEADBEEF; 2291 // "p = 0" is not noted as "Null pointer value stored to 'p'" but 2292 // instead "int *p" is noted as 2293 // "Variable 'p' initialized to a null pointer value" 2294 2295 static SimpleProgramPointTag tag(TagProviderName, "Location"); 2296 Bldr.generateNode(NodeEx, Pred, state, &tag); 2297 } 2298 ExplodedNodeSet Tmp; 2299 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad, 2300 NodeEx, BoundEx, *this); 2301 BldrTop.addNodes(Tmp); 2302 } 2303 2304 std::pair<const ProgramPointTag *, const ProgramPointTag*> 2305 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() { 2306 static SimpleProgramPointTag 2307 eagerlyAssumeBinOpBifurcationTrue(TagProviderName, 2308 "Eagerly Assume True"), 2309 eagerlyAssumeBinOpBifurcationFalse(TagProviderName, 2310 "Eagerly Assume False"); 2311 return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue, 2312 &eagerlyAssumeBinOpBifurcationFalse); 2313 } 2314 2315 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, 2316 ExplodedNodeSet &Src, 2317 const Expr *Ex) { 2318 StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx); 2319 2320 for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) { 2321 ExplodedNode *Pred = *I; 2322 // Test if the previous node was as the same expression. This can happen 2323 // when the expression fails to evaluate to anything meaningful and 2324 // (as an optimization) we don't generate a node. 2325 ProgramPoint P = Pred->getLocation(); 2326 if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) { 2327 continue; 2328 } 2329 2330 ProgramStateRef state = Pred->getState(); 2331 SVal V = state->getSVal(Ex, Pred->getLocationContext()); 2332 Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>(); 2333 if (SEV && SEV->isExpression()) { 2334 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags = 2335 geteagerlyAssumeBinOpBifurcationTags(); 2336 2337 ProgramStateRef StateTrue, StateFalse; 2338 std::tie(StateTrue, StateFalse) = state->assume(*SEV); 2339 2340 // First assume that the condition is true. 2341 if (StateTrue) { 2342 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType()); 2343 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val); 2344 Bldr.generateNode(Ex, Pred, StateTrue, tags.first); 2345 } 2346 2347 // Next, assume that the condition is false. 2348 if (StateFalse) { 2349 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType()); 2350 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val); 2351 Bldr.generateNode(Ex, Pred, StateFalse, tags.second); 2352 } 2353 } 2354 } 2355 } 2356 2357 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, 2358 ExplodedNodeSet &Dst) { 2359 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 2360 // We have processed both the inputs and the outputs. All of the outputs 2361 // should evaluate to Locs. Nuke all of their values. 2362 2363 // FIXME: Some day in the future it would be nice to allow a "plug-in" 2364 // which interprets the inline asm and stores proper results in the 2365 // outputs. 2366 2367 ProgramStateRef state = Pred->getState(); 2368 2369 for (const Expr *O : A->outputs()) { 2370 SVal X = state->getSVal(O, Pred->getLocationContext()); 2371 assert (!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef. 2372 2373 if (Optional<Loc> LV = X.getAs<Loc>()) 2374 state = state->bindLoc(*LV, UnknownVal()); 2375 } 2376 2377 Bldr.generateNode(A, Pred, state); 2378 } 2379 2380 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred, 2381 ExplodedNodeSet &Dst) { 2382 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 2383 Bldr.generateNode(A, Pred, Pred->getState()); 2384 } 2385 2386 //===----------------------------------------------------------------------===// 2387 // Visualization. 2388 //===----------------------------------------------------------------------===// 2389 2390 #ifndef NDEBUG 2391 static ExprEngine* GraphPrintCheckerState; 2392 static SourceManager* GraphPrintSourceManager; 2393 2394 namespace llvm { 2395 template<> 2396 struct DOTGraphTraits<ExplodedNode*> : 2397 public DefaultDOTGraphTraits { 2398 2399 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 2400 2401 // FIXME: Since we do not cache error nodes in ExprEngine now, this does not 2402 // work. 2403 static std::string getNodeAttributes(const ExplodedNode *N, void*) { 2404 2405 #if 0 2406 // FIXME: Replace with a general scheme to tell if the node is 2407 // an error node. 2408 if (GraphPrintCheckerState->isImplicitNullDeref(N) || 2409 GraphPrintCheckerState->isExplicitNullDeref(N) || 2410 GraphPrintCheckerState->isUndefDeref(N) || 2411 GraphPrintCheckerState->isUndefStore(N) || 2412 GraphPrintCheckerState->isUndefControlFlow(N) || 2413 GraphPrintCheckerState->isUndefResult(N) || 2414 GraphPrintCheckerState->isBadCall(N) || 2415 GraphPrintCheckerState->isUndefArg(N)) 2416 return "color=\"red\",style=\"filled\""; 2417 2418 if (GraphPrintCheckerState->isNoReturnCall(N)) 2419 return "color=\"blue\",style=\"filled\""; 2420 #endif 2421 return ""; 2422 } 2423 2424 static void printLocation(raw_ostream &Out, SourceLocation SLoc) { 2425 if (SLoc.isFileID()) { 2426 Out << "\\lline=" 2427 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 2428 << " col=" 2429 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc) 2430 << "\\l"; 2431 } 2432 } 2433 2434 static std::string getNodeLabel(const ExplodedNode *N, void*){ 2435 2436 std::string sbuf; 2437 llvm::raw_string_ostream Out(sbuf); 2438 2439 // Program Location. 2440 ProgramPoint Loc = N->getLocation(); 2441 2442 switch (Loc.getKind()) { 2443 case ProgramPoint::BlockEntranceKind: { 2444 Out << "Block Entrance: B" 2445 << Loc.castAs<BlockEntrance>().getBlock()->getBlockID(); 2446 if (const NamedDecl *ND = 2447 dyn_cast<NamedDecl>(Loc.getLocationContext()->getDecl())) { 2448 Out << " ("; 2449 ND->printName(Out); 2450 Out << ")"; 2451 } 2452 break; 2453 } 2454 2455 case ProgramPoint::BlockExitKind: 2456 assert (false); 2457 break; 2458 2459 case ProgramPoint::CallEnterKind: 2460 Out << "CallEnter"; 2461 break; 2462 2463 case ProgramPoint::CallExitBeginKind: 2464 Out << "CallExitBegin"; 2465 break; 2466 2467 case ProgramPoint::CallExitEndKind: 2468 Out << "CallExitEnd"; 2469 break; 2470 2471 case ProgramPoint::PostStmtPurgeDeadSymbolsKind: 2472 Out << "PostStmtPurgeDeadSymbols"; 2473 break; 2474 2475 case ProgramPoint::PreStmtPurgeDeadSymbolsKind: 2476 Out << "PreStmtPurgeDeadSymbols"; 2477 break; 2478 2479 case ProgramPoint::EpsilonKind: 2480 Out << "Epsilon Point"; 2481 break; 2482 2483 case ProgramPoint::PreImplicitCallKind: { 2484 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>(); 2485 Out << "PreCall: "; 2486 2487 // FIXME: Get proper printing options. 2488 PC.getDecl()->print(Out, LangOptions()); 2489 printLocation(Out, PC.getLocation()); 2490 break; 2491 } 2492 2493 case ProgramPoint::PostImplicitCallKind: { 2494 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>(); 2495 Out << "PostCall: "; 2496 2497 // FIXME: Get proper printing options. 2498 PC.getDecl()->print(Out, LangOptions()); 2499 printLocation(Out, PC.getLocation()); 2500 break; 2501 } 2502 2503 case ProgramPoint::PostInitializerKind: { 2504 Out << "PostInitializer: "; 2505 const CXXCtorInitializer *Init = 2506 Loc.castAs<PostInitializer>().getInitializer(); 2507 if (const FieldDecl *FD = Init->getAnyMember()) 2508 Out << *FD; 2509 else { 2510 QualType Ty = Init->getTypeSourceInfo()->getType(); 2511 Ty = Ty.getLocalUnqualifiedType(); 2512 LangOptions LO; // FIXME. 2513 Ty.print(Out, LO); 2514 } 2515 break; 2516 } 2517 2518 case ProgramPoint::BlockEdgeKind: { 2519 const BlockEdge &E = Loc.castAs<BlockEdge>(); 2520 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B" 2521 << E.getDst()->getBlockID() << ')'; 2522 2523 if (const Stmt *T = E.getSrc()->getTerminator()) { 2524 SourceLocation SLoc = T->getLocStart(); 2525 2526 Out << "\\|Terminator: "; 2527 LangOptions LO; // FIXME. 2528 E.getSrc()->printTerminator(Out, LO); 2529 2530 if (SLoc.isFileID()) { 2531 Out << "\\lline=" 2532 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 2533 << " col=" 2534 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc); 2535 } 2536 2537 if (isa<SwitchStmt>(T)) { 2538 const Stmt *Label = E.getDst()->getLabel(); 2539 2540 if (Label) { 2541 if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) { 2542 Out << "\\lcase "; 2543 LangOptions LO; // FIXME. 2544 if (C->getLHS()) 2545 C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO)); 2546 2547 if (const Stmt *RHS = C->getRHS()) { 2548 Out << " .. "; 2549 RHS->printPretty(Out, nullptr, PrintingPolicy(LO)); 2550 } 2551 2552 Out << ":"; 2553 } 2554 else { 2555 assert (isa<DefaultStmt>(Label)); 2556 Out << "\\ldefault:"; 2557 } 2558 } 2559 else 2560 Out << "\\l(implicit) default:"; 2561 } 2562 else if (isa<IndirectGotoStmt>(T)) { 2563 // FIXME 2564 } 2565 else { 2566 Out << "\\lCondition: "; 2567 if (*E.getSrc()->succ_begin() == E.getDst()) 2568 Out << "true"; 2569 else 2570 Out << "false"; 2571 } 2572 2573 Out << "\\l"; 2574 } 2575 2576 #if 0 2577 // FIXME: Replace with a general scheme to determine 2578 // the name of the check. 2579 if (GraphPrintCheckerState->isUndefControlFlow(N)) { 2580 Out << "\\|Control-flow based on\\lUndefined value.\\l"; 2581 } 2582 #endif 2583 break; 2584 } 2585 2586 default: { 2587 const Stmt *S = Loc.castAs<StmtPoint>().getStmt(); 2588 assert(S != nullptr && "Expecting non-null Stmt"); 2589 2590 Out << S->getStmtClassName() << ' ' << (const void*) S << ' '; 2591 LangOptions LO; // FIXME. 2592 S->printPretty(Out, nullptr, PrintingPolicy(LO)); 2593 printLocation(Out, S->getLocStart()); 2594 2595 if (Loc.getAs<PreStmt>()) 2596 Out << "\\lPreStmt\\l;"; 2597 else if (Loc.getAs<PostLoad>()) 2598 Out << "\\lPostLoad\\l;"; 2599 else if (Loc.getAs<PostStore>()) 2600 Out << "\\lPostStore\\l"; 2601 else if (Loc.getAs<PostLValue>()) 2602 Out << "\\lPostLValue\\l"; 2603 2604 #if 0 2605 // FIXME: Replace with a general scheme to determine 2606 // the name of the check. 2607 if (GraphPrintCheckerState->isImplicitNullDeref(N)) 2608 Out << "\\|Implicit-Null Dereference.\\l"; 2609 else if (GraphPrintCheckerState->isExplicitNullDeref(N)) 2610 Out << "\\|Explicit-Null Dereference.\\l"; 2611 else if (GraphPrintCheckerState->isUndefDeref(N)) 2612 Out << "\\|Dereference of undefialied value.\\l"; 2613 else if (GraphPrintCheckerState->isUndefStore(N)) 2614 Out << "\\|Store to Undefined Loc."; 2615 else if (GraphPrintCheckerState->isUndefResult(N)) 2616 Out << "\\|Result of operation is undefined."; 2617 else if (GraphPrintCheckerState->isNoReturnCall(N)) 2618 Out << "\\|Call to function marked \"noreturn\"."; 2619 else if (GraphPrintCheckerState->isBadCall(N)) 2620 Out << "\\|Call to NULL/Undefined."; 2621 else if (GraphPrintCheckerState->isUndefArg(N)) 2622 Out << "\\|Argument in call is undefined"; 2623 #endif 2624 2625 break; 2626 } 2627 } 2628 2629 ProgramStateRef state = N->getState(); 2630 Out << "\\|StateID: " << (const void*) state.get() 2631 << " NodeID: " << (const void*) N << "\\|"; 2632 state->printDOT(Out); 2633 2634 Out << "\\l"; 2635 2636 if (const ProgramPointTag *tag = Loc.getTag()) { 2637 Out << "\\|Tag: " << tag->getTagDescription(); 2638 Out << "\\l"; 2639 } 2640 return Out.str(); 2641 } 2642 }; 2643 } // end llvm namespace 2644 #endif 2645 2646 #ifndef NDEBUG 2647 template <typename ITERATOR> 2648 ExplodedNode *GetGraphNode(ITERATOR I) { return *I; } 2649 2650 template <> ExplodedNode* 2651 GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator> 2652 (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) { 2653 return I->first; 2654 } 2655 #endif 2656 2657 void ExprEngine::ViewGraph(bool trim) { 2658 #ifndef NDEBUG 2659 if (trim) { 2660 std::vector<const ExplodedNode*> Src; 2661 2662 // Flush any outstanding reports to make sure we cover all the nodes. 2663 // This does not cause them to get displayed. 2664 for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I) 2665 const_cast<BugType*>(*I)->FlushReports(BR); 2666 2667 // Iterate through the reports and get their nodes. 2668 for (BugReporter::EQClasses_iterator 2669 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) { 2670 ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode()); 2671 if (N) Src.push_back(N); 2672 } 2673 2674 ViewGraph(Src); 2675 } 2676 else { 2677 GraphPrintCheckerState = this; 2678 GraphPrintSourceManager = &getContext().getSourceManager(); 2679 2680 llvm::ViewGraph(*G.roots_begin(), "ExprEngine"); 2681 2682 GraphPrintCheckerState = nullptr; 2683 GraphPrintSourceManager = nullptr; 2684 } 2685 #endif 2686 } 2687 2688 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) { 2689 #ifndef NDEBUG 2690 GraphPrintCheckerState = this; 2691 GraphPrintSourceManager = &getContext().getSourceManager(); 2692 2693 std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes)); 2694 2695 if (!TrimmedG.get()) 2696 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n"; 2697 else 2698 llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine"); 2699 2700 GraphPrintCheckerState = nullptr; 2701 GraphPrintSourceManager = nullptr; 2702 #endif 2703 } 2704