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