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