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