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