clang API Documentation

ProgramState.cpp
Go to the documentation of this file.
00001 //= ProgramState.cpp - Path-Sensitive "State" for tracking values --*- 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 implements ProgramState and ProgramStateManager.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
00015 #include "clang/Analysis/CFG.h"
00016 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
00017 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
00018 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
00019 #include "clang/StaticAnalyzer/Core/PathSensitive/TaintManager.h"
00020 #include "llvm/Support/raw_ostream.h"
00021 
00022 using namespace clang;
00023 using namespace ento;
00024 
00025 namespace clang { namespace  ento {
00026 /// Increments the number of times this state is referenced.
00027 
00028 void ProgramStateRetain(const ProgramState *state) {
00029   ++const_cast<ProgramState*>(state)->refCount;
00030 }
00031 
00032 /// Decrement the number of times this state is referenced.
00033 void ProgramStateRelease(const ProgramState *state) {
00034   assert(state->refCount > 0);
00035   ProgramState *s = const_cast<ProgramState*>(state);
00036   if (--s->refCount == 0) {
00037     ProgramStateManager &Mgr = s->getStateManager();
00038     Mgr.StateSet.RemoveNode(s);
00039     s->~ProgramState();    
00040     Mgr.freeStates.push_back(s);
00041   }
00042 }
00043 }}
00044 
00045 ProgramState::ProgramState(ProgramStateManager *mgr, const Environment& env,
00046                  StoreRef st, GenericDataMap gdm)
00047   : stateMgr(mgr),
00048     Env(env),
00049     store(st.getStore()),
00050     GDM(gdm),
00051     refCount(0) {
00052   stateMgr->getStoreManager().incrementReferenceCount(store);
00053 }
00054 
00055 ProgramState::ProgramState(const ProgramState &RHS)
00056     : llvm::FoldingSetNode(),
00057       stateMgr(RHS.stateMgr),
00058       Env(RHS.Env),
00059       store(RHS.store),
00060       GDM(RHS.GDM),
00061       refCount(0) {
00062   stateMgr->getStoreManager().incrementReferenceCount(store);
00063 }
00064 
00065 ProgramState::~ProgramState() {
00066   if (store)
00067     stateMgr->getStoreManager().decrementReferenceCount(store);
00068 }
00069 
00070 ProgramStateManager::ProgramStateManager(ASTContext &Ctx,
00071                                          StoreManagerCreator CreateSMgr,
00072                                          ConstraintManagerCreator CreateCMgr,
00073                                          llvm::BumpPtrAllocator &alloc,
00074                                          SubEngine *SubEng)
00075   : Eng(SubEng), EnvMgr(alloc), GDMFactory(alloc),
00076     svalBuilder(createSimpleSValBuilder(alloc, Ctx, *this)),
00077     CallEventMgr(new CallEventManager(alloc)), Alloc(alloc) {
00078   StoreMgr = (*CreateSMgr)(*this);
00079   ConstraintMgr = (*CreateCMgr)(*this, SubEng);
00080 }
00081 
00082 
00083 ProgramStateManager::~ProgramStateManager() {
00084   for (GDMContextsTy::iterator I=GDMContexts.begin(), E=GDMContexts.end();
00085        I!=E; ++I)
00086     I->second.second(I->second.first);
00087 }
00088 
00089 ProgramStateRef 
00090 ProgramStateManager::removeDeadBindings(ProgramStateRef state,
00091                                    const StackFrameContext *LCtx,
00092                                    SymbolReaper& SymReaper) {
00093 
00094   // This code essentially performs a "mark-and-sweep" of the VariableBindings.
00095   // The roots are any Block-level exprs and Decls that our liveness algorithm
00096   // tells us are live.  We then see what Decls they may reference, and keep
00097   // those around.  This code more than likely can be made faster, and the
00098   // frequency of which this method is called should be experimented with
00099   // for optimum performance.
00100   ProgramState NewState = *state;
00101 
00102   NewState.Env = EnvMgr.removeDeadBindings(NewState.Env, SymReaper, state);
00103 
00104   // Clean up the store.
00105   StoreRef newStore = StoreMgr->removeDeadBindings(NewState.getStore(), LCtx,
00106                                                    SymReaper);
00107   NewState.setStore(newStore);
00108   SymReaper.setReapedStore(newStore);
00109 
00110   ProgramStateRef Result = getPersistentState(NewState);
00111   return ConstraintMgr->removeDeadBindings(Result, SymReaper);
00112 }
00113 
00114 ProgramStateRef ProgramState::bindLoc(Loc LV, SVal V, bool notifyChanges) const {
00115   ProgramStateManager &Mgr = getStateManager();
00116   ProgramStateRef newState = makeWithStore(Mgr.StoreMgr->Bind(getStore(), 
00117                                                              LV, V));
00118   const MemRegion *MR = LV.getAsRegion();
00119   if (MR && Mgr.getOwningEngine() && notifyChanges)
00120     return Mgr.getOwningEngine()->processRegionChange(newState, MR);
00121 
00122   return newState;
00123 }
00124 
00125 ProgramStateRef ProgramState::bindDefault(SVal loc, SVal V) const {
00126   ProgramStateManager &Mgr = getStateManager();
00127   const MemRegion *R = loc.castAs<loc::MemRegionVal>().getRegion();
00128   const StoreRef &newStore = Mgr.StoreMgr->BindDefault(getStore(), R, V);
00129   ProgramStateRef new_state = makeWithStore(newStore);
00130   return Mgr.getOwningEngine() ? 
00131            Mgr.getOwningEngine()->processRegionChange(new_state, R) : 
00132            new_state;
00133 }
00134 
00135 typedef ArrayRef<const MemRegion *> RegionList;
00136 typedef ArrayRef<SVal> ValueList;
00137 
00138 ProgramStateRef 
00139 ProgramState::invalidateRegions(RegionList Regions,
00140                              const Expr *E, unsigned Count,
00141                              const LocationContext *LCtx,
00142                              bool CausedByPointerEscape,
00143                              InvalidatedSymbols *IS,
00144                              const CallEvent *Call,
00145                              RegionAndSymbolInvalidationTraits *ITraits) const {
00146   SmallVector<SVal, 8> Values;
00147   for (RegionList::const_iterator I = Regions.begin(),
00148                                   End = Regions.end(); I != End; ++I)
00149     Values.push_back(loc::MemRegionVal(*I));
00150 
00151   return invalidateRegionsImpl(Values, E, Count, LCtx, CausedByPointerEscape,
00152                                IS, ITraits, Call);
00153 }
00154 
00155 ProgramStateRef
00156 ProgramState::invalidateRegions(ValueList Values,
00157                              const Expr *E, unsigned Count,
00158                              const LocationContext *LCtx,
00159                              bool CausedByPointerEscape,
00160                              InvalidatedSymbols *IS,
00161                              const CallEvent *Call,
00162                              RegionAndSymbolInvalidationTraits *ITraits) const {
00163 
00164   return invalidateRegionsImpl(Values, E, Count, LCtx, CausedByPointerEscape,
00165                                IS, ITraits, Call);
00166 }
00167 
00168 ProgramStateRef
00169 ProgramState::invalidateRegionsImpl(ValueList Values,
00170                                     const Expr *E, unsigned Count,
00171                                     const LocationContext *LCtx,
00172                                     bool CausedByPointerEscape,
00173                                     InvalidatedSymbols *IS,
00174                                     RegionAndSymbolInvalidationTraits *ITraits,
00175                                     const CallEvent *Call) const {
00176   ProgramStateManager &Mgr = getStateManager();
00177   SubEngine* Eng = Mgr.getOwningEngine();
00178 
00179   InvalidatedSymbols Invalidated;
00180   if (!IS)
00181     IS = &Invalidated;
00182 
00183   RegionAndSymbolInvalidationTraits ITraitsLocal;
00184   if (!ITraits)
00185     ITraits = &ITraitsLocal;
00186 
00187   if (Eng) {
00188     StoreManager::InvalidatedRegions TopLevelInvalidated;
00189     StoreManager::InvalidatedRegions Invalidated;
00190     const StoreRef &newStore
00191     = Mgr.StoreMgr->invalidateRegions(getStore(), Values, E, Count, LCtx, Call,
00192                                       *IS, *ITraits, &TopLevelInvalidated,
00193                                       &Invalidated);
00194 
00195     ProgramStateRef newState = makeWithStore(newStore);
00196 
00197     if (CausedByPointerEscape) {
00198       newState = Eng->notifyCheckersOfPointerEscape(newState, IS,
00199                                                     TopLevelInvalidated,
00200                                                     Invalidated, Call, 
00201                                                     *ITraits);
00202     }
00203 
00204     return Eng->processRegionChanges(newState, IS, TopLevelInvalidated, 
00205                                      Invalidated, Call);
00206   }
00207 
00208   const StoreRef &newStore =
00209   Mgr.StoreMgr->invalidateRegions(getStore(), Values, E, Count, LCtx, Call,
00210                                   *IS, *ITraits, nullptr, nullptr);
00211   return makeWithStore(newStore);
00212 }
00213 
00214 ProgramStateRef ProgramState::killBinding(Loc LV) const {
00215   assert(!LV.getAs<loc::MemRegionVal>() && "Use invalidateRegion instead.");
00216 
00217   Store OldStore = getStore();
00218   const StoreRef &newStore =
00219     getStateManager().StoreMgr->killBinding(OldStore, LV);
00220 
00221   if (newStore.getStore() == OldStore)
00222     return this;
00223 
00224   return makeWithStore(newStore);
00225 }
00226 
00227 ProgramStateRef 
00228 ProgramState::enterStackFrame(const CallEvent &Call,
00229                               const StackFrameContext *CalleeCtx) const {
00230   const StoreRef &NewStore =
00231     getStateManager().StoreMgr->enterStackFrame(getStore(), Call, CalleeCtx);
00232   return makeWithStore(NewStore);
00233 }
00234 
00235 SVal ProgramState::getSValAsScalarOrLoc(const MemRegion *R) const {
00236   // We only want to do fetches from regions that we can actually bind
00237   // values.  For example, SymbolicRegions of type 'id<...>' cannot
00238   // have direct bindings (but their can be bindings on their subregions).
00239   if (!R->isBoundable())
00240     return UnknownVal();
00241 
00242   if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
00243     QualType T = TR->getValueType();
00244     if (Loc::isLocType(T) || T->isIntegralOrEnumerationType())
00245       return getSVal(R);
00246   }
00247 
00248   return UnknownVal();
00249 }
00250 
00251 SVal ProgramState::getSVal(Loc location, QualType T) const {
00252   SVal V = getRawSVal(cast<Loc>(location), T);
00253 
00254   // If 'V' is a symbolic value that is *perfectly* constrained to
00255   // be a constant value, use that value instead to lessen the burden
00256   // on later analysis stages (so we have less symbolic values to reason
00257   // about).
00258   if (!T.isNull()) {
00259     if (SymbolRef sym = V.getAsSymbol()) {
00260       if (const llvm::APSInt *Int = getStateManager()
00261                                     .getConstraintManager()
00262                                     .getSymVal(this, sym)) {
00263         // FIXME: Because we don't correctly model (yet) sign-extension
00264         // and truncation of symbolic values, we need to convert
00265         // the integer value to the correct signedness and bitwidth.
00266         //
00267         // This shows up in the following:
00268         //
00269         //   char foo();
00270         //   unsigned x = foo();
00271         //   if (x == 54)
00272         //     ...
00273         //
00274         //  The symbolic value stored to 'x' is actually the conjured
00275         //  symbol for the call to foo(); the type of that symbol is 'char',
00276         //  not unsigned.
00277         const llvm::APSInt &NewV = getBasicVals().Convert(T, *Int);
00278         
00279         if (V.getAs<Loc>())
00280           return loc::ConcreteInt(NewV);
00281         else
00282           return nonloc::ConcreteInt(NewV);
00283       }
00284     }
00285   }
00286   
00287   return V;
00288 }
00289 
00290 ProgramStateRef ProgramState::BindExpr(const Stmt *S,
00291                                            const LocationContext *LCtx,
00292                                            SVal V, bool Invalidate) const{
00293   Environment NewEnv =
00294     getStateManager().EnvMgr.bindExpr(Env, EnvironmentEntry(S, LCtx), V,
00295                                       Invalidate);
00296   if (NewEnv == Env)
00297     return this;
00298 
00299   ProgramState NewSt = *this;
00300   NewSt.Env = NewEnv;
00301   return getStateManager().getPersistentState(NewSt);
00302 }
00303 
00304 ProgramStateRef ProgramState::assumeInBound(DefinedOrUnknownSVal Idx,
00305                                       DefinedOrUnknownSVal UpperBound,
00306                                       bool Assumption,
00307                                       QualType indexTy) const {
00308   if (Idx.isUnknown() || UpperBound.isUnknown())
00309     return this;
00310 
00311   // Build an expression for 0 <= Idx < UpperBound.
00312   // This is the same as Idx + MIN < UpperBound + MIN, if overflow is allowed.
00313   // FIXME: This should probably be part of SValBuilder.
00314   ProgramStateManager &SM = getStateManager();
00315   SValBuilder &svalBuilder = SM.getSValBuilder();
00316   ASTContext &Ctx = svalBuilder.getContext();
00317 
00318   // Get the offset: the minimum value of the array index type.
00319   BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
00320   // FIXME: This should be using ValueManager::ArrayindexTy...somehow.
00321   if (indexTy.isNull())
00322     indexTy = Ctx.IntTy;
00323   nonloc::ConcreteInt Min(BVF.getMinValue(indexTy));
00324 
00325   // Adjust the index.
00326   SVal newIdx = svalBuilder.evalBinOpNN(this, BO_Add,
00327                                         Idx.castAs<NonLoc>(), Min, indexTy);
00328   if (newIdx.isUnknownOrUndef())
00329     return this;
00330 
00331   // Adjust the upper bound.
00332   SVal newBound =
00333     svalBuilder.evalBinOpNN(this, BO_Add, UpperBound.castAs<NonLoc>(),
00334                             Min, indexTy);
00335 
00336   if (newBound.isUnknownOrUndef())
00337     return this;
00338 
00339   // Build the actual comparison.
00340   SVal inBound = svalBuilder.evalBinOpNN(this, BO_LT, newIdx.castAs<NonLoc>(),
00341                                          newBound.castAs<NonLoc>(), Ctx.IntTy);
00342   if (inBound.isUnknownOrUndef())
00343     return this;
00344 
00345   // Finally, let the constraint manager take care of it.
00346   ConstraintManager &CM = SM.getConstraintManager();
00347   return CM.assume(this, inBound.castAs<DefinedSVal>(), Assumption);
00348 }
00349 
00350 ConditionTruthVal ProgramState::isNull(SVal V) const {
00351   if (V.isZeroConstant())
00352     return true;
00353 
00354   if (V.isConstant())
00355     return false;
00356   
00357   SymbolRef Sym = V.getAsSymbol(/* IncludeBaseRegion */ true);
00358   if (!Sym)
00359     return ConditionTruthVal();
00360   
00361   return getStateManager().ConstraintMgr->isNull(this, Sym);
00362 }
00363 
00364 ProgramStateRef ProgramStateManager::getInitialState(const LocationContext *InitLoc) {
00365   ProgramState State(this,
00366                 EnvMgr.getInitialEnvironment(),
00367                 StoreMgr->getInitialStore(InitLoc),
00368                 GDMFactory.getEmptyMap());
00369 
00370   return getPersistentState(State);
00371 }
00372 
00373 ProgramStateRef ProgramStateManager::getPersistentStateWithGDM(
00374                                                      ProgramStateRef FromState,
00375                                                      ProgramStateRef GDMState) {
00376   ProgramState NewState(*FromState);
00377   NewState.GDM = GDMState->GDM;
00378   return getPersistentState(NewState);
00379 }
00380 
00381 ProgramStateRef ProgramStateManager::getPersistentState(ProgramState &State) {
00382 
00383   llvm::FoldingSetNodeID ID;
00384   State.Profile(ID);
00385   void *InsertPos;
00386 
00387   if (ProgramState *I = StateSet.FindNodeOrInsertPos(ID, InsertPos))
00388     return I;
00389 
00390   ProgramState *newState = nullptr;
00391   if (!freeStates.empty()) {
00392     newState = freeStates.back();
00393     freeStates.pop_back();    
00394   }
00395   else {
00396     newState = (ProgramState*) Alloc.Allocate<ProgramState>();
00397   }
00398   new (newState) ProgramState(State);
00399   StateSet.InsertNode(newState, InsertPos);
00400   return newState;
00401 }
00402 
00403 ProgramStateRef ProgramState::makeWithStore(const StoreRef &store) const {
00404   ProgramState NewSt(*this);
00405   NewSt.setStore(store);
00406   return getStateManager().getPersistentState(NewSt);
00407 }
00408 
00409 void ProgramState::setStore(const StoreRef &newStore) {
00410   Store newStoreStore = newStore.getStore();
00411   if (newStoreStore)
00412     stateMgr->getStoreManager().incrementReferenceCount(newStoreStore);
00413   if (store)
00414     stateMgr->getStoreManager().decrementReferenceCount(store);
00415   store = newStoreStore;
00416 }
00417 
00418 //===----------------------------------------------------------------------===//
00419 //  State pretty-printing.
00420 //===----------------------------------------------------------------------===//
00421 
00422 void ProgramState::print(raw_ostream &Out,
00423                          const char *NL, const char *Sep) const {
00424   // Print the store.
00425   ProgramStateManager &Mgr = getStateManager();
00426   Mgr.getStoreManager().print(getStore(), Out, NL, Sep);
00427 
00428   // Print out the environment.
00429   Env.print(Out, NL, Sep);
00430 
00431   // Print out the constraints.
00432   Mgr.getConstraintManager().print(this, Out, NL, Sep);
00433 
00434   // Print checker-specific data.
00435   Mgr.getOwningEngine()->printState(Out, this, NL, Sep);
00436 }
00437 
00438 void ProgramState::printDOT(raw_ostream &Out) const {
00439   print(Out, "\\l", "\\|");
00440 }
00441 
00442 void ProgramState::dump() const {
00443   print(llvm::errs());
00444 }
00445 
00446 void ProgramState::printTaint(raw_ostream &Out,
00447                               const char *NL, const char *Sep) const {
00448   TaintMapImpl TM = get<TaintMap>();
00449 
00450   if (!TM.isEmpty())
00451     Out <<"Tainted Symbols:" << NL;
00452 
00453   for (TaintMapImpl::iterator I = TM.begin(), E = TM.end(); I != E; ++I) {
00454     Out << I->first << " : " << I->second << NL;
00455   }
00456 }
00457 
00458 void ProgramState::dumpTaint() const {
00459   printTaint(llvm::errs());
00460 }
00461 
00462 //===----------------------------------------------------------------------===//
00463 // Generic Data Map.
00464 //===----------------------------------------------------------------------===//
00465 
00466 void *const* ProgramState::FindGDM(void *K) const {
00467   return GDM.lookup(K);
00468 }
00469 
00470 void*
00471 ProgramStateManager::FindGDMContext(void *K,
00472                                void *(*CreateContext)(llvm::BumpPtrAllocator&),
00473                                void (*DeleteContext)(void*)) {
00474 
00475   std::pair<void*, void (*)(void*)>& p = GDMContexts[K];
00476   if (!p.first) {
00477     p.first = CreateContext(Alloc);
00478     p.second = DeleteContext;
00479   }
00480 
00481   return p.first;
00482 }
00483 
00484 ProgramStateRef ProgramStateManager::addGDM(ProgramStateRef St, void *Key, void *Data){
00485   ProgramState::GenericDataMap M1 = St->getGDM();
00486   ProgramState::GenericDataMap M2 = GDMFactory.add(M1, Key, Data);
00487 
00488   if (M1 == M2)
00489     return St;
00490 
00491   ProgramState NewSt = *St;
00492   NewSt.GDM = M2;
00493   return getPersistentState(NewSt);
00494 }
00495 
00496 ProgramStateRef ProgramStateManager::removeGDM(ProgramStateRef state, void *Key) {
00497   ProgramState::GenericDataMap OldM = state->getGDM();
00498   ProgramState::GenericDataMap NewM = GDMFactory.remove(OldM, Key);
00499 
00500   if (NewM == OldM)
00501     return state;
00502 
00503   ProgramState NewState = *state;
00504   NewState.GDM = NewM;
00505   return getPersistentState(NewState);
00506 }
00507 
00508 bool ScanReachableSymbols::scan(nonloc::LazyCompoundVal val) {
00509   bool wasVisited = !visited.insert(val.getCVData()).second;
00510   if (wasVisited)
00511     return true;
00512 
00513   StoreManager &StoreMgr = state->getStateManager().getStoreManager();
00514   // FIXME: We don't really want to use getBaseRegion() here because pointer
00515   // arithmetic doesn't apply, but scanReachableSymbols only accepts base
00516   // regions right now.
00517   const MemRegion *R = val.getRegion()->getBaseRegion();
00518   return StoreMgr.scanReachableSymbols(val.getStore(), R, *this);
00519 }
00520 
00521 bool ScanReachableSymbols::scan(nonloc::CompoundVal val) {
00522   for (nonloc::CompoundVal::iterator I=val.begin(), E=val.end(); I!=E; ++I)
00523     if (!scan(*I))
00524       return false;
00525 
00526   return true;
00527 }
00528 
00529 bool ScanReachableSymbols::scan(const SymExpr *sym) {
00530   bool wasVisited = !visited.insert(sym).second;
00531   if (wasVisited)
00532     return true;
00533   
00534   if (!visitor.VisitSymbol(sym))
00535     return false;
00536   
00537   // TODO: should be rewritten using SymExpr::symbol_iterator.
00538   switch (sym->getKind()) {
00539     case SymExpr::RegionValueKind:
00540     case SymExpr::ConjuredKind:
00541     case SymExpr::DerivedKind:
00542     case SymExpr::ExtentKind:
00543     case SymExpr::MetadataKind:
00544       break;
00545     case SymExpr::CastSymbolKind:
00546       return scan(cast<SymbolCast>(sym)->getOperand());
00547     case SymExpr::SymIntKind:
00548       return scan(cast<SymIntExpr>(sym)->getLHS());
00549     case SymExpr::IntSymKind:
00550       return scan(cast<IntSymExpr>(sym)->getRHS());
00551     case SymExpr::SymSymKind: {
00552       const SymSymExpr *x = cast<SymSymExpr>(sym);
00553       return scan(x->getLHS()) && scan(x->getRHS());
00554     }
00555   }
00556   return true;
00557 }
00558 
00559 bool ScanReachableSymbols::scan(SVal val) {
00560   if (Optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>())
00561     return scan(X->getRegion());
00562 
00563   if (Optional<nonloc::LazyCompoundVal> X =
00564           val.getAs<nonloc::LazyCompoundVal>())
00565     return scan(*X);
00566 
00567   if (Optional<nonloc::LocAsInteger> X = val.getAs<nonloc::LocAsInteger>())
00568     return scan(X->getLoc());
00569 
00570   if (SymbolRef Sym = val.getAsSymbol())
00571     return scan(Sym);
00572 
00573   if (const SymExpr *Sym = val.getAsSymbolicExpression())
00574     return scan(Sym);
00575 
00576   if (Optional<nonloc::CompoundVal> X = val.getAs<nonloc::CompoundVal>())
00577     return scan(*X);
00578 
00579   return true;
00580 }
00581 
00582 bool ScanReachableSymbols::scan(const MemRegion *R) {
00583   if (isa<MemSpaceRegion>(R))
00584     return true;
00585   
00586   bool wasVisited = !visited.insert(R).second;
00587   if (wasVisited)
00588     return true;
00589   
00590   if (!visitor.VisitMemRegion(R))
00591     return false;
00592 
00593   // If this is a symbolic region, visit the symbol for the region.
00594   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
00595     if (!visitor.VisitSymbol(SR->getSymbol()))
00596       return false;
00597 
00598   // If this is a subregion, also visit the parent regions.
00599   if (const SubRegion *SR = dyn_cast<SubRegion>(R)) {
00600     const MemRegion *Super = SR->getSuperRegion();
00601     if (!scan(Super))
00602       return false;
00603 
00604     // When we reach the topmost region, scan all symbols in it.
00605     if (isa<MemSpaceRegion>(Super)) {
00606       StoreManager &StoreMgr = state->getStateManager().getStoreManager();
00607       if (!StoreMgr.scanReachableSymbols(state->getStore(), SR, *this))
00608         return false;
00609     }
00610   }
00611 
00612   // Regions captured by a block are also implicitly reachable.
00613   if (const BlockDataRegion *BDR = dyn_cast<BlockDataRegion>(R)) {
00614     BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
00615                                               E = BDR->referenced_vars_end();
00616     for ( ; I != E; ++I) {
00617       if (!scan(I.getCapturedRegion()))
00618         return false;
00619     }
00620   }
00621 
00622   return true;
00623 }
00624 
00625 bool ProgramState::scanReachableSymbols(SVal val, SymbolVisitor& visitor) const {
00626   ScanReachableSymbols S(this, visitor);
00627   return S.scan(val);
00628 }
00629 
00630 bool ProgramState::scanReachableSymbols(const SVal *I, const SVal *E,
00631                                    SymbolVisitor &visitor) const {
00632   ScanReachableSymbols S(this, visitor);
00633   for ( ; I != E; ++I) {
00634     if (!S.scan(*I))
00635       return false;
00636   }
00637   return true;
00638 }
00639 
00640 bool ProgramState::scanReachableSymbols(const MemRegion * const *I,
00641                                    const MemRegion * const *E,
00642                                    SymbolVisitor &visitor) const {
00643   ScanReachableSymbols S(this, visitor);
00644   for ( ; I != E; ++I) {
00645     if (!S.scan(*I))
00646       return false;
00647   }
00648   return true;
00649 }
00650 
00651 ProgramStateRef ProgramState::addTaint(const Stmt *S,
00652                                            const LocationContext *LCtx,
00653                                            TaintTagType Kind) const {
00654   if (const Expr *E = dyn_cast_or_null<Expr>(S))
00655     S = E->IgnoreParens();
00656 
00657   SymbolRef Sym = getSVal(S, LCtx).getAsSymbol();
00658   if (Sym)
00659     return addTaint(Sym, Kind);
00660 
00661   const MemRegion *R = getSVal(S, LCtx).getAsRegion();
00662   addTaint(R, Kind);
00663 
00664   // Cannot add taint, so just return the state.
00665   return this;
00666 }
00667 
00668 ProgramStateRef ProgramState::addTaint(const MemRegion *R,
00669                                            TaintTagType Kind) const {
00670   if (const SymbolicRegion *SR = dyn_cast_or_null<SymbolicRegion>(R))
00671     return addTaint(SR->getSymbol(), Kind);
00672   return this;
00673 }
00674 
00675 ProgramStateRef ProgramState::addTaint(SymbolRef Sym,
00676                                            TaintTagType Kind) const {
00677   // If this is a symbol cast, remove the cast before adding the taint. Taint
00678   // is cast agnostic.
00679   while (const SymbolCast *SC = dyn_cast<SymbolCast>(Sym))
00680     Sym = SC->getOperand();
00681 
00682   ProgramStateRef NewState = set<TaintMap>(Sym, Kind);
00683   assert(NewState);
00684   return NewState;
00685 }
00686 
00687 bool ProgramState::isTainted(const Stmt *S, const LocationContext *LCtx,
00688                              TaintTagType Kind) const {
00689   if (const Expr *E = dyn_cast_or_null<Expr>(S))
00690     S = E->IgnoreParens();
00691 
00692   SVal val = getSVal(S, LCtx);
00693   return isTainted(val, Kind);
00694 }
00695 
00696 bool ProgramState::isTainted(SVal V, TaintTagType Kind) const {
00697   if (const SymExpr *Sym = V.getAsSymExpr())
00698     return isTainted(Sym, Kind);
00699   if (const MemRegion *Reg = V.getAsRegion())
00700     return isTainted(Reg, Kind);
00701   return false;
00702 }
00703 
00704 bool ProgramState::isTainted(const MemRegion *Reg, TaintTagType K) const {
00705   if (!Reg)
00706     return false;
00707 
00708   // Element region (array element) is tainted if either the base or the offset
00709   // are tainted.
00710   if (const ElementRegion *ER = dyn_cast<ElementRegion>(Reg))
00711     return isTainted(ER->getSuperRegion(), K) || isTainted(ER->getIndex(), K);
00712 
00713   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(Reg))
00714     return isTainted(SR->getSymbol(), K);
00715 
00716   if (const SubRegion *ER = dyn_cast<SubRegion>(Reg))
00717     return isTainted(ER->getSuperRegion(), K);
00718 
00719   return false;
00720 }
00721 
00722 bool ProgramState::isTainted(SymbolRef Sym, TaintTagType Kind) const {
00723   if (!Sym)
00724     return false;
00725   
00726   // Traverse all the symbols this symbol depends on to see if any are tainted.
00727   bool Tainted = false;
00728   for (SymExpr::symbol_iterator SI = Sym->symbol_begin(), SE =Sym->symbol_end();
00729        SI != SE; ++SI) {
00730     if (!isa<SymbolData>(*SI))
00731       continue;
00732     
00733     const TaintTagType *Tag = get<TaintMap>(*SI);
00734     Tainted = (Tag && *Tag == Kind);
00735 
00736     // If this is a SymbolDerived with a tainted parent, it's also tainted.
00737     if (const SymbolDerived *SD = dyn_cast<SymbolDerived>(*SI))
00738       Tainted = Tainted || isTainted(SD->getParentSymbol(), Kind);
00739 
00740     // If memory region is tainted, data is also tainted.
00741     if (const SymbolRegionValue *SRV = dyn_cast<SymbolRegionValue>(*SI))
00742       Tainted = Tainted || isTainted(SRV->getRegion(), Kind);
00743 
00744     // If If this is a SymbolCast from a tainted value, it's also tainted.
00745     if (const SymbolCast *SC = dyn_cast<SymbolCast>(*SI))
00746       Tainted = Tainted || isTainted(SC->getOperand(), Kind);
00747 
00748     if (Tainted)
00749       return true;
00750   }
00751   
00752   return Tainted;
00753 }
00754 
00755 /// The GDM component containing the dynamic type info. This is a map from a
00756 /// symbol to its most likely type.
00757 REGISTER_TRAIT_WITH_PROGRAMSTATE(DynamicTypeMap,
00758                                  CLANG_ENTO_PROGRAMSTATE_MAP(const MemRegion *,
00759                                                              DynamicTypeInfo))
00760 
00761 DynamicTypeInfo ProgramState::getDynamicTypeInfo(const MemRegion *Reg) const {
00762   Reg = Reg->StripCasts();
00763 
00764   // Look up the dynamic type in the GDM.
00765   const DynamicTypeInfo *GDMType = get<DynamicTypeMap>(Reg);
00766   if (GDMType)
00767     return *GDMType;
00768 
00769   // Otherwise, fall back to what we know about the region.
00770   if (const TypedRegion *TR = dyn_cast<TypedRegion>(Reg))
00771     return DynamicTypeInfo(TR->getLocationType(), /*CanBeSubclass=*/false);
00772 
00773   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(Reg)) {
00774     SymbolRef Sym = SR->getSymbol();
00775     return DynamicTypeInfo(Sym->getType());
00776   }
00777 
00778   return DynamicTypeInfo();
00779 }
00780 
00781 ProgramStateRef ProgramState::setDynamicTypeInfo(const MemRegion *Reg,
00782                                                  DynamicTypeInfo NewTy) const {
00783   Reg = Reg->StripCasts();
00784   ProgramStateRef NewState = set<DynamicTypeMap>(Reg, NewTy);
00785   assert(NewState);
00786   return NewState;
00787 }