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