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