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