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