clang API Documentation
00001 //=-- GRExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- C++ -*-= 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file defines a meta-engine for path-sensitive dataflow analysis that 00011 // is built on GREngine, but provides the boilerplate to execute transfer 00012 // functions and build the ExplodedGraph at the expression level. 00013 // 00014 //===----------------------------------------------------------------------===// 00015 #include "GRExprEngineInternalChecks.h" 00016 #include "clang/Checker/BugReporter/BugType.h" 00017 #include "clang/Checker/PathSensitive/AnalysisManager.h" 00018 #include "clang/Checker/PathSensitive/GRExprEngine.h" 00019 #include "clang/Checker/PathSensitive/GRExprEngineBuilders.h" 00020 #include "clang/Checker/PathSensitive/Checker.h" 00021 #include "clang/AST/CharUnits.h" 00022 #include "clang/AST/ParentMap.h" 00023 #include "clang/AST/StmtObjC.h" 00024 #include "clang/AST/DeclCXX.h" 00025 #include "clang/Basic/Builtins.h" 00026 #include "clang/Basic/SourceManager.h" 00027 #include "clang/Basic/SourceManager.h" 00028 #include "clang/Basic/PrettyStackTrace.h" 00029 #include "llvm/Support/raw_ostream.h" 00030 #include "llvm/ADT/ImmutableList.h" 00031 00032 #ifndef NDEBUG 00033 #include "llvm/Support/GraphWriter.h" 00034 #endif 00035 00036 using namespace clang; 00037 using llvm::dyn_cast; 00038 using llvm::dyn_cast_or_null; 00039 using llvm::cast; 00040 using llvm::APSInt; 00041 00042 namespace { 00043 // Trait class for recording returned expression in the state. 00044 struct ReturnExpr { 00045 static int TagInt; 00046 typedef const Stmt *data_type; 00047 }; 00048 int ReturnExpr::TagInt; 00049 } 00050 00051 //===----------------------------------------------------------------------===// 00052 // Utility functions. 00053 //===----------------------------------------------------------------------===// 00054 00055 static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) { 00056 IdentifierInfo* II = &Ctx.Idents.get(name); 00057 return Ctx.Selectors.getSelector(0, &II); 00058 } 00059 00060 //===----------------------------------------------------------------------===// 00061 // Checker worklist routines. 00062 //===----------------------------------------------------------------------===// 00063 00064 void GRExprEngine::CheckerVisit(const Stmt *S, ExplodedNodeSet &Dst, 00065 ExplodedNodeSet &Src, CallbackKind Kind) { 00066 00067 // Determine if we already have a cached 'CheckersOrdered' vector 00068 // specifically tailored for the provided <CallbackKind, Stmt kind>. This 00069 // can reduce the number of checkers actually called. 00070 CheckersOrdered *CO = &Checkers; 00071 llvm::OwningPtr<CheckersOrdered> NewCO; 00072 00073 // The cache key is made up of the and the callback kind (pre- or post-visit) 00074 // and the statement kind. 00075 CallbackTag K = GetCallbackTag(Kind, S->getStmtClass()); 00076 00077 CheckersOrdered *& CO_Ref = COCache[K]; 00078 00079 if (!CO_Ref) { 00080 // If we have no previously cached CheckersOrdered vector for this 00081 // statement kind, then create one. 00082 NewCO.reset(new CheckersOrdered); 00083 } 00084 else { 00085 // Use the already cached set. 00086 CO = CO_Ref; 00087 } 00088 00089 if (CO->empty()) { 00090 // If there are no checkers, return early without doing any 00091 // more work. 00092 Dst.insert(Src); 00093 return; 00094 } 00095 00096 ExplodedNodeSet Tmp; 00097 ExplodedNodeSet *PrevSet = &Src; 00098 unsigned checkersEvaluated = 0; 00099 00100 for (CheckersOrdered::iterator I=CO->begin(), E=CO->end(); I!=E; ++I) { 00101 // If all nodes are sunk, bail out early. 00102 if (PrevSet->empty()) 00103 break; 00104 ExplodedNodeSet *CurrSet = 0; 00105 if (I+1 == E) 00106 CurrSet = &Dst; 00107 else { 00108 CurrSet = (PrevSet == &Tmp) ? &Src : &Tmp; 00109 CurrSet->clear(); 00110 } 00111 void *tag = I->first; 00112 Checker *checker = I->second; 00113 bool respondsToCallback = true; 00114 00115 for (ExplodedNodeSet::iterator NI = PrevSet->begin(), NE = PrevSet->end(); 00116 NI != NE; ++NI) { 00117 00118 checker->GR_Visit(*CurrSet, *Builder, *this, S, *NI, tag, 00119 Kind == PreVisitStmtCallback, respondsToCallback); 00120 00121 } 00122 00123 PrevSet = CurrSet; 00124 00125 if (NewCO.get()) { 00126 ++checkersEvaluated; 00127 if (respondsToCallback) 00128 NewCO->push_back(*I); 00129 } 00130 } 00131 00132 // If we built NewCO, check if we called all the checkers. This is important 00133 // so that we know that we accurately determined the entire set of checkers 00134 // that responds to this callback. Note that 'checkersEvaluated' might 00135 // not be the same as Checkers.size() if one of the Checkers generates 00136 // a sink node. 00137 if (NewCO.get() && checkersEvaluated == Checkers.size()) 00138 CO_Ref = NewCO.take(); 00139 00140 // Don't autotransition. The CheckerContext objects should do this 00141 // automatically. 00142 } 00143 00144 void GRExprEngine::CheckerEvalNilReceiver(const ObjCMessageExpr *ME, 00145 ExplodedNodeSet &Dst, 00146 const GRState *state, 00147 ExplodedNode *Pred) { 00148 bool evaluated = false; 00149 ExplodedNodeSet DstTmp; 00150 00151 for (CheckersOrdered::iterator I=Checkers.begin(),E=Checkers.end();I!=E;++I) { 00152 void *tag = I->first; 00153 Checker *checker = I->second; 00154 00155 if (checker->GR_evalNilReceiver(DstTmp, *Builder, *this, ME, Pred, state, 00156 tag)) { 00157 evaluated = true; 00158 break; 00159 } else 00160 // The checker didn't evaluate the expr. Restore the Dst. 00161 DstTmp.clear(); 00162 } 00163 00164 if (evaluated) 00165 Dst.insert(DstTmp); 00166 else 00167 Dst.insert(Pred); 00168 } 00169 00170 // CheckerEvalCall returns true if one of the checkers processed the node. 00171 // This may return void when all call evaluation logic goes to some checker 00172 // in the future. 00173 bool GRExprEngine::CheckerEvalCall(const CallExpr *CE, 00174 ExplodedNodeSet &Dst, 00175 ExplodedNode *Pred) { 00176 bool evaluated = false; 00177 ExplodedNodeSet DstTmp; 00178 00179 for (CheckersOrdered::iterator I=Checkers.begin(),E=Checkers.end();I!=E;++I) { 00180 void *tag = I->first; 00181 Checker *checker = I->second; 00182 00183 if (checker->GR_evalCallExpr(DstTmp, *Builder, *this, CE, Pred, tag)) { 00184 evaluated = true; 00185 break; 00186 } else 00187 // The checker didn't evaluate the expr. Restore the DstTmp set. 00188 DstTmp.clear(); 00189 } 00190 00191 if (evaluated) 00192 Dst.insert(DstTmp); 00193 else 00194 Dst.insert(Pred); 00195 00196 return evaluated; 00197 } 00198 00199 // FIXME: This is largely copy-paste from CheckerVisit(). Need to 00200 // unify. 00201 void GRExprEngine::CheckerVisitBind(const Stmt *StoreE, ExplodedNodeSet &Dst, 00202 ExplodedNodeSet &Src, SVal location, 00203 SVal val, bool isPrevisit) { 00204 00205 if (Checkers.empty()) { 00206 Dst.insert(Src); 00207 return; 00208 } 00209 00210 ExplodedNodeSet Tmp; 00211 ExplodedNodeSet *PrevSet = &Src; 00212 00213 for (CheckersOrdered::iterator I=Checkers.begin(),E=Checkers.end(); I!=E; ++I) 00214 { 00215 ExplodedNodeSet *CurrSet = 0; 00216 if (I+1 == E) 00217 CurrSet = &Dst; 00218 else { 00219 CurrSet = (PrevSet == &Tmp) ? &Src : &Tmp; 00220 CurrSet->clear(); 00221 } 00222 00223 void *tag = I->first; 00224 Checker *checker = I->second; 00225 00226 for (ExplodedNodeSet::iterator NI = PrevSet->begin(), NE = PrevSet->end(); 00227 NI != NE; ++NI) 00228 checker->GR_VisitBind(*CurrSet, *Builder, *this, StoreE, 00229 *NI, tag, location, val, isPrevisit); 00230 00231 // Update which NodeSet is the current one. 00232 PrevSet = CurrSet; 00233 } 00234 00235 // Don't autotransition. The CheckerContext objects should do this 00236 // automatically. 00237 } 00238 //===----------------------------------------------------------------------===// 00239 // Engine construction and deletion. 00240 //===----------------------------------------------------------------------===// 00241 00242 static void RegisterInternalChecks(GRExprEngine &Eng) { 00243 // Register internal "built-in" BugTypes with the BugReporter. These BugTypes 00244 // are different than what probably many checks will do since they don't 00245 // create BugReports on-the-fly but instead wait until GRExprEngine finishes 00246 // analyzing a function. Generation of BugReport objects is done via a call 00247 // to 'FlushReports' from BugReporter. 00248 // The following checks do not need to have their associated BugTypes 00249 // explicitly registered with the BugReporter. If they issue any BugReports, 00250 // their associated BugType will get registered with the BugReporter 00251 // automatically. Note that the check itself is owned by the GRExprEngine 00252 // object. 00253 RegisterAdjustedReturnValueChecker(Eng); 00254 // CallAndMessageChecker should be registered before AttrNonNullChecker, 00255 // where we assume arguments are not undefined. 00256 RegisterCallAndMessageChecker(Eng); 00257 RegisterAttrNonNullChecker(Eng); 00258 RegisterDereferenceChecker(Eng); 00259 RegisterVLASizeChecker(Eng); 00260 RegisterDivZeroChecker(Eng); 00261 RegisterReturnUndefChecker(Eng); 00262 RegisterUndefinedArraySubscriptChecker(Eng); 00263 RegisterUndefinedAssignmentChecker(Eng); 00264 RegisterUndefBranchChecker(Eng); 00265 RegisterUndefCapturedBlockVarChecker(Eng); 00266 RegisterUndefResultChecker(Eng); 00267 RegisterStackAddrLeakChecker(Eng); 00268 RegisterObjCAtSyncChecker(Eng); 00269 00270 // This is not a checker yet. 00271 RegisterNoReturnFunctionChecker(Eng); 00272 RegisterBuiltinFunctionChecker(Eng); 00273 RegisterOSAtomicChecker(Eng); 00274 RegisterUnixAPIChecker(Eng); 00275 RegisterMacOSXAPIChecker(Eng); 00276 } 00277 00278 GRExprEngine::GRExprEngine(AnalysisManager &mgr, GRTransferFuncs *tf) 00279 : AMgr(mgr), 00280 CoreEngine(*this), 00281 G(CoreEngine.getGraph()), 00282 Builder(NULL), 00283 StateMgr(getContext(), mgr.getStoreManagerCreator(), 00284 mgr.getConstraintManagerCreator(), G.getAllocator(), 00285 *this), 00286 SymMgr(StateMgr.getSymbolManager()), 00287 svalBuilder(StateMgr.getSValBuilder()), 00288 EntryNode(NULL), currentStmt(NULL), 00289 NSExceptionII(NULL), NSExceptionInstanceRaiseSelectors(NULL), 00290 RaiseSel(GetNullarySelector("raise", getContext())), 00291 BR(mgr, *this), TF(tf) { 00292 // Register internal checks. 00293 RegisterInternalChecks(*this); 00294 00295 // FIXME: Eventually remove the TF object entirely. 00296 TF->RegisterChecks(*this); 00297 TF->RegisterPrinters(getStateManager().Printers); 00298 } 00299 00300 GRExprEngine::~GRExprEngine() { 00301 BR.FlushReports(); 00302 delete [] NSExceptionInstanceRaiseSelectors; 00303 00304 // Delete the set of checkers. 00305 for (CheckersOrdered::iterator I=Checkers.begin(), E=Checkers.end(); I!=E;++I) 00306 delete I->second; 00307 00308 for (CheckersOrderedCache::iterator I=COCache.begin(), E=COCache.end(); 00309 I!=E;++I) 00310 delete I->second; 00311 } 00312 00313 //===----------------------------------------------------------------------===// 00314 // Utility methods. 00315 //===----------------------------------------------------------------------===// 00316 00317 const GRState* GRExprEngine::getInitialState(const LocationContext *InitLoc) { 00318 const GRState *state = StateMgr.getInitialState(InitLoc); 00319 00320 // Preconditions. 00321 00322 // FIXME: It would be nice if we had a more general mechanism to add 00323 // such preconditions. Some day. 00324 do { 00325 const Decl *D = InitLoc->getDecl(); 00326 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 00327 // Precondition: the first argument of 'main' is an integer guaranteed 00328 // to be > 0. 00329 const IdentifierInfo *II = FD->getIdentifier(); 00330 if (!II || !(II->getName() == "main" && FD->getNumParams() > 0)) 00331 break; 00332 00333 const ParmVarDecl *PD = FD->getParamDecl(0); 00334 QualType T = PD->getType(); 00335 if (!T->isIntegerType()) 00336 break; 00337 00338 const MemRegion *R = state->getRegion(PD, InitLoc); 00339 if (!R) 00340 break; 00341 00342 SVal V = state->getSVal(loc::MemRegionVal(R)); 00343 SVal Constraint_untested = evalBinOp(state, BO_GT, V, 00344 svalBuilder.makeZeroVal(T), 00345 getContext().IntTy); 00346 00347 DefinedOrUnknownSVal *Constraint = 00348 dyn_cast<DefinedOrUnknownSVal>(&Constraint_untested); 00349 00350 if (!Constraint) 00351 break; 00352 00353 if (const GRState *newState = state->assume(*Constraint, true)) 00354 state = newState; 00355 00356 break; 00357 } 00358 00359 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 00360 // Precondition: 'self' is always non-null upon entry to an Objective-C 00361 // method. 00362 const ImplicitParamDecl *SelfD = MD->getSelfDecl(); 00363 const MemRegion *R = state->getRegion(SelfD, InitLoc); 00364 SVal V = state->getSVal(loc::MemRegionVal(R)); 00365 00366 if (const Loc *LV = dyn_cast<Loc>(&V)) { 00367 // Assume that the pointer value in 'self' is non-null. 00368 state = state->assume(*LV, true); 00369 assert(state && "'self' cannot be null"); 00370 } 00371 } 00372 } while (0); 00373 00374 return state; 00375 } 00376 00377 //===----------------------------------------------------------------------===// 00378 // Top-level transfer function logic (Dispatcher). 00379 //===----------------------------------------------------------------------===// 00380 00381 /// evalAssume - Called by ConstraintManager. Used to call checker-specific 00382 /// logic for handling assumptions on symbolic values. 00383 const GRState *GRExprEngine::ProcessAssume(const GRState *state, SVal cond, 00384 bool assumption) { 00385 // Determine if we already have a cached 'CheckersOrdered' vector 00386 // specifically tailored for processing assumptions. This 00387 // can reduce the number of checkers actually called. 00388 CheckersOrdered *CO = &Checkers; 00389 llvm::OwningPtr<CheckersOrdered> NewCO; 00390 00391 CallbackTag K = GetCallbackTag(ProcessAssumeCallback); 00392 CheckersOrdered *& CO_Ref = COCache[K]; 00393 00394 if (!CO_Ref) { 00395 // If we have no previously cached CheckersOrdered vector for this 00396 // statement kind, then create one. 00397 NewCO.reset(new CheckersOrdered); 00398 } 00399 else { 00400 // Use the already cached set. 00401 CO = CO_Ref; 00402 } 00403 00404 if (!CO->empty()) { 00405 // Let the checkers have a crack at the assume before the transfer functions 00406 // get their turn. 00407 for (CheckersOrdered::iterator I = CO->begin(), E = CO->end(); I!=E; ++I) { 00408 00409 // If any checker declares the state infeasible (or if it starts that 00410 // way), bail out. 00411 if (!state) 00412 return NULL; 00413 00414 Checker *C = I->second; 00415 bool respondsToCallback = true; 00416 00417 state = C->evalAssume(state, cond, assumption, &respondsToCallback); 00418 00419 // Check if we're building the cache of checkers that care about 00420 // assumptions. 00421 if (NewCO.get() && respondsToCallback) 00422 NewCO->push_back(*I); 00423 } 00424 00425 // If we got through all the checkers, and we built a list of those that 00426 // care about assumptions, save it. 00427 if (NewCO.get()) 00428 CO_Ref = NewCO.take(); 00429 } 00430 00431 // If the state is infeasible at this point, bail out. 00432 if (!state) 00433 return NULL; 00434 00435 return TF->evalAssume(state, cond, assumption); 00436 } 00437 00438 bool GRExprEngine::WantsRegionChangeUpdate(const GRState* state) { 00439 CallbackTag K = GetCallbackTag(EvalRegionChangesCallback); 00440 CheckersOrdered *CO = COCache[K]; 00441 00442 if (!CO) 00443 CO = &Checkers; 00444 00445 for (CheckersOrdered::iterator I = CO->begin(), E = CO->end(); I != E; ++I) { 00446 Checker *C = I->second; 00447 if (C->WantsRegionChangeUpdate(state)) 00448 return true; 00449 } 00450 00451 return false; 00452 } 00453 00454 const GRState * 00455 GRExprEngine::ProcessRegionChanges(const GRState *state, 00456 const MemRegion * const *Begin, 00457 const MemRegion * const *End) { 00458 // FIXME: Most of this method is copy-pasted from ProcessAssume. 00459 00460 // Determine if we already have a cached 'CheckersOrdered' vector 00461 // specifically tailored for processing region changes. This 00462 // can reduce the number of checkers actually called. 00463 CheckersOrdered *CO = &Checkers; 00464 llvm::OwningPtr<CheckersOrdered> NewCO; 00465 00466 CallbackTag K = GetCallbackTag(EvalRegionChangesCallback); 00467 CheckersOrdered *& CO_Ref = COCache[K]; 00468 00469 if (!CO_Ref) { 00470 // If we have no previously cached CheckersOrdered vector for this 00471 // callback, then create one. 00472 NewCO.reset(new CheckersOrdered); 00473 } 00474 else { 00475 // Use the already cached set. 00476 CO = CO_Ref; 00477 } 00478 00479 // If there are no checkers, just return the state as is. 00480 if (CO->empty()) 00481 return state; 00482 00483 for (CheckersOrdered::iterator I = CO->begin(), E = CO->end(); I != E; ++I) { 00484 // If any checker declares the state infeasible (or if it starts that way), 00485 // bail out. 00486 if (!state) 00487 return NULL; 00488 00489 Checker *C = I->second; 00490 bool respondsToCallback = true; 00491 00492 state = C->EvalRegionChanges(state, Begin, End, &respondsToCallback); 00493 00494 // See if we're building a cache of checkers that care about region changes. 00495 if (NewCO.get() && respondsToCallback) 00496 NewCO->push_back(*I); 00497 } 00498 00499 // If we got through all the checkers, and we built a list of those that 00500 // care about region changes, save it. 00501 if (NewCO.get()) 00502 CO_Ref = NewCO.take(); 00503 00504 return state; 00505 } 00506 00507 void GRExprEngine::ProcessEndWorklist(bool hasWorkRemaining) { 00508 for (CheckersOrdered::iterator I = Checkers.begin(), E = Checkers.end(); 00509 I != E; ++I) { 00510 I->second->VisitEndAnalysis(G, BR, *this); 00511 } 00512 } 00513 00514 void GRExprEngine::ProcessElement(const CFGElement E, 00515 GRStmtNodeBuilder& builder) { 00516 switch (E.getKind()) { 00517 case CFGElement::Statement: 00518 ProcessStmt(E.getAs<CFGStmt>(), builder); 00519 break; 00520 case CFGElement::Initializer: 00521 ProcessInitializer(E.getAs<CFGInitializer>(), builder); 00522 break; 00523 case CFGElement::ImplicitDtor: 00524 ProcessImplicitDtor(E.getAs<CFGImplicitDtor>(), builder); 00525 break; 00526 default: 00527 // Suppress compiler warning. 00528 llvm_unreachable("Unexpected CFGElement kind."); 00529 } 00530 } 00531 00532 void GRExprEngine::ProcessStmt(const CFGStmt S, GRStmtNodeBuilder& builder) { 00533 currentStmt = S.getStmt(); 00534 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 00535 currentStmt->getLocStart(), 00536 "Error evaluating statement"); 00537 00538 Builder = &builder; 00539 EntryNode = builder.getBasePredecessor(); 00540 00541 // Create the cleaned state. 00542 const LocationContext *LC = EntryNode->getLocationContext(); 00543 SymbolReaper SymReaper(LC, currentStmt, SymMgr); 00544 00545 if (AMgr.shouldPurgeDead()) { 00546 const GRState *St = EntryNode->getState(); 00547 00548 for (CheckersOrdered::iterator I = Checkers.begin(), E = Checkers.end(); 00549 I != E; ++I) { 00550 Checker *checker = I->second; 00551 checker->MarkLiveSymbols(St, SymReaper); 00552 } 00553 00554 const StackFrameContext *SFC = LC->getCurrentStackFrame(); 00555 CleanedState = StateMgr.RemoveDeadBindings(St, SFC, SymReaper); 00556 } else { 00557 CleanedState = EntryNode->getState(); 00558 } 00559 00560 // Process any special transfer function for dead symbols. 00561 ExplodedNodeSet Tmp; 00562 00563 if (!SymReaper.hasDeadSymbols()) 00564 Tmp.Add(EntryNode); 00565 else { 00566 SaveAndRestore<bool> OldSink(Builder->BuildSinks); 00567 SaveOr OldHasGen(Builder->HasGeneratedNode); 00568 00569 SaveAndRestore<bool> OldPurgeDeadSymbols(Builder->PurgingDeadSymbols); 00570 Builder->PurgingDeadSymbols = true; 00571 00572 // FIXME: This should soon be removed. 00573 ExplodedNodeSet Tmp2; 00574 getTF().evalDeadSymbols(Tmp2, *this, *Builder, EntryNode, 00575 CleanedState, SymReaper); 00576 00577 if (Checkers.empty()) 00578 Tmp.insert(Tmp2); 00579 else { 00580 ExplodedNodeSet Tmp3; 00581 ExplodedNodeSet *SrcSet = &Tmp2; 00582 for (CheckersOrdered::iterator I = Checkers.begin(), E = Checkers.end(); 00583 I != E; ++I) { 00584 ExplodedNodeSet *DstSet = 0; 00585 if (I+1 == E) 00586 DstSet = &Tmp; 00587 else { 00588 DstSet = (SrcSet == &Tmp2) ? &Tmp3 : &Tmp2; 00589 DstSet->clear(); 00590 } 00591 00592 void *tag = I->first; 00593 Checker *checker = I->second; 00594 for (ExplodedNodeSet::iterator NI = SrcSet->begin(), NE = SrcSet->end(); 00595 NI != NE; ++NI) 00596 checker->GR_evalDeadSymbols(*DstSet, *Builder, *this, currentStmt, 00597 *NI, SymReaper, tag); 00598 SrcSet = DstSet; 00599 } 00600 } 00601 00602 if (!Builder->BuildSinks && !Builder->HasGeneratedNode) 00603 Tmp.Add(EntryNode); 00604 } 00605 00606 bool HasAutoGenerated = false; 00607 00608 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { 00609 ExplodedNodeSet Dst; 00610 00611 // Set the cleaned state. 00612 Builder->SetCleanedState(*I == EntryNode ? CleanedState : GetState(*I)); 00613 00614 // Visit the statement. 00615 Visit(currentStmt, *I, Dst); 00616 00617 // Do we need to auto-generate a node? We only need to do this to generate 00618 // a node with a "cleaned" state; GRCoreEngine will actually handle 00619 // auto-transitions for other cases. 00620 if (Dst.size() == 1 && *Dst.begin() == EntryNode 00621 && !Builder->HasGeneratedNode && !HasAutoGenerated) { 00622 HasAutoGenerated = true; 00623 builder.generateNode(currentStmt, GetState(EntryNode), *I); 00624 } 00625 } 00626 00627 // NULL out these variables to cleanup. 00628 CleanedState = NULL; 00629 EntryNode = NULL; 00630 00631 currentStmt = 0; 00632 00633 Builder = NULL; 00634 } 00635 00636 void GRExprEngine::ProcessInitializer(const CFGInitializer Init, 00637 GRStmtNodeBuilder &builder) { 00638 // We don't set EntryNode and currentStmt. And we don't clean up state. 00639 const CXXBaseOrMemberInitializer *BMI = Init.getInitializer(); 00640 00641 ExplodedNode *Pred = builder.getBasePredecessor(); 00642 const LocationContext *LC = Pred->getLocationContext(); 00643 00644 if (BMI->isAnyMemberInitializer()) { 00645 ExplodedNodeSet Dst; 00646 00647 // Evaluate the initializer. 00648 Visit(BMI->getInit(), Pred, Dst); 00649 00650 for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end(); I != E; ++I){ 00651 ExplodedNode *Pred = *I; 00652 const GRState *state = Pred->getState(); 00653 00654 const FieldDecl *FD = BMI->getAnyMember(); 00655 const RecordDecl *RD = FD->getParent(); 00656 const CXXThisRegion *ThisR = getCXXThisRegion(cast<CXXRecordDecl>(RD), 00657 cast<StackFrameContext>(LC)); 00658 00659 SVal ThisV = state->getSVal(ThisR); 00660 SVal FieldLoc = state->getLValue(FD, ThisV); 00661 SVal InitVal = state->getSVal(BMI->getInit()); 00662 state = state->bindLoc(FieldLoc, InitVal); 00663 00664 // Use a custom node building process. 00665 PostInitializer PP(BMI, LC); 00666 // Builder automatically add the generated node to the deferred set, 00667 // which are processed in the builder's dtor. 00668 builder.generateNode(PP, state, Pred); 00669 } 00670 } 00671 } 00672 00673 void GRExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D, 00674 GRStmtNodeBuilder &builder) { 00675 Builder = &builder; 00676 00677 switch (D.getDtorKind()) { 00678 case CFGElement::AutomaticObjectDtor: 00679 ProcessAutomaticObjDtor(cast<CFGAutomaticObjDtor>(D), builder); 00680 break; 00681 case CFGElement::BaseDtor: 00682 ProcessBaseDtor(cast<CFGBaseDtor>(D), builder); 00683 break; 00684 case CFGElement::MemberDtor: 00685 ProcessMemberDtor(cast<CFGMemberDtor>(D), builder); 00686 break; 00687 case CFGElement::TemporaryDtor: 00688 ProcessTemporaryDtor(cast<CFGTemporaryDtor>(D), builder); 00689 break; 00690 default: 00691 llvm_unreachable("Unexpected dtor kind."); 00692 } 00693 } 00694 00695 void GRExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor dtor, 00696 GRStmtNodeBuilder &builder) { 00697 ExplodedNode *pred = builder.getBasePredecessor(); 00698 const GRState *state = pred->getState(); 00699 const VarDecl *varDecl = dtor.getVarDecl(); 00700 00701 QualType varType = varDecl->getType(); 00702 00703 if (const ReferenceType *refType = varType->getAs<ReferenceType>()) 00704 varType = refType->getPointeeType(); 00705 00706 const CXXRecordDecl *recordDecl = varType->getAsCXXRecordDecl(); 00707 assert(recordDecl && "get CXXRecordDecl fail"); 00708 const CXXDestructorDecl *dtorDecl = recordDecl->getDestructor(); 00709 00710 Loc dest = state->getLValue(varDecl, pred->getLocationContext()); 00711 00712 ExplodedNodeSet dstSet; 00713 VisitCXXDestructor(dtorDecl, cast<loc::MemRegionVal>(dest).getRegion(), 00714 dtor.getTriggerStmt(), pred, dstSet); 00715 } 00716 00717 void GRExprEngine::ProcessBaseDtor(const CFGBaseDtor D, 00718 GRStmtNodeBuilder &builder) { 00719 } 00720 00721 void GRExprEngine::ProcessMemberDtor(const CFGMemberDtor D, 00722 GRStmtNodeBuilder &builder) { 00723 } 00724 00725 void GRExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D, 00726 GRStmtNodeBuilder &builder) { 00727 } 00728 00729 void GRExprEngine::Visit(const Stmt* S, ExplodedNode* Pred, 00730 ExplodedNodeSet& Dst) { 00731 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 00732 S->getLocStart(), 00733 "Error evaluating statement"); 00734 00735 // Expressions to ignore. 00736 if (const Expr *Ex = dyn_cast<Expr>(S)) 00737 S = Ex->IgnoreParens(); 00738 00739 // FIXME: add metadata to the CFG so that we can disable 00740 // this check when we KNOW that there is no block-level subexpression. 00741 // The motivation is that this check requires a hashtable lookup. 00742 00743 if (S != currentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(S)) { 00744 Dst.Add(Pred); 00745 return; 00746 } 00747 00748 switch (S->getStmtClass()) { 00749 // C++ stuff we don't support yet. 00750 case Stmt::CXXBindTemporaryExprClass: 00751 case Stmt::CXXCatchStmtClass: 00752 case Stmt::CXXDefaultArgExprClass: 00753 case Stmt::CXXDependentScopeMemberExprClass: 00754 case Stmt::ExprWithCleanupsClass: 00755 case Stmt::CXXNullPtrLiteralExprClass: 00756 case Stmt::CXXPseudoDestructorExprClass: 00757 case Stmt::CXXTemporaryObjectExprClass: 00758 case Stmt::CXXThrowExprClass: 00759 case Stmt::CXXTryStmtClass: 00760 case Stmt::CXXTypeidExprClass: 00761 case Stmt::CXXUuidofExprClass: 00762 case Stmt::CXXUnresolvedConstructExprClass: 00763 case Stmt::CXXScalarValueInitExprClass: 00764 case Stmt::DependentScopeDeclRefExprClass: 00765 case Stmt::UnaryTypeTraitExprClass: 00766 case Stmt::BinaryTypeTraitExprClass: 00767 case Stmt::UnresolvedLookupExprClass: 00768 case Stmt::UnresolvedMemberExprClass: 00769 case Stmt::CXXNoexceptExprClass: 00770 { 00771 SaveAndRestore<bool> OldSink(Builder->BuildSinks); 00772 Builder->BuildSinks = true; 00773 MakeNode(Dst, S, Pred, GetState(Pred)); 00774 break; 00775 } 00776 00777 case Stmt::ParenExprClass: 00778 llvm_unreachable("ParenExprs already handled."); 00779 // Cases that should never be evaluated simply because they shouldn't 00780 // appear in the CFG. 00781 case Stmt::BreakStmtClass: 00782 case Stmt::CaseStmtClass: 00783 case Stmt::CompoundStmtClass: 00784 case Stmt::ContinueStmtClass: 00785 case Stmt::DefaultStmtClass: 00786 case Stmt::DoStmtClass: 00787 case Stmt::GotoStmtClass: 00788 case Stmt::IndirectGotoStmtClass: 00789 case Stmt::LabelStmtClass: 00790 case Stmt::NoStmtClass: 00791 case Stmt::NullStmtClass: 00792 case Stmt::SwitchCaseClass: 00793 case Stmt::OpaqueValueExprClass: 00794 llvm_unreachable("Stmt should not be in analyzer evaluation loop"); 00795 break; 00796 00797 case Stmt::GNUNullExprClass: { 00798 MakeNode(Dst, S, Pred, GetState(Pred)->BindExpr(S, svalBuilder.makeNull())); 00799 break; 00800 } 00801 00802 case Stmt::ObjCAtSynchronizedStmtClass: 00803 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst); 00804 break; 00805 00806 // Cases not handled yet; but will handle some day. 00807 case Stmt::DesignatedInitExprClass: 00808 case Stmt::ExtVectorElementExprClass: 00809 case Stmt::ImaginaryLiteralClass: 00810 case Stmt::ImplicitValueInitExprClass: 00811 case Stmt::ObjCAtCatchStmtClass: 00812 case Stmt::ObjCAtFinallyStmtClass: 00813 case Stmt::ObjCAtTryStmtClass: 00814 case Stmt::ObjCEncodeExprClass: 00815 case Stmt::ObjCIsaExprClass: 00816 case Stmt::ObjCPropertyRefExprClass: 00817 case Stmt::ObjCProtocolExprClass: 00818 case Stmt::ObjCSelectorExprClass: 00819 case Stmt::ObjCStringLiteralClass: 00820 case Stmt::ParenListExprClass: 00821 case Stmt::PredefinedExprClass: 00822 case Stmt::ShuffleVectorExprClass: 00823 case Stmt::VAArgExprClass: 00824 // Fall through. 00825 00826 // Cases we intentionally don't evaluate, since they don't need 00827 // to be explicitly evaluated. 00828 case Stmt::AddrLabelExprClass: 00829 case Stmt::IntegerLiteralClass: 00830 case Stmt::CharacterLiteralClass: 00831 case Stmt::CXXBoolLiteralExprClass: 00832 case Stmt::FloatingLiteralClass: 00833 Dst.Add(Pred); // No-op. Simply propagate the current state unchanged. 00834 break; 00835 00836 case Stmt::ArraySubscriptExprClass: 00837 VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst); 00838 break; 00839 00840 case Stmt::AsmStmtClass: 00841 VisitAsmStmt(cast<AsmStmt>(S), Pred, Dst); 00842 break; 00843 00844 case Stmt::BlockDeclRefExprClass: { 00845 const BlockDeclRefExpr *BE = cast<BlockDeclRefExpr>(S); 00846 VisitCommonDeclRefExpr(BE, BE->getDecl(), Pred, Dst); 00847 break; 00848 } 00849 00850 case Stmt::BlockExprClass: 00851 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst); 00852 break; 00853 00854 case Stmt::BinaryOperatorClass: { 00855 const BinaryOperator* B = cast<BinaryOperator>(S); 00856 if (B->isLogicalOp()) { 00857 VisitLogicalExpr(B, Pred, Dst); 00858 break; 00859 } 00860 else if (B->getOpcode() == BO_Comma) { 00861 const GRState* state = GetState(Pred); 00862 MakeNode(Dst, B, Pred, state->BindExpr(B, state->getSVal(B->getRHS()))); 00863 break; 00864 } 00865 00866 if (AMgr.shouldEagerlyAssume() && 00867 (B->isRelationalOp() || B->isEqualityOp())) { 00868 ExplodedNodeSet Tmp; 00869 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp); 00870 evalEagerlyAssume(Dst, Tmp, cast<Expr>(S)); 00871 } 00872 else 00873 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 00874 00875 break; 00876 } 00877 00878 case Stmt::CallExprClass: { 00879 const CallExpr* C = cast<CallExpr>(S); 00880 VisitCall(C, Pred, C->arg_begin(), C->arg_end(), Dst); 00881 break; 00882 } 00883 00884 case Stmt::CXXConstructExprClass: { 00885 const CXXConstructExpr *C = cast<CXXConstructExpr>(S); 00886 // For block-level CXXConstructExpr, we don't have a destination region. 00887 // Let VisitCXXConstructExpr() create one. 00888 VisitCXXConstructExpr(C, 0, Pred, Dst); 00889 break; 00890 } 00891 00892 case Stmt::CXXMemberCallExprClass: { 00893 const CXXMemberCallExpr *MCE = cast<CXXMemberCallExpr>(S); 00894 VisitCXXMemberCallExpr(MCE, Pred, Dst); 00895 break; 00896 } 00897 00898 case Stmt::CXXOperatorCallExprClass: { 00899 const CXXOperatorCallExpr *C = cast<CXXOperatorCallExpr>(S); 00900 VisitCXXOperatorCallExpr(C, Pred, Dst); 00901 break; 00902 } 00903 00904 case Stmt::CXXNewExprClass: { 00905 const CXXNewExpr *NE = cast<CXXNewExpr>(S); 00906 VisitCXXNewExpr(NE, Pred, Dst); 00907 break; 00908 } 00909 00910 case Stmt::CXXDeleteExprClass: { 00911 const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S); 00912 VisitCXXDeleteExpr(CDE, Pred, Dst); 00913 break; 00914 } 00915 // FIXME: ChooseExpr is really a constant. We need to fix 00916 // the CFG do not model them as explicit control-flow. 00917 00918 case Stmt::ChooseExprClass: { // __builtin_choose_expr 00919 const ChooseExpr* C = cast<ChooseExpr>(S); 00920 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst); 00921 break; 00922 } 00923 00924 case Stmt::CompoundAssignOperatorClass: 00925 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 00926 break; 00927 00928 case Stmt::CompoundLiteralExprClass: 00929 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst); 00930 break; 00931 00932 case Stmt::ConditionalOperatorClass: { // '?' operator 00933 const ConditionalOperator* C = cast<ConditionalOperator>(S); 00934 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst); 00935 break; 00936 } 00937 00938 case Stmt::CXXThisExprClass: 00939 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst); 00940 break; 00941 00942 case Stmt::DeclRefExprClass: { 00943 const DeclRefExpr *DE = cast<DeclRefExpr>(S); 00944 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst); 00945 break; 00946 } 00947 00948 case Stmt::DeclStmtClass: 00949 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst); 00950 break; 00951 00952 case Stmt::ForStmtClass: 00953 // This case isn't for branch processing, but for handling the 00954 // initialization of a condition variable. 00955 VisitCondInit(cast<ForStmt>(S)->getConditionVariable(), S, Pred, Dst); 00956 break; 00957 00958 case Stmt::ImplicitCastExprClass: 00959 case Stmt::CStyleCastExprClass: 00960 case Stmt::CXXStaticCastExprClass: 00961 case Stmt::CXXDynamicCastExprClass: 00962 case Stmt::CXXReinterpretCastExprClass: 00963 case Stmt::CXXConstCastExprClass: 00964 case Stmt::CXXFunctionalCastExprClass: { 00965 const CastExpr* C = cast<CastExpr>(S); 00966 VisitCast(C, C->getSubExpr(), Pred, Dst); 00967 break; 00968 } 00969 00970 case Stmt::IfStmtClass: 00971 // This case isn't for branch processing, but for handling the 00972 // initialization of a condition variable. 00973 VisitCondInit(cast<IfStmt>(S)->getConditionVariable(), S, Pred, Dst); 00974 break; 00975 00976 case Stmt::InitListExprClass: 00977 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst); 00978 break; 00979 00980 case Stmt::MemberExprClass: 00981 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst); 00982 break; 00983 case Stmt::ObjCIvarRefExprClass: 00984 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst); 00985 break; 00986 00987 case Stmt::ObjCForCollectionStmtClass: 00988 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst); 00989 break; 00990 00991 case Stmt::ObjCMessageExprClass: 00992 VisitObjCMessageExpr(cast<ObjCMessageExpr>(S), Pred, Dst); 00993 break; 00994 00995 case Stmt::ObjCAtThrowStmtClass: { 00996 // FIXME: This is not complete. We basically treat @throw as 00997 // an abort. 00998 SaveAndRestore<bool> OldSink(Builder->BuildSinks); 00999 Builder->BuildSinks = true; 01000 MakeNode(Dst, S, Pred, GetState(Pred)); 01001 break; 01002 } 01003 01004 case Stmt::ReturnStmtClass: 01005 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst); 01006 break; 01007 01008 case Stmt::OffsetOfExprClass: 01009 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst); 01010 break; 01011 01012 case Stmt::SizeOfAlignOfExprClass: 01013 VisitSizeOfAlignOfExpr(cast<SizeOfAlignOfExpr>(S), Pred, Dst); 01014 break; 01015 01016 case Stmt::StmtExprClass: { 01017 const StmtExpr* SE = cast<StmtExpr>(S); 01018 01019 if (SE->getSubStmt()->body_empty()) { 01020 // Empty statement expression. 01021 assert(SE->getType() == getContext().VoidTy 01022 && "Empty statement expression must have void type."); 01023 Dst.Add(Pred); 01024 break; 01025 } 01026 01027 if (Expr* LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) { 01028 const GRState* state = GetState(Pred); 01029 MakeNode(Dst, SE, Pred, state->BindExpr(SE, state->getSVal(LastExpr))); 01030 } 01031 else 01032 Dst.Add(Pred); 01033 01034 break; 01035 } 01036 01037 case Stmt::StringLiteralClass: { 01038 const GRState* state = GetState(Pred); 01039 SVal V = state->getLValue(cast<StringLiteral>(S)); 01040 MakeNode(Dst, S, Pred, state->BindExpr(S, V)); 01041 return; 01042 } 01043 01044 case Stmt::SwitchStmtClass: 01045 // This case isn't for branch processing, but for handling the 01046 // initialization of a condition variable. 01047 VisitCondInit(cast<SwitchStmt>(S)->getConditionVariable(), S, Pred, Dst); 01048 break; 01049 01050 case Stmt::UnaryOperatorClass: { 01051 const UnaryOperator *U = cast<UnaryOperator>(S); 01052 if (AMgr.shouldEagerlyAssume()&&(U->getOpcode() == UO_LNot)) { 01053 ExplodedNodeSet Tmp; 01054 VisitUnaryOperator(U, Pred, Tmp); 01055 evalEagerlyAssume(Dst, Tmp, U); 01056 } 01057 else 01058 VisitUnaryOperator(U, Pred, Dst); 01059 break; 01060 } 01061 01062 case Stmt::WhileStmtClass: 01063 // This case isn't for branch processing, but for handling the 01064 // initialization of a condition variable. 01065 VisitCondInit(cast<WhileStmt>(S)->getConditionVariable(), S, Pred, Dst); 01066 break; 01067 } 01068 } 01069 01070 //===----------------------------------------------------------------------===// 01071 // Block entrance. (Update counters). 01072 //===----------------------------------------------------------------------===// 01073 01074 bool GRExprEngine::ProcessBlockEntrance(const CFGBlock* B, 01075 const ExplodedNode *Pred, 01076 GRBlockCounter BC) { 01077 return BC.getNumVisited(Pred->getLocationContext()->getCurrentStackFrame(), 01078 B->getBlockID()) < AMgr.getMaxVisit(); 01079 } 01080 01081 //===----------------------------------------------------------------------===// 01082 // Generic node creation. 01083 //===----------------------------------------------------------------------===// 01084 01085 ExplodedNode* GRExprEngine::MakeNode(ExplodedNodeSet& Dst, const Stmt* S, 01086 ExplodedNode* Pred, const GRState* St, 01087 ProgramPoint::Kind K, const void *tag) { 01088 assert (Builder && "GRStmtNodeBuilder not present."); 01089 SaveAndRestore<const void*> OldTag(Builder->Tag); 01090 Builder->Tag = tag; 01091 return Builder->MakeNode(Dst, S, Pred, St, K); 01092 } 01093 01094 //===----------------------------------------------------------------------===// 01095 // Branch processing. 01096 //===----------------------------------------------------------------------===// 01097 01098 const GRState* GRExprEngine::MarkBranch(const GRState* state, 01099 const Stmt* Terminator, 01100 bool branchTaken) { 01101 01102 switch (Terminator->getStmtClass()) { 01103 default: 01104 return state; 01105 01106 case Stmt::BinaryOperatorClass: { // '&&' and '||' 01107 01108 const BinaryOperator* B = cast<BinaryOperator>(Terminator); 01109 BinaryOperator::Opcode Op = B->getOpcode(); 01110 01111 assert (Op == BO_LAnd || Op == BO_LOr); 01112 01113 // For &&, if we take the true branch, then the value of the whole 01114 // expression is that of the RHS expression. 01115 // 01116 // For ||, if we take the false branch, then the value of the whole 01117 // expression is that of the RHS expression. 01118 01119 const Expr* Ex = (Op == BO_LAnd && branchTaken) || 01120 (Op == BO_LOr && !branchTaken) 01121 ? B->getRHS() : B->getLHS(); 01122 01123 return state->BindExpr(B, UndefinedVal(Ex)); 01124 } 01125 01126 case Stmt::ConditionalOperatorClass: { // ?: 01127 01128 const ConditionalOperator* C = cast<ConditionalOperator>(Terminator); 01129 01130 // For ?, if branchTaken == true then the value is either the LHS or 01131 // the condition itself. (GNU extension). 01132 01133 const Expr* Ex; 01134 01135 if (branchTaken) 01136 Ex = C->getLHS() ? C->getLHS() : C->getCond(); 01137 else 01138 Ex = C->getRHS(); 01139 01140 return state->BindExpr(C, UndefinedVal(Ex)); 01141 } 01142 01143 case Stmt::ChooseExprClass: { // ?: 01144 01145 const ChooseExpr* C = cast<ChooseExpr>(Terminator); 01146 01147 const Expr* Ex = branchTaken ? C->getLHS() : C->getRHS(); 01148 return state->BindExpr(C, UndefinedVal(Ex)); 01149 } 01150 } 01151 } 01152 01153 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used 01154 /// to try to recover some path-sensitivity for casts of symbolic 01155 /// integers that promote their values (which are currently not tracked well). 01156 /// This function returns the SVal bound to Condition->IgnoreCasts if all the 01157 // cast(s) did was sign-extend the original value. 01158 static SVal RecoverCastedSymbol(GRStateManager& StateMgr, const GRState* state, 01159 const Stmt* Condition, ASTContext& Ctx) { 01160 01161 const Expr *Ex = dyn_cast<Expr>(Condition); 01162 if (!Ex) 01163 return UnknownVal(); 01164 01165 uint64_t bits = 0; 01166 bool bitsInit = false; 01167 01168 while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) { 01169 QualType T = CE->getType(); 01170 01171 if (!T->isIntegerType()) 01172 return UnknownVal(); 01173 01174 uint64_t newBits = Ctx.getTypeSize(T); 01175 if (!bitsInit || newBits < bits) { 01176 bitsInit = true; 01177 bits = newBits; 01178 } 01179 01180 Ex = CE->getSubExpr(); 01181 } 01182 01183 // We reached a non-cast. Is it a symbolic value? 01184 QualType T = Ex->getType(); 01185 01186 if (!bitsInit || !T->isIntegerType() || Ctx.getTypeSize(T) > bits) 01187 return UnknownVal(); 01188 01189 return state->getSVal(Ex); 01190 } 01191 01192 void GRExprEngine::ProcessBranch(const Stmt* Condition, const Stmt* Term, 01193 GRBranchNodeBuilder& builder) { 01194 01195 // Check for NULL conditions; e.g. "for(;;)" 01196 if (!Condition) { 01197 builder.markInfeasible(false); 01198 return; 01199 } 01200 01201 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 01202 Condition->getLocStart(), 01203 "Error evaluating branch"); 01204 01205 for (CheckersOrdered::iterator I=Checkers.begin(),E=Checkers.end();I!=E;++I) { 01206 void *tag = I->first; 01207 Checker *checker = I->second; 01208 checker->VisitBranchCondition(builder, *this, Condition, tag); 01209 } 01210 01211 // If the branch condition is undefined, return; 01212 if (!builder.isFeasible(true) && !builder.isFeasible(false)) 01213 return; 01214 01215 const GRState* PrevState = builder.getState(); 01216 SVal X = PrevState->getSVal(Condition); 01217 01218 if (X.isUnknown()) { 01219 // Give it a chance to recover from unknown. 01220 if (const Expr *Ex = dyn_cast<Expr>(Condition)) { 01221 if (Ex->getType()->isIntegerType()) { 01222 // Try to recover some path-sensitivity. Right now casts of symbolic 01223 // integers that promote their values are currently not tracked well. 01224 // If 'Condition' is such an expression, try and recover the 01225 // underlying value and use that instead. 01226 SVal recovered = RecoverCastedSymbol(getStateManager(), 01227 builder.getState(), Condition, 01228 getContext()); 01229 01230 if (!recovered.isUnknown()) { 01231 X = recovered; 01232 } 01233 } 01234 } 01235 // If the condition is still unknown, give up. 01236 if (X.isUnknown()) { 01237 builder.generateNode(MarkBranch(PrevState, Term, true), true); 01238 builder.generateNode(MarkBranch(PrevState, Term, false), false); 01239 return; 01240 } 01241 } 01242 01243 DefinedSVal V = cast<DefinedSVal>(X); 01244 01245 // Process the true branch. 01246 if (builder.isFeasible(true)) { 01247 if (const GRState *state = PrevState->assume(V, true)) 01248 builder.generateNode(MarkBranch(state, Term, true), true); 01249 else 01250 builder.markInfeasible(true); 01251 } 01252 01253 // Process the false branch. 01254 if (builder.isFeasible(false)) { 01255 if (const GRState *state = PrevState->assume(V, false)) 01256 builder.generateNode(MarkBranch(state, Term, false), false); 01257 else 01258 builder.markInfeasible(false); 01259 } 01260 } 01261 01262 /// ProcessIndirectGoto - Called by GRCoreEngine. Used to generate successor 01263 /// nodes by processing the 'effects' of a computed goto jump. 01264 void GRExprEngine::ProcessIndirectGoto(GRIndirectGotoNodeBuilder& builder) { 01265 01266 const GRState *state = builder.getState(); 01267 SVal V = state->getSVal(builder.getTarget()); 01268 01269 // Three possibilities: 01270 // 01271 // (1) We know the computed label. 01272 // (2) The label is NULL (or some other constant), or Undefined. 01273 // (3) We have no clue about the label. Dispatch to all targets. 01274 // 01275 01276 typedef GRIndirectGotoNodeBuilder::iterator iterator; 01277 01278 if (isa<loc::GotoLabel>(V)) { 01279 const LabelStmt* L = cast<loc::GotoLabel>(V).getLabel(); 01280 01281 for (iterator I=builder.begin(), E=builder.end(); I != E; ++I) { 01282 if (I.getLabel() == L) { 01283 builder.generateNode(I, state); 01284 return; 01285 } 01286 } 01287 01288 assert (false && "No block with label."); 01289 return; 01290 } 01291 01292 if (isa<loc::ConcreteInt>(V) || isa<UndefinedVal>(V)) { 01293 // Dispatch to the first target and mark it as a sink. 01294 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true); 01295 // FIXME: add checker visit. 01296 // UndefBranches.insert(N); 01297 return; 01298 } 01299 01300 // This is really a catch-all. We don't support symbolics yet. 01301 // FIXME: Implement dispatch for symbolic pointers. 01302 01303 for (iterator I=builder.begin(), E=builder.end(); I != E; ++I) 01304 builder.generateNode(I, state); 01305 } 01306 01307 01308 void GRExprEngine::VisitGuardedExpr(const Expr* Ex, const Expr* L, 01309 const Expr* R, 01310 ExplodedNode* Pred, ExplodedNodeSet& Dst) { 01311 01312 assert(Ex == currentStmt && 01313 Pred->getLocationContext()->getCFG()->isBlkExpr(Ex)); 01314 01315 const GRState* state = GetState(Pred); 01316 SVal X = state->getSVal(Ex); 01317 01318 assert (X.isUndef()); 01319 01320 const Expr *SE = (Expr*) cast<UndefinedVal>(X).getData(); 01321 assert(SE); 01322 X = state->getSVal(SE); 01323 01324 // Make sure that we invalidate the previous binding. 01325 MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, X, true)); 01326 } 01327 01328 /// ProcessEndPath - Called by GRCoreEngine. Used to generate end-of-path 01329 /// nodes when the control reaches the end of a function. 01330 void GRExprEngine::ProcessEndPath(GREndPathNodeBuilder& builder) { 01331 getTF().evalEndPath(*this, builder); 01332 StateMgr.EndPath(builder.getState()); 01333 for (CheckersOrdered::iterator I=Checkers.begin(),E=Checkers.end(); I!=E;++I){ 01334 void *tag = I->first; 01335 Checker *checker = I->second; 01336 checker->evalEndPath(builder, tag, *this); 01337 } 01338 } 01339 01340 /// ProcessSwitch - Called by GRCoreEngine. Used to generate successor 01341 /// nodes by processing the 'effects' of a switch statement. 01342 void GRExprEngine::ProcessSwitch(GRSwitchNodeBuilder& builder) { 01343 typedef GRSwitchNodeBuilder::iterator iterator; 01344 const GRState* state = builder.getState(); 01345 const Expr* CondE = builder.getCondition(); 01346 SVal CondV_untested = state->getSVal(CondE); 01347 01348 if (CondV_untested.isUndef()) { 01349 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true); 01350 // FIXME: add checker 01351 //UndefBranches.insert(N); 01352 01353 return; 01354 } 01355 DefinedOrUnknownSVal CondV = cast<DefinedOrUnknownSVal>(CondV_untested); 01356 01357 const GRState *DefaultSt = state; 01358 01359 iterator I = builder.begin(), EI = builder.end(); 01360 bool defaultIsFeasible = I == EI; 01361 01362 for ( ; I != EI; ++I) { 01363 const CaseStmt* Case = I.getCase(); 01364 01365 // Evaluate the LHS of the case value. 01366 Expr::EvalResult V1; 01367 bool b = Case->getLHS()->Evaluate(V1, getContext()); 01368 01369 // Sanity checks. These go away in Release builds. 01370 assert(b && V1.Val.isInt() && !V1.HasSideEffects 01371 && "Case condition must evaluate to an integer constant."); 01372 b = b; // silence unused variable warning 01373 assert(V1.Val.getInt().getBitWidth() == 01374 getContext().getTypeSize(CondE->getType())); 01375 01376 // Get the RHS of the case, if it exists. 01377 Expr::EvalResult V2; 01378 01379 if (const Expr* E = Case->getRHS()) { 01380 b = E->Evaluate(V2, getContext()); 01381 assert(b && V2.Val.isInt() && !V2.HasSideEffects 01382 && "Case condition must evaluate to an integer constant."); 01383 b = b; // silence unused variable warning 01384 } 01385 else 01386 V2 = V1; 01387 01388 // FIXME: Eventually we should replace the logic below with a range 01389 // comparison, rather than concretize the values within the range. 01390 // This should be easy once we have "ranges" for NonLVals. 01391 01392 do { 01393 nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1.Val.getInt())); 01394 DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state, 01395 CondV, CaseVal); 01396 01397 // Now "assume" that the case matches. 01398 if (const GRState* stateNew = state->assume(Res, true)) { 01399 builder.generateCaseStmtNode(I, stateNew); 01400 01401 // If CondV evaluates to a constant, then we know that this 01402 // is the *only* case that we can take, so stop evaluating the 01403 // others. 01404 if (isa<nonloc::ConcreteInt>(CondV)) 01405 return; 01406 } 01407 01408 // Now "assume" that the case doesn't match. Add this state 01409 // to the default state (if it is feasible). 01410 if (DefaultSt) { 01411 if (const GRState *stateNew = DefaultSt->assume(Res, false)) { 01412 defaultIsFeasible = true; 01413 DefaultSt = stateNew; 01414 } 01415 else { 01416 defaultIsFeasible = false; 01417 DefaultSt = NULL; 01418 } 01419 } 01420 01421 // Concretize the next value in the range. 01422 if (V1.Val.getInt() == V2.Val.getInt()) 01423 break; 01424 01425 ++V1.Val.getInt(); 01426 assert (V1.Val.getInt() <= V2.Val.getInt()); 01427 01428 } while (true); 01429 } 01430 01431 if (!defaultIsFeasible) 01432 return; 01433 01434 // If we have switch(enum value), the default branch is not 01435 // feasible if all of the enum constants not covered by 'case:' statements 01436 // are not feasible values for the switch condition. 01437 // 01438 // Note that this isn't as accurate as it could be. Even if there isn't 01439 // a case for a particular enum value as long as that enum value isn't 01440 // feasible then it shouldn't be considered for making 'default:' reachable. 01441 const SwitchStmt *SS = builder.getSwitch(); 01442 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts(); 01443 if (CondExpr->getType()->getAs<EnumType>()) { 01444 if (SS->isAllEnumCasesCovered()) 01445 return; 01446 } 01447 01448 builder.generateDefaultCaseNode(DefaultSt); 01449 } 01450 01451 void GRExprEngine::ProcessCallEnter(GRCallEnterNodeBuilder &B) { 01452 const GRState *state = B.getState()->EnterStackFrame(B.getCalleeContext()); 01453 B.generateNode(state); 01454 } 01455 01456 void GRExprEngine::ProcessCallExit(GRCallExitNodeBuilder &B) { 01457 const GRState *state = B.getState(); 01458 const ExplodedNode *Pred = B.getPredecessor(); 01459 const StackFrameContext *calleeCtx = 01460 cast<StackFrameContext>(Pred->getLocationContext()); 01461 const Stmt *CE = calleeCtx->getCallSite(); 01462 01463 // If the callee returns an expression, bind its value to CallExpr. 01464 const Stmt *ReturnedExpr = state->get<ReturnExpr>(); 01465 if (ReturnedExpr) { 01466 SVal RetVal = state->getSVal(ReturnedExpr); 01467 state = state->BindExpr(CE, RetVal); 01468 // Clear the return expr GDM. 01469 state = state->remove<ReturnExpr>(); 01470 } 01471 01472 // Bind the constructed object value to CXXConstructExpr. 01473 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(CE)) { 01474 const CXXThisRegion *ThisR = 01475 getCXXThisRegion(CCE->getConstructor()->getParent(), calleeCtx); 01476 01477 SVal ThisV = state->getSVal(ThisR); 01478 // Always bind the region to the CXXConstructExpr. 01479 state = state->BindExpr(CCE, ThisV); 01480 } 01481 01482 B.generateNode(state); 01483 } 01484 01485 //===----------------------------------------------------------------------===// 01486 // Transfer functions: logical operations ('&&', '||'). 01487 //===----------------------------------------------------------------------===// 01488 01489 void GRExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode* Pred, 01490 ExplodedNodeSet& Dst) { 01491 01492 assert(B->getOpcode() == BO_LAnd || 01493 B->getOpcode() == BO_LOr); 01494 01495 assert(B==currentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(B)); 01496 01497 const GRState* state = GetState(Pred); 01498 SVal X = state->getSVal(B); 01499 assert(X.isUndef()); 01500 01501 const Expr *Ex = (const Expr*) cast<UndefinedVal>(X).getData(); 01502 assert(Ex); 01503 01504 if (Ex == B->getRHS()) { 01505 X = state->getSVal(Ex); 01506 01507 // Handle undefined values. 01508 if (X.isUndef()) { 01509 MakeNode(Dst, B, Pred, state->BindExpr(B, X)); 01510 return; 01511 } 01512 01513 DefinedOrUnknownSVal XD = cast<DefinedOrUnknownSVal>(X); 01514 01515 // We took the RHS. Because the value of the '&&' or '||' expression must 01516 // evaluate to 0 or 1, we must assume the value of the RHS evaluates to 0 01517 // or 1. Alternatively, we could take a lazy approach, and calculate this 01518 // value later when necessary. We don't have the machinery in place for 01519 // this right now, and since most logical expressions are used for branches, 01520 // the payoff is not likely to be large. Instead, we do eager evaluation. 01521 if (const GRState *newState = state->assume(XD, true)) 01522 MakeNode(Dst, B, Pred, 01523 newState->BindExpr(B, svalBuilder.makeIntVal(1U, B->getType()))); 01524 01525 if (const GRState *newState = state->assume(XD, false)) 01526 MakeNode(Dst, B, Pred, 01527 newState->BindExpr(B, svalBuilder.makeIntVal(0U, B->getType()))); 01528 } 01529 else { 01530 // We took the LHS expression. Depending on whether we are '&&' or 01531 // '||' we know what the value of the expression is via properties of 01532 // the short-circuiting. 01533 X = svalBuilder.makeIntVal(B->getOpcode() == BO_LAnd ? 0U : 1U, 01534 B->getType()); 01535 MakeNode(Dst, B, Pred, state->BindExpr(B, X)); 01536 } 01537 } 01538 01539 //===----------------------------------------------------------------------===// 01540 // Transfer functions: Loads and stores. 01541 //===----------------------------------------------------------------------===// 01542 01543 void GRExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, 01544 ExplodedNodeSet &Dst) { 01545 01546 ExplodedNodeSet Tmp; 01547 01548 CanQualType T = getContext().getCanonicalType(BE->getType()); 01549 SVal V = svalBuilder.getBlockPointer(BE->getBlockDecl(), T, 01550 Pred->getLocationContext()); 01551 01552 MakeNode(Tmp, BE, Pred, GetState(Pred)->BindExpr(BE, V), 01553 ProgramPoint::PostLValueKind); 01554 01555 // Post-visit the BlockExpr. 01556 CheckerVisit(BE, Dst, Tmp, PostVisitStmtCallback); 01557 } 01558 01559 void GRExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D, 01560 ExplodedNode *Pred, 01561 ExplodedNodeSet &Dst) { 01562 const GRState *state = GetState(Pred); 01563 01564 if (const VarDecl* VD = dyn_cast<VarDecl>(D)) { 01565 assert(Ex->isLValue()); 01566 SVal V = state->getLValue(VD, Pred->getLocationContext()); 01567 01568 // For references, the 'lvalue' is the pointer address stored in the 01569 // reference region. 01570 if (VD->getType()->isReferenceType()) { 01571 if (const MemRegion *R = V.getAsRegion()) 01572 V = state->getSVal(R); 01573 else 01574 V = UnknownVal(); 01575 } 01576 01577 MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V), 01578 ProgramPoint::PostLValueKind); 01579 return; 01580 } 01581 if (const EnumConstantDecl* ED = dyn_cast<EnumConstantDecl>(D)) { 01582 assert(!Ex->isLValue()); 01583 SVal V = svalBuilder.makeIntVal(ED->getInitVal()); 01584 MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V)); 01585 return; 01586 } 01587 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) { 01588 SVal V = svalBuilder.getFunctionPointer(FD); 01589 MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V), 01590 ProgramPoint::PostLValueKind); 01591 return; 01592 } 01593 assert (false && 01594 "ValueDecl support for this ValueDecl not implemented."); 01595 } 01596 01597 /// VisitArraySubscriptExpr - Transfer function for array accesses 01598 void GRExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr* A, 01599 ExplodedNode* Pred, 01600 ExplodedNodeSet& Dst){ 01601 01602 const Expr* Base = A->getBase()->IgnoreParens(); 01603 const Expr* Idx = A->getIdx()->IgnoreParens(); 01604 01605 // Evaluate the base. 01606 ExplodedNodeSet Tmp; 01607 Visit(Base, Pred, Tmp); 01608 01609 for (ExplodedNodeSet::iterator I1=Tmp.begin(), E1=Tmp.end(); I1!=E1; ++I1) { 01610 ExplodedNodeSet Tmp2; 01611 Visit(Idx, *I1, Tmp2); // Evaluate the index. 01612 ExplodedNodeSet Tmp3; 01613 CheckerVisit(A, Tmp3, Tmp2, PreVisitStmtCallback); 01614 01615 for (ExplodedNodeSet::iterator I2=Tmp3.begin(),E2=Tmp3.end();I2!=E2; ++I2) { 01616 const GRState* state = GetState(*I2); 01617 SVal V = state->getLValue(A->getType(), state->getSVal(Idx), 01618 state->getSVal(Base)); 01619 assert(A->isLValue()); 01620 MakeNode(Dst, A, *I2, state->BindExpr(A, V), ProgramPoint::PostLValueKind); 01621 } 01622 } 01623 } 01624 01625 /// VisitMemberExpr - Transfer function for member expressions. 01626 void GRExprEngine::VisitMemberExpr(const MemberExpr* M, ExplodedNode* Pred, 01627 ExplodedNodeSet& Dst) { 01628 01629 Expr *baseExpr = M->getBase()->IgnoreParens(); 01630 ExplodedNodeSet dstBase; 01631 Visit(baseExpr, Pred, dstBase); 01632 01633 FieldDecl *field = dyn_cast<FieldDecl>(M->getMemberDecl()); 01634 if (!field) // FIXME: skipping member expressions for non-fields 01635 return; 01636 01637 for (ExplodedNodeSet::iterator I = dstBase.begin(), E = dstBase.end(); 01638 I != E; ++I) { 01639 const GRState* state = GetState(*I); 01640 SVal baseExprVal = state->getSVal(baseExpr); 01641 if (isa<nonloc::LazyCompoundVal>(baseExprVal) || 01642 isa<nonloc::CompoundVal>(baseExprVal)) { 01643 MakeNode(Dst, M, *I, state->BindExpr(M, UnknownVal())); 01644 continue; 01645 } 01646 01647 // FIXME: Should we insert some assumption logic in here to determine 01648 // if "Base" is a valid piece of memory? Before we put this assumption 01649 // later when using FieldOffset lvals (which we no longer have). 01650 01651 // For all other cases, compute an lvalue. 01652 SVal L = state->getLValue(field, baseExprVal); 01653 if (M->isLValue()) 01654 MakeNode(Dst, M, *I, state->BindExpr(M, L), ProgramPoint::PostLValueKind); 01655 else 01656 evalLoad(Dst, M, *I, state, L); 01657 } 01658 } 01659 01660 /// evalBind - Handle the semantics of binding a value to a specific location. 01661 /// This method is used by evalStore and (soon) VisitDeclStmt, and others. 01662 void GRExprEngine::evalBind(ExplodedNodeSet& Dst, const Stmt* StoreE, 01663 ExplodedNode* Pred, const GRState* state, 01664 SVal location, SVal Val, bool atDeclInit) { 01665 01666 01667 // Do a previsit of the bind. 01668 ExplodedNodeSet CheckedSet, Src; 01669 Src.Add(Pred); 01670 CheckerVisitBind(StoreE, CheckedSet, Src, location, Val, true); 01671 01672 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 01673 I!=E; ++I) { 01674 01675 if (Pred != *I) 01676 state = GetState(*I); 01677 01678 const GRState* newState = 0; 01679 01680 if (atDeclInit) { 01681 const VarRegion *VR = 01682 cast<VarRegion>(cast<loc::MemRegionVal>(location).getRegion()); 01683 01684 newState = state->bindDecl(VR, Val); 01685 } 01686 else { 01687 if (location.isUnknown()) { 01688 // We know that the new state will be the same as the old state since 01689 // the location of the binding is "unknown". Consequently, there 01690 // is no reason to just create a new node. 01691 newState = state; 01692 } 01693 else { 01694 // We are binding to a value other than 'unknown'. Perform the binding 01695 // using the StoreManager. 01696 newState = state->bindLoc(cast<Loc>(location), Val); 01697 } 01698 } 01699 01700 // The next thing to do is check if the GRTransferFuncs object wants to 01701 // update the state based on the new binding. If the GRTransferFunc object 01702 // doesn't do anything, just auto-propagate the current state. 01703 01704 // NOTE: We use 'AssignE' for the location of the PostStore if 'AssignE' 01705 // is non-NULL. Checkers typically care about 01706 01707 GRStmtNodeBuilderRef BuilderRef(Dst, *Builder, *this, *I, newState, StoreE, 01708 true); 01709 01710 getTF().evalBind(BuilderRef, location, Val); 01711 } 01712 } 01713 01714 /// evalStore - Handle the semantics of a store via an assignment. 01715 /// @param Dst The node set to store generated state nodes 01716 /// @param AssignE The assignment expression if the store happens in an 01717 /// assignment. 01718 /// @param LocatioinE The location expression that is stored to. 01719 /// @param state The current simulation state 01720 /// @param location The location to store the value 01721 /// @param Val The value to be stored 01722 void GRExprEngine::evalStore(ExplodedNodeSet& Dst, const Expr *AssignE, 01723 const Expr* LocationE, 01724 ExplodedNode* Pred, 01725 const GRState* state, SVal location, SVal Val, 01726 const void *tag) { 01727 01728 assert(Builder && "GRStmtNodeBuilder must be defined."); 01729 01730 // Evaluate the location (checks for bad dereferences). 01731 ExplodedNodeSet Tmp; 01732 evalLocation(Tmp, LocationE, Pred, state, location, tag, false); 01733 01734 if (Tmp.empty()) 01735 return; 01736 01737 assert(!location.isUndef()); 01738 01739 SaveAndRestore<ProgramPoint::Kind> OldSPointKind(Builder->PointKind, 01740 ProgramPoint::PostStoreKind); 01741 SaveAndRestore<const void*> OldTag(Builder->Tag, tag); 01742 01743 // Proceed with the store. We use AssignE as the anchor for the PostStore 01744 // ProgramPoint if it is non-NULL, and LocationE otherwise. 01745 const Expr *StoreE = AssignE ? AssignE : LocationE; 01746 01747 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) 01748 evalBind(Dst, StoreE, *NI, GetState(*NI), location, Val); 01749 } 01750 01751 void GRExprEngine::evalLoad(ExplodedNodeSet& Dst, const Expr *Ex, 01752 ExplodedNode* Pred, 01753 const GRState* state, SVal location, 01754 const void *tag, QualType LoadTy) { 01755 assert(!isa<NonLoc>(location) && "location cannot be a NonLoc."); 01756 01757 // Are we loading from a region? This actually results in two loads; one 01758 // to fetch the address of the referenced value and one to fetch the 01759 // referenced value. 01760 if (const TypedRegion *TR = 01761 dyn_cast_or_null<TypedRegion>(location.getAsRegion())) { 01762 01763 QualType ValTy = TR->getValueType(); 01764 if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) { 01765 static int loadReferenceTag = 0; 01766 ExplodedNodeSet Tmp; 01767 evalLoadCommon(Tmp, Ex, Pred, state, location, &loadReferenceTag, 01768 getContext().getPointerType(RT->getPointeeType())); 01769 01770 // Perform the load from the referenced value. 01771 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) { 01772 state = GetState(*I); 01773 location = state->getSVal(Ex); 01774 evalLoadCommon(Dst, Ex, *I, state, location, tag, LoadTy); 01775 } 01776 return; 01777 } 01778 } 01779 01780 evalLoadCommon(Dst, Ex, Pred, state, location, tag, LoadTy); 01781 } 01782 01783 void GRExprEngine::evalLoadCommon(ExplodedNodeSet& Dst, const Expr *Ex, 01784 ExplodedNode* Pred, 01785 const GRState* state, SVal location, 01786 const void *tag, QualType LoadTy) { 01787 01788 // Evaluate the location (checks for bad dereferences). 01789 ExplodedNodeSet Tmp; 01790 evalLocation(Tmp, Ex, Pred, state, location, tag, true); 01791 01792 if (Tmp.empty()) 01793 return; 01794 01795 assert(!location.isUndef()); 01796 01797 SaveAndRestore<ProgramPoint::Kind> OldSPointKind(Builder->PointKind); 01798 SaveAndRestore<const void*> OldTag(Builder->Tag); 01799 01800 // Proceed with the load. 01801 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) { 01802 state = GetState(*NI); 01803 01804 if (location.isUnknown()) { 01805 // This is important. We must nuke the old binding. 01806 MakeNode(Dst, Ex, *NI, state->BindExpr(Ex, UnknownVal()), 01807 ProgramPoint::PostLoadKind, tag); 01808 } 01809 else { 01810 if (LoadTy.isNull()) 01811 LoadTy = Ex->getType(); 01812 SVal V = state->getSVal(cast<Loc>(location), LoadTy); 01813 MakeNode(Dst, Ex, *NI, state->bindExprAndLocation(Ex, location, V), 01814 ProgramPoint::PostLoadKind, tag); 01815 } 01816 } 01817 } 01818 01819 void GRExprEngine::evalLocation(ExplodedNodeSet &Dst, const Stmt *S, 01820 ExplodedNode* Pred, 01821 const GRState* state, SVal location, 01822 const void *tag, bool isLoad) { 01823 // Early checks for performance reason. 01824 if (location.isUnknown() || Checkers.empty()) { 01825 Dst.Add(Pred); 01826 return; 01827 } 01828 01829 ExplodedNodeSet Src, Tmp; 01830 Src.Add(Pred); 01831 ExplodedNodeSet *PrevSet = &Src; 01832 01833 for (CheckersOrdered::iterator I=Checkers.begin(),E=Checkers.end(); I!=E; ++I) 01834 { 01835 ExplodedNodeSet *CurrSet = 0; 01836 if (I+1 == E) 01837 CurrSet = &Dst; 01838 else { 01839 CurrSet = (PrevSet == &Tmp) ? &Src : &Tmp; 01840 CurrSet->clear(); 01841 } 01842 01843 void *tag = I->first; 01844 Checker *checker = I->second; 01845 01846 for (ExplodedNodeSet::iterator NI = PrevSet->begin(), NE = PrevSet->end(); 01847 NI != NE; ++NI) { 01848 // Use the 'state' argument only when the predecessor node is the 01849 // same as Pred. This allows us to catch updates to the state. 01850 checker->GR_visitLocation(*CurrSet, *Builder, *this, S, *NI, 01851 *NI == Pred ? state : GetState(*NI), 01852 location, tag, isLoad); 01853 } 01854 01855 // Update which NodeSet is the current one. 01856 PrevSet = CurrSet; 01857 } 01858 } 01859 01860 bool GRExprEngine::InlineCall(ExplodedNodeSet &Dst, const CallExpr *CE, 01861 ExplodedNode *Pred) { 01862 const GRState *state = GetState(Pred); 01863 const Expr *Callee = CE->getCallee(); 01864 SVal L = state->getSVal(Callee); 01865 01866 const FunctionDecl *FD = L.getAsFunctionDecl(); 01867 if (!FD) 01868 return false; 01869 01870 // Check if the function definition is in the same translation unit. 01871 if (FD->hasBody(FD)) { 01872 const StackFrameContext *stackFrame = 01873 AMgr.getStackFrame(AMgr.getAnalysisContext(FD), 01874 Pred->getLocationContext(), 01875 CE, Builder->getBlock(), Builder->getIndex()); 01876 // Now we have the definition of the callee, create a CallEnter node. 01877 CallEnter Loc(CE, stackFrame, Pred->getLocationContext()); 01878 01879 ExplodedNode *N = Builder->generateNode(Loc, state, Pred); 01880 Dst.Add(N); 01881 return true; 01882 } 01883 01884 // Check if we can find the function definition in other translation units. 01885 if (AMgr.hasIndexer()) { 01886 AnalysisContext *C = AMgr.getAnalysisContextInAnotherTU(FD); 01887 if (C == 0) 01888 return false; 01889 const StackFrameContext *stackFrame = 01890 AMgr.getStackFrame(C, Pred->getLocationContext(), 01891 CE, Builder->getBlock(), Builder->getIndex()); 01892 CallEnter Loc(CE, stackFrame, Pred->getLocationContext()); 01893 ExplodedNode *N = Builder->generateNode(Loc, state, Pred); 01894 Dst.Add(N); 01895 return true; 01896 } 01897 01898 return false; 01899 } 01900 01901 void GRExprEngine::VisitCall(const CallExpr* CE, ExplodedNode* Pred, 01902 CallExpr::const_arg_iterator AI, 01903 CallExpr::const_arg_iterator AE, 01904 ExplodedNodeSet& Dst) { 01905 01906 // Determine the type of function we're calling (if available). 01907 const FunctionProtoType *Proto = NULL; 01908 QualType FnType = CE->getCallee()->IgnoreParens()->getType(); 01909 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) 01910 Proto = FnTypePtr->getPointeeType()->getAs<FunctionProtoType>(); 01911 01912 // Evaluate the arguments. 01913 ExplodedNodeSet ArgsEvaluated; 01914 evalArguments(CE->arg_begin(), CE->arg_end(), Proto, Pred, ArgsEvaluated); 01915 01916 // Now process the call itself. 01917 ExplodedNodeSet DstTmp; 01918 const Expr* Callee = CE->getCallee()->IgnoreParens(); 01919 01920 for (ExplodedNodeSet::iterator NI=ArgsEvaluated.begin(), 01921 NE=ArgsEvaluated.end(); NI != NE; ++NI) { 01922 // Evaluate the callee. 01923 ExplodedNodeSet DstTmp2; 01924 Visit(Callee, *NI, DstTmp2); 01925 // Perform the previsit of the CallExpr, storing the results in DstTmp. 01926 CheckerVisit(CE, DstTmp, DstTmp2, PreVisitStmtCallback); 01927 } 01928 01929 // Finally, evaluate the function call. We try each of the checkers 01930 // to see if the can evaluate the function call. 01931 ExplodedNodeSet DstTmp3; 01932 01933 for (ExplodedNodeSet::iterator DI = DstTmp.begin(), DE = DstTmp.end(); 01934 DI != DE; ++DI) { 01935 01936 const GRState* state = GetState(*DI); 01937 SVal L = state->getSVal(Callee); 01938 01939 // FIXME: Add support for symbolic function calls (calls involving 01940 // function pointer values that are symbolic). 01941 SaveAndRestore<bool> OldSink(Builder->BuildSinks); 01942 ExplodedNodeSet DstChecker; 01943 01944 // If the callee is processed by a checker, skip the rest logic. 01945 if (CheckerEvalCall(CE, DstChecker, *DI)) 01946 DstTmp3.insert(DstChecker); 01947 else if (AMgr.shouldInlineCall() && InlineCall(Dst, CE, *DI)) { 01948 // Callee is inlined. We shouldn't do post call checking. 01949 return; 01950 } 01951 else { 01952 for (ExplodedNodeSet::iterator DI_Checker = DstChecker.begin(), 01953 DE_Checker = DstChecker.end(); 01954 DI_Checker != DE_Checker; ++DI_Checker) { 01955 01956 // Dispatch to the plug-in transfer function. 01957 unsigned oldSize = DstTmp3.size(); 01958 SaveOr OldHasGen(Builder->HasGeneratedNode); 01959 Pred = *DI_Checker; 01960 01961 // Dispatch to transfer function logic to handle the call itself. 01962 // FIXME: Allow us to chain together transfer functions. 01963 assert(Builder && "GRStmtNodeBuilder must be defined."); 01964 getTF().evalCall(DstTmp3, *this, *Builder, CE, L, Pred); 01965 01966 // Handle the case where no nodes where generated. Auto-generate that 01967 // contains the updated state if we aren't generating sinks. 01968 if (!Builder->BuildSinks && DstTmp3.size() == oldSize && 01969 !Builder->HasGeneratedNode) 01970 MakeNode(DstTmp3, CE, Pred, state); 01971 } 01972 } 01973 } 01974 01975 // Finally, perform the post-condition check of the CallExpr and store 01976 // the created nodes in 'Dst'. 01977 CheckerVisit(CE, Dst, DstTmp3, PostVisitStmtCallback); 01978 } 01979 01980 //===----------------------------------------------------------------------===// 01981 // Transfer function: Objective-C ivar references. 01982 //===----------------------------------------------------------------------===// 01983 01984 static std::pair<const void*,const void*> EagerlyAssumeTag 01985 = std::pair<const void*,const void*>(&EagerlyAssumeTag,static_cast<void*>(0)); 01986 01987 void GRExprEngine::evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, 01988 const Expr *Ex) { 01989 for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) { 01990 ExplodedNode *Pred = *I; 01991 01992 // Test if the previous node was as the same expression. This can happen 01993 // when the expression fails to evaluate to anything meaningful and 01994 // (as an optimization) we don't generate a node. 01995 ProgramPoint P = Pred->getLocation(); 01996 if (!isa<PostStmt>(P) || cast<PostStmt>(P).getStmt() != Ex) { 01997 Dst.Add(Pred); 01998 continue; 01999 } 02000 02001 const GRState* state = GetState(Pred); 02002 SVal V = state->getSVal(Ex); 02003 if (nonloc::SymExprVal *SEV = dyn_cast<nonloc::SymExprVal>(&V)) { 02004 // First assume that the condition is true. 02005 if (const GRState *stateTrue = state->assume(*SEV, true)) { 02006 stateTrue = stateTrue->BindExpr(Ex, 02007 svalBuilder.makeIntVal(1U, Ex->getType())); 02008 Dst.Add(Builder->generateNode(PostStmtCustom(Ex, 02009 &EagerlyAssumeTag, Pred->getLocationContext()), 02010 stateTrue, Pred)); 02011 } 02012 02013 // Next, assume that the condition is false. 02014 if (const GRState *stateFalse = state->assume(*SEV, false)) { 02015 stateFalse = stateFalse->BindExpr(Ex, 02016 svalBuilder.makeIntVal(0U, Ex->getType())); 02017 Dst.Add(Builder->generateNode(PostStmtCustom(Ex, &EagerlyAssumeTag, 02018 Pred->getLocationContext()), 02019 stateFalse, Pred)); 02020 } 02021 } 02022 else 02023 Dst.Add(Pred); 02024 } 02025 } 02026 02027 //===----------------------------------------------------------------------===// 02028 // Transfer function: Objective-C @synchronized. 02029 //===----------------------------------------------------------------------===// 02030 02031 void GRExprEngine::VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S, 02032 ExplodedNode *Pred, 02033 ExplodedNodeSet &Dst) { 02034 02035 // The mutex expression is a CFGElement, so we don't need to explicitly 02036 // visit it since it will already be processed. 02037 02038 // Pre-visit the ObjCAtSynchronizedStmt. 02039 ExplodedNodeSet Tmp; 02040 Tmp.Add(Pred); 02041 CheckerVisit(S, Dst, Tmp, PreVisitStmtCallback); 02042 } 02043 02044 //===----------------------------------------------------------------------===// 02045 // Transfer function: Objective-C ivar references. 02046 //===----------------------------------------------------------------------===// 02047 02048 void GRExprEngine::VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr* Ex, 02049 ExplodedNode* Pred, 02050 ExplodedNodeSet& Dst) { 02051 02052 // Visit the base expression, which is needed for computing the lvalue 02053 // of the ivar. 02054 ExplodedNodeSet dstBase; 02055 const Expr *baseExpr = Ex->getBase(); 02056 Visit(baseExpr, Pred, dstBase); 02057 02058 // Using the base, compute the lvalue of the instance variable. 02059 for (ExplodedNodeSet::iterator I = dstBase.begin(), E = dstBase.end(); 02060 I!=E; ++I) { 02061 ExplodedNode *nodeBase = *I; 02062 const GRState *state = GetState(nodeBase); 02063 SVal baseVal = state->getSVal(baseExpr); 02064 SVal location = state->getLValue(Ex->getDecl(), baseVal); 02065 MakeNode(Dst, Ex, *I, state->BindExpr(Ex, location)); 02066 } 02067 } 02068 02069 //===----------------------------------------------------------------------===// 02070 // Transfer function: Objective-C fast enumeration 'for' statements. 02071 //===----------------------------------------------------------------------===// 02072 02073 void GRExprEngine::VisitObjCForCollectionStmt(const ObjCForCollectionStmt* S, 02074 ExplodedNode* Pred, ExplodedNodeSet& Dst) { 02075 02076 // ObjCForCollectionStmts are processed in two places. This method 02077 // handles the case where an ObjCForCollectionStmt* occurs as one of the 02078 // statements within a basic block. This transfer function does two things: 02079 // 02080 // (1) binds the next container value to 'element'. This creates a new 02081 // node in the ExplodedGraph. 02082 // 02083 // (2) binds the value 0/1 to the ObjCForCollectionStmt* itself, indicating 02084 // whether or not the container has any more elements. This value 02085 // will be tested in ProcessBranch. We need to explicitly bind 02086 // this value because a container can contain nil elements. 02087 // 02088 // FIXME: Eventually this logic should actually do dispatches to 02089 // 'countByEnumeratingWithState:objects:count:' (NSFastEnumeration). 02090 // This will require simulating a temporary NSFastEnumerationState, either 02091 // through an SVal or through the use of MemRegions. This value can 02092 // be affixed to the ObjCForCollectionStmt* instead of 0/1; when the loop 02093 // terminates we reclaim the temporary (it goes out of scope) and we 02094 // we can test if the SVal is 0 or if the MemRegion is null (depending 02095 // on what approach we take). 02096 // 02097 // For now: simulate (1) by assigning either a symbol or nil if the 02098 // container is empty. Thus this transfer function will by default 02099 // result in state splitting. 02100 02101 const Stmt* elem = S->getElement(); 02102 SVal ElementV; 02103 02104 if (const DeclStmt* DS = dyn_cast<DeclStmt>(elem)) { 02105 const VarDecl* ElemD = cast<VarDecl>(DS->getSingleDecl()); 02106 assert (ElemD->getInit() == 0); 02107 ElementV = GetState(Pred)->getLValue(ElemD, Pred->getLocationContext()); 02108 VisitObjCForCollectionStmtAux(S, Pred, Dst, ElementV); 02109 return; 02110 } 02111 02112 ExplodedNodeSet Tmp; 02113 Visit(cast<Expr>(elem), Pred, Tmp); 02114 for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I) { 02115 const GRState* state = GetState(*I); 02116 VisitObjCForCollectionStmtAux(S, *I, Dst, state->getSVal(elem)); 02117 } 02118 } 02119 02120 void GRExprEngine::VisitObjCForCollectionStmtAux(const ObjCForCollectionStmt* S, 02121 ExplodedNode* Pred, ExplodedNodeSet& Dst, 02122 SVal ElementV) { 02123 02124 // Check if the location we are writing back to is a null pointer. 02125 const Stmt* elem = S->getElement(); 02126 ExplodedNodeSet Tmp; 02127 evalLocation(Tmp, elem, Pred, GetState(Pred), ElementV, NULL, false); 02128 02129 if (Tmp.empty()) 02130 return; 02131 02132 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) { 02133 Pred = *NI; 02134 const GRState *state = GetState(Pred); 02135 02136 // Handle the case where the container still has elements. 02137 SVal TrueV = svalBuilder.makeTruthVal(1); 02138 const GRState *hasElems = state->BindExpr(S, TrueV); 02139 02140 // Handle the case where the container has no elements. 02141 SVal FalseV = svalBuilder.makeTruthVal(0); 02142 const GRState *noElems = state->BindExpr(S, FalseV); 02143 02144 if (loc::MemRegionVal* MV = dyn_cast<loc::MemRegionVal>(&ElementV)) 02145 if (const TypedRegion* R = dyn_cast<TypedRegion>(MV->getRegion())) { 02146 // FIXME: The proper thing to do is to really iterate over the 02147 // container. We will do this with dispatch logic to the store. 02148 // For now, just 'conjure' up a symbolic value. 02149 QualType T = R->getValueType(); 02150 assert(Loc::IsLocType(T)); 02151 unsigned Count = Builder->getCurrentBlockCount(); 02152 SymbolRef Sym = SymMgr.getConjuredSymbol(elem, T, Count); 02153 SVal V = svalBuilder.makeLoc(Sym); 02154 hasElems = hasElems->bindLoc(ElementV, V); 02155 02156 // Bind the location to 'nil' on the false branch. 02157 SVal nilV = svalBuilder.makeIntVal(0, T); 02158 noElems = noElems->bindLoc(ElementV, nilV); 02159 } 02160 02161 // Create the new nodes. 02162 MakeNode(Dst, S, Pred, hasElems); 02163 MakeNode(Dst, S, Pred, noElems); 02164 } 02165 } 02166 02167 //===----------------------------------------------------------------------===// 02168 // Transfer function: Objective-C message expressions. 02169 //===----------------------------------------------------------------------===// 02170 02171 namespace { 02172 class ObjCMsgWLItem { 02173 public: 02174 ObjCMessageExpr::const_arg_iterator I; 02175 ExplodedNode *N; 02176 02177 ObjCMsgWLItem(const ObjCMessageExpr::const_arg_iterator &i, ExplodedNode *n) 02178 : I(i), N(n) {} 02179 }; 02180 } // end anonymous namespace 02181 02182 void GRExprEngine::VisitObjCMessageExpr(const ObjCMessageExpr* ME, 02183 ExplodedNode* Pred, 02184 ExplodedNodeSet& Dst){ 02185 02186 // Create a worklist to process both the arguments. 02187 llvm::SmallVector<ObjCMsgWLItem, 20> WL; 02188 02189 // But first evaluate the receiver (if any). 02190 ObjCMessageExpr::const_arg_iterator AI = ME->arg_begin(), AE = ME->arg_end(); 02191 if (const Expr *Receiver = ME->getInstanceReceiver()) { 02192 ExplodedNodeSet Tmp; 02193 Visit(Receiver, Pred, Tmp); 02194 02195 if (Tmp.empty()) 02196 return; 02197 02198 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) 02199 WL.push_back(ObjCMsgWLItem(AI, *I)); 02200 } 02201 else 02202 WL.push_back(ObjCMsgWLItem(AI, Pred)); 02203 02204 // Evaluate the arguments. 02205 ExplodedNodeSet ArgsEvaluated; 02206 while (!WL.empty()) { 02207 ObjCMsgWLItem Item = WL.back(); 02208 WL.pop_back(); 02209 02210 if (Item.I == AE) { 02211 ArgsEvaluated.insert(Item.N); 02212 continue; 02213 } 02214 02215 // Evaluate the subexpression. 02216 ExplodedNodeSet Tmp; 02217 02218 // FIXME: [Objective-C++] handle arguments that are references 02219 Visit(*Item.I, Item.N, Tmp); 02220 02221 // Enqueue evaluating the next argument on the worklist. 02222 ++(Item.I); 02223 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) 02224 WL.push_back(ObjCMsgWLItem(Item.I, *NI)); 02225 } 02226 02227 // Now that the arguments are processed, handle the previsits checks. 02228 ExplodedNodeSet DstPrevisit; 02229 CheckerVisit(ME, DstPrevisit, ArgsEvaluated, PreVisitStmtCallback); 02230 02231 // Proceed with evaluate the message expression. 02232 ExplodedNodeSet dstEval; 02233 02234 for (ExplodedNodeSet::iterator DI = DstPrevisit.begin(), 02235 DE = DstPrevisit.end(); DI != DE; ++DI) { 02236 02237 Pred = *DI; 02238 bool RaisesException = false; 02239 unsigned oldSize = dstEval.size(); 02240 SaveAndRestore<bool> OldSink(Builder->BuildSinks); 02241 SaveOr OldHasGen(Builder->HasGeneratedNode); 02242 02243 if (const Expr *Receiver = ME->getInstanceReceiver()) { 02244 const GRState *state = GetState(Pred); 02245 02246 // Bifurcate the state into nil and non-nil ones. 02247 DefinedOrUnknownSVal receiverVal = 02248 cast<DefinedOrUnknownSVal>(state->getSVal(Receiver)); 02249 02250 const GRState *notNilState, *nilState; 02251 llvm::tie(notNilState, nilState) = state->assume(receiverVal); 02252 02253 // There are three cases: can be nil or non-nil, must be nil, must be 02254 // non-nil. We handle must be nil, and merge the rest two into non-nil. 02255 if (nilState && !notNilState) { 02256 CheckerEvalNilReceiver(ME, dstEval, nilState, Pred); 02257 continue; 02258 } 02259 02260 // Check if the "raise" message was sent. 02261 assert(notNilState); 02262 if (ME->getSelector() == RaiseSel) 02263 RaisesException = true; 02264 02265 // Check if we raise an exception. For now treat these as sinks. 02266 // Eventually we will want to handle exceptions properly. 02267 if (RaisesException) 02268 Builder->BuildSinks = true; 02269 02270 // Dispatch to plug-in transfer function. 02271 evalObjCMessageExpr(dstEval, ME, Pred, notNilState); 02272 } 02273 else if (ObjCInterfaceDecl *Iface = ME->getReceiverInterface()) { 02274 IdentifierInfo* ClsName = Iface->getIdentifier(); 02275 Selector S = ME->getSelector(); 02276 02277 // Check for special instance methods. 02278 if (!NSExceptionII) { 02279 ASTContext& Ctx = getContext(); 02280 NSExceptionII = &Ctx.Idents.get("NSException"); 02281 } 02282 02283 if (ClsName == NSExceptionII) { 02284 enum { NUM_RAISE_SELECTORS = 2 }; 02285 02286 // Lazily create a cache of the selectors. 02287 if (!NSExceptionInstanceRaiseSelectors) { 02288 ASTContext& Ctx = getContext(); 02289 NSExceptionInstanceRaiseSelectors = 02290 new Selector[NUM_RAISE_SELECTORS]; 02291 llvm::SmallVector<IdentifierInfo*, NUM_RAISE_SELECTORS> II; 02292 unsigned idx = 0; 02293 02294 // raise:format: 02295 II.push_back(&Ctx.Idents.get("raise")); 02296 II.push_back(&Ctx.Idents.get("format")); 02297 NSExceptionInstanceRaiseSelectors[idx++] = 02298 Ctx.Selectors.getSelector(II.size(), &II[0]); 02299 02300 // raise:format::arguments: 02301 II.push_back(&Ctx.Idents.get("arguments")); 02302 NSExceptionInstanceRaiseSelectors[idx++] = 02303 Ctx.Selectors.getSelector(II.size(), &II[0]); 02304 } 02305 02306 for (unsigned i = 0; i < NUM_RAISE_SELECTORS; ++i) 02307 if (S == NSExceptionInstanceRaiseSelectors[i]) { 02308 RaisesException = true; 02309 break; 02310 } 02311 } 02312 02313 // Check if we raise an exception. For now treat these as sinks. 02314 // Eventually we will want to handle exceptions properly. 02315 if (RaisesException) 02316 Builder->BuildSinks = true; 02317 02318 // Dispatch to plug-in transfer function. 02319 evalObjCMessageExpr(dstEval, ME, Pred, Builder->GetState(Pred)); 02320 } 02321 02322 // Handle the case where no nodes where generated. Auto-generate that 02323 // contains the updated state if we aren't generating sinks. 02324 if (!Builder->BuildSinks && dstEval.size() == oldSize && 02325 !Builder->HasGeneratedNode) 02326 MakeNode(dstEval, ME, Pred, GetState(Pred)); 02327 } 02328 02329 // Finally, perform the post-condition check of the ObjCMessageExpr and store 02330 // the created nodes in 'Dst'. 02331 CheckerVisit(ME, Dst, dstEval, PostVisitStmtCallback); 02332 } 02333 02334 //===----------------------------------------------------------------------===// 02335 // Transfer functions: Miscellaneous statements. 02336 //===----------------------------------------------------------------------===// 02337 02338 void GRExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex, 02339 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 02340 02341 ExplodedNodeSet S1; 02342 Visit(Ex, Pred, S1); 02343 ExplodedNodeSet S2; 02344 CheckerVisit(CastE, S2, S1, PreVisitStmtCallback); 02345 02346 if (CastE->getCastKind() == CK_LValueToRValue) { 02347 for (ExplodedNodeSet::iterator I = S2.begin(), E = S2.end(); I!=E; ++I) { 02348 ExplodedNode *subExprNode = *I; 02349 const GRState *state = GetState(subExprNode); 02350 evalLoad(Dst, CastE, subExprNode, state, state->getSVal(Ex)); 02351 } 02352 return; 02353 } 02354 02355 // All other casts. 02356 QualType T = CastE->getType(); 02357 QualType ExTy = Ex->getType(); 02358 02359 if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE)) 02360 T = ExCast->getTypeAsWritten(); 02361 02362 #if 0 02363 // If we are evaluating the cast in an lvalue context, we implicitly want 02364 // the cast to evaluate to a location. 02365 if (asLValue) { 02366 ASTContext &Ctx = getContext(); 02367 T = Ctx.getPointerType(Ctx.getCanonicalType(T)); 02368 ExTy = Ctx.getPointerType(Ctx.getCanonicalType(ExTy)); 02369 } 02370 #endif 02371 02372 switch (CastE->getCastKind()) { 02373 case CK_ToVoid: 02374 for (ExplodedNodeSet::iterator I = S2.begin(), E = S2.end(); I != E; ++I) 02375 Dst.Add(*I); 02376 return; 02377 02378 case CK_LValueToRValue: 02379 case CK_NoOp: 02380 case CK_FunctionToPointerDecay: 02381 for (ExplodedNodeSet::iterator I = S2.begin(), E = S2.end(); I != E; ++I) { 02382 // Copy the SVal of Ex to CastE. 02383 ExplodedNode *N = *I; 02384 const GRState *state = GetState(N); 02385 SVal V = state->getSVal(Ex); 02386 state = state->BindExpr(CastE, V); 02387 MakeNode(Dst, CastE, N, state); 02388 } 02389 return; 02390 02391 case CK_GetObjCProperty: 02392 case CK_Dependent: 02393 case CK_ArrayToPointerDecay: 02394 case CK_BitCast: 02395 case CK_LValueBitCast: 02396 case CK_IntegralCast: 02397 case CK_NullToPointer: 02398 case CK_IntegralToPointer: 02399 case CK_PointerToIntegral: 02400 case CK_PointerToBoolean: 02401 case CK_IntegralToBoolean: 02402 case CK_IntegralToFloating: 02403 case CK_FloatingToIntegral: 02404 case CK_FloatingToBoolean: 02405 case CK_FloatingCast: 02406 case CK_FloatingRealToComplex: 02407 case CK_FloatingComplexToReal: 02408 case CK_FloatingComplexToBoolean: 02409 case CK_FloatingComplexCast: 02410 case CK_FloatingComplexToIntegralComplex: 02411 case CK_IntegralRealToComplex: 02412 case CK_IntegralComplexToReal: 02413 case CK_IntegralComplexToBoolean: 02414 case CK_IntegralComplexCast: 02415 case CK_IntegralComplexToFloatingComplex: 02416 case CK_AnyPointerToObjCPointerCast: 02417 case CK_AnyPointerToBlockPointerCast: 02418 02419 case CK_ObjCObjectLValueCast: { 02420 // Delegate to SValBuilder to process. 02421 for (ExplodedNodeSet::iterator I = S2.begin(), E = S2.end(); I != E; ++I) { 02422 ExplodedNode* N = *I; 02423 const GRState* state = GetState(N); 02424 SVal V = state->getSVal(Ex); 02425 V = svalBuilder.evalCast(V, T, ExTy); 02426 state = state->BindExpr(CastE, V); 02427 MakeNode(Dst, CastE, N, state); 02428 } 02429 return; 02430 } 02431 02432 case CK_DerivedToBase: 02433 case CK_UncheckedDerivedToBase: 02434 // For DerivedToBase cast, delegate to the store manager. 02435 for (ExplodedNodeSet::iterator I = S2.begin(), E = S2.end(); I != E; ++I) { 02436 ExplodedNode *node = *I; 02437 const GRState *state = GetState(node); 02438 SVal val = state->getSVal(Ex); 02439 val = getStoreManager().evalDerivedToBase(val, T); 02440 state = state->BindExpr(CastE, val); 02441 MakeNode(Dst, CastE, node, state); 02442 } 02443 return; 02444 02445 // Various C++ casts that are not handled yet. 02446 case CK_Dynamic: 02447 case CK_ToUnion: 02448 case CK_BaseToDerived: 02449 case CK_NullToMemberPointer: 02450 case CK_BaseToDerivedMemberPointer: 02451 case CK_DerivedToBaseMemberPointer: 02452 case CK_UserDefinedConversion: 02453 case CK_ConstructorConversion: 02454 case CK_VectorSplat: 02455 case CK_MemberPointerToBoolean: { 02456 SaveAndRestore<bool> OldSink(Builder->BuildSinks); 02457 Builder->BuildSinks = true; 02458 MakeNode(Dst, CastE, Pred, GetState(Pred)); 02459 return; 02460 } 02461 } 02462 } 02463 02464 void GRExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr* CL, 02465 ExplodedNode* Pred, 02466 ExplodedNodeSet& Dst) { 02467 const InitListExpr* ILE 02468 = cast<InitListExpr>(CL->getInitializer()->IgnoreParens()); 02469 ExplodedNodeSet Tmp; 02470 Visit(ILE, Pred, Tmp); 02471 02472 for (ExplodedNodeSet::iterator I = Tmp.begin(), EI = Tmp.end(); I!=EI; ++I) { 02473 const GRState* state = GetState(*I); 02474 SVal ILV = state->getSVal(ILE); 02475 const LocationContext *LC = (*I)->getLocationContext(); 02476 state = state->bindCompoundLiteral(CL, LC, ILV); 02477 02478 if (CL->isLValue()) { 02479 MakeNode(Dst, CL, *I, state->BindExpr(CL, state->getLValue(CL, LC))); 02480 } 02481 else 02482 MakeNode(Dst, CL, *I, state->BindExpr(CL, ILV)); 02483 } 02484 } 02485 02486 void GRExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred, 02487 ExplodedNodeSet& Dst) { 02488 02489 // The CFG has one DeclStmt per Decl. 02490 const Decl* D = *DS->decl_begin(); 02491 02492 if (!D || !isa<VarDecl>(D)) 02493 return; 02494 02495 const VarDecl* VD = dyn_cast<VarDecl>(D); 02496 const Expr* InitEx = VD->getInit(); 02497 02498 // FIXME: static variables may have an initializer, but the second 02499 // time a function is called those values may not be current. 02500 ExplodedNodeSet Tmp; 02501 02502 if (InitEx) { 02503 if (VD->getType()->isReferenceType() && !InitEx->isLValue()) { 02504 // If the initializer is C++ record type, it should already has a 02505 // temp object. 02506 if (!InitEx->getType()->isRecordType()) 02507 CreateCXXTemporaryObject(InitEx, Pred, Tmp); 02508 else 02509 Tmp.Add(Pred); 02510 } else 02511 Visit(InitEx, Pred, Tmp); 02512 } else 02513 Tmp.Add(Pred); 02514 02515 ExplodedNodeSet Tmp2; 02516 CheckerVisit(DS, Tmp2, Tmp, PreVisitStmtCallback); 02517 02518 for (ExplodedNodeSet::iterator I=Tmp2.begin(), E=Tmp2.end(); I!=E; ++I) { 02519 ExplodedNode *N = *I; 02520 const GRState *state = GetState(N); 02521 02522 // Decls without InitExpr are not initialized explicitly. 02523 const LocationContext *LC = N->getLocationContext(); 02524 02525 if (InitEx) { 02526 SVal InitVal = state->getSVal(InitEx); 02527 02528 // We bound the temp obj region to the CXXConstructExpr. Now recover 02529 // the lazy compound value when the variable is not a reference. 02530 if (AMgr.getLangOptions().CPlusPlus && VD->getType()->isRecordType() && 02531 !VD->getType()->isReferenceType() && isa<loc::MemRegionVal>(InitVal)){ 02532 InitVal = state->getSVal(cast<loc::MemRegionVal>(InitVal).getRegion()); 02533 assert(isa<nonloc::LazyCompoundVal>(InitVal)); 02534 } 02535 02536 // Recover some path-sensitivity if a scalar value evaluated to 02537 // UnknownVal. 02538 if ((InitVal.isUnknown() || 02539 !getConstraintManager().canReasonAbout(InitVal)) && 02540 !VD->getType()->isReferenceType()) { 02541 InitVal = svalBuilder.getConjuredSymbolVal(NULL, InitEx, 02542 Builder->getCurrentBlockCount()); 02543 } 02544 02545 evalBind(Dst, DS, *I, state, 02546 loc::MemRegionVal(state->getRegion(VD, LC)), InitVal, true); 02547 } 02548 else { 02549 state = state->bindDeclWithNoInit(state->getRegion(VD, LC)); 02550 MakeNode(Dst, DS, *I, state); 02551 } 02552 } 02553 } 02554 02555 void GRExprEngine::VisitCondInit(const VarDecl *VD, const Stmt *S, 02556 ExplodedNode *Pred, ExplodedNodeSet& Dst) { 02557 02558 const Expr* InitEx = VD->getInit(); 02559 ExplodedNodeSet Tmp; 02560 Visit(InitEx, Pred, Tmp); 02561 02562 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { 02563 ExplodedNode *N = *I; 02564 const GRState *state = GetState(N); 02565 02566 const LocationContext *LC = N->getLocationContext(); 02567 SVal InitVal = state->getSVal(InitEx); 02568 02569 // Recover some path-sensitivity if a scalar value evaluated to 02570 // UnknownVal. 02571 if (InitVal.isUnknown() || 02572 !getConstraintManager().canReasonAbout(InitVal)) { 02573 InitVal = svalBuilder.getConjuredSymbolVal(NULL, InitEx, 02574 Builder->getCurrentBlockCount()); 02575 } 02576 02577 evalBind(Dst, S, N, state, 02578 loc::MemRegionVal(state->getRegion(VD, LC)), InitVal, true); 02579 } 02580 } 02581 02582 namespace { 02583 // This class is used by VisitInitListExpr as an item in a worklist 02584 // for processing the values contained in an InitListExpr. 02585 class InitListWLItem { 02586 public: 02587 llvm::ImmutableList<SVal> Vals; 02588 ExplodedNode* N; 02589 InitListExpr::const_reverse_iterator Itr; 02590 02591 InitListWLItem(ExplodedNode* n, llvm::ImmutableList<SVal> vals, 02592 InitListExpr::const_reverse_iterator itr) 02593 : Vals(vals), N(n), Itr(itr) {} 02594 }; 02595 } 02596 02597 02598 void GRExprEngine::VisitInitListExpr(const InitListExpr* E, ExplodedNode* Pred, 02599 ExplodedNodeSet& Dst) { 02600 02601 const GRState* state = GetState(Pred); 02602 QualType T = getContext().getCanonicalType(E->getType()); 02603 unsigned NumInitElements = E->getNumInits(); 02604 02605 if (T->isArrayType() || T->isRecordType() || T->isVectorType()) { 02606 llvm::ImmutableList<SVal> StartVals = getBasicVals().getEmptySValList(); 02607 02608 // Handle base case where the initializer has no elements. 02609 // e.g: static int* myArray[] = {}; 02610 if (NumInitElements == 0) { 02611 SVal V = svalBuilder.makeCompoundVal(T, StartVals); 02612 MakeNode(Dst, E, Pred, state->BindExpr(E, V)); 02613 return; 02614 } 02615 02616 // Create a worklist to process the initializers. 02617 llvm::SmallVector<InitListWLItem, 10> WorkList; 02618 WorkList.reserve(NumInitElements); 02619 WorkList.push_back(InitListWLItem(Pred, StartVals, E->rbegin())); 02620 InitListExpr::const_reverse_iterator ItrEnd = E->rend(); 02621 assert(!(E->rbegin() == E->rend())); 02622 02623 // Process the worklist until it is empty. 02624 while (!WorkList.empty()) { 02625 InitListWLItem X = WorkList.back(); 02626 WorkList.pop_back(); 02627 02628 ExplodedNodeSet Tmp; 02629 Visit(*X.Itr, X.N, Tmp); 02630 02631 InitListExpr::const_reverse_iterator NewItr = X.Itr + 1; 02632 02633 for (ExplodedNodeSet::iterator NI=Tmp.begin(),NE=Tmp.end();NI!=NE;++NI) { 02634 // Get the last initializer value. 02635 state = GetState(*NI); 02636 SVal InitV = state->getSVal(cast<Expr>(*X.Itr)); 02637 02638 // Construct the new list of values by prepending the new value to 02639 // the already constructed list. 02640 llvm::ImmutableList<SVal> NewVals = 02641 getBasicVals().consVals(InitV, X.Vals); 02642 02643 if (NewItr == ItrEnd) { 02644 // Now we have a list holding all init values. Make CompoundValData. 02645 SVal V = svalBuilder.makeCompoundVal(T, NewVals); 02646 02647 // Make final state and node. 02648 MakeNode(Dst, E, *NI, state->BindExpr(E, V)); 02649 } 02650 else { 02651 // Still some initializer values to go. Push them onto the worklist. 02652 WorkList.push_back(InitListWLItem(*NI, NewVals, NewItr)); 02653 } 02654 } 02655 } 02656 02657 return; 02658 } 02659 02660 if (Loc::IsLocType(T) || T->isIntegerType()) { 02661 assert (E->getNumInits() == 1); 02662 ExplodedNodeSet Tmp; 02663 const Expr* Init = E->getInit(0); 02664 Visit(Init, Pred, Tmp); 02665 for (ExplodedNodeSet::iterator I=Tmp.begin(), EI=Tmp.end(); I != EI; ++I) { 02666 state = GetState(*I); 02667 MakeNode(Dst, E, *I, state->BindExpr(E, state->getSVal(Init))); 02668 } 02669 return; 02670 } 02671 02672 assert(0 && "unprocessed InitListExpr type"); 02673 } 02674 02675 /// VisitSizeOfAlignOfExpr - Transfer function for sizeof(type). 02676 void GRExprEngine::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr* Ex, 02677 ExplodedNode* Pred, 02678 ExplodedNodeSet& Dst) { 02679 QualType T = Ex->getTypeOfArgument(); 02680 CharUnits amt; 02681 02682 if (Ex->isSizeOf()) { 02683 if (T == getContext().VoidTy) { 02684 // sizeof(void) == 1 byte. 02685 amt = CharUnits::One(); 02686 } 02687 else if (!T->isConstantSizeType()) { 02688 assert(T->isVariableArrayType() && "Unknown non-constant-sized type."); 02689 02690 // FIXME: Add support for VLA type arguments, not just VLA expressions. 02691 // When that happens, we should probably refactor VLASizeChecker's code. 02692 if (Ex->isArgumentType()) { 02693 Dst.Add(Pred); 02694 return; 02695 } 02696 02697 // Get the size by getting the extent of the sub-expression. 02698 // First, visit the sub-expression to find its region. 02699 const Expr *Arg = Ex->getArgumentExpr(); 02700 ExplodedNodeSet Tmp; 02701 Visit(Arg, Pred, Tmp); 02702 02703 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { 02704 const GRState* state = GetState(*I); 02705 const MemRegion *MR = state->getSVal(Arg).getAsRegion(); 02706 02707 // If the subexpression can't be resolved to a region, we don't know 02708 // anything about its size. Just leave the state as is and continue. 02709 if (!MR) { 02710 Dst.Add(*I); 02711 continue; 02712 } 02713 02714 // The result is the extent of the VLA. 02715 SVal Extent = cast<SubRegion>(MR)->getExtent(svalBuilder); 02716 MakeNode(Dst, Ex, *I, state->BindExpr(Ex, Extent)); 02717 } 02718 02719 return; 02720 } 02721 else if (T->getAs<ObjCObjectType>()) { 02722 // Some code tries to take the sizeof an ObjCObjectType, relying that 02723 // the compiler has laid out its representation. Just report Unknown 02724 // for these. 02725 Dst.Add(Pred); 02726 return; 02727 } 02728 else { 02729 // All other cases. 02730 amt = getContext().getTypeSizeInChars(T); 02731 } 02732 } 02733 else // Get alignment of the type. 02734 amt = getContext().getTypeAlignInChars(T); 02735 02736 MakeNode(Dst, Ex, Pred, 02737 GetState(Pred)->BindExpr(Ex, 02738 svalBuilder.makeIntVal(amt.getQuantity(), Ex->getType()))); 02739 } 02740 02741 void GRExprEngine::VisitOffsetOfExpr(const OffsetOfExpr* OOE, 02742 ExplodedNode* Pred, ExplodedNodeSet& Dst) { 02743 Expr::EvalResult Res; 02744 if (OOE->Evaluate(Res, getContext()) && Res.Val.isInt()) { 02745 const APSInt &IV = Res.Val.getInt(); 02746 assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType())); 02747 assert(OOE->getType()->isIntegerType()); 02748 assert(IV.isSigned() == OOE->getType()->isSignedIntegerType()); 02749 SVal X = svalBuilder.makeIntVal(IV); 02750 MakeNode(Dst, OOE, Pred, GetState(Pred)->BindExpr(OOE, X)); 02751 return; 02752 } 02753 // FIXME: Handle the case where __builtin_offsetof is not a constant. 02754 Dst.Add(Pred); 02755 } 02756 02757 void GRExprEngine::VisitUnaryOperator(const UnaryOperator* U, 02758 ExplodedNode* Pred, 02759 ExplodedNodeSet& Dst) { 02760 02761 switch (U->getOpcode()) { 02762 02763 default: 02764 break; 02765 02766 case UO_Real: { 02767 const Expr* Ex = U->getSubExpr()->IgnoreParens(); 02768 ExplodedNodeSet Tmp; 02769 Visit(Ex, Pred, Tmp); 02770 02771 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { 02772 02773 // FIXME: We don't have complex SValues yet. 02774 if (Ex->getType()->isAnyComplexType()) { 02775 // Just report "Unknown." 02776 Dst.Add(*I); 02777 continue; 02778 } 02779 02780 // For all other types, UO_Real is an identity operation. 02781 assert (U->getType() == Ex->getType()); 02782 const GRState* state = GetState(*I); 02783 MakeNode(Dst, U, *I, state->BindExpr(U, state->getSVal(Ex))); 02784 } 02785 02786 return; 02787 } 02788 02789 case UO_Imag: { 02790 02791 const Expr* Ex = U->getSubExpr()->IgnoreParens(); 02792 ExplodedNodeSet Tmp; 02793 Visit(Ex, Pred, Tmp); 02794 02795 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { 02796 // FIXME: We don't have complex SValues yet. 02797 if (Ex->getType()->isAnyComplexType()) { 02798 // Just report "Unknown." 02799 Dst.Add(*I); 02800 continue; 02801 } 02802 02803 // For all other types, UO_Imag returns 0. 02804 const GRState* state = GetState(*I); 02805 SVal X = svalBuilder.makeZeroVal(Ex->getType()); 02806 MakeNode(Dst, U, *I, state->BindExpr(U, X)); 02807 } 02808 02809 return; 02810 } 02811 02812 case UO_Plus: 02813 assert(!U->isLValue()); 02814 // FALL-THROUGH. 02815 case UO_Deref: 02816 case UO_AddrOf: 02817 case UO_Extension: { 02818 02819 // Unary "+" is a no-op, similar to a parentheses. We still have places 02820 // where it may be a block-level expression, so we need to 02821 // generate an extra node that just propagates the value of the 02822 // subexpression. 02823 02824 const Expr* Ex = U->getSubExpr()->IgnoreParens(); 02825 ExplodedNodeSet Tmp; 02826 Visit(Ex, Pred, Tmp); 02827 02828 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { 02829 const GRState* state = GetState(*I); 02830 MakeNode(Dst, U, *I, state->BindExpr(U, state->getSVal(Ex))); 02831 } 02832 02833 return; 02834 } 02835 02836 case UO_LNot: 02837 case UO_Minus: 02838 case UO_Not: { 02839 assert (!U->isLValue()); 02840 const Expr* Ex = U->getSubExpr()->IgnoreParens(); 02841 ExplodedNodeSet Tmp; 02842 Visit(Ex, Pred, Tmp); 02843 02844 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { 02845 const GRState* state = GetState(*I); 02846 02847 // Get the value of the subexpression. 02848 SVal V = state->getSVal(Ex); 02849 02850 if (V.isUnknownOrUndef()) { 02851 MakeNode(Dst, U, *I, state->BindExpr(U, V)); 02852 continue; 02853 } 02854 02855 // QualType DstT = getContext().getCanonicalType(U->getType()); 02856 // QualType SrcT = getContext().getCanonicalType(Ex->getType()); 02857 // 02858 // if (DstT != SrcT) // Perform promotions. 02859 // V = evalCast(V, DstT); 02860 // 02861 // if (V.isUnknownOrUndef()) { 02862 // MakeNode(Dst, U, *I, BindExpr(St, U, V)); 02863 // continue; 02864 // } 02865 02866 switch (U->getOpcode()) { 02867 default: 02868 assert(false && "Invalid Opcode."); 02869 break; 02870 02871 case UO_Not: 02872 // FIXME: Do we need to handle promotions? 02873 state = state->BindExpr(U, evalComplement(cast<NonLoc>(V))); 02874 break; 02875 02876 case UO_Minus: 02877 // FIXME: Do we need to handle promotions? 02878 state = state->BindExpr(U, evalMinus(cast<NonLoc>(V))); 02879 break; 02880 02881 case UO_LNot: 02882 02883 // C99 6.5.3.3: "The expression !E is equivalent to (0==E)." 02884 // 02885 // Note: technically we do "E == 0", but this is the same in the 02886 // transfer functions as "0 == E". 02887 SVal Result; 02888 02889 if (isa<Loc>(V)) { 02890 Loc X = svalBuilder.makeNull(); 02891 Result = evalBinOp(state, BO_EQ, cast<Loc>(V), X, 02892 U->getType()); 02893 } 02894 else { 02895 nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType())); 02896 Result = evalBinOp(state, BO_EQ, cast<NonLoc>(V), X, 02897 U->getType()); 02898 } 02899 02900 state = state->BindExpr(U, Result); 02901 02902 break; 02903 } 02904 02905 MakeNode(Dst, U, *I, state); 02906 } 02907 02908 return; 02909 } 02910 } 02911 02912 // Handle ++ and -- (both pre- and post-increment). 02913 assert (U->isIncrementDecrementOp()); 02914 ExplodedNodeSet Tmp; 02915 const Expr* Ex = U->getSubExpr()->IgnoreParens(); 02916 Visit(Ex, Pred, Tmp); 02917 02918 for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I) { 02919 02920 const GRState* state = GetState(*I); 02921 SVal loc = state->getSVal(Ex); 02922 02923 // Perform a load. 02924 ExplodedNodeSet Tmp2; 02925 evalLoad(Tmp2, Ex, *I, state, loc); 02926 02927 for (ExplodedNodeSet::iterator I2=Tmp2.begin(), E2=Tmp2.end();I2!=E2;++I2) { 02928 02929 state = GetState(*I2); 02930 SVal V2_untested = state->getSVal(Ex); 02931 02932 // Propagate unknown and undefined values. 02933 if (V2_untested.isUnknownOrUndef()) { 02934 MakeNode(Dst, U, *I2, state->BindExpr(U, V2_untested)); 02935 continue; 02936 } 02937 DefinedSVal V2 = cast<DefinedSVal>(V2_untested); 02938 02939 // Handle all other values. 02940 BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add 02941 : BO_Sub; 02942 02943 // If the UnaryOperator has non-location type, use its type to create the 02944 // constant value. If the UnaryOperator has location type, create the 02945 // constant with int type and pointer width. 02946 SVal RHS; 02947 02948 if (U->getType()->isAnyPointerType()) 02949 RHS = svalBuilder.makeIntValWithPtrWidth(1, false); 02950 else 02951 RHS = svalBuilder.makeIntVal(1, U->getType()); 02952 02953 SVal Result = evalBinOp(state, Op, V2, RHS, U->getType()); 02954 02955 // Conjure a new symbol if necessary to recover precision. 02956 if (Result.isUnknown() || !getConstraintManager().canReasonAbout(Result)){ 02957 DefinedOrUnknownSVal SymVal = 02958 svalBuilder.getConjuredSymbolVal(NULL, Ex, 02959 Builder->getCurrentBlockCount()); 02960 Result = SymVal; 02961 02962 // If the value is a location, ++/-- should always preserve 02963 // non-nullness. Check if the original value was non-null, and if so 02964 // propagate that constraint. 02965 if (Loc::IsLocType(U->getType())) { 02966 DefinedOrUnknownSVal Constraint = 02967 svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType())); 02968 02969 if (!state->assume(Constraint, true)) { 02970 // It isn't feasible for the original value to be null. 02971 // Propagate this constraint. 02972 Constraint = svalBuilder.evalEQ(state, SymVal, 02973 svalBuilder.makeZeroVal(U->getType())); 02974 02975 02976 state = state->assume(Constraint, false); 02977 assert(state); 02978 } 02979 } 02980 } 02981 02982 // Since the lvalue-to-rvalue conversion is explicit in the AST, 02983 // we bind an l-value if the operator is prefix and an lvalue (in C++). 02984 if (U->isPrefix() && U->isLValue()) 02985 state = state->BindExpr(U, loc); 02986 else 02987 state = state->BindExpr(U, V2); 02988 02989 // Perform the store. 02990 evalStore(Dst, NULL, U, *I2, state, loc, Result); 02991 } 02992 } 02993 } 02994 02995 void GRExprEngine::VisitAsmStmt(const AsmStmt* A, ExplodedNode* Pred, 02996 ExplodedNodeSet& Dst) { 02997 VisitAsmStmtHelperOutputs(A, A->begin_outputs(), A->end_outputs(), Pred, Dst); 02998 } 02999 03000 void GRExprEngine::VisitAsmStmtHelperOutputs(const AsmStmt* A, 03001 AsmStmt::const_outputs_iterator I, 03002 AsmStmt::const_outputs_iterator E, 03003 ExplodedNode* Pred, ExplodedNodeSet& Dst) { 03004 if (I == E) { 03005 VisitAsmStmtHelperInputs(A, A->begin_inputs(), A->end_inputs(), Pred, Dst); 03006 return; 03007 } 03008 03009 ExplodedNodeSet Tmp; 03010 Visit(*I, Pred, Tmp); 03011 ++I; 03012 03013 for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end();NI != NE;++NI) 03014 VisitAsmStmtHelperOutputs(A, I, E, *NI, Dst); 03015 } 03016 03017 void GRExprEngine::VisitAsmStmtHelperInputs(const AsmStmt* A, 03018 AsmStmt::const_inputs_iterator I, 03019 AsmStmt::const_inputs_iterator E, 03020 ExplodedNode* Pred, 03021 ExplodedNodeSet& Dst) { 03022 if (I == E) { 03023 03024 // We have processed both the inputs and the outputs. All of the outputs 03025 // should evaluate to Locs. Nuke all of their values. 03026 03027 // FIXME: Some day in the future it would be nice to allow a "plug-in" 03028 // which interprets the inline asm and stores proper results in the 03029 // outputs. 03030 03031 const GRState* state = GetState(Pred); 03032 03033 for (AsmStmt::const_outputs_iterator OI = A->begin_outputs(), 03034 OE = A->end_outputs(); OI != OE; ++OI) { 03035 03036 SVal X = state->getSVal(*OI); 03037 assert (!isa<NonLoc>(X)); // Should be an Lval, or unknown, undef. 03038 03039 if (isa<Loc>(X)) 03040 state = state->bindLoc(cast<Loc>(X), UnknownVal()); 03041 } 03042 03043 MakeNode(Dst, A, Pred, state); 03044 return; 03045 } 03046 03047 ExplodedNodeSet Tmp; 03048 Visit(*I, Pred, Tmp); 03049 03050 ++I; 03051 03052 for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end(); NI!=NE; ++NI) 03053 VisitAsmStmtHelperInputs(A, I, E, *NI, Dst); 03054 } 03055 03056 void GRExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred, 03057 ExplodedNodeSet &Dst) { 03058 ExplodedNodeSet Src; 03059 if (const Expr *RetE = RS->getRetValue()) { 03060 // Record the returned expression in the state. It will be used in 03061 // ProcessCallExit to bind the return value to the call expr. 03062 { 03063 static int Tag = 0; 03064 SaveAndRestore<const void *> OldTag(Builder->Tag, &Tag); 03065 const GRState *state = GetState(Pred); 03066 state = state->set<ReturnExpr>(RetE); 03067 Pred = Builder->generateNode(RetE, state, Pred); 03068 } 03069 // We may get a NULL Pred because we generated a cached node. 03070 if (Pred) 03071 Visit(RetE, Pred, Src); 03072 } 03073 else { 03074 Src.Add(Pred); 03075 } 03076 03077 ExplodedNodeSet CheckedSet; 03078 CheckerVisit(RS, CheckedSet, Src, PreVisitStmtCallback); 03079 03080 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 03081 I != E; ++I) { 03082 03083 assert(Builder && "GRStmtNodeBuilder must be defined."); 03084 03085 Pred = *I; 03086 unsigned size = Dst.size(); 03087 03088 SaveAndRestore<bool> OldSink(Builder->BuildSinks); 03089 SaveOr OldHasGen(Builder->HasGeneratedNode); 03090 03091 getTF().evalReturn(Dst, *this, *Builder, RS, Pred); 03092 03093 // Handle the case where no nodes where generated. 03094 if (!Builder->BuildSinks && Dst.size() == size && 03095 !Builder->HasGeneratedNode) 03096 MakeNode(Dst, RS, Pred, GetState(Pred)); 03097 } 03098 } 03099 03100 //===----------------------------------------------------------------------===// 03101 // Transfer functions: Binary operators. 03102 //===----------------------------------------------------------------------===// 03103 03104 void GRExprEngine::VisitBinaryOperator(const BinaryOperator* B, 03105 ExplodedNode* Pred, 03106 ExplodedNodeSet& Dst) { 03107 ExplodedNodeSet Tmp1; 03108 Expr* LHS = B->getLHS()->IgnoreParens(); 03109 Expr* RHS = B->getRHS()->IgnoreParens(); 03110 03111 Visit(LHS, Pred, Tmp1); 03112 ExplodedNodeSet Tmp3; 03113 03114 for (ExplodedNodeSet::iterator I1=Tmp1.begin(), E1=Tmp1.end(); I1!=E1; ++I1) { 03115 SVal LeftV = GetState(*I1)->getSVal(LHS); 03116 ExplodedNodeSet Tmp2; 03117 Visit(RHS, *I1, Tmp2); 03118 03119 ExplodedNodeSet CheckedSet; 03120 CheckerVisit(B, CheckedSet, Tmp2, PreVisitStmtCallback); 03121 03122 // With both the LHS and RHS evaluated, process the operation itself. 03123 03124 for (ExplodedNodeSet::iterator I2=CheckedSet.begin(), E2=CheckedSet.end(); 03125 I2 != E2; ++I2) { 03126 03127 const GRState *state = GetState(*I2); 03128 SVal RightV = state->getSVal(RHS); 03129 03130 BinaryOperator::Opcode Op = B->getOpcode(); 03131 03132 if (Op == BO_Assign) { 03133 // EXPERIMENTAL: "Conjured" symbols. 03134 // FIXME: Handle structs. 03135 QualType T = RHS->getType(); 03136 03137 if (RightV.isUnknown() ||!getConstraintManager().canReasonAbout(RightV)) 03138 { 03139 unsigned Count = Builder->getCurrentBlockCount(); 03140 RightV = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), Count); 03141 } 03142 03143 SVal ExprVal = B->isLValue() ? LeftV : RightV; 03144 03145 // Simulate the effects of a "store": bind the value of the RHS 03146 // to the L-Value represented by the LHS. 03147 evalStore(Tmp3, B, LHS, *I2, state->BindExpr(B, ExprVal), LeftV,RightV); 03148 continue; 03149 } 03150 03151 if (!B->isAssignmentOp()) { 03152 // Process non-assignments except commas or short-circuited 03153 // logical expressions (LAnd and LOr). 03154 SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType()); 03155 03156 if (Result.isUnknown()) { 03157 MakeNode(Tmp3, B, *I2, state); 03158 continue; 03159 } 03160 03161 state = state->BindExpr(B, Result); 03162 03163 MakeNode(Tmp3, B, *I2, state); 03164 continue; 03165 } 03166 03167 assert (B->isCompoundAssignmentOp()); 03168 03169 switch (Op) { 03170 default: 03171 assert(0 && "Invalid opcode for compound assignment."); 03172 case BO_MulAssign: Op = BO_Mul; break; 03173 case BO_DivAssign: Op = BO_Div; break; 03174 case BO_RemAssign: Op = BO_Rem; break; 03175 case BO_AddAssign: Op = BO_Add; break; 03176 case BO_SubAssign: Op = BO_Sub; break; 03177 case BO_ShlAssign: Op = BO_Shl; break; 03178 case BO_ShrAssign: Op = BO_Shr; break; 03179 case BO_AndAssign: Op = BO_And; break; 03180 case BO_XorAssign: Op = BO_Xor; break; 03181 case BO_OrAssign: Op = BO_Or; break; 03182 } 03183 03184 // Perform a load (the LHS). This performs the checks for 03185 // null dereferences, and so on. 03186 ExplodedNodeSet Tmp4; 03187 SVal location = state->getSVal(LHS); 03188 evalLoad(Tmp4, LHS, *I2, state, location); 03189 03190 for (ExplodedNodeSet::iterator I4=Tmp4.begin(), E4=Tmp4.end(); I4!=E4; 03191 ++I4) { 03192 state = GetState(*I4); 03193 SVal V = state->getSVal(LHS); 03194 03195 // Get the computation type. 03196 QualType CTy = 03197 cast<CompoundAssignOperator>(B)->getComputationResultType(); 03198 CTy = getContext().getCanonicalType(CTy); 03199 03200 QualType CLHSTy = 03201 cast<CompoundAssignOperator>(B)->getComputationLHSType(); 03202 CLHSTy = getContext().getCanonicalType(CLHSTy); 03203 03204 QualType LTy = getContext().getCanonicalType(LHS->getType()); 03205 QualType RTy = getContext().getCanonicalType(RHS->getType()); 03206 03207 // Promote LHS. 03208 V = svalBuilder.evalCast(V, CLHSTy, LTy); 03209 03210 // Compute the result of the operation. 03211 SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy), 03212 B->getType(), CTy); 03213 03214 // EXPERIMENTAL: "Conjured" symbols. 03215 // FIXME: Handle structs. 03216 03217 SVal LHSVal; 03218 03219 if (Result.isUnknown() || 03220 !getConstraintManager().canReasonAbout(Result)) { 03221 03222 unsigned Count = Builder->getCurrentBlockCount(); 03223 03224 // The symbolic value is actually for the type of the left-hand side 03225 // expression, not the computation type, as this is the value the 03226 // LValue on the LHS will bind to. 03227 LHSVal = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), LTy, Count); 03228 03229 // However, we need to convert the symbol to the computation type. 03230 Result = svalBuilder.evalCast(LHSVal, CTy, LTy); 03231 } 03232 else { 03233 // The left-hand side may bind to a different value then the 03234 // computation type. 03235 LHSVal = svalBuilder.evalCast(Result, LTy, CTy); 03236 } 03237 03238 evalStore(Tmp3, B, LHS, *I4, state->BindExpr(B, Result), 03239 location, LHSVal); 03240 } 03241 } 03242 } 03243 03244 CheckerVisit(B, Dst, Tmp3, PostVisitStmtCallback); 03245 } 03246 03247 //===----------------------------------------------------------------------===// 03248 // Checker registration/lookup. 03249 //===----------------------------------------------------------------------===// 03250 03251 Checker *GRExprEngine::lookupChecker(void *tag) const { 03252 CheckerMap::const_iterator I = CheckerM.find(tag); 03253 return (I == CheckerM.end()) ? NULL : Checkers[I->second].second; 03254 } 03255 03256 //===----------------------------------------------------------------------===// 03257 // Visualization. 03258 //===----------------------------------------------------------------------===// 03259 03260 #ifndef NDEBUG 03261 static GRExprEngine* GraphPrintCheckerState; 03262 static SourceManager* GraphPrintSourceManager; 03263 03264 namespace llvm { 03265 template<> 03266 struct DOTGraphTraits<ExplodedNode*> : 03267 public DefaultDOTGraphTraits { 03268 03269 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 03270 03271 // FIXME: Since we do not cache error nodes in GRExprEngine now, this does not 03272 // work. 03273 static std::string getNodeAttributes(const ExplodedNode* N, void*) { 03274 03275 #if 0 03276 // FIXME: Replace with a general scheme to tell if the node is 03277 // an error node. 03278 if (GraphPrintCheckerState->isImplicitNullDeref(N) || 03279 GraphPrintCheckerState->isExplicitNullDeref(N) || 03280 GraphPrintCheckerState->isUndefDeref(N) || 03281 GraphPrintCheckerState->isUndefStore(N) || 03282 GraphPrintCheckerState->isUndefControlFlow(N) || 03283 GraphPrintCheckerState->isUndefResult(N) || 03284 GraphPrintCheckerState->isBadCall(N) || 03285 GraphPrintCheckerState->isUndefArg(N)) 03286 return "color=\"red\",style=\"filled\""; 03287 03288 if (GraphPrintCheckerState->isNoReturnCall(N)) 03289 return "color=\"blue\",style=\"filled\""; 03290 #endif 03291 return ""; 03292 } 03293 03294 static std::string getNodeLabel(const ExplodedNode* N, void*){ 03295 03296 std::string sbuf; 03297 llvm::raw_string_ostream Out(sbuf); 03298 03299 // Program Location. 03300 ProgramPoint Loc = N->getLocation(); 03301 03302 switch (Loc.getKind()) { 03303 case ProgramPoint::BlockEntranceKind: 03304 Out << "Block Entrance: B" 03305 << cast<BlockEntrance>(Loc).getBlock()->getBlockID(); 03306 break; 03307 03308 case ProgramPoint::BlockExitKind: 03309 assert (false); 03310 break; 03311 03312 case ProgramPoint::CallEnterKind: 03313 Out << "CallEnter"; 03314 break; 03315 03316 case ProgramPoint::CallExitKind: 03317 Out << "CallExit"; 03318 break; 03319 03320 default: { 03321 if (StmtPoint *L = dyn_cast<StmtPoint>(&Loc)) { 03322 const Stmt* S = L->getStmt(); 03323 SourceLocation SLoc = S->getLocStart(); 03324 03325 Out << S->getStmtClassName() << ' ' << (void*) S << ' '; 03326 LangOptions LO; // FIXME. 03327 S->printPretty(Out, 0, PrintingPolicy(LO)); 03328 03329 if (SLoc.isFileID()) { 03330 Out << "\\lline=" 03331 << GraphPrintSourceManager->getInstantiationLineNumber(SLoc) 03332 << " col=" 03333 << GraphPrintSourceManager->getInstantiationColumnNumber(SLoc) 03334 << "\\l"; 03335 } 03336 03337 if (isa<PreStmt>(Loc)) 03338 Out << "\\lPreStmt\\l;"; 03339 else if (isa<PostLoad>(Loc)) 03340 Out << "\\lPostLoad\\l;"; 03341 else if (isa<PostStore>(Loc)) 03342 Out << "\\lPostStore\\l"; 03343 else if (isa<PostLValue>(Loc)) 03344 Out << "\\lPostLValue\\l"; 03345 03346 #if 0 03347 // FIXME: Replace with a general scheme to determine 03348 // the name of the check. 03349 if (GraphPrintCheckerState->isImplicitNullDeref(N)) 03350 Out << "\\|Implicit-Null Dereference.\\l"; 03351 else if (GraphPrintCheckerState->isExplicitNullDeref(N)) 03352 Out << "\\|Explicit-Null Dereference.\\l"; 03353 else if (GraphPrintCheckerState->isUndefDeref(N)) 03354 Out << "\\|Dereference of undefialied value.\\l"; 03355 else if (GraphPrintCheckerState->isUndefStore(N)) 03356 Out << "\\|Store to Undefined Loc."; 03357 else if (GraphPrintCheckerState->isUndefResult(N)) 03358 Out << "\\|Result of operation is undefined."; 03359 else if (GraphPrintCheckerState->isNoReturnCall(N)) 03360 Out << "\\|Call to function marked \"noreturn\"."; 03361 else if (GraphPrintCheckerState->isBadCall(N)) 03362 Out << "\\|Call to NULL/Undefined."; 03363 else if (GraphPrintCheckerState->isUndefArg(N)) 03364 Out << "\\|Argument in call is undefined"; 03365 #endif 03366 03367 break; 03368 } 03369 03370 const BlockEdge& E = cast<BlockEdge>(Loc); 03371 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B" 03372 << E.getDst()->getBlockID() << ')'; 03373 03374 if (const Stmt* T = E.getSrc()->getTerminator()) { 03375 03376 SourceLocation SLoc = T->getLocStart(); 03377 03378 Out << "\\|Terminator: "; 03379 LangOptions LO; // FIXME. 03380 E.getSrc()->printTerminator(Out, LO); 03381 03382 if (SLoc.isFileID()) { 03383 Out << "\\lline=" 03384 << GraphPrintSourceManager->getInstantiationLineNumber(SLoc) 03385 << " col=" 03386 << GraphPrintSourceManager->getInstantiationColumnNumber(SLoc); 03387 } 03388 03389 if (isa<SwitchStmt>(T)) { 03390 const Stmt* Label = E.getDst()->getLabel(); 03391 03392 if (Label) { 03393 if (const CaseStmt* C = dyn_cast<CaseStmt>(Label)) { 03394 Out << "\\lcase "; 03395 LangOptions LO; // FIXME. 03396 C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO)); 03397 03398 if (const Stmt* RHS = C->getRHS()) { 03399 Out << " .. "; 03400 RHS->printPretty(Out, 0, PrintingPolicy(LO)); 03401 } 03402 03403 Out << ":"; 03404 } 03405 else { 03406 assert (isa<DefaultStmt>(Label)); 03407 Out << "\\ldefault:"; 03408 } 03409 } 03410 else 03411 Out << "\\l(implicit) default:"; 03412 } 03413 else if (isa<IndirectGotoStmt>(T)) { 03414 // FIXME 03415 } 03416 else { 03417 Out << "\\lCondition: "; 03418 if (*E.getSrc()->succ_begin() == E.getDst()) 03419 Out << "true"; 03420 else 03421 Out << "false"; 03422 } 03423 03424 Out << "\\l"; 03425 } 03426 03427 #if 0 03428 // FIXME: Replace with a general scheme to determine 03429 // the name of the check. 03430 if (GraphPrintCheckerState->isUndefControlFlow(N)) { 03431 Out << "\\|Control-flow based on\\lUndefined value.\\l"; 03432 } 03433 #endif 03434 } 03435 } 03436 03437 const GRState *state = N->getState(); 03438 Out << "\\|StateID: " << (void*) state 03439 << " NodeID: " << (void*) N << "\\|"; 03440 state->printDOT(Out, *N->getLocationContext()->getCFG()); 03441 Out << "\\l"; 03442 return Out.str(); 03443 } 03444 }; 03445 } // end llvm namespace 03446 #endif 03447 03448 #ifndef NDEBUG 03449 template <typename ITERATOR> 03450 ExplodedNode* GetGraphNode(ITERATOR I) { return *I; } 03451 03452 template <> ExplodedNode* 03453 GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator> 03454 (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) { 03455 return I->first; 03456 } 03457 #endif 03458 03459 void GRExprEngine::ViewGraph(bool trim) { 03460 #ifndef NDEBUG 03461 if (trim) { 03462 std::vector<ExplodedNode*> Src; 03463 03464 // Flush any outstanding reports to make sure we cover all the nodes. 03465 // This does not cause them to get displayed. 03466 for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I) 03467 const_cast<BugType*>(*I)->FlushReports(BR); 03468 03469 // Iterate through the reports and get their nodes. 03470 for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I) { 03471 for (BugType::const_iterator I2=(*I)->begin(), E2=(*I)->end(); 03472 I2!=E2; ++I2) { 03473 const BugReportEquivClass& EQ = *I2; 03474 const BugReport &R = **EQ.begin(); 03475 ExplodedNode *N = const_cast<ExplodedNode*>(R.getErrorNode()); 03476 if (N) Src.push_back(N); 03477 } 03478 } 03479 03480 ViewGraph(&Src[0], &Src[0]+Src.size()); 03481 } 03482 else { 03483 GraphPrintCheckerState = this; 03484 GraphPrintSourceManager = &getContext().getSourceManager(); 03485 03486 llvm::ViewGraph(*G.roots_begin(), "GRExprEngine"); 03487 03488 GraphPrintCheckerState = NULL; 03489 GraphPrintSourceManager = NULL; 03490 } 03491 #endif 03492 } 03493 03494 void GRExprEngine::ViewGraph(ExplodedNode** Beg, ExplodedNode** End) { 03495 #ifndef NDEBUG 03496 GraphPrintCheckerState = this; 03497 GraphPrintSourceManager = &getContext().getSourceManager(); 03498 03499 std::auto_ptr<ExplodedGraph> TrimmedG(G.Trim(Beg, End).first); 03500 03501 if (!TrimmedG.get()) 03502 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n"; 03503 else 03504 llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedGRExprEngine"); 03505 03506 GraphPrintCheckerState = NULL; 03507 GraphPrintSourceManager = NULL; 03508 #endif 03509 }