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