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