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