1 //=-- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- C++ -*-= 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines a meta-engine for path-sensitive dataflow analysis that 11 // is built on GREngine, but provides the boilerplate to execute transfer 12 // functions and build the ExplodedGraph at the expression level. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "clang/StaticAnalyzer/Core/CheckerManager.h" 17 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 18 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 19 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 20 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngineBuilders.h" 21 #include "clang/AST/CharUnits.h" 22 #include "clang/AST/ParentMap.h" 23 #include "clang/AST/StmtObjC.h" 24 #include "clang/AST/DeclCXX.h" 25 #include "clang/Basic/Builtins.h" 26 #include "clang/Basic/SourceManager.h" 27 #include "clang/Basic/SourceManager.h" 28 #include "clang/Basic/PrettyStackTrace.h" 29 #include "llvm/Support/raw_ostream.h" 30 #include "llvm/ADT/ImmutableList.h" 31 32 #ifndef NDEBUG 33 #include "llvm/Support/GraphWriter.h" 34 #endif 35 36 using namespace clang; 37 using namespace ento; 38 using llvm::APSInt; 39 40 namespace { 41 // Trait class for recording returned expression in the state. 42 struct ReturnExpr { 43 static int TagInt; 44 typedef const Stmt *data_type; 45 }; 46 int ReturnExpr::TagInt; 47 } 48 49 //===----------------------------------------------------------------------===// 50 // Utility functions. 51 //===----------------------------------------------------------------------===// 52 53 static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) { 54 IdentifierInfo* II = &Ctx.Idents.get(name); 55 return Ctx.Selectors.getSelector(0, &II); 56 } 57 58 //===----------------------------------------------------------------------===// 59 // Engine construction and deletion. 60 //===----------------------------------------------------------------------===// 61 62 ExprEngine::ExprEngine(AnalysisManager &mgr, TransferFuncs *tf) 63 : AMgr(mgr), 64 Engine(*this), 65 G(Engine.getGraph()), 66 Builder(NULL), 67 StateMgr(getContext(), mgr.getStoreManagerCreator(), 68 mgr.getConstraintManagerCreator(), G.getAllocator(), 69 *this), 70 SymMgr(StateMgr.getSymbolManager()), 71 svalBuilder(StateMgr.getSValBuilder()), 72 EntryNode(NULL), currentStmt(NULL), 73 NSExceptionII(NULL), NSExceptionInstanceRaiseSelectors(NULL), 74 RaiseSel(GetNullarySelector("raise", getContext())), 75 BR(mgr, *this), TF(tf) { 76 77 // FIXME: Eventually remove the TF object entirely. 78 TF->RegisterChecks(*this); 79 TF->RegisterPrinters(getStateManager().Printers); 80 81 if (mgr.shouldEagerlyTrimExplodedGraph()) { 82 // Enable eager node reclaimation when constructing the ExplodedGraph. 83 G.enableNodeReclamation(); 84 } 85 } 86 87 ExprEngine::~ExprEngine() { 88 BR.FlushReports(); 89 delete [] NSExceptionInstanceRaiseSelectors; 90 } 91 92 //===----------------------------------------------------------------------===// 93 // Utility methods. 94 //===----------------------------------------------------------------------===// 95 96 const GRState* ExprEngine::getInitialState(const LocationContext *InitLoc) { 97 const GRState *state = StateMgr.getInitialState(InitLoc); 98 99 // Preconditions. 100 101 // FIXME: It would be nice if we had a more general mechanism to add 102 // such preconditions. Some day. 103 do { 104 const Decl *D = InitLoc->getDecl(); 105 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 106 // Precondition: the first argument of 'main' is an integer guaranteed 107 // to be > 0. 108 const IdentifierInfo *II = FD->getIdentifier(); 109 if (!II || !(II->getName() == "main" && FD->getNumParams() > 0)) 110 break; 111 112 const ParmVarDecl *PD = FD->getParamDecl(0); 113 QualType T = PD->getType(); 114 if (!T->isIntegerType()) 115 break; 116 117 const MemRegion *R = state->getRegion(PD, InitLoc); 118 if (!R) 119 break; 120 121 SVal V = state->getSVal(loc::MemRegionVal(R)); 122 SVal Constraint_untested = evalBinOp(state, BO_GT, V, 123 svalBuilder.makeZeroVal(T), 124 getContext().IntTy); 125 126 DefinedOrUnknownSVal *Constraint = 127 dyn_cast<DefinedOrUnknownSVal>(&Constraint_untested); 128 129 if (!Constraint) 130 break; 131 132 if (const GRState *newState = state->assume(*Constraint, true)) 133 state = newState; 134 135 break; 136 } 137 138 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 139 // Precondition: 'self' is always non-null upon entry to an Objective-C 140 // method. 141 const ImplicitParamDecl *SelfD = MD->getSelfDecl(); 142 const MemRegion *R = state->getRegion(SelfD, InitLoc); 143 SVal V = state->getSVal(loc::MemRegionVal(R)); 144 145 if (const Loc *LV = dyn_cast<Loc>(&V)) { 146 // Assume that the pointer value in 'self' is non-null. 147 state = state->assume(*LV, true); 148 assert(state && "'self' cannot be null"); 149 } 150 } 151 } while (0); 152 153 return state; 154 } 155 156 bool 157 ExprEngine::doesInvalidateGlobals(const CallOrObjCMessage &callOrMessage) const 158 { 159 if (callOrMessage.isFunctionCall() && !callOrMessage.isCXXCall()) { 160 SVal calleeV = callOrMessage.getFunctionCallee(); 161 if (const FunctionTextRegion *codeR = 162 dyn_cast_or_null<FunctionTextRegion>(calleeV.getAsRegion())) { 163 164 const FunctionDecl *fd = codeR->getDecl(); 165 if (const IdentifierInfo *ii = fd->getIdentifier()) { 166 StringRef fname = ii->getName(); 167 if (fname == "strlen") 168 return false; 169 } 170 } 171 } 172 173 // The conservative answer: invalidates globals. 174 return true; 175 } 176 177 //===----------------------------------------------------------------------===// 178 // Top-level transfer function logic (Dispatcher). 179 //===----------------------------------------------------------------------===// 180 181 /// evalAssume - Called by ConstraintManager. Used to call checker-specific 182 /// logic for handling assumptions on symbolic values. 183 const GRState *ExprEngine::processAssume(const GRState *state, SVal cond, 184 bool assumption) { 185 state = getCheckerManager().runCheckersForEvalAssume(state, cond, assumption); 186 187 // If the state is infeasible at this point, bail out. 188 if (!state) 189 return NULL; 190 191 return TF->evalAssume(state, cond, assumption); 192 } 193 194 bool ExprEngine::wantsRegionChangeUpdate(const GRState* state) { 195 return getCheckerManager().wantsRegionChangeUpdate(state); 196 } 197 198 const GRState * 199 ExprEngine::processRegionChanges(const GRState *state, 200 const StoreManager::InvalidatedSymbols *invalidated, 201 const MemRegion * const *Begin, 202 const MemRegion * const *End) { 203 return getCheckerManager().runCheckersForRegionChanges(state, invalidated, 204 Begin, End); 205 } 206 207 void ExprEngine::processEndWorklist(bool hasWorkRemaining) { 208 getCheckerManager().runCheckersForEndAnalysis(G, BR, *this); 209 } 210 211 void ExprEngine::processCFGElement(const CFGElement E, 212 StmtNodeBuilder& builder) { 213 switch (E.getKind()) { 214 case CFGElement::Invalid: 215 llvm_unreachable("Unexpected CFGElement kind."); 216 case CFGElement::Statement: 217 ProcessStmt(E.getAs<CFGStmt>()->getStmt(), builder); 218 return; 219 case CFGElement::Initializer: 220 ProcessInitializer(E.getAs<CFGInitializer>()->getInitializer(), builder); 221 return; 222 case CFGElement::AutomaticObjectDtor: 223 case CFGElement::BaseDtor: 224 case CFGElement::MemberDtor: 225 case CFGElement::TemporaryDtor: 226 ProcessImplicitDtor(*E.getAs<CFGImplicitDtor>(), builder); 227 return; 228 } 229 } 230 231 void ExprEngine::ProcessStmt(const CFGStmt S, StmtNodeBuilder& builder) { 232 // Reclaim any unnecessary nodes in the ExplodedGraph. 233 G.reclaimRecentlyAllocatedNodes(); 234 // Recycle any unused states in the GRStateManager. 235 StateMgr.recycleUnusedStates(); 236 237 currentStmt = S.getStmt(); 238 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 239 currentStmt->getLocStart(), 240 "Error evaluating statement"); 241 242 Builder = &builder; 243 EntryNode = builder.getPredecessor(); 244 245 // Create the cleaned state. 246 const LocationContext *LC = EntryNode->getLocationContext(); 247 SymbolReaper SymReaper(LC, currentStmt, SymMgr, getStoreManager()); 248 249 if (AMgr.shouldPurgeDead()) { 250 const GRState *St = EntryNode->getState(); 251 getCheckerManager().runCheckersForLiveSymbols(St, SymReaper); 252 253 const StackFrameContext *SFC = LC->getCurrentStackFrame(); 254 CleanedState = StateMgr.removeDeadBindings(St, SFC, SymReaper); 255 } else { 256 CleanedState = EntryNode->getState(); 257 } 258 259 // Process any special transfer function for dead symbols. 260 ExplodedNodeSet Tmp; 261 262 if (!SymReaper.hasDeadSymbols()) 263 Tmp.Add(EntryNode); 264 else { 265 SaveAndRestore<bool> OldSink(Builder->BuildSinks); 266 SaveOr OldHasGen(Builder->hasGeneratedNode); 267 268 SaveAndRestore<bool> OldPurgeDeadSymbols(Builder->PurgingDeadSymbols); 269 Builder->PurgingDeadSymbols = true; 270 271 // FIXME: This should soon be removed. 272 ExplodedNodeSet Tmp2; 273 getTF().evalDeadSymbols(Tmp2, *this, *Builder, EntryNode, 274 CleanedState, SymReaper); 275 276 getCheckerManager().runCheckersForDeadSymbols(Tmp, Tmp2, 277 SymReaper, currentStmt, *this); 278 279 if (!Builder->BuildSinks && !Builder->hasGeneratedNode) 280 Tmp.Add(EntryNode); 281 } 282 283 bool HasAutoGenerated = false; 284 285 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { 286 ExplodedNodeSet Dst; 287 288 // Set the cleaned state. 289 Builder->SetCleanedState(*I == EntryNode ? CleanedState : GetState(*I)); 290 291 // Visit the statement. 292 Visit(currentStmt, *I, Dst); 293 294 // Do we need to auto-generate a node? We only need to do this to generate 295 // a node with a "cleaned" state; CoreEngine will actually handle 296 // auto-transitions for other cases. 297 if (Dst.size() == 1 && *Dst.begin() == EntryNode 298 && !Builder->hasGeneratedNode && !HasAutoGenerated) { 299 HasAutoGenerated = true; 300 builder.generateNode(currentStmt, GetState(EntryNode), *I); 301 } 302 } 303 304 // NULL out these variables to cleanup. 305 CleanedState = NULL; 306 EntryNode = NULL; 307 308 currentStmt = 0; 309 310 Builder = NULL; 311 } 312 313 void ExprEngine::ProcessInitializer(const CFGInitializer Init, 314 StmtNodeBuilder &builder) { 315 // We don't set EntryNode and currentStmt. And we don't clean up state. 316 const CXXCtorInitializer *BMI = Init.getInitializer(); 317 318 ExplodedNode *pred = builder.getPredecessor(); 319 320 const StackFrameContext *stackFrame = cast<StackFrameContext>(pred->getLocationContext()); 321 const CXXConstructorDecl *decl = cast<CXXConstructorDecl>(stackFrame->getDecl()); 322 const CXXThisRegion *thisReg = getCXXThisRegion(decl, stackFrame); 323 324 SVal thisVal = pred->getState()->getSVal(thisReg); 325 326 if (BMI->isAnyMemberInitializer()) { 327 ExplodedNodeSet Dst; 328 329 // Evaluate the initializer. 330 Visit(BMI->getInit(), pred, Dst); 331 332 for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end(); I != E; ++I){ 333 ExplodedNode *Pred = *I; 334 const GRState *state = Pred->getState(); 335 336 const FieldDecl *FD = BMI->getAnyMember(); 337 338 SVal FieldLoc = state->getLValue(FD, thisVal); 339 SVal InitVal = state->getSVal(BMI->getInit()); 340 state = state->bindLoc(FieldLoc, InitVal); 341 342 // Use a custom node building process. 343 PostInitializer PP(BMI, stackFrame); 344 // Builder automatically add the generated node to the deferred set, 345 // which are processed in the builder's dtor. 346 builder.generateNode(PP, state, Pred); 347 } 348 return; 349 } 350 351 assert(BMI->isBaseInitializer()); 352 353 // Get the base class declaration. 354 const CXXConstructExpr *ctorExpr = cast<CXXConstructExpr>(BMI->getInit()); 355 356 // Create the base object region. 357 SVal baseVal = 358 getStoreManager().evalDerivedToBase(thisVal, ctorExpr->getType()); 359 const MemRegion *baseReg = baseVal.getAsRegion(); 360 assert(baseReg); 361 Builder = &builder; 362 ExplodedNodeSet dst; 363 VisitCXXConstructExpr(ctorExpr, baseReg, pred, dst); 364 } 365 366 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D, 367 StmtNodeBuilder &builder) { 368 Builder = &builder; 369 370 switch (D.getKind()) { 371 case CFGElement::AutomaticObjectDtor: 372 ProcessAutomaticObjDtor(cast<CFGAutomaticObjDtor>(D), builder); 373 break; 374 case CFGElement::BaseDtor: 375 ProcessBaseDtor(cast<CFGBaseDtor>(D), builder); 376 break; 377 case CFGElement::MemberDtor: 378 ProcessMemberDtor(cast<CFGMemberDtor>(D), builder); 379 break; 380 case CFGElement::TemporaryDtor: 381 ProcessTemporaryDtor(cast<CFGTemporaryDtor>(D), builder); 382 break; 383 default: 384 llvm_unreachable("Unexpected dtor kind."); 385 } 386 } 387 388 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor dtor, 389 StmtNodeBuilder &builder) { 390 ExplodedNode *pred = builder.getPredecessor(); 391 const GRState *state = pred->getState(); 392 const VarDecl *varDecl = dtor.getVarDecl(); 393 394 QualType varType = varDecl->getType(); 395 396 if (const ReferenceType *refType = varType->getAs<ReferenceType>()) 397 varType = refType->getPointeeType(); 398 399 const CXXRecordDecl *recordDecl = varType->getAsCXXRecordDecl(); 400 assert(recordDecl && "get CXXRecordDecl fail"); 401 const CXXDestructorDecl *dtorDecl = recordDecl->getDestructor(); 402 403 Loc dest = state->getLValue(varDecl, pred->getLocationContext()); 404 405 ExplodedNodeSet dstSet; 406 VisitCXXDestructor(dtorDecl, cast<loc::MemRegionVal>(dest).getRegion(), 407 dtor.getTriggerStmt(), pred, dstSet); 408 } 409 410 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D, 411 StmtNodeBuilder &builder) { 412 } 413 414 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D, 415 StmtNodeBuilder &builder) { 416 } 417 418 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D, 419 StmtNodeBuilder &builder) { 420 } 421 422 void ExprEngine::Visit(const Stmt* S, ExplodedNode* Pred, 423 ExplodedNodeSet& Dst) { 424 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 425 S->getLocStart(), 426 "Error evaluating statement"); 427 428 // Expressions to ignore. 429 if (const Expr *Ex = dyn_cast<Expr>(S)) 430 S = Ex->IgnoreParens(); 431 432 // FIXME: add metadata to the CFG so that we can disable 433 // this check when we KNOW that there is no block-level subexpression. 434 // The motivation is that this check requires a hashtable lookup. 435 436 if (S != currentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(S)) { 437 Dst.Add(Pred); 438 return; 439 } 440 441 switch (S->getStmtClass()) { 442 // C++ and ARC stuff we don't support yet. 443 case Expr::ObjCIndirectCopyRestoreExprClass: 444 case Stmt::CXXBindTemporaryExprClass: 445 case Stmt::CXXCatchStmtClass: 446 case Stmt::CXXDependentScopeMemberExprClass: 447 case Stmt::CXXForRangeStmtClass: 448 case Stmt::CXXPseudoDestructorExprClass: 449 case Stmt::CXXTemporaryObjectExprClass: 450 case Stmt::CXXThrowExprClass: 451 case Stmt::CXXTryStmtClass: 452 case Stmt::CXXTypeidExprClass: 453 case Stmt::CXXUuidofExprClass: 454 case Stmt::CXXUnresolvedConstructExprClass: 455 case Stmt::CXXScalarValueInitExprClass: 456 case Stmt::DependentScopeDeclRefExprClass: 457 case Stmt::UnaryTypeTraitExprClass: 458 case Stmt::BinaryTypeTraitExprClass: 459 case Stmt::ArrayTypeTraitExprClass: 460 case Stmt::ExpressionTraitExprClass: 461 case Stmt::UnresolvedLookupExprClass: 462 case Stmt::UnresolvedMemberExprClass: 463 case Stmt::CXXNoexceptExprClass: 464 case Stmt::PackExpansionExprClass: 465 case Stmt::SubstNonTypeTemplateParmPackExprClass: 466 case Stmt::SEHTryStmtClass: 467 case Stmt::SEHExceptStmtClass: 468 case Stmt::SEHFinallyStmtClass: 469 { 470 SaveAndRestore<bool> OldSink(Builder->BuildSinks); 471 Builder->BuildSinks = true; 472 const ExplodedNode *node = MakeNode(Dst, S, Pred, GetState(Pred)); 473 Engine.addAbortedBlock(node, Builder->getBlock()); 474 break; 475 } 476 477 // We don't handle default arguments either yet, but we can fake it 478 // for now by just skipping them. 479 case Stmt::SubstNonTypeTemplateParmExprClass: 480 case Stmt::CXXDefaultArgExprClass: { 481 Dst.Add(Pred); 482 break; 483 } 484 485 case Stmt::ParenExprClass: 486 llvm_unreachable("ParenExprs already handled."); 487 case Stmt::GenericSelectionExprClass: 488 llvm_unreachable("GenericSelectionExprs already handled."); 489 // Cases that should never be evaluated simply because they shouldn't 490 // appear in the CFG. 491 case Stmt::BreakStmtClass: 492 case Stmt::CaseStmtClass: 493 case Stmt::CompoundStmtClass: 494 case Stmt::ContinueStmtClass: 495 case Stmt::DefaultStmtClass: 496 case Stmt::DoStmtClass: 497 case Stmt::ForStmtClass: 498 case Stmt::GotoStmtClass: 499 case Stmt::IfStmtClass: 500 case Stmt::IndirectGotoStmtClass: 501 case Stmt::LabelStmtClass: 502 case Stmt::NoStmtClass: 503 case Stmt::NullStmtClass: 504 case Stmt::SwitchStmtClass: 505 case Stmt::WhileStmtClass: 506 llvm_unreachable("Stmt should not be in analyzer evaluation loop"); 507 break; 508 509 case Stmt::GNUNullExprClass: { 510 // GNU __null is a pointer-width integer, not an actual pointer. 511 const GRState *state = GetState(Pred); 512 state = state->BindExpr(S, svalBuilder.makeIntValWithPtrWidth(0, false)); 513 MakeNode(Dst, S, Pred, state); 514 break; 515 } 516 517 case Stmt::ObjCAtSynchronizedStmtClass: 518 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst); 519 break; 520 521 case Stmt::ObjCPropertyRefExprClass: 522 VisitObjCPropertyRefExpr(cast<ObjCPropertyRefExpr>(S), Pred, Dst); 523 break; 524 525 case Stmt::ImplicitValueInitExprClass: { 526 const GRState *state = GetState(Pred); 527 QualType ty = cast<ImplicitValueInitExpr>(S)->getType(); 528 SVal val = svalBuilder.makeZeroVal(ty); 529 MakeNode(Dst, S, Pred, state->BindExpr(S, val)); 530 break; 531 } 532 533 case Stmt::ExprWithCleanupsClass: { 534 Visit(cast<ExprWithCleanups>(S)->getSubExpr(), Pred, Dst); 535 break; 536 } 537 538 // Cases not handled yet; but will handle some day. 539 case Stmt::DesignatedInitExprClass: 540 case Stmt::ExtVectorElementExprClass: 541 case Stmt::ImaginaryLiteralClass: 542 case Stmt::ObjCAtCatchStmtClass: 543 case Stmt::ObjCAtFinallyStmtClass: 544 case Stmt::ObjCAtTryStmtClass: 545 case Stmt::ObjCAutoreleasePoolStmtClass: 546 case Stmt::ObjCEncodeExprClass: 547 case Stmt::ObjCIsaExprClass: 548 case Stmt::ObjCProtocolExprClass: 549 case Stmt::ObjCSelectorExprClass: 550 case Stmt::ObjCStringLiteralClass: 551 case Stmt::ParenListExprClass: 552 case Stmt::PredefinedExprClass: 553 case Stmt::ShuffleVectorExprClass: 554 case Stmt::VAArgExprClass: 555 case Stmt::CUDAKernelCallExprClass: 556 case Stmt::OpaqueValueExprClass: 557 case Stmt::AsTypeExprClass: 558 // Fall through. 559 560 // Cases we intentionally don't evaluate, since they don't need 561 // to be explicitly evaluated. 562 case Stmt::AddrLabelExprClass: 563 case Stmt::IntegerLiteralClass: 564 case Stmt::CharacterLiteralClass: 565 case Stmt::CXXBoolLiteralExprClass: 566 case Stmt::FloatingLiteralClass: 567 case Stmt::SizeOfPackExprClass: 568 case Stmt::CXXNullPtrLiteralExprClass: 569 Dst.Add(Pred); // No-op. Simply propagate the current state unchanged. 570 break; 571 572 case Stmt::ArraySubscriptExprClass: 573 VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst); 574 break; 575 576 case Stmt::AsmStmtClass: 577 VisitAsmStmt(cast<AsmStmt>(S), Pred, Dst); 578 break; 579 580 case Stmt::BlockDeclRefExprClass: { 581 const BlockDeclRefExpr *BE = cast<BlockDeclRefExpr>(S); 582 VisitCommonDeclRefExpr(BE, BE->getDecl(), Pred, Dst); 583 break; 584 } 585 586 case Stmt::BlockExprClass: 587 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst); 588 break; 589 590 case Stmt::BinaryOperatorClass: { 591 const BinaryOperator* B = cast<BinaryOperator>(S); 592 if (B->isLogicalOp()) { 593 VisitLogicalExpr(B, Pred, Dst); 594 break; 595 } 596 else if (B->getOpcode() == BO_Comma) { 597 const GRState* state = GetState(Pred); 598 MakeNode(Dst, B, Pred, state->BindExpr(B, state->getSVal(B->getRHS()))); 599 break; 600 } 601 602 if (AMgr.shouldEagerlyAssume() && 603 (B->isRelationalOp() || B->isEqualityOp())) { 604 ExplodedNodeSet Tmp; 605 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp); 606 evalEagerlyAssume(Dst, Tmp, cast<Expr>(S)); 607 } 608 else 609 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 610 611 break; 612 } 613 614 case Stmt::CallExprClass: 615 case Stmt::CXXOperatorCallExprClass: 616 case Stmt::CXXMemberCallExprClass: { 617 VisitCallExpr(cast<CallExpr>(S), Pred, Dst); 618 break; 619 } 620 621 case Stmt::CXXConstructExprClass: { 622 const CXXConstructExpr *C = cast<CXXConstructExpr>(S); 623 // For block-level CXXConstructExpr, we don't have a destination region. 624 // Let VisitCXXConstructExpr() create one. 625 VisitCXXConstructExpr(C, 0, Pred, Dst); 626 break; 627 } 628 629 case Stmt::CXXNewExprClass: { 630 const CXXNewExpr *NE = cast<CXXNewExpr>(S); 631 VisitCXXNewExpr(NE, Pred, Dst); 632 break; 633 } 634 635 case Stmt::CXXDeleteExprClass: { 636 const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S); 637 VisitCXXDeleteExpr(CDE, Pred, Dst); 638 break; 639 } 640 // FIXME: ChooseExpr is really a constant. We need to fix 641 // the CFG do not model them as explicit control-flow. 642 643 case Stmt::ChooseExprClass: { // __builtin_choose_expr 644 const ChooseExpr* C = cast<ChooseExpr>(S); 645 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst); 646 break; 647 } 648 649 case Stmt::CompoundAssignOperatorClass: 650 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 651 break; 652 653 case Stmt::CompoundLiteralExprClass: 654 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst); 655 break; 656 657 case Stmt::BinaryConditionalOperatorClass: 658 case Stmt::ConditionalOperatorClass: { // '?' operator 659 const AbstractConditionalOperator *C 660 = cast<AbstractConditionalOperator>(S); 661 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst); 662 break; 663 } 664 665 case Stmt::CXXThisExprClass: 666 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst); 667 break; 668 669 case Stmt::DeclRefExprClass: { 670 const DeclRefExpr *DE = cast<DeclRefExpr>(S); 671 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst); 672 break; 673 } 674 675 case Stmt::DeclStmtClass: 676 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst); 677 break; 678 679 case Stmt::ImplicitCastExprClass: 680 case Stmt::CStyleCastExprClass: 681 case Stmt::CXXStaticCastExprClass: 682 case Stmt::CXXDynamicCastExprClass: 683 case Stmt::CXXReinterpretCastExprClass: 684 case Stmt::CXXConstCastExprClass: 685 case Stmt::CXXFunctionalCastExprClass: 686 case Stmt::ObjCBridgedCastExprClass: { 687 const CastExpr* C = cast<CastExpr>(S); 688 // Handle the previsit checks. 689 ExplodedNodeSet dstPrevisit; 690 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this); 691 692 // Handle the expression itself. 693 ExplodedNodeSet dstExpr; 694 for (ExplodedNodeSet::iterator i = dstPrevisit.begin(), 695 e = dstPrevisit.end(); i != e ; ++i) { 696 VisitCast(C, C->getSubExpr(), *i, dstExpr); 697 } 698 699 // Handle the postvisit checks. 700 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this); 701 break; 702 } 703 704 case Expr::MaterializeTemporaryExprClass: { 705 const MaterializeTemporaryExpr *Materialize 706 = cast<MaterializeTemporaryExpr>(S); 707 if (!Materialize->getType()->isRecordType()) 708 CreateCXXTemporaryObject(Materialize, Pred, Dst); 709 else 710 Visit(Materialize->GetTemporaryExpr(), Pred, Dst); 711 break; 712 } 713 714 case Stmt::InitListExprClass: 715 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst); 716 break; 717 718 case Stmt::MemberExprClass: 719 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst); 720 break; 721 case Stmt::ObjCIvarRefExprClass: 722 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst); 723 break; 724 725 case Stmt::ObjCForCollectionStmtClass: 726 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst); 727 break; 728 729 case Stmt::ObjCMessageExprClass: 730 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst); 731 break; 732 733 case Stmt::ObjCAtThrowStmtClass: { 734 // FIXME: This is not complete. We basically treat @throw as 735 // an abort. 736 SaveAndRestore<bool> OldSink(Builder->BuildSinks); 737 Builder->BuildSinks = true; 738 MakeNode(Dst, S, Pred, GetState(Pred)); 739 break; 740 } 741 742 case Stmt::ReturnStmtClass: 743 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst); 744 break; 745 746 case Stmt::OffsetOfExprClass: 747 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst); 748 break; 749 750 case Stmt::UnaryExprOrTypeTraitExprClass: 751 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S), 752 Pred, Dst); 753 break; 754 755 case Stmt::StmtExprClass: { 756 const StmtExpr* SE = cast<StmtExpr>(S); 757 758 if (SE->getSubStmt()->body_empty()) { 759 // Empty statement expression. 760 assert(SE->getType() == getContext().VoidTy 761 && "Empty statement expression must have void type."); 762 Dst.Add(Pred); 763 break; 764 } 765 766 if (Expr* LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) { 767 const GRState* state = GetState(Pred); 768 MakeNode(Dst, SE, Pred, state->BindExpr(SE, state->getSVal(LastExpr))); 769 } 770 else 771 Dst.Add(Pred); 772 773 break; 774 } 775 776 case Stmt::StringLiteralClass: { 777 const GRState* state = GetState(Pred); 778 SVal V = state->getLValue(cast<StringLiteral>(S)); 779 MakeNode(Dst, S, Pred, state->BindExpr(S, V)); 780 return; 781 } 782 783 case Stmt::UnaryOperatorClass: { 784 const UnaryOperator *U = cast<UnaryOperator>(S); 785 if (AMgr.shouldEagerlyAssume()&&(U->getOpcode() == UO_LNot)) { 786 ExplodedNodeSet Tmp; 787 VisitUnaryOperator(U, Pred, Tmp); 788 evalEagerlyAssume(Dst, Tmp, U); 789 } 790 else 791 VisitUnaryOperator(U, Pred, Dst); 792 break; 793 } 794 } 795 } 796 797 //===----------------------------------------------------------------------===// 798 // Block entrance. (Update counters). 799 //===----------------------------------------------------------------------===// 800 801 void ExprEngine::processCFGBlockEntrance(ExplodedNodeSet &dstNodes, 802 GenericNodeBuilder<BlockEntrance> &nodeBuilder){ 803 804 // FIXME: Refactor this into a checker. 805 const CFGBlock *block = nodeBuilder.getProgramPoint().getBlock(); 806 ExplodedNode *pred = nodeBuilder.getPredecessor(); 807 808 if (nodeBuilder.getBlockCounter().getNumVisited( 809 pred->getLocationContext()->getCurrentStackFrame(), 810 block->getBlockID()) >= AMgr.getMaxVisit()) { 811 812 static int tag = 0; 813 nodeBuilder.generateNode(pred->getState(), pred, &tag, true); 814 } 815 } 816 817 //===----------------------------------------------------------------------===// 818 // Generic node creation. 819 //===----------------------------------------------------------------------===// 820 821 ExplodedNode* ExprEngine::MakeNode(ExplodedNodeSet& Dst, const Stmt* S, 822 ExplodedNode* Pred, const GRState* St, 823 ProgramPoint::Kind K, const void *tag) { 824 assert (Builder && "StmtNodeBuilder not present."); 825 SaveAndRestore<const void*> OldTag(Builder->Tag); 826 Builder->Tag = tag; 827 return Builder->MakeNode(Dst, S, Pred, St, K); 828 } 829 830 //===----------------------------------------------------------------------===// 831 // Branch processing. 832 //===----------------------------------------------------------------------===// 833 834 const GRState* ExprEngine::MarkBranch(const GRState* state, 835 const Stmt* Terminator, 836 bool branchTaken) { 837 838 switch (Terminator->getStmtClass()) { 839 default: 840 return state; 841 842 case Stmt::BinaryOperatorClass: { // '&&' and '||' 843 844 const BinaryOperator* B = cast<BinaryOperator>(Terminator); 845 BinaryOperator::Opcode Op = B->getOpcode(); 846 847 assert (Op == BO_LAnd || Op == BO_LOr); 848 849 // For &&, if we take the true branch, then the value of the whole 850 // expression is that of the RHS expression. 851 // 852 // For ||, if we take the false branch, then the value of the whole 853 // expression is that of the RHS expression. 854 855 const Expr* Ex = (Op == BO_LAnd && branchTaken) || 856 (Op == BO_LOr && !branchTaken) 857 ? B->getRHS() : B->getLHS(); 858 859 return state->BindExpr(B, UndefinedVal(Ex)); 860 } 861 862 case Stmt::BinaryConditionalOperatorClass: 863 case Stmt::ConditionalOperatorClass: { // ?: 864 const AbstractConditionalOperator* C 865 = cast<AbstractConditionalOperator>(Terminator); 866 867 // For ?, if branchTaken == true then the value is either the LHS or 868 // the condition itself. (GNU extension). 869 870 const Expr* Ex; 871 872 if (branchTaken) 873 Ex = C->getTrueExpr(); 874 else 875 Ex = C->getFalseExpr(); 876 877 return state->BindExpr(C, UndefinedVal(Ex)); 878 } 879 880 case Stmt::ChooseExprClass: { // ?: 881 882 const ChooseExpr* C = cast<ChooseExpr>(Terminator); 883 884 const Expr* Ex = branchTaken ? C->getLHS() : C->getRHS(); 885 return state->BindExpr(C, UndefinedVal(Ex)); 886 } 887 } 888 } 889 890 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used 891 /// to try to recover some path-sensitivity for casts of symbolic 892 /// integers that promote their values (which are currently not tracked well). 893 /// This function returns the SVal bound to Condition->IgnoreCasts if all the 894 // cast(s) did was sign-extend the original value. 895 static SVal RecoverCastedSymbol(GRStateManager& StateMgr, const GRState* state, 896 const Stmt* Condition, ASTContext& Ctx) { 897 898 const Expr *Ex = dyn_cast<Expr>(Condition); 899 if (!Ex) 900 return UnknownVal(); 901 902 uint64_t bits = 0; 903 bool bitsInit = false; 904 905 while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) { 906 QualType T = CE->getType(); 907 908 if (!T->isIntegerType()) 909 return UnknownVal(); 910 911 uint64_t newBits = Ctx.getTypeSize(T); 912 if (!bitsInit || newBits < bits) { 913 bitsInit = true; 914 bits = newBits; 915 } 916 917 Ex = CE->getSubExpr(); 918 } 919 920 // We reached a non-cast. Is it a symbolic value? 921 QualType T = Ex->getType(); 922 923 if (!bitsInit || !T->isIntegerType() || Ctx.getTypeSize(T) > bits) 924 return UnknownVal(); 925 926 return state->getSVal(Ex); 927 } 928 929 void ExprEngine::processBranch(const Stmt* Condition, const Stmt* Term, 930 BranchNodeBuilder& builder) { 931 932 // Check for NULL conditions; e.g. "for(;;)" 933 if (!Condition) { 934 builder.markInfeasible(false); 935 return; 936 } 937 938 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 939 Condition->getLocStart(), 940 "Error evaluating branch"); 941 942 getCheckerManager().runCheckersForBranchCondition(Condition, builder, *this); 943 944 // If the branch condition is undefined, return; 945 if (!builder.isFeasible(true) && !builder.isFeasible(false)) 946 return; 947 948 const GRState* PrevState = builder.getState(); 949 SVal X = PrevState->getSVal(Condition); 950 951 if (X.isUnknownOrUndef()) { 952 // Give it a chance to recover from unknown. 953 if (const Expr *Ex = dyn_cast<Expr>(Condition)) { 954 if (Ex->getType()->isIntegerType()) { 955 // Try to recover some path-sensitivity. Right now casts of symbolic 956 // integers that promote their values are currently not tracked well. 957 // If 'Condition' is such an expression, try and recover the 958 // underlying value and use that instead. 959 SVal recovered = RecoverCastedSymbol(getStateManager(), 960 builder.getState(), Condition, 961 getContext()); 962 963 if (!recovered.isUnknown()) { 964 X = recovered; 965 } 966 } 967 } 968 // If the condition is still unknown, give up. 969 if (X.isUnknownOrUndef()) { 970 builder.generateNode(MarkBranch(PrevState, Term, true), true); 971 builder.generateNode(MarkBranch(PrevState, Term, false), false); 972 return; 973 } 974 } 975 976 DefinedSVal V = cast<DefinedSVal>(X); 977 978 // Process the true branch. 979 if (builder.isFeasible(true)) { 980 if (const GRState *state = PrevState->assume(V, true)) 981 builder.generateNode(MarkBranch(state, Term, true), true); 982 else 983 builder.markInfeasible(true); 984 } 985 986 // Process the false branch. 987 if (builder.isFeasible(false)) { 988 if (const GRState *state = PrevState->assume(V, false)) 989 builder.generateNode(MarkBranch(state, Term, false), false); 990 else 991 builder.markInfeasible(false); 992 } 993 } 994 995 /// processIndirectGoto - Called by CoreEngine. Used to generate successor 996 /// nodes by processing the 'effects' of a computed goto jump. 997 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) { 998 999 const GRState *state = builder.getState(); 1000 SVal V = state->getSVal(builder.getTarget()); 1001 1002 // Three possibilities: 1003 // 1004 // (1) We know the computed label. 1005 // (2) The label is NULL (or some other constant), or Undefined. 1006 // (3) We have no clue about the label. Dispatch to all targets. 1007 // 1008 1009 typedef IndirectGotoNodeBuilder::iterator iterator; 1010 1011 if (isa<loc::GotoLabel>(V)) { 1012 const LabelDecl *L = cast<loc::GotoLabel>(V).getLabel(); 1013 1014 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) { 1015 if (I.getLabel() == L) { 1016 builder.generateNode(I, state); 1017 return; 1018 } 1019 } 1020 1021 assert(false && "No block with label."); 1022 return; 1023 } 1024 1025 if (isa<loc::ConcreteInt>(V) || isa<UndefinedVal>(V)) { 1026 // Dispatch to the first target and mark it as a sink. 1027 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true); 1028 // FIXME: add checker visit. 1029 // UndefBranches.insert(N); 1030 return; 1031 } 1032 1033 // This is really a catch-all. We don't support symbolics yet. 1034 // FIXME: Implement dispatch for symbolic pointers. 1035 1036 for (iterator I=builder.begin(), E=builder.end(); I != E; ++I) 1037 builder.generateNode(I, state); 1038 } 1039 1040 1041 void ExprEngine::VisitGuardedExpr(const Expr* Ex, const Expr* L, 1042 const Expr* R, 1043 ExplodedNode* Pred, ExplodedNodeSet& Dst) { 1044 1045 assert(Ex == currentStmt && 1046 Pred->getLocationContext()->getCFG()->isBlkExpr(Ex)); 1047 1048 const GRState* state = GetState(Pred); 1049 SVal X = state->getSVal(Ex); 1050 1051 assert (X.isUndef()); 1052 1053 const Expr *SE = (Expr*) cast<UndefinedVal>(X).getData(); 1054 assert(SE); 1055 X = state->getSVal(SE); 1056 1057 // Make sure that we invalidate the previous binding. 1058 MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, X, true)); 1059 } 1060 1061 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path 1062 /// nodes when the control reaches the end of a function. 1063 void ExprEngine::processEndOfFunction(EndOfFunctionNodeBuilder& builder) { 1064 getTF().evalEndPath(*this, builder); 1065 StateMgr.EndPath(builder.getState()); 1066 getCheckerManager().runCheckersForEndPath(builder, *this); 1067 } 1068 1069 /// ProcessSwitch - Called by CoreEngine. Used to generate successor 1070 /// nodes by processing the 'effects' of a switch statement. 1071 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) { 1072 typedef SwitchNodeBuilder::iterator iterator; 1073 const GRState* state = builder.getState(); 1074 const Expr* CondE = builder.getCondition(); 1075 SVal CondV_untested = state->getSVal(CondE); 1076 1077 if (CondV_untested.isUndef()) { 1078 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true); 1079 // FIXME: add checker 1080 //UndefBranches.insert(N); 1081 1082 return; 1083 } 1084 DefinedOrUnknownSVal CondV = cast<DefinedOrUnknownSVal>(CondV_untested); 1085 1086 const GRState *DefaultSt = state; 1087 1088 iterator I = builder.begin(), EI = builder.end(); 1089 bool defaultIsFeasible = I == EI; 1090 1091 for ( ; I != EI; ++I) { 1092 // Successor may be pruned out during CFG construction. 1093 if (!I.getBlock()) 1094 continue; 1095 1096 const CaseStmt* Case = I.getCase(); 1097 1098 // Evaluate the LHS of the case value. 1099 Expr::EvalResult V1; 1100 bool b = Case->getLHS()->Evaluate(V1, getContext()); 1101 1102 // Sanity checks. These go away in Release builds. 1103 assert(b && V1.Val.isInt() && !V1.HasSideEffects 1104 && "Case condition must evaluate to an integer constant."); 1105 (void)b; // silence unused variable warning 1106 assert(V1.Val.getInt().getBitWidth() == 1107 getContext().getTypeSize(CondE->getType())); 1108 1109 // Get the RHS of the case, if it exists. 1110 Expr::EvalResult V2; 1111 1112 if (const Expr* E = Case->getRHS()) { 1113 b = E->Evaluate(V2, getContext()); 1114 assert(b && V2.Val.isInt() && !V2.HasSideEffects 1115 && "Case condition must evaluate to an integer constant."); 1116 (void)b; // silence unused variable warning 1117 } 1118 else 1119 V2 = V1; 1120 1121 // FIXME: Eventually we should replace the logic below with a range 1122 // comparison, rather than concretize the values within the range. 1123 // This should be easy once we have "ranges" for NonLVals. 1124 1125 do { 1126 nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1.Val.getInt())); 1127 DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state, 1128 CondV, CaseVal); 1129 1130 // Now "assume" that the case matches. 1131 if (const GRState* stateNew = state->assume(Res, true)) { 1132 builder.generateCaseStmtNode(I, stateNew); 1133 1134 // If CondV evaluates to a constant, then we know that this 1135 // is the *only* case that we can take, so stop evaluating the 1136 // others. 1137 if (isa<nonloc::ConcreteInt>(CondV)) 1138 return; 1139 } 1140 1141 // Now "assume" that the case doesn't match. Add this state 1142 // to the default state (if it is feasible). 1143 if (DefaultSt) { 1144 if (const GRState *stateNew = DefaultSt->assume(Res, false)) { 1145 defaultIsFeasible = true; 1146 DefaultSt = stateNew; 1147 } 1148 else { 1149 defaultIsFeasible = false; 1150 DefaultSt = NULL; 1151 } 1152 } 1153 1154 // Concretize the next value in the range. 1155 if (V1.Val.getInt() == V2.Val.getInt()) 1156 break; 1157 1158 ++V1.Val.getInt(); 1159 assert (V1.Val.getInt() <= V2.Val.getInt()); 1160 1161 } while (true); 1162 } 1163 1164 if (!defaultIsFeasible) 1165 return; 1166 1167 // If we have switch(enum value), the default branch is not 1168 // feasible if all of the enum constants not covered by 'case:' statements 1169 // are not feasible values for the switch condition. 1170 // 1171 // Note that this isn't as accurate as it could be. Even if there isn't 1172 // a case for a particular enum value as long as that enum value isn't 1173 // feasible then it shouldn't be considered for making 'default:' reachable. 1174 const SwitchStmt *SS = builder.getSwitch(); 1175 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts(); 1176 if (CondExpr->getType()->getAs<EnumType>()) { 1177 if (SS->isAllEnumCasesCovered()) 1178 return; 1179 } 1180 1181 builder.generateDefaultCaseNode(DefaultSt); 1182 } 1183 1184 void ExprEngine::processCallEnter(CallEnterNodeBuilder &B) { 1185 const GRState *state = B.getState()->enterStackFrame(B.getCalleeContext()); 1186 B.generateNode(state); 1187 } 1188 1189 void ExprEngine::processCallExit(CallExitNodeBuilder &B) { 1190 const GRState *state = B.getState(); 1191 const ExplodedNode *Pred = B.getPredecessor(); 1192 const StackFrameContext *calleeCtx = 1193 cast<StackFrameContext>(Pred->getLocationContext()); 1194 const Stmt *CE = calleeCtx->getCallSite(); 1195 1196 // If the callee returns an expression, bind its value to CallExpr. 1197 const Stmt *ReturnedExpr = state->get<ReturnExpr>(); 1198 if (ReturnedExpr) { 1199 SVal RetVal = state->getSVal(ReturnedExpr); 1200 state = state->BindExpr(CE, RetVal); 1201 // Clear the return expr GDM. 1202 state = state->remove<ReturnExpr>(); 1203 } 1204 1205 // Bind the constructed object value to CXXConstructExpr. 1206 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(CE)) { 1207 const CXXThisRegion *ThisR = 1208 getCXXThisRegion(CCE->getConstructor()->getParent(), calleeCtx); 1209 1210 SVal ThisV = state->getSVal(ThisR); 1211 // Always bind the region to the CXXConstructExpr. 1212 state = state->BindExpr(CCE, ThisV); 1213 } 1214 1215 B.generateNode(state); 1216 } 1217 1218 //===----------------------------------------------------------------------===// 1219 // Transfer functions: logical operations ('&&', '||'). 1220 //===----------------------------------------------------------------------===// 1221 1222 void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode* Pred, 1223 ExplodedNodeSet& Dst) { 1224 1225 assert(B->getOpcode() == BO_LAnd || 1226 B->getOpcode() == BO_LOr); 1227 1228 assert(B==currentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(B)); 1229 1230 const GRState* state = GetState(Pred); 1231 SVal X = state->getSVal(B); 1232 assert(X.isUndef()); 1233 1234 const Expr *Ex = (const Expr*) cast<UndefinedVal>(X).getData(); 1235 assert(Ex); 1236 1237 if (Ex == B->getRHS()) { 1238 X = state->getSVal(Ex); 1239 1240 // Handle undefined values. 1241 if (X.isUndef()) { 1242 MakeNode(Dst, B, Pred, state->BindExpr(B, X)); 1243 return; 1244 } 1245 1246 DefinedOrUnknownSVal XD = cast<DefinedOrUnknownSVal>(X); 1247 1248 // We took the RHS. Because the value of the '&&' or '||' expression must 1249 // evaluate to 0 or 1, we must assume the value of the RHS evaluates to 0 1250 // or 1. Alternatively, we could take a lazy approach, and calculate this 1251 // value later when necessary. We don't have the machinery in place for 1252 // this right now, and since most logical expressions are used for branches, 1253 // the payoff is not likely to be large. Instead, we do eager evaluation. 1254 if (const GRState *newState = state->assume(XD, true)) 1255 MakeNode(Dst, B, Pred, 1256 newState->BindExpr(B, svalBuilder.makeIntVal(1U, B->getType()))); 1257 1258 if (const GRState *newState = state->assume(XD, false)) 1259 MakeNode(Dst, B, Pred, 1260 newState->BindExpr(B, svalBuilder.makeIntVal(0U, B->getType()))); 1261 } 1262 else { 1263 // We took the LHS expression. Depending on whether we are '&&' or 1264 // '||' we know what the value of the expression is via properties of 1265 // the short-circuiting. 1266 X = svalBuilder.makeIntVal(B->getOpcode() == BO_LAnd ? 0U : 1U, 1267 B->getType()); 1268 MakeNode(Dst, B, Pred, state->BindExpr(B, X)); 1269 } 1270 } 1271 1272 //===----------------------------------------------------------------------===// 1273 // Transfer functions: Loads and stores. 1274 //===----------------------------------------------------------------------===// 1275 1276 void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, 1277 ExplodedNodeSet &Dst) { 1278 1279 ExplodedNodeSet Tmp; 1280 1281 CanQualType T = getContext().getCanonicalType(BE->getType()); 1282 SVal V = svalBuilder.getBlockPointer(BE->getBlockDecl(), T, 1283 Pred->getLocationContext()); 1284 1285 MakeNode(Tmp, BE, Pred, GetState(Pred)->BindExpr(BE, V), 1286 ProgramPoint::PostLValueKind); 1287 1288 // Post-visit the BlockExpr. 1289 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this); 1290 } 1291 1292 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D, 1293 ExplodedNode *Pred, 1294 ExplodedNodeSet &Dst) { 1295 const GRState *state = GetState(Pred); 1296 1297 if (const VarDecl* VD = dyn_cast<VarDecl>(D)) { 1298 assert(Ex->isLValue()); 1299 SVal V = state->getLValue(VD, Pred->getLocationContext()); 1300 1301 // For references, the 'lvalue' is the pointer address stored in the 1302 // reference region. 1303 if (VD->getType()->isReferenceType()) { 1304 if (const MemRegion *R = V.getAsRegion()) 1305 V = state->getSVal(R); 1306 else 1307 V = UnknownVal(); 1308 } 1309 1310 MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V), 1311 ProgramPoint::PostLValueKind); 1312 return; 1313 } 1314 if (const EnumConstantDecl* ED = dyn_cast<EnumConstantDecl>(D)) { 1315 assert(!Ex->isLValue()); 1316 SVal V = svalBuilder.makeIntVal(ED->getInitVal()); 1317 MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V)); 1318 return; 1319 } 1320 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) { 1321 SVal V = svalBuilder.getFunctionPointer(FD); 1322 MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V), 1323 ProgramPoint::PostLValueKind); 1324 return; 1325 } 1326 assert (false && 1327 "ValueDecl support for this ValueDecl not implemented."); 1328 } 1329 1330 /// VisitArraySubscriptExpr - Transfer function for array accesses 1331 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr* A, 1332 ExplodedNode* Pred, 1333 ExplodedNodeSet& Dst){ 1334 1335 const Expr* Base = A->getBase()->IgnoreParens(); 1336 const Expr* Idx = A->getIdx()->IgnoreParens(); 1337 1338 1339 ExplodedNodeSet checkerPreStmt; 1340 getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this); 1341 1342 for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(), 1343 ei = checkerPreStmt.end(); it != ei; ++it) { 1344 const GRState* state = GetState(*it); 1345 SVal V = state->getLValue(A->getType(), state->getSVal(Idx), 1346 state->getSVal(Base)); 1347 assert(A->isLValue()); 1348 MakeNode(Dst, A, *it, state->BindExpr(A, V), ProgramPoint::PostLValueKind); 1349 } 1350 } 1351 1352 /// VisitMemberExpr - Transfer function for member expressions. 1353 void ExprEngine::VisitMemberExpr(const MemberExpr* M, ExplodedNode *Pred, 1354 ExplodedNodeSet& Dst) { 1355 1356 FieldDecl *field = dyn_cast<FieldDecl>(M->getMemberDecl()); 1357 if (!field) // FIXME: skipping member expressions for non-fields 1358 return; 1359 1360 Expr *baseExpr = M->getBase()->IgnoreParens(); 1361 const GRState* state = GetState(Pred); 1362 SVal baseExprVal = state->getSVal(baseExpr); 1363 if (isa<nonloc::LazyCompoundVal>(baseExprVal) || 1364 isa<nonloc::CompoundVal>(baseExprVal) || 1365 // FIXME: This can originate by conjuring a symbol for an unknown 1366 // temporary struct object, see test/Analysis/fields.c: 1367 // (p = getit()).x 1368 isa<nonloc::SymbolVal>(baseExprVal)) { 1369 MakeNode(Dst, M, Pred, state->BindExpr(M, UnknownVal())); 1370 return; 1371 } 1372 1373 // FIXME: Should we insert some assumption logic in here to determine 1374 // if "Base" is a valid piece of memory? Before we put this assumption 1375 // later when using FieldOffset lvals (which we no longer have). 1376 1377 // For all other cases, compute an lvalue. 1378 SVal L = state->getLValue(field, baseExprVal); 1379 if (M->isLValue()) 1380 MakeNode(Dst, M, Pred, state->BindExpr(M, L), ProgramPoint::PostLValueKind); 1381 else 1382 evalLoad(Dst, M, Pred, state, L); 1383 } 1384 1385 /// evalBind - Handle the semantics of binding a value to a specific location. 1386 /// This method is used by evalStore and (soon) VisitDeclStmt, and others. 1387 void ExprEngine::evalBind(ExplodedNodeSet& Dst, const Stmt* StoreE, 1388 ExplodedNode* Pred, const GRState* state, 1389 SVal location, SVal Val, bool atDeclInit) { 1390 1391 1392 // Do a previsit of the bind. 1393 ExplodedNodeSet CheckedSet, Src; 1394 Src.Add(Pred); 1395 getCheckerManager().runCheckersForBind(CheckedSet, Src, location, Val, StoreE, 1396 *this); 1397 1398 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 1399 I!=E; ++I) { 1400 1401 if (Pred != *I) 1402 state = GetState(*I); 1403 1404 const GRState* newState = 0; 1405 1406 if (atDeclInit) { 1407 const VarRegion *VR = 1408 cast<VarRegion>(cast<loc::MemRegionVal>(location).getRegion()); 1409 1410 newState = state->bindDecl(VR, Val); 1411 } 1412 else { 1413 if (location.isUnknown()) { 1414 // We know that the new state will be the same as the old state since 1415 // the location of the binding is "unknown". Consequently, there 1416 // is no reason to just create a new node. 1417 newState = state; 1418 } 1419 else { 1420 // We are binding to a value other than 'unknown'. Perform the binding 1421 // using the StoreManager. 1422 newState = state->bindLoc(cast<Loc>(location), Val); 1423 } 1424 } 1425 1426 // The next thing to do is check if the TransferFuncs object wants to 1427 // update the state based on the new binding. If the GRTransferFunc object 1428 // doesn't do anything, just auto-propagate the current state. 1429 1430 // NOTE: We use 'AssignE' for the location of the PostStore if 'AssignE' 1431 // is non-NULL. Checkers typically care about 1432 1433 StmtNodeBuilderRef BuilderRef(Dst, *Builder, *this, *I, newState, StoreE, 1434 true); 1435 1436 getTF().evalBind(BuilderRef, location, Val); 1437 } 1438 } 1439 1440 /// evalStore - Handle the semantics of a store via an assignment. 1441 /// @param Dst The node set to store generated state nodes 1442 /// @param AssignE The assignment expression if the store happens in an 1443 /// assignment. 1444 /// @param LocatioinE The location expression that is stored to. 1445 /// @param state The current simulation state 1446 /// @param location The location to store the value 1447 /// @param Val The value to be stored 1448 void ExprEngine::evalStore(ExplodedNodeSet& Dst, const Expr *AssignE, 1449 const Expr* LocationE, 1450 ExplodedNode* Pred, 1451 const GRState* state, SVal location, SVal Val, 1452 const void *tag) { 1453 1454 assert(Builder && "StmtNodeBuilder must be defined."); 1455 1456 // Proceed with the store. We use AssignE as the anchor for the PostStore 1457 // ProgramPoint if it is non-NULL, and LocationE otherwise. 1458 const Expr *StoreE = AssignE ? AssignE : LocationE; 1459 1460 if (isa<loc::ObjCPropRef>(location)) { 1461 loc::ObjCPropRef prop = cast<loc::ObjCPropRef>(location); 1462 return VisitObjCMessage(ObjCPropertySetter(prop.getPropRefExpr(), 1463 StoreE, Val), Pred, Dst); 1464 } 1465 1466 // Evaluate the location (checks for bad dereferences). 1467 ExplodedNodeSet Tmp; 1468 evalLocation(Tmp, LocationE, Pred, state, location, tag, false); 1469 1470 if (Tmp.empty()) 1471 return; 1472 1473 if (location.isUndef()) 1474 return; 1475 1476 SaveAndRestore<ProgramPoint::Kind> OldSPointKind(Builder->PointKind, 1477 ProgramPoint::PostStoreKind); 1478 1479 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) 1480 evalBind(Dst, StoreE, *NI, GetState(*NI), location, Val); 1481 } 1482 1483 void ExprEngine::evalLoad(ExplodedNodeSet& Dst, const Expr *Ex, 1484 ExplodedNode* Pred, 1485 const GRState* state, SVal location, 1486 const void *tag, QualType LoadTy) { 1487 assert(!isa<NonLoc>(location) && "location cannot be a NonLoc."); 1488 1489 if (isa<loc::ObjCPropRef>(location)) { 1490 loc::ObjCPropRef prop = cast<loc::ObjCPropRef>(location); 1491 return VisitObjCMessage(ObjCPropertyGetter(prop.getPropRefExpr(), Ex), 1492 Pred, Dst); 1493 } 1494 1495 // Are we loading from a region? This actually results in two loads; one 1496 // to fetch the address of the referenced value and one to fetch the 1497 // referenced value. 1498 if (const TypedRegion *TR = 1499 dyn_cast_or_null<TypedRegion>(location.getAsRegion())) { 1500 1501 QualType ValTy = TR->getValueType(); 1502 if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) { 1503 static int loadReferenceTag = 0; 1504 ExplodedNodeSet Tmp; 1505 evalLoadCommon(Tmp, Ex, Pred, state, location, &loadReferenceTag, 1506 getContext().getPointerType(RT->getPointeeType())); 1507 1508 // Perform the load from the referenced value. 1509 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) { 1510 state = GetState(*I); 1511 location = state->getSVal(Ex); 1512 evalLoadCommon(Dst, Ex, *I, state, location, tag, LoadTy); 1513 } 1514 return; 1515 } 1516 } 1517 1518 evalLoadCommon(Dst, Ex, Pred, state, location, tag, LoadTy); 1519 } 1520 1521 void ExprEngine::evalLoadCommon(ExplodedNodeSet& Dst, const Expr *Ex, 1522 ExplodedNode* Pred, 1523 const GRState* state, SVal location, 1524 const void *tag, QualType LoadTy) { 1525 1526 // Evaluate the location (checks for bad dereferences). 1527 ExplodedNodeSet Tmp; 1528 evalLocation(Tmp, Ex, Pred, state, location, tag, true); 1529 1530 if (Tmp.empty()) 1531 return; 1532 1533 if (location.isUndef()) 1534 return; 1535 1536 SaveAndRestore<ProgramPoint::Kind> OldSPointKind(Builder->PointKind); 1537 1538 // Proceed with the load. 1539 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) { 1540 state = GetState(*NI); 1541 1542 if (location.isUnknown()) { 1543 // This is important. We must nuke the old binding. 1544 MakeNode(Dst, Ex, *NI, state->BindExpr(Ex, UnknownVal()), 1545 ProgramPoint::PostLoadKind, tag); 1546 } 1547 else { 1548 if (LoadTy.isNull()) 1549 LoadTy = Ex->getType(); 1550 SVal V = state->getSVal(cast<Loc>(location), LoadTy); 1551 MakeNode(Dst, Ex, *NI, state->bindExprAndLocation(Ex, location, V), 1552 ProgramPoint::PostLoadKind, tag); 1553 } 1554 } 1555 } 1556 1557 void ExprEngine::evalLocation(ExplodedNodeSet &Dst, const Stmt *S, 1558 ExplodedNode* Pred, 1559 const GRState* state, SVal location, 1560 const void *tag, bool isLoad) { 1561 // Early checks for performance reason. 1562 if (location.isUnknown()) { 1563 Dst.Add(Pred); 1564 return; 1565 } 1566 1567 ExplodedNodeSet Src; 1568 if (Builder->GetState(Pred) == state) { 1569 Src.Add(Pred); 1570 } else { 1571 // Associate this new state with an ExplodedNode. 1572 // FIXME: If I pass null tag, the graph is incorrect, e.g for 1573 // int *p; 1574 // p = 0; 1575 // *p = 0xDEADBEEF; 1576 // "p = 0" is not noted as "Null pointer value stored to 'p'" but 1577 // instead "int *p" is noted as 1578 // "Variable 'p' initialized to a null pointer value" 1579 ExplodedNode *N = Builder->generateNode(S, state, Pred, this); 1580 Src.Add(N ? N : Pred); 1581 } 1582 getCheckerManager().runCheckersForLocation(Dst, Src, location, isLoad, S, 1583 *this); 1584 } 1585 1586 bool ExprEngine::InlineCall(ExplodedNodeSet &Dst, const CallExpr *CE, 1587 ExplodedNode *Pred) { 1588 return false; 1589 1590 // Inlining isn't correct right now because we: 1591 // (a) don't generate CallExit nodes. 1592 // (b) we need a way to postpone doing post-visits of CallExprs until 1593 // the CallExit. This means we need CallExits for the non-inline 1594 // cases as well. 1595 1596 #if 0 1597 const GRState *state = GetState(Pred); 1598 const Expr *Callee = CE->getCallee(); 1599 SVal L = state->getSVal(Callee); 1600 1601 const FunctionDecl *FD = L.getAsFunctionDecl(); 1602 if (!FD) 1603 return false; 1604 1605 // Specially handle CXXMethods. 1606 const CXXMethodDecl *methodDecl = 0; 1607 1608 switch (CE->getStmtClass()) { 1609 default: break; 1610 case Stmt::CXXOperatorCallExprClass: { 1611 const CXXOperatorCallExpr *opCall = cast<CXXOperatorCallExpr>(CE); 1612 methodDecl = 1613 dyn_cast_or_null<CXXMethodDecl>(opCall->getCalleeDecl()); 1614 break; 1615 } 1616 case Stmt::CXXMemberCallExprClass: { 1617 const CXXMemberCallExpr *memberCall = cast<CXXMemberCallExpr>(CE); 1618 const MemberExpr *memberExpr = 1619 cast<MemberExpr>(memberCall->getCallee()->IgnoreParens()); 1620 methodDecl = cast<CXXMethodDecl>(memberExpr->getMemberDecl()); 1621 break; 1622 } 1623 } 1624 1625 1626 1627 1628 // Check if the function definition is in the same translation unit. 1629 if (FD->hasBody(FD)) { 1630 const StackFrameContext *stackFrame = 1631 AMgr.getStackFrame(AMgr.getAnalysisContext(FD), 1632 Pred->getLocationContext(), 1633 CE, Builder->getBlock(), Builder->getIndex()); 1634 // Now we have the definition of the callee, create a CallEnter node. 1635 CallEnter Loc(CE, stackFrame, Pred->getLocationContext()); 1636 1637 ExplodedNode *N = Builder->generateNode(Loc, state, Pred); 1638 Dst.Add(N); 1639 return true; 1640 } 1641 1642 // Check if we can find the function definition in other translation units. 1643 if (AMgr.hasIndexer()) { 1644 AnalysisContext *C = AMgr.getAnalysisContextInAnotherTU(FD); 1645 if (C == 0) 1646 return false; 1647 const StackFrameContext *stackFrame = 1648 AMgr.getStackFrame(C, Pred->getLocationContext(), 1649 CE, Builder->getBlock(), Builder->getIndex()); 1650 CallEnter Loc(CE, stackFrame, Pred->getLocationContext()); 1651 ExplodedNode *N = Builder->generateNode(Loc, state, Pred); 1652 Dst.Add(N); 1653 return true; 1654 } 1655 1656 // Generate the CallExit node. 1657 1658 return false; 1659 #endif 1660 } 1661 1662 void ExprEngine::VisitCallExpr(const CallExpr* CE, ExplodedNode* Pred, 1663 ExplodedNodeSet& dst) { 1664 // Perform the previsit of the CallExpr. 1665 ExplodedNodeSet dstPreVisit; 1666 getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, CE, *this); 1667 1668 // Now evaluate the call itself. 1669 class DefaultEval : public GraphExpander { 1670 ExprEngine &Eng; 1671 const CallExpr *CE; 1672 public: 1673 1674 DefaultEval(ExprEngine &eng, const CallExpr *ce) 1675 : Eng(eng), CE(ce) {} 1676 virtual void expandGraph(ExplodedNodeSet &Dst, ExplodedNode *Pred) { 1677 // Should we inline the call? 1678 if (Eng.getAnalysisManager().shouldInlineCall() && 1679 Eng.InlineCall(Dst, CE, Pred)) { 1680 return; 1681 } 1682 1683 StmtNodeBuilder &Builder = Eng.getBuilder(); 1684 assert(&Builder && "StmtNodeBuilder must be defined."); 1685 1686 // Dispatch to the plug-in transfer function. 1687 unsigned oldSize = Dst.size(); 1688 SaveOr OldHasGen(Builder.hasGeneratedNode); 1689 1690 // Dispatch to transfer function logic to handle the call itself. 1691 const Expr* Callee = CE->getCallee()->IgnoreParens(); 1692 const GRState* state = Eng.GetState(Pred); 1693 SVal L = state->getSVal(Callee); 1694 Eng.getTF().evalCall(Dst, Eng, Builder, CE, L, Pred); 1695 1696 // Handle the case where no nodes where generated. Auto-generate that 1697 // contains the updated state if we aren't generating sinks. 1698 if (!Builder.BuildSinks && Dst.size() == oldSize && 1699 !Builder.hasGeneratedNode) 1700 Eng.MakeNode(Dst, CE, Pred, state); 1701 } 1702 }; 1703 1704 // Finally, evaluate the function call. We try each of the checkers 1705 // to see if the can evaluate the function call. 1706 ExplodedNodeSet dstCallEvaluated; 1707 DefaultEval defEval(*this, CE); 1708 getCheckerManager().runCheckersForEvalCall(dstCallEvaluated, 1709 dstPreVisit, 1710 CE, *this, &defEval); 1711 1712 // Finally, perform the post-condition check of the CallExpr and store 1713 // the created nodes in 'Dst'. 1714 getCheckerManager().runCheckersForPostStmt(dst, dstCallEvaluated, CE, 1715 *this); 1716 } 1717 1718 //===----------------------------------------------------------------------===// 1719 // Transfer function: Objective-C dot-syntax to access a property. 1720 //===----------------------------------------------------------------------===// 1721 1722 void ExprEngine::VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *Ex, 1723 ExplodedNode *Pred, 1724 ExplodedNodeSet &Dst) { 1725 MakeNode(Dst, Ex, Pred, GetState(Pred)->BindExpr(Ex, loc::ObjCPropRef(Ex))); 1726 } 1727 1728 //===----------------------------------------------------------------------===// 1729 // Transfer function: Objective-C ivar references. 1730 //===----------------------------------------------------------------------===// 1731 1732 static std::pair<const void*,const void*> EagerlyAssumeTag 1733 = std::pair<const void*,const void*>(&EagerlyAssumeTag,static_cast<void*>(0)); 1734 1735 void ExprEngine::evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, 1736 const Expr *Ex) { 1737 for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) { 1738 ExplodedNode *Pred = *I; 1739 1740 // Test if the previous node was as the same expression. This can happen 1741 // when the expression fails to evaluate to anything meaningful and 1742 // (as an optimization) we don't generate a node. 1743 ProgramPoint P = Pred->getLocation(); 1744 if (!isa<PostStmt>(P) || cast<PostStmt>(P).getStmt() != Ex) { 1745 Dst.Add(Pred); 1746 continue; 1747 } 1748 1749 const GRState* state = GetState(Pred); 1750 SVal V = state->getSVal(Ex); 1751 if (nonloc::SymExprVal *SEV = dyn_cast<nonloc::SymExprVal>(&V)) { 1752 // First assume that the condition is true. 1753 if (const GRState *stateTrue = state->assume(*SEV, true)) { 1754 stateTrue = stateTrue->BindExpr(Ex, 1755 svalBuilder.makeIntVal(1U, Ex->getType())); 1756 Dst.Add(Builder->generateNode(PostStmtCustom(Ex, 1757 &EagerlyAssumeTag, Pred->getLocationContext()), 1758 stateTrue, Pred)); 1759 } 1760 1761 // Next, assume that the condition is false. 1762 if (const GRState *stateFalse = state->assume(*SEV, false)) { 1763 stateFalse = stateFalse->BindExpr(Ex, 1764 svalBuilder.makeIntVal(0U, Ex->getType())); 1765 Dst.Add(Builder->generateNode(PostStmtCustom(Ex, &EagerlyAssumeTag, 1766 Pred->getLocationContext()), 1767 stateFalse, Pred)); 1768 } 1769 } 1770 else 1771 Dst.Add(Pred); 1772 } 1773 } 1774 1775 //===----------------------------------------------------------------------===// 1776 // Transfer function: Objective-C @synchronized. 1777 //===----------------------------------------------------------------------===// 1778 1779 void ExprEngine::VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S, 1780 ExplodedNode *Pred, 1781 ExplodedNodeSet &Dst) { 1782 getCheckerManager().runCheckersForPreStmt(Dst, Pred, S, *this); 1783 } 1784 1785 //===----------------------------------------------------------------------===// 1786 // Transfer function: Objective-C ivar references. 1787 //===----------------------------------------------------------------------===// 1788 1789 void ExprEngine::VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr* Ex, 1790 ExplodedNode* Pred, 1791 ExplodedNodeSet& Dst) { 1792 1793 const GRState *state = GetState(Pred); 1794 SVal baseVal = state->getSVal(Ex->getBase()); 1795 SVal location = state->getLValue(Ex->getDecl(), baseVal); 1796 1797 ExplodedNodeSet dstIvar; 1798 MakeNode(dstIvar, Ex, Pred, state->BindExpr(Ex, location)); 1799 1800 // Perform the post-condition check of the ObjCIvarRefExpr and store 1801 // the created nodes in 'Dst'. 1802 getCheckerManager().runCheckersForPostStmt(Dst, dstIvar, Ex, *this); 1803 } 1804 1805 //===----------------------------------------------------------------------===// 1806 // Transfer function: Objective-C fast enumeration 'for' statements. 1807 //===----------------------------------------------------------------------===// 1808 1809 void ExprEngine::VisitObjCForCollectionStmt(const ObjCForCollectionStmt* S, 1810 ExplodedNode* Pred, ExplodedNodeSet& Dst) { 1811 1812 // ObjCForCollectionStmts are processed in two places. This method 1813 // handles the case where an ObjCForCollectionStmt* occurs as one of the 1814 // statements within a basic block. This transfer function does two things: 1815 // 1816 // (1) binds the next container value to 'element'. This creates a new 1817 // node in the ExplodedGraph. 1818 // 1819 // (2) binds the value 0/1 to the ObjCForCollectionStmt* itself, indicating 1820 // whether or not the container has any more elements. This value 1821 // will be tested in ProcessBranch. We need to explicitly bind 1822 // this value because a container can contain nil elements. 1823 // 1824 // FIXME: Eventually this logic should actually do dispatches to 1825 // 'countByEnumeratingWithState:objects:count:' (NSFastEnumeration). 1826 // This will require simulating a temporary NSFastEnumerationState, either 1827 // through an SVal or through the use of MemRegions. This value can 1828 // be affixed to the ObjCForCollectionStmt* instead of 0/1; when the loop 1829 // terminates we reclaim the temporary (it goes out of scope) and we 1830 // we can test if the SVal is 0 or if the MemRegion is null (depending 1831 // on what approach we take). 1832 // 1833 // For now: simulate (1) by assigning either a symbol or nil if the 1834 // container is empty. Thus this transfer function will by default 1835 // result in state splitting. 1836 1837 const Stmt* elem = S->getElement(); 1838 const GRState *state = GetState(Pred); 1839 SVal elementV; 1840 1841 if (const DeclStmt* DS = dyn_cast<DeclStmt>(elem)) { 1842 const VarDecl* elemD = cast<VarDecl>(DS->getSingleDecl()); 1843 assert(elemD->getInit() == 0); 1844 elementV = state->getLValue(elemD, Pred->getLocationContext()); 1845 } 1846 else { 1847 elementV = state->getSVal(elem); 1848 } 1849 1850 ExplodedNodeSet dstLocation; 1851 evalLocation(dstLocation, elem, Pred, state, elementV, NULL, false); 1852 1853 if (dstLocation.empty()) 1854 return; 1855 1856 for (ExplodedNodeSet::iterator NI = dstLocation.begin(), 1857 NE = dstLocation.end(); NI!=NE; ++NI) { 1858 Pred = *NI; 1859 const GRState *state = GetState(Pred); 1860 1861 // Handle the case where the container still has elements. 1862 SVal TrueV = svalBuilder.makeTruthVal(1); 1863 const GRState *hasElems = state->BindExpr(S, TrueV); 1864 1865 // Handle the case where the container has no elements. 1866 SVal FalseV = svalBuilder.makeTruthVal(0); 1867 const GRState *noElems = state->BindExpr(S, FalseV); 1868 1869 if (loc::MemRegionVal *MV = dyn_cast<loc::MemRegionVal>(&elementV)) 1870 if (const TypedRegion *R = dyn_cast<TypedRegion>(MV->getRegion())) { 1871 // FIXME: The proper thing to do is to really iterate over the 1872 // container. We will do this with dispatch logic to the store. 1873 // For now, just 'conjure' up a symbolic value. 1874 QualType T = R->getValueType(); 1875 assert(Loc::isLocType(T)); 1876 unsigned Count = Builder->getCurrentBlockCount(); 1877 SymbolRef Sym = SymMgr.getConjuredSymbol(elem, T, Count); 1878 SVal V = svalBuilder.makeLoc(Sym); 1879 hasElems = hasElems->bindLoc(elementV, V); 1880 1881 // Bind the location to 'nil' on the false branch. 1882 SVal nilV = svalBuilder.makeIntVal(0, T); 1883 noElems = noElems->bindLoc(elementV, nilV); 1884 } 1885 1886 // Create the new nodes. 1887 MakeNode(Dst, S, Pred, hasElems); 1888 MakeNode(Dst, S, Pred, noElems); 1889 } 1890 } 1891 1892 //===----------------------------------------------------------------------===// 1893 // Transfer function: Objective-C message expressions. 1894 //===----------------------------------------------------------------------===// 1895 1896 void ExprEngine::VisitObjCMessage(const ObjCMessage &msg, 1897 ExplodedNode *Pred, ExplodedNodeSet& Dst) { 1898 1899 // Handle the previsits checks. 1900 ExplodedNodeSet dstPrevisit; 1901 getCheckerManager().runCheckersForPreObjCMessage(dstPrevisit, Pred, 1902 msg, *this); 1903 1904 // Proceed with evaluate the message expression. 1905 ExplodedNodeSet dstEval; 1906 1907 for (ExplodedNodeSet::iterator DI = dstPrevisit.begin(), 1908 DE = dstPrevisit.end(); DI != DE; ++DI) { 1909 1910 ExplodedNode *Pred = *DI; 1911 bool RaisesException = false; 1912 unsigned oldSize = dstEval.size(); 1913 SaveAndRestore<bool> OldSink(Builder->BuildSinks); 1914 SaveOr OldHasGen(Builder->hasGeneratedNode); 1915 1916 if (const Expr *Receiver = msg.getInstanceReceiver()) { 1917 const GRState *state = GetState(Pred); 1918 SVal recVal = state->getSVal(Receiver); 1919 if (!recVal.isUndef()) { 1920 // Bifurcate the state into nil and non-nil ones. 1921 DefinedOrUnknownSVal receiverVal = cast<DefinedOrUnknownSVal>(recVal); 1922 1923 const GRState *notNilState, *nilState; 1924 llvm::tie(notNilState, nilState) = state->assume(receiverVal); 1925 1926 // There are three cases: can be nil or non-nil, must be nil, must be 1927 // non-nil. We ignore must be nil, and merge the rest two into non-nil. 1928 if (nilState && !notNilState) { 1929 dstEval.insert(Pred); 1930 continue; 1931 } 1932 1933 // Check if the "raise" message was sent. 1934 assert(notNilState); 1935 if (msg.getSelector() == RaiseSel) 1936 RaisesException = true; 1937 1938 // Check if we raise an exception. For now treat these as sinks. 1939 // Eventually we will want to handle exceptions properly. 1940 if (RaisesException) 1941 Builder->BuildSinks = true; 1942 1943 // Dispatch to plug-in transfer function. 1944 evalObjCMessage(dstEval, msg, Pred, notNilState); 1945 } 1946 } 1947 else if (const ObjCInterfaceDecl *Iface = msg.getReceiverInterface()) { 1948 IdentifierInfo* ClsName = Iface->getIdentifier(); 1949 Selector S = msg.getSelector(); 1950 1951 // Check for special instance methods. 1952 if (!NSExceptionII) { 1953 ASTContext& Ctx = getContext(); 1954 NSExceptionII = &Ctx.Idents.get("NSException"); 1955 } 1956 1957 if (ClsName == NSExceptionII) { 1958 enum { NUM_RAISE_SELECTORS = 2 }; 1959 1960 // Lazily create a cache of the selectors. 1961 if (!NSExceptionInstanceRaiseSelectors) { 1962 ASTContext& Ctx = getContext(); 1963 NSExceptionInstanceRaiseSelectors = 1964 new Selector[NUM_RAISE_SELECTORS]; 1965 SmallVector<IdentifierInfo*, NUM_RAISE_SELECTORS> II; 1966 unsigned idx = 0; 1967 1968 // raise:format: 1969 II.push_back(&Ctx.Idents.get("raise")); 1970 II.push_back(&Ctx.Idents.get("format")); 1971 NSExceptionInstanceRaiseSelectors[idx++] = 1972 Ctx.Selectors.getSelector(II.size(), &II[0]); 1973 1974 // raise:format::arguments: 1975 II.push_back(&Ctx.Idents.get("arguments")); 1976 NSExceptionInstanceRaiseSelectors[idx++] = 1977 Ctx.Selectors.getSelector(II.size(), &II[0]); 1978 } 1979 1980 for (unsigned i = 0; i < NUM_RAISE_SELECTORS; ++i) 1981 if (S == NSExceptionInstanceRaiseSelectors[i]) { 1982 RaisesException = true; 1983 break; 1984 } 1985 } 1986 1987 // Check if we raise an exception. For now treat these as sinks. 1988 // Eventually we will want to handle exceptions properly. 1989 if (RaisesException) 1990 Builder->BuildSinks = true; 1991 1992 // Dispatch to plug-in transfer function. 1993 evalObjCMessage(dstEval, msg, Pred, Builder->GetState(Pred)); 1994 } 1995 1996 // Handle the case where no nodes where generated. Auto-generate that 1997 // contains the updated state if we aren't generating sinks. 1998 if (!Builder->BuildSinks && dstEval.size() == oldSize && 1999 !Builder->hasGeneratedNode) 2000 MakeNode(dstEval, msg.getOriginExpr(), Pred, GetState(Pred)); 2001 } 2002 2003 // Finally, perform the post-condition check of the ObjCMessageExpr and store 2004 // the created nodes in 'Dst'. 2005 getCheckerManager().runCheckersForPostObjCMessage(Dst, dstEval, msg, *this); 2006 } 2007 2008 //===----------------------------------------------------------------------===// 2009 // Transfer functions: Miscellaneous statements. 2010 //===----------------------------------------------------------------------===// 2011 2012 void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex, 2013 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 2014 2015 ExplodedNodeSet dstPreStmt; 2016 getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this); 2017 2018 if (CastE->getCastKind() == CK_LValueToRValue || 2019 CastE->getCastKind() == CK_GetObjCProperty) { 2020 for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end(); 2021 I!=E; ++I) { 2022 ExplodedNode *subExprNode = *I; 2023 const GRState *state = GetState(subExprNode); 2024 evalLoad(Dst, CastE, subExprNode, state, state->getSVal(Ex)); 2025 } 2026 return; 2027 } 2028 2029 // All other casts. 2030 QualType T = CastE->getType(); 2031 QualType ExTy = Ex->getType(); 2032 2033 if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE)) 2034 T = ExCast->getTypeAsWritten(); 2035 2036 for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end(); 2037 I != E; ++I) { 2038 2039 Pred = *I; 2040 2041 switch (CastE->getCastKind()) { 2042 case CK_LValueToRValue: 2043 assert(false && "LValueToRValue casts handled earlier."); 2044 case CK_GetObjCProperty: 2045 assert(false && "GetObjCProperty casts handled earlier."); 2046 case CK_ToVoid: 2047 Dst.Add(Pred); 2048 continue; 2049 // The analyzer doesn't do anything special with these casts, 2050 // since it understands retain/release semantics already. 2051 case CK_ObjCProduceObject: 2052 case CK_ObjCConsumeObject: 2053 case CK_ObjCReclaimReturnedObject: // Fall-through. 2054 // True no-ops. 2055 case CK_NoOp: 2056 case CK_FunctionToPointerDecay: { 2057 // Copy the SVal of Ex to CastE. 2058 const GRState *state = GetState(Pred); 2059 SVal V = state->getSVal(Ex); 2060 state = state->BindExpr(CastE, V); 2061 MakeNode(Dst, CastE, Pred, state); 2062 continue; 2063 } 2064 case CK_Dependent: 2065 case CK_ArrayToPointerDecay: 2066 case CK_BitCast: 2067 case CK_LValueBitCast: 2068 case CK_IntegralCast: 2069 case CK_NullToPointer: 2070 case CK_IntegralToPointer: 2071 case CK_PointerToIntegral: 2072 case CK_PointerToBoolean: 2073 case CK_IntegralToBoolean: 2074 case CK_IntegralToFloating: 2075 case CK_FloatingToIntegral: 2076 case CK_FloatingToBoolean: 2077 case CK_FloatingCast: 2078 case CK_FloatingRealToComplex: 2079 case CK_FloatingComplexToReal: 2080 case CK_FloatingComplexToBoolean: 2081 case CK_FloatingComplexCast: 2082 case CK_FloatingComplexToIntegralComplex: 2083 case CK_IntegralRealToComplex: 2084 case CK_IntegralComplexToReal: 2085 case CK_IntegralComplexToBoolean: 2086 case CK_IntegralComplexCast: 2087 case CK_IntegralComplexToFloatingComplex: 2088 case CK_AnyPointerToObjCPointerCast: 2089 case CK_AnyPointerToBlockPointerCast: 2090 case CK_ObjCObjectLValueCast: { 2091 // Delegate to SValBuilder to process. 2092 const GRState* state = GetState(Pred); 2093 SVal V = state->getSVal(Ex); 2094 V = svalBuilder.evalCast(V, T, ExTy); 2095 state = state->BindExpr(CastE, V); 2096 MakeNode(Dst, CastE, Pred, state); 2097 continue; 2098 } 2099 case CK_DerivedToBase: 2100 case CK_UncheckedDerivedToBase: { 2101 // For DerivedToBase cast, delegate to the store manager. 2102 const GRState *state = GetState(Pred); 2103 SVal val = state->getSVal(Ex); 2104 val = getStoreManager().evalDerivedToBase(val, T); 2105 state = state->BindExpr(CastE, val); 2106 MakeNode(Dst, CastE, Pred, state); 2107 continue; 2108 } 2109 // Various C++ casts that are not handled yet. 2110 case CK_Dynamic: 2111 case CK_ToUnion: 2112 case CK_BaseToDerived: 2113 case CK_NullToMemberPointer: 2114 case CK_BaseToDerivedMemberPointer: 2115 case CK_DerivedToBaseMemberPointer: 2116 case CK_UserDefinedConversion: 2117 case CK_ConstructorConversion: 2118 case CK_VectorSplat: 2119 case CK_MemberPointerToBoolean: { 2120 // Recover some path-sensitivty by conjuring a new value. 2121 QualType resultType = CastE->getType(); 2122 if (CastE->isLValue()) 2123 resultType = getContext().getPointerType(resultType); 2124 2125 SVal result = 2126 svalBuilder.getConjuredSymbolVal(NULL, CastE, resultType, 2127 Builder->getCurrentBlockCount()); 2128 2129 const GRState *state = GetState(Pred)->BindExpr(CastE, result); 2130 MakeNode(Dst, CastE, Pred, state); 2131 continue; 2132 } 2133 } 2134 } 2135 } 2136 2137 void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr* CL, 2138 ExplodedNode* Pred, 2139 ExplodedNodeSet& Dst) { 2140 const InitListExpr* ILE 2141 = cast<InitListExpr>(CL->getInitializer()->IgnoreParens()); 2142 2143 const GRState* state = GetState(Pred); 2144 SVal ILV = state->getSVal(ILE); 2145 2146 const LocationContext *LC = Pred->getLocationContext(); 2147 state = state->bindCompoundLiteral(CL, LC, ILV); 2148 2149 if (CL->isLValue()) { 2150 MakeNode(Dst, CL, Pred, state->BindExpr(CL, state->getLValue(CL, LC))); 2151 } 2152 else 2153 MakeNode(Dst, CL, Pred, state->BindExpr(CL, ILV)); 2154 } 2155 2156 void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred, 2157 ExplodedNodeSet& Dst) { 2158 2159 // FIXME: static variables may have an initializer, but the second 2160 // time a function is called those values may not be current. 2161 // This may need to be reflected in the CFG. 2162 2163 // Assumption: The CFG has one DeclStmt per Decl. 2164 const Decl* D = *DS->decl_begin(); 2165 2166 if (!D || !isa<VarDecl>(D)) 2167 return; 2168 2169 2170 ExplodedNodeSet dstPreVisit; 2171 getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this); 2172 2173 const VarDecl *VD = dyn_cast<VarDecl>(D); 2174 2175 for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end(); 2176 I!=E; ++I) 2177 { 2178 ExplodedNode *N = *I; 2179 const GRState *state = GetState(N); 2180 2181 // Decls without InitExpr are not initialized explicitly. 2182 const LocationContext *LC = N->getLocationContext(); 2183 2184 if (const Expr *InitEx = VD->getInit()) { 2185 SVal InitVal = state->getSVal(InitEx); 2186 2187 // We bound the temp obj region to the CXXConstructExpr. Now recover 2188 // the lazy compound value when the variable is not a reference. 2189 if (AMgr.getLangOptions().CPlusPlus && VD->getType()->isRecordType() && 2190 !VD->getType()->isReferenceType() && isa<loc::MemRegionVal>(InitVal)){ 2191 InitVal = state->getSVal(cast<loc::MemRegionVal>(InitVal).getRegion()); 2192 assert(isa<nonloc::LazyCompoundVal>(InitVal)); 2193 } 2194 2195 // Recover some path-sensitivity if a scalar value evaluated to 2196 // UnknownVal. 2197 if ((InitVal.isUnknown() || 2198 !getConstraintManager().canReasonAbout(InitVal)) && 2199 !VD->getType()->isReferenceType()) { 2200 InitVal = svalBuilder.getConjuredSymbolVal(NULL, InitEx, 2201 Builder->getCurrentBlockCount()); 2202 } 2203 2204 evalBind(Dst, DS, N, state, 2205 loc::MemRegionVal(state->getRegion(VD, LC)), InitVal, true); 2206 } 2207 else { 2208 MakeNode(Dst, DS, N, state->bindDeclWithNoInit(state->getRegion(VD, LC))); 2209 } 2210 } 2211 } 2212 2213 void ExprEngine::VisitInitListExpr(const InitListExpr *IE, ExplodedNode *Pred, 2214 ExplodedNodeSet& Dst) { 2215 2216 const GRState* state = GetState(Pred); 2217 QualType T = getContext().getCanonicalType(IE->getType()); 2218 unsigned NumInitElements = IE->getNumInits(); 2219 2220 if (T->isArrayType() || T->isRecordType() || T->isVectorType()) { 2221 llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList(); 2222 2223 // Handle base case where the initializer has no elements. 2224 // e.g: static int* myArray[] = {}; 2225 if (NumInitElements == 0) { 2226 SVal V = svalBuilder.makeCompoundVal(T, vals); 2227 MakeNode(Dst, IE, Pred, state->BindExpr(IE, V)); 2228 return; 2229 } 2230 2231 for (InitListExpr::const_reverse_iterator it = IE->rbegin(), 2232 ei = IE->rend(); it != ei; ++it) { 2233 vals = getBasicVals().consVals(state->getSVal(cast<Expr>(*it)), vals); 2234 } 2235 2236 MakeNode(Dst, IE, Pred, 2237 state->BindExpr(IE, svalBuilder.makeCompoundVal(T, vals))); 2238 return; 2239 } 2240 2241 if (Loc::isLocType(T) || T->isIntegerType()) { 2242 assert(IE->getNumInits() == 1); 2243 const Expr *initEx = IE->getInit(0); 2244 MakeNode(Dst, IE, Pred, state->BindExpr(IE, state->getSVal(initEx))); 2245 return; 2246 } 2247 2248 llvm_unreachable("unprocessed InitListExpr type"); 2249 } 2250 2251 /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof(type). 2252 void ExprEngine::VisitUnaryExprOrTypeTraitExpr( 2253 const UnaryExprOrTypeTraitExpr* Ex, 2254 ExplodedNode* Pred, 2255 ExplodedNodeSet& Dst) { 2256 QualType T = Ex->getTypeOfArgument(); 2257 2258 if (Ex->getKind() == UETT_SizeOf) { 2259 if (!T->isIncompleteType() && !T->isConstantSizeType()) { 2260 assert(T->isVariableArrayType() && "Unknown non-constant-sized type."); 2261 2262 // FIXME: Add support for VLA type arguments, not just VLA expressions. 2263 // When that happens, we should probably refactor VLASizeChecker's code. 2264 if (Ex->isArgumentType()) { 2265 Dst.Add(Pred); 2266 return; 2267 } 2268 2269 // Get the size by getting the extent of the sub-expression. 2270 // First, visit the sub-expression to find its region. 2271 const Expr *Arg = Ex->getArgumentExpr(); 2272 const GRState *state = GetState(Pred); 2273 const MemRegion *MR = state->getSVal(Arg).getAsRegion(); 2274 2275 // If the subexpression can't be resolved to a region, we don't know 2276 // anything about its size. Just leave the state as is and continue. 2277 if (!MR) { 2278 Dst.Add(Pred); 2279 return; 2280 } 2281 2282 // The result is the extent of the VLA. 2283 SVal Extent = cast<SubRegion>(MR)->getExtent(svalBuilder); 2284 MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, Extent)); 2285 2286 return; 2287 } 2288 else if (T->getAs<ObjCObjectType>()) { 2289 // Some code tries to take the sizeof an ObjCObjectType, relying that 2290 // the compiler has laid out its representation. Just report Unknown 2291 // for these. 2292 Dst.Add(Pred); 2293 return; 2294 } 2295 } 2296 2297 Expr::EvalResult Result; 2298 Ex->Evaluate(Result, getContext()); 2299 CharUnits amt = CharUnits::fromQuantity(Result.Val.getInt().getZExtValue()); 2300 2301 MakeNode(Dst, Ex, Pred, 2302 GetState(Pred)->BindExpr(Ex, 2303 svalBuilder.makeIntVal(amt.getQuantity(), Ex->getType()))); 2304 } 2305 2306 void ExprEngine::VisitOffsetOfExpr(const OffsetOfExpr* OOE, 2307 ExplodedNode* Pred, ExplodedNodeSet& Dst) { 2308 Expr::EvalResult Res; 2309 if (OOE->Evaluate(Res, getContext()) && Res.Val.isInt()) { 2310 const APSInt &IV = Res.Val.getInt(); 2311 assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType())); 2312 assert(OOE->getType()->isIntegerType()); 2313 assert(IV.isSigned() == OOE->getType()->isSignedIntegerOrEnumerationType()); 2314 SVal X = svalBuilder.makeIntVal(IV); 2315 MakeNode(Dst, OOE, Pred, GetState(Pred)->BindExpr(OOE, X)); 2316 return; 2317 } 2318 // FIXME: Handle the case where __builtin_offsetof is not a constant. 2319 Dst.Add(Pred); 2320 } 2321 2322 void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, 2323 ExplodedNode* Pred, 2324 ExplodedNodeSet& Dst) { 2325 2326 switch (U->getOpcode()) { 2327 2328 default: 2329 break; 2330 2331 case UO_Real: { 2332 const Expr* Ex = U->getSubExpr()->IgnoreParens(); 2333 ExplodedNodeSet Tmp; 2334 Visit(Ex, Pred, Tmp); 2335 2336 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { 2337 2338 // FIXME: We don't have complex SValues yet. 2339 if (Ex->getType()->isAnyComplexType()) { 2340 // Just report "Unknown." 2341 Dst.Add(*I); 2342 continue; 2343 } 2344 2345 // For all other types, UO_Real is an identity operation. 2346 assert (U->getType() == Ex->getType()); 2347 const GRState* state = GetState(*I); 2348 MakeNode(Dst, U, *I, state->BindExpr(U, state->getSVal(Ex))); 2349 } 2350 2351 return; 2352 } 2353 2354 case UO_Imag: { 2355 2356 const Expr* Ex = U->getSubExpr()->IgnoreParens(); 2357 ExplodedNodeSet Tmp; 2358 Visit(Ex, Pred, Tmp); 2359 2360 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { 2361 // FIXME: We don't have complex SValues yet. 2362 if (Ex->getType()->isAnyComplexType()) { 2363 // Just report "Unknown." 2364 Dst.Add(*I); 2365 continue; 2366 } 2367 2368 // For all other types, UO_Imag returns 0. 2369 const GRState* state = GetState(*I); 2370 SVal X = svalBuilder.makeZeroVal(Ex->getType()); 2371 MakeNode(Dst, U, *I, state->BindExpr(U, X)); 2372 } 2373 2374 return; 2375 } 2376 2377 case UO_Plus: 2378 assert(!U->isLValue()); 2379 // FALL-THROUGH. 2380 case UO_Deref: 2381 case UO_AddrOf: 2382 case UO_Extension: { 2383 2384 // Unary "+" is a no-op, similar to a parentheses. We still have places 2385 // where it may be a block-level expression, so we need to 2386 // generate an extra node that just propagates the value of the 2387 // subexpression. 2388 2389 const Expr* Ex = U->getSubExpr()->IgnoreParens(); 2390 ExplodedNodeSet Tmp; 2391 Visit(Ex, Pred, Tmp); 2392 2393 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { 2394 const GRState* state = GetState(*I); 2395 MakeNode(Dst, U, *I, state->BindExpr(U, state->getSVal(Ex))); 2396 } 2397 2398 return; 2399 } 2400 2401 case UO_LNot: 2402 case UO_Minus: 2403 case UO_Not: { 2404 assert (!U->isLValue()); 2405 const Expr* Ex = U->getSubExpr()->IgnoreParens(); 2406 ExplodedNodeSet Tmp; 2407 Visit(Ex, Pred, Tmp); 2408 2409 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { 2410 const GRState* state = GetState(*I); 2411 2412 // Get the value of the subexpression. 2413 SVal V = state->getSVal(Ex); 2414 2415 if (V.isUnknownOrUndef()) { 2416 MakeNode(Dst, U, *I, state->BindExpr(U, V)); 2417 continue; 2418 } 2419 2420 // QualType DstT = getContext().getCanonicalType(U->getType()); 2421 // QualType SrcT = getContext().getCanonicalType(Ex->getType()); 2422 // 2423 // if (DstT != SrcT) // Perform promotions. 2424 // V = evalCast(V, DstT); 2425 // 2426 // if (V.isUnknownOrUndef()) { 2427 // MakeNode(Dst, U, *I, BindExpr(St, U, V)); 2428 // continue; 2429 // } 2430 2431 switch (U->getOpcode()) { 2432 default: 2433 assert(false && "Invalid Opcode."); 2434 break; 2435 2436 case UO_Not: 2437 // FIXME: Do we need to handle promotions? 2438 state = state->BindExpr(U, evalComplement(cast<NonLoc>(V))); 2439 break; 2440 2441 case UO_Minus: 2442 // FIXME: Do we need to handle promotions? 2443 state = state->BindExpr(U, evalMinus(cast<NonLoc>(V))); 2444 break; 2445 2446 case UO_LNot: 2447 2448 // C99 6.5.3.3: "The expression !E is equivalent to (0==E)." 2449 // 2450 // Note: technically we do "E == 0", but this is the same in the 2451 // transfer functions as "0 == E". 2452 SVal Result; 2453 2454 if (isa<Loc>(V)) { 2455 Loc X = svalBuilder.makeNull(); 2456 Result = evalBinOp(state, BO_EQ, cast<Loc>(V), X, 2457 U->getType()); 2458 } 2459 else { 2460 nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType())); 2461 Result = evalBinOp(state, BO_EQ, cast<NonLoc>(V), X, 2462 U->getType()); 2463 } 2464 2465 state = state->BindExpr(U, Result); 2466 2467 break; 2468 } 2469 2470 MakeNode(Dst, U, *I, state); 2471 } 2472 2473 return; 2474 } 2475 } 2476 2477 // Handle ++ and -- (both pre- and post-increment). 2478 assert (U->isIncrementDecrementOp()); 2479 ExplodedNodeSet Tmp; 2480 const Expr* Ex = U->getSubExpr()->IgnoreParens(); 2481 Visit(Ex, Pred, Tmp); 2482 2483 for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I) { 2484 2485 const GRState* state = GetState(*I); 2486 SVal loc = state->getSVal(Ex); 2487 2488 // Perform a load. 2489 ExplodedNodeSet Tmp2; 2490 evalLoad(Tmp2, Ex, *I, state, loc); 2491 2492 for (ExplodedNodeSet::iterator I2=Tmp2.begin(), E2=Tmp2.end();I2!=E2;++I2) { 2493 2494 state = GetState(*I2); 2495 SVal V2_untested = state->getSVal(Ex); 2496 2497 // Propagate unknown and undefined values. 2498 if (V2_untested.isUnknownOrUndef()) { 2499 MakeNode(Dst, U, *I2, state->BindExpr(U, V2_untested)); 2500 continue; 2501 } 2502 DefinedSVal V2 = cast<DefinedSVal>(V2_untested); 2503 2504 // Handle all other values. 2505 BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add 2506 : BO_Sub; 2507 2508 // If the UnaryOperator has non-location type, use its type to create the 2509 // constant value. If the UnaryOperator has location type, create the 2510 // constant with int type and pointer width. 2511 SVal RHS; 2512 2513 if (U->getType()->isAnyPointerType()) 2514 RHS = svalBuilder.makeArrayIndex(1); 2515 else 2516 RHS = svalBuilder.makeIntVal(1, U->getType()); 2517 2518 SVal Result = evalBinOp(state, Op, V2, RHS, U->getType()); 2519 2520 // Conjure a new symbol if necessary to recover precision. 2521 if (Result.isUnknown() || !getConstraintManager().canReasonAbout(Result)){ 2522 DefinedOrUnknownSVal SymVal = 2523 svalBuilder.getConjuredSymbolVal(NULL, Ex, 2524 Builder->getCurrentBlockCount()); 2525 Result = SymVal; 2526 2527 // If the value is a location, ++/-- should always preserve 2528 // non-nullness. Check if the original value was non-null, and if so 2529 // propagate that constraint. 2530 if (Loc::isLocType(U->getType())) { 2531 DefinedOrUnknownSVal Constraint = 2532 svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType())); 2533 2534 if (!state->assume(Constraint, true)) { 2535 // It isn't feasible for the original value to be null. 2536 // Propagate this constraint. 2537 Constraint = svalBuilder.evalEQ(state, SymVal, 2538 svalBuilder.makeZeroVal(U->getType())); 2539 2540 2541 state = state->assume(Constraint, false); 2542 assert(state); 2543 } 2544 } 2545 } 2546 2547 // Since the lvalue-to-rvalue conversion is explicit in the AST, 2548 // we bind an l-value if the operator is prefix and an lvalue (in C++). 2549 if (U->isLValue()) 2550 state = state->BindExpr(U, loc); 2551 else 2552 state = state->BindExpr(U, U->isPostfix() ? V2 : Result); 2553 2554 // Perform the store. 2555 evalStore(Dst, NULL, U, *I2, state, loc, Result); 2556 } 2557 } 2558 } 2559 2560 void ExprEngine::VisitAsmStmt(const AsmStmt* A, ExplodedNode* Pred, 2561 ExplodedNodeSet& Dst) { 2562 VisitAsmStmtHelperOutputs(A, A->begin_outputs(), A->end_outputs(), Pred, Dst); 2563 } 2564 2565 void ExprEngine::VisitAsmStmtHelperOutputs(const AsmStmt* A, 2566 AsmStmt::const_outputs_iterator I, 2567 AsmStmt::const_outputs_iterator E, 2568 ExplodedNode* Pred, ExplodedNodeSet& Dst) { 2569 if (I == E) { 2570 VisitAsmStmtHelperInputs(A, A->begin_inputs(), A->end_inputs(), Pred, Dst); 2571 return; 2572 } 2573 2574 ExplodedNodeSet Tmp; 2575 Visit(*I, Pred, Tmp); 2576 ++I; 2577 2578 for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end();NI != NE;++NI) 2579 VisitAsmStmtHelperOutputs(A, I, E, *NI, Dst); 2580 } 2581 2582 void ExprEngine::VisitAsmStmtHelperInputs(const AsmStmt* A, 2583 AsmStmt::const_inputs_iterator I, 2584 AsmStmt::const_inputs_iterator E, 2585 ExplodedNode* Pred, 2586 ExplodedNodeSet& Dst) { 2587 if (I == E) { 2588 2589 // We have processed both the inputs and the outputs. All of the outputs 2590 // should evaluate to Locs. Nuke all of their values. 2591 2592 // FIXME: Some day in the future it would be nice to allow a "plug-in" 2593 // which interprets the inline asm and stores proper results in the 2594 // outputs. 2595 2596 const GRState* state = GetState(Pred); 2597 2598 for (AsmStmt::const_outputs_iterator OI = A->begin_outputs(), 2599 OE = A->end_outputs(); OI != OE; ++OI) { 2600 2601 SVal X = state->getSVal(*OI); 2602 assert (!isa<NonLoc>(X)); // Should be an Lval, or unknown, undef. 2603 2604 if (isa<Loc>(X)) 2605 state = state->bindLoc(cast<Loc>(X), UnknownVal()); 2606 } 2607 2608 MakeNode(Dst, A, Pred, state); 2609 return; 2610 } 2611 2612 ExplodedNodeSet Tmp; 2613 Visit(*I, Pred, Tmp); 2614 2615 ++I; 2616 2617 for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end(); NI!=NE; ++NI) 2618 VisitAsmStmtHelperInputs(A, I, E, *NI, Dst); 2619 } 2620 2621 void ExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred, 2622 ExplodedNodeSet &Dst) { 2623 ExplodedNodeSet Src; 2624 if (const Expr *RetE = RS->getRetValue()) { 2625 // Record the returned expression in the state. It will be used in 2626 // processCallExit to bind the return value to the call expr. 2627 { 2628 static int tag = 0; 2629 const GRState *state = GetState(Pred); 2630 state = state->set<ReturnExpr>(RetE); 2631 Pred = Builder->generateNode(RetE, state, Pred, &tag); 2632 } 2633 // We may get a NULL Pred because we generated a cached node. 2634 if (Pred) 2635 Visit(RetE, Pred, Src); 2636 } 2637 else { 2638 Src.Add(Pred); 2639 } 2640 2641 ExplodedNodeSet CheckedSet; 2642 getCheckerManager().runCheckersForPreStmt(CheckedSet, Src, RS, *this); 2643 2644 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 2645 I != E; ++I) { 2646 2647 assert(Builder && "StmtNodeBuilder must be defined."); 2648 2649 Pred = *I; 2650 unsigned size = Dst.size(); 2651 2652 SaveAndRestore<bool> OldSink(Builder->BuildSinks); 2653 SaveOr OldHasGen(Builder->hasGeneratedNode); 2654 2655 getTF().evalReturn(Dst, *this, *Builder, RS, Pred); 2656 2657 // Handle the case where no nodes where generated. 2658 if (!Builder->BuildSinks && Dst.size() == size && 2659 !Builder->hasGeneratedNode) 2660 MakeNode(Dst, RS, Pred, GetState(Pred)); 2661 } 2662 } 2663 2664 //===----------------------------------------------------------------------===// 2665 // Transfer functions: Binary operators. 2666 //===----------------------------------------------------------------------===// 2667 2668 void ExprEngine::VisitBinaryOperator(const BinaryOperator* B, 2669 ExplodedNode* Pred, 2670 ExplodedNodeSet& Dst) { 2671 ExplodedNodeSet Tmp1; 2672 Expr* LHS = B->getLHS()->IgnoreParens(); 2673 Expr* RHS = B->getRHS()->IgnoreParens(); 2674 2675 Visit(LHS, Pred, Tmp1); 2676 ExplodedNodeSet Tmp3; 2677 2678 for (ExplodedNodeSet::iterator I1=Tmp1.begin(), E1=Tmp1.end(); I1!=E1; ++I1) { 2679 SVal LeftV = GetState(*I1)->getSVal(LHS); 2680 ExplodedNodeSet Tmp2; 2681 Visit(RHS, *I1, Tmp2); 2682 2683 ExplodedNodeSet CheckedSet; 2684 getCheckerManager().runCheckersForPreStmt(CheckedSet, Tmp2, B, *this); 2685 2686 // With both the LHS and RHS evaluated, process the operation itself. 2687 2688 for (ExplodedNodeSet::iterator I2=CheckedSet.begin(), E2=CheckedSet.end(); 2689 I2 != E2; ++I2) { 2690 2691 const GRState *state = GetState(*I2); 2692 SVal RightV = state->getSVal(RHS); 2693 2694 BinaryOperator::Opcode Op = B->getOpcode(); 2695 2696 if (Op == BO_Assign) { 2697 // EXPERIMENTAL: "Conjured" symbols. 2698 // FIXME: Handle structs. 2699 if (RightV.isUnknown() ||!getConstraintManager().canReasonAbout(RightV)) 2700 { 2701 unsigned Count = Builder->getCurrentBlockCount(); 2702 RightV = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), Count); 2703 } 2704 2705 SVal ExprVal = B->isLValue() ? LeftV : RightV; 2706 2707 // Simulate the effects of a "store": bind the value of the RHS 2708 // to the L-Value represented by the LHS. 2709 evalStore(Tmp3, B, LHS, *I2, state->BindExpr(B, ExprVal), LeftV,RightV); 2710 continue; 2711 } 2712 2713 if (!B->isAssignmentOp()) { 2714 // Process non-assignments except commas or short-circuited 2715 // logical expressions (LAnd and LOr). 2716 SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType()); 2717 2718 if (Result.isUnknown()) { 2719 MakeNode(Tmp3, B, *I2, state); 2720 continue; 2721 } 2722 2723 state = state->BindExpr(B, Result); 2724 2725 MakeNode(Tmp3, B, *I2, state); 2726 continue; 2727 } 2728 2729 assert (B->isCompoundAssignmentOp()); 2730 2731 switch (Op) { 2732 default: 2733 assert(0 && "Invalid opcode for compound assignment."); 2734 case BO_MulAssign: Op = BO_Mul; break; 2735 case BO_DivAssign: Op = BO_Div; break; 2736 case BO_RemAssign: Op = BO_Rem; break; 2737 case BO_AddAssign: Op = BO_Add; break; 2738 case BO_SubAssign: Op = BO_Sub; break; 2739 case BO_ShlAssign: Op = BO_Shl; break; 2740 case BO_ShrAssign: Op = BO_Shr; break; 2741 case BO_AndAssign: Op = BO_And; break; 2742 case BO_XorAssign: Op = BO_Xor; break; 2743 case BO_OrAssign: Op = BO_Or; break; 2744 } 2745 2746 // Perform a load (the LHS). This performs the checks for 2747 // null dereferences, and so on. 2748 ExplodedNodeSet Tmp4; 2749 SVal location = state->getSVal(LHS); 2750 evalLoad(Tmp4, LHS, *I2, state, location); 2751 2752 for (ExplodedNodeSet::iterator I4=Tmp4.begin(), E4=Tmp4.end(); I4!=E4; 2753 ++I4) { 2754 state = GetState(*I4); 2755 SVal V = state->getSVal(LHS); 2756 2757 // Get the computation type. 2758 QualType CTy = 2759 cast<CompoundAssignOperator>(B)->getComputationResultType(); 2760 CTy = getContext().getCanonicalType(CTy); 2761 2762 QualType CLHSTy = 2763 cast<CompoundAssignOperator>(B)->getComputationLHSType(); 2764 CLHSTy = getContext().getCanonicalType(CLHSTy); 2765 2766 QualType LTy = getContext().getCanonicalType(LHS->getType()); 2767 2768 // Promote LHS. 2769 V = svalBuilder.evalCast(V, CLHSTy, LTy); 2770 2771 // Compute the result of the operation. 2772 SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy), 2773 B->getType(), CTy); 2774 2775 // EXPERIMENTAL: "Conjured" symbols. 2776 // FIXME: Handle structs. 2777 2778 SVal LHSVal; 2779 2780 if (Result.isUnknown() || 2781 !getConstraintManager().canReasonAbout(Result)) { 2782 2783 unsigned Count = Builder->getCurrentBlockCount(); 2784 2785 // The symbolic value is actually for the type of the left-hand side 2786 // expression, not the computation type, as this is the value the 2787 // LValue on the LHS will bind to. 2788 LHSVal = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), LTy, Count); 2789 2790 // However, we need to convert the symbol to the computation type. 2791 Result = svalBuilder.evalCast(LHSVal, CTy, LTy); 2792 } 2793 else { 2794 // The left-hand side may bind to a different value then the 2795 // computation type. 2796 LHSVal = svalBuilder.evalCast(Result, LTy, CTy); 2797 } 2798 2799 // In C++, assignment and compound assignment operators return an 2800 // lvalue. 2801 if (B->isLValue()) 2802 state = state->BindExpr(B, location); 2803 else 2804 state = state->BindExpr(B, Result); 2805 2806 evalStore(Tmp3, B, LHS, *I4, state, location, LHSVal); 2807 } 2808 } 2809 } 2810 2811 getCheckerManager().runCheckersForPostStmt(Dst, Tmp3, B, *this); 2812 } 2813 2814 //===----------------------------------------------------------------------===// 2815 // Visualization. 2816 //===----------------------------------------------------------------------===// 2817 2818 #ifndef NDEBUG 2819 static ExprEngine* GraphPrintCheckerState; 2820 static SourceManager* GraphPrintSourceManager; 2821 2822 namespace llvm { 2823 template<> 2824 struct DOTGraphTraits<ExplodedNode*> : 2825 public DefaultDOTGraphTraits { 2826 2827 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 2828 2829 // FIXME: Since we do not cache error nodes in ExprEngine now, this does not 2830 // work. 2831 static std::string getNodeAttributes(const ExplodedNode* N, void*) { 2832 2833 #if 0 2834 // FIXME: Replace with a general scheme to tell if the node is 2835 // an error node. 2836 if (GraphPrintCheckerState->isImplicitNullDeref(N) || 2837 GraphPrintCheckerState->isExplicitNullDeref(N) || 2838 GraphPrintCheckerState->isUndefDeref(N) || 2839 GraphPrintCheckerState->isUndefStore(N) || 2840 GraphPrintCheckerState->isUndefControlFlow(N) || 2841 GraphPrintCheckerState->isUndefResult(N) || 2842 GraphPrintCheckerState->isBadCall(N) || 2843 GraphPrintCheckerState->isUndefArg(N)) 2844 return "color=\"red\",style=\"filled\""; 2845 2846 if (GraphPrintCheckerState->isNoReturnCall(N)) 2847 return "color=\"blue\",style=\"filled\""; 2848 #endif 2849 return ""; 2850 } 2851 2852 static std::string getNodeLabel(const ExplodedNode* N, void*){ 2853 2854 std::string sbuf; 2855 llvm::raw_string_ostream Out(sbuf); 2856 2857 // Program Location. 2858 ProgramPoint Loc = N->getLocation(); 2859 2860 switch (Loc.getKind()) { 2861 case ProgramPoint::BlockEntranceKind: 2862 Out << "Block Entrance: B" 2863 << cast<BlockEntrance>(Loc).getBlock()->getBlockID(); 2864 break; 2865 2866 case ProgramPoint::BlockExitKind: 2867 assert (false); 2868 break; 2869 2870 case ProgramPoint::CallEnterKind: 2871 Out << "CallEnter"; 2872 break; 2873 2874 case ProgramPoint::CallExitKind: 2875 Out << "CallExit"; 2876 break; 2877 2878 default: { 2879 if (StmtPoint *L = dyn_cast<StmtPoint>(&Loc)) { 2880 const Stmt* S = L->getStmt(); 2881 SourceLocation SLoc = S->getLocStart(); 2882 2883 Out << S->getStmtClassName() << ' ' << (void*) S << ' '; 2884 LangOptions LO; // FIXME. 2885 S->printPretty(Out, 0, PrintingPolicy(LO)); 2886 2887 if (SLoc.isFileID()) { 2888 Out << "\\lline=" 2889 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 2890 << " col=" 2891 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc) 2892 << "\\l"; 2893 } 2894 2895 if (isa<PreStmt>(Loc)) 2896 Out << "\\lPreStmt\\l;"; 2897 else if (isa<PostLoad>(Loc)) 2898 Out << "\\lPostLoad\\l;"; 2899 else if (isa<PostStore>(Loc)) 2900 Out << "\\lPostStore\\l"; 2901 else if (isa<PostLValue>(Loc)) 2902 Out << "\\lPostLValue\\l"; 2903 2904 #if 0 2905 // FIXME: Replace with a general scheme to determine 2906 // the name of the check. 2907 if (GraphPrintCheckerState->isImplicitNullDeref(N)) 2908 Out << "\\|Implicit-Null Dereference.\\l"; 2909 else if (GraphPrintCheckerState->isExplicitNullDeref(N)) 2910 Out << "\\|Explicit-Null Dereference.\\l"; 2911 else if (GraphPrintCheckerState->isUndefDeref(N)) 2912 Out << "\\|Dereference of undefialied value.\\l"; 2913 else if (GraphPrintCheckerState->isUndefStore(N)) 2914 Out << "\\|Store to Undefined Loc."; 2915 else if (GraphPrintCheckerState->isUndefResult(N)) 2916 Out << "\\|Result of operation is undefined."; 2917 else if (GraphPrintCheckerState->isNoReturnCall(N)) 2918 Out << "\\|Call to function marked \"noreturn\"."; 2919 else if (GraphPrintCheckerState->isBadCall(N)) 2920 Out << "\\|Call to NULL/Undefined."; 2921 else if (GraphPrintCheckerState->isUndefArg(N)) 2922 Out << "\\|Argument in call is undefined"; 2923 #endif 2924 2925 break; 2926 } 2927 2928 const BlockEdge& E = cast<BlockEdge>(Loc); 2929 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B" 2930 << E.getDst()->getBlockID() << ')'; 2931 2932 if (const Stmt* T = E.getSrc()->getTerminator()) { 2933 2934 SourceLocation SLoc = T->getLocStart(); 2935 2936 Out << "\\|Terminator: "; 2937 LangOptions LO; // FIXME. 2938 E.getSrc()->printTerminator(Out, LO); 2939 2940 if (SLoc.isFileID()) { 2941 Out << "\\lline=" 2942 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 2943 << " col=" 2944 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc); 2945 } 2946 2947 if (isa<SwitchStmt>(T)) { 2948 const Stmt* Label = E.getDst()->getLabel(); 2949 2950 if (Label) { 2951 if (const CaseStmt* C = dyn_cast<CaseStmt>(Label)) { 2952 Out << "\\lcase "; 2953 LangOptions LO; // FIXME. 2954 C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO)); 2955 2956 if (const Stmt* RHS = C->getRHS()) { 2957 Out << " .. "; 2958 RHS->printPretty(Out, 0, PrintingPolicy(LO)); 2959 } 2960 2961 Out << ":"; 2962 } 2963 else { 2964 assert (isa<DefaultStmt>(Label)); 2965 Out << "\\ldefault:"; 2966 } 2967 } 2968 else 2969 Out << "\\l(implicit) default:"; 2970 } 2971 else if (isa<IndirectGotoStmt>(T)) { 2972 // FIXME 2973 } 2974 else { 2975 Out << "\\lCondition: "; 2976 if (*E.getSrc()->succ_begin() == E.getDst()) 2977 Out << "true"; 2978 else 2979 Out << "false"; 2980 } 2981 2982 Out << "\\l"; 2983 } 2984 2985 #if 0 2986 // FIXME: Replace with a general scheme to determine 2987 // the name of the check. 2988 if (GraphPrintCheckerState->isUndefControlFlow(N)) { 2989 Out << "\\|Control-flow based on\\lUndefined value.\\l"; 2990 } 2991 #endif 2992 } 2993 } 2994 2995 const GRState *state = N->getState(); 2996 Out << "\\|StateID: " << (void*) state 2997 << " NodeID: " << (void*) N << "\\|"; 2998 state->printDOT(Out, *N->getLocationContext()->getCFG()); 2999 Out << "\\l"; 3000 return Out.str(); 3001 } 3002 }; 3003 } // end llvm namespace 3004 #endif 3005 3006 #ifndef NDEBUG 3007 template <typename ITERATOR> 3008 ExplodedNode* GetGraphNode(ITERATOR I) { return *I; } 3009 3010 template <> ExplodedNode* 3011 GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator> 3012 (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) { 3013 return I->first; 3014 } 3015 #endif 3016 3017 void ExprEngine::ViewGraph(bool trim) { 3018 #ifndef NDEBUG 3019 if (trim) { 3020 std::vector<ExplodedNode*> Src; 3021 3022 // Flush any outstanding reports to make sure we cover all the nodes. 3023 // This does not cause them to get displayed. 3024 for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I) 3025 const_cast<BugType*>(*I)->FlushReports(BR); 3026 3027 // Iterate through the reports and get their nodes. 3028 for (BugReporter::EQClasses_iterator 3029 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) { 3030 BugReportEquivClass& EQ = *EI; 3031 const BugReport &R = **EQ.begin(); 3032 ExplodedNode *N = const_cast<ExplodedNode*>(R.getErrorNode()); 3033 if (N) Src.push_back(N); 3034 } 3035 3036 ViewGraph(&Src[0], &Src[0]+Src.size()); 3037 } 3038 else { 3039 GraphPrintCheckerState = this; 3040 GraphPrintSourceManager = &getContext().getSourceManager(); 3041 3042 llvm::ViewGraph(*G.roots_begin(), "ExprEngine"); 3043 3044 GraphPrintCheckerState = NULL; 3045 GraphPrintSourceManager = NULL; 3046 } 3047 #endif 3048 } 3049 3050 void ExprEngine::ViewGraph(ExplodedNode** Beg, ExplodedNode** End) { 3051 #ifndef NDEBUG 3052 GraphPrintCheckerState = this; 3053 GraphPrintSourceManager = &getContext().getSourceManager(); 3054 3055 std::auto_ptr<ExplodedGraph> TrimmedG(G.Trim(Beg, End).first); 3056 3057 if (!TrimmedG.get()) 3058 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n"; 3059 else 3060 llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine"); 3061 3062 GraphPrintCheckerState = NULL; 3063 GraphPrintSourceManager = NULL; 3064 #endif 3065 } 3066