ProgramState.cpp revision b9b0f6fb6e113b5e6be3ed9754c4bf01186a17bf
1//= ProgramState.cpp - Path-Sensitive "State" for tracking values --*- C++ -*--=
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements ProgramState and ProgramStateManager.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Analysis/CFG.h"
15#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
16#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
17#include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/TaintManager.h"
19#include "llvm/Support/raw_ostream.h"
20
21using namespace clang;
22using namespace ento;
23
24// Give the vtable for ConstraintManager somewhere to live.
25// FIXME: Move this elsewhere.
26ConstraintManager::~ConstraintManager() {}
27
28ProgramState::ProgramState(ProgramStateManager *mgr, const Environment& env,
29                 StoreRef st, GenericDataMap gdm)
30  : stateMgr(mgr),
31    Env(env),
32    store(st.getStore()),
33    GDM(gdm),
34    refCount(0) {
35  stateMgr->getStoreManager().incrementReferenceCount(store);
36}
37
38ProgramState::ProgramState(const ProgramState &RHS)
39    : llvm::FoldingSetNode(),
40      stateMgr(RHS.stateMgr),
41      Env(RHS.Env),
42      store(RHS.store),
43      GDM(RHS.GDM),
44      refCount(0) {
45  stateMgr->getStoreManager().incrementReferenceCount(store);
46}
47
48ProgramState::~ProgramState() {
49  if (store)
50    stateMgr->getStoreManager().decrementReferenceCount(store);
51}
52
53ProgramStateManager::~ProgramStateManager() {
54  for (GDMContextsTy::iterator I=GDMContexts.begin(), E=GDMContexts.end();
55       I!=E; ++I)
56    I->second.second(I->second.first);
57}
58
59ProgramStateRef
60ProgramStateManager::removeDeadBindings(ProgramStateRef state,
61                                   const StackFrameContext *LCtx,
62                                   SymbolReaper& SymReaper) {
63
64  // This code essentially performs a "mark-and-sweep" of the VariableBindings.
65  // The roots are any Block-level exprs and Decls that our liveness algorithm
66  // tells us are live.  We then see what Decls they may reference, and keep
67  // those around.  This code more than likely can be made faster, and the
68  // frequency of which this method is called should be experimented with
69  // for optimum performance.
70  ProgramState NewState = *state;
71
72  NewState.Env = EnvMgr.removeDeadBindings(NewState.Env, SymReaper, state);
73
74  // Clean up the store.
75  StoreRef newStore = StoreMgr->removeDeadBindings(NewState.getStore(), LCtx,
76                                                   SymReaper);
77  NewState.setStore(newStore);
78  SymReaper.setReapedStore(newStore);
79
80  return getPersistentState(NewState);
81}
82
83ProgramStateRef ProgramStateManager::MarshalState(ProgramStateRef state,
84                                            const StackFrameContext *InitLoc) {
85  // make up an empty state for now.
86  ProgramState State(this,
87                EnvMgr.getInitialEnvironment(),
88                StoreMgr->getInitialStore(InitLoc),
89                GDMFactory.getEmptyMap());
90
91  return getPersistentState(State);
92}
93
94ProgramStateRef ProgramState::bindCompoundLiteral(const CompoundLiteralExpr *CL,
95                                            const LocationContext *LC,
96                                            SVal V) const {
97  const StoreRef &newStore =
98    getStateManager().StoreMgr->BindCompoundLiteral(getStore(), CL, LC, V);
99  return makeWithStore(newStore);
100}
101
102ProgramStateRef ProgramState::bindDecl(const VarRegion* VR, SVal IVal) const {
103  const StoreRef &newStore =
104    getStateManager().StoreMgr->BindDecl(getStore(), VR, IVal);
105  return makeWithStore(newStore);
106}
107
108ProgramStateRef ProgramState::bindDeclWithNoInit(const VarRegion* VR) const {
109  const StoreRef &newStore =
110    getStateManager().StoreMgr->BindDeclWithNoInit(getStore(), VR);
111  return makeWithStore(newStore);
112}
113
114ProgramStateRef ProgramState::bindLoc(Loc LV, SVal V) const {
115  ProgramStateManager &Mgr = getStateManager();
116  ProgramStateRef newState = makeWithStore(Mgr.StoreMgr->Bind(getStore(),
117                                                             LV, V));
118  const MemRegion *MR = LV.getAsRegion();
119  if (MR && Mgr.getOwningEngine())
120    return Mgr.getOwningEngine()->processRegionChange(newState, MR);
121
122  return newState;
123}
124
125ProgramStateRef ProgramState::bindDefault(SVal loc, SVal V) const {
126  ProgramStateManager &Mgr = getStateManager();
127  const MemRegion *R = cast<loc::MemRegionVal>(loc).getRegion();
128  const StoreRef &newStore = Mgr.StoreMgr->BindDefault(getStore(), R, V);
129  ProgramStateRef new_state = makeWithStore(newStore);
130  return Mgr.getOwningEngine() ?
131           Mgr.getOwningEngine()->processRegionChange(new_state, R) :
132           new_state;
133}
134
135ProgramStateRef
136ProgramState::invalidateRegions(ArrayRef<const MemRegion *> Regions,
137                                const Expr *E, unsigned Count,
138                                StoreManager::InvalidatedSymbols *IS,
139                                const CallOrObjCMessage *Call) const {
140  if (!IS) {
141    StoreManager::InvalidatedSymbols invalidated;
142    return invalidateRegionsImpl(Regions, E, Count,
143                                 invalidated, Call);
144  }
145  return invalidateRegionsImpl(Regions, E, Count, *IS, Call);
146}
147
148ProgramStateRef
149ProgramState::invalidateRegionsImpl(ArrayRef<const MemRegion *> Regions,
150                                    const Expr *E, unsigned Count,
151                                    StoreManager::InvalidatedSymbols &IS,
152                                    const CallOrObjCMessage *Call) const {
153  ProgramStateManager &Mgr = getStateManager();
154  SubEngine* Eng = Mgr.getOwningEngine();
155
156  if (Eng && Eng->wantsRegionChangeUpdate(this)) {
157    StoreManager::InvalidatedRegions Invalidated;
158    const StoreRef &newStore
159      = Mgr.StoreMgr->invalidateRegions(getStore(), Regions, E, Count, IS,
160                                        Call, &Invalidated);
161    ProgramStateRef newState = makeWithStore(newStore);
162    return Eng->processRegionChanges(newState, &IS, Regions, Invalidated);
163  }
164
165  const StoreRef &newStore =
166    Mgr.StoreMgr->invalidateRegions(getStore(), Regions, E, Count, IS,
167                                    Call, NULL);
168  return makeWithStore(newStore);
169}
170
171ProgramStateRef ProgramState::unbindLoc(Loc LV) const {
172  assert(!isa<loc::MemRegionVal>(LV) && "Use invalidateRegion instead.");
173
174  Store OldStore = getStore();
175  const StoreRef &newStore = getStateManager().StoreMgr->Remove(OldStore, LV);
176
177  if (newStore.getStore() == OldStore)
178    return this;
179
180  return makeWithStore(newStore);
181}
182
183ProgramStateRef
184ProgramState::enterStackFrame(const LocationContext *callerCtx,
185                              const StackFrameContext *calleeCtx) const {
186  const StoreRef &new_store =
187    getStateManager().StoreMgr->enterStackFrame(this, callerCtx, calleeCtx);
188  return makeWithStore(new_store);
189}
190
191SVal ProgramState::getSValAsScalarOrLoc(const MemRegion *R) const {
192  // We only want to do fetches from regions that we can actually bind
193  // values.  For example, SymbolicRegions of type 'id<...>' cannot
194  // have direct bindings (but their can be bindings on their subregions).
195  if (!R->isBoundable())
196    return UnknownVal();
197
198  if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
199    QualType T = TR->getValueType();
200    if (Loc::isLocType(T) || T->isIntegerType())
201      return getSVal(R);
202  }
203
204  return UnknownVal();
205}
206
207SVal ProgramState::getSVal(Loc location, QualType T) const {
208  SVal V = getRawSVal(cast<Loc>(location), T);
209
210  // If 'V' is a symbolic value that is *perfectly* constrained to
211  // be a constant value, use that value instead to lessen the burden
212  // on later analysis stages (so we have less symbolic values to reason
213  // about).
214  if (!T.isNull()) {
215    if (SymbolRef sym = V.getAsSymbol()) {
216      if (const llvm::APSInt *Int = getSymVal(sym)) {
217        // FIXME: Because we don't correctly model (yet) sign-extension
218        // and truncation of symbolic values, we need to convert
219        // the integer value to the correct signedness and bitwidth.
220        //
221        // This shows up in the following:
222        //
223        //   char foo();
224        //   unsigned x = foo();
225        //   if (x == 54)
226        //     ...
227        //
228        //  The symbolic value stored to 'x' is actually the conjured
229        //  symbol for the call to foo(); the type of that symbol is 'char',
230        //  not unsigned.
231        const llvm::APSInt &NewV = getBasicVals().Convert(T, *Int);
232
233        if (isa<Loc>(V))
234          return loc::ConcreteInt(NewV);
235        else
236          return nonloc::ConcreteInt(NewV);
237      }
238    }
239  }
240
241  return V;
242}
243
244ProgramStateRef ProgramState::BindExpr(const Stmt *S,
245                                           const LocationContext *LCtx,
246                                           SVal V, bool Invalidate) const{
247  Environment NewEnv =
248    getStateManager().EnvMgr.bindExpr(Env, EnvironmentEntry(S, LCtx), V,
249                                      Invalidate);
250  if (NewEnv == Env)
251    return this;
252
253  ProgramState NewSt = *this;
254  NewSt.Env = NewEnv;
255  return getStateManager().getPersistentState(NewSt);
256}
257
258ProgramStateRef
259ProgramState::bindExprAndLocation(const Stmt *S, const LocationContext *LCtx,
260                                  SVal location,
261                                  SVal V) const {
262  Environment NewEnv =
263    getStateManager().EnvMgr.bindExprAndLocation(Env,
264                                                 EnvironmentEntry(S, LCtx),
265                                                 location, V);
266
267  if (NewEnv == Env)
268    return this;
269
270  ProgramState NewSt = *this;
271  NewSt.Env = NewEnv;
272  return getStateManager().getPersistentState(NewSt);
273}
274
275ProgramStateRef ProgramState::assumeInBound(DefinedOrUnknownSVal Idx,
276                                      DefinedOrUnknownSVal UpperBound,
277                                      bool Assumption,
278                                      QualType indexTy) const {
279  if (Idx.isUnknown() || UpperBound.isUnknown())
280    return this;
281
282  // Build an expression for 0 <= Idx < UpperBound.
283  // This is the same as Idx + MIN < UpperBound + MIN, if overflow is allowed.
284  // FIXME: This should probably be part of SValBuilder.
285  ProgramStateManager &SM = getStateManager();
286  SValBuilder &svalBuilder = SM.getSValBuilder();
287  ASTContext &Ctx = svalBuilder.getContext();
288
289  // Get the offset: the minimum value of the array index type.
290  BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
291  // FIXME: This should be using ValueManager::ArrayindexTy...somehow.
292  if (indexTy.isNull())
293    indexTy = Ctx.IntTy;
294  nonloc::ConcreteInt Min(BVF.getMinValue(indexTy));
295
296  // Adjust the index.
297  SVal newIdx = svalBuilder.evalBinOpNN(this, BO_Add,
298                                        cast<NonLoc>(Idx), Min, indexTy);
299  if (newIdx.isUnknownOrUndef())
300    return this;
301
302  // Adjust the upper bound.
303  SVal newBound =
304    svalBuilder.evalBinOpNN(this, BO_Add, cast<NonLoc>(UpperBound),
305                            Min, indexTy);
306
307  if (newBound.isUnknownOrUndef())
308    return this;
309
310  // Build the actual comparison.
311  SVal inBound = svalBuilder.evalBinOpNN(this, BO_LT,
312                                cast<NonLoc>(newIdx), cast<NonLoc>(newBound),
313                                Ctx.IntTy);
314  if (inBound.isUnknownOrUndef())
315    return this;
316
317  // Finally, let the constraint manager take care of it.
318  ConstraintManager &CM = SM.getConstraintManager();
319  return CM.assume(this, cast<DefinedSVal>(inBound), Assumption);
320}
321
322ProgramStateRef ProgramStateManager::getInitialState(const LocationContext *InitLoc) {
323  ProgramState State(this,
324                EnvMgr.getInitialEnvironment(),
325                StoreMgr->getInitialStore(InitLoc),
326                GDMFactory.getEmptyMap());
327
328  return getPersistentState(State);
329}
330
331void ProgramStateManager::recycleUnusedStates() {
332  for (std::vector<ProgramState*>::iterator i = recentlyAllocatedStates.begin(),
333       e = recentlyAllocatedStates.end(); i != e; ++i) {
334    ProgramState *state = *i;
335    if (state->referencedByExplodedNode())
336      continue;
337    StateSet.RemoveNode(state);
338    freeStates.push_back(state);
339    state->~ProgramState();
340  }
341  recentlyAllocatedStates.clear();
342}
343
344ProgramStateRef ProgramStateManager::getPersistentStateWithGDM(
345                                                     ProgramStateRef FromState,
346                                                     ProgramStateRef GDMState) {
347  ProgramState NewState = *FromState;
348  NewState.GDM = GDMState->GDM;
349  return getPersistentState(NewState);
350}
351
352ProgramStateRef ProgramStateManager::getPersistentState(ProgramState &State) {
353
354  llvm::FoldingSetNodeID ID;
355  State.Profile(ID);
356  void *InsertPos;
357
358  if (ProgramState *I = StateSet.FindNodeOrInsertPos(ID, InsertPos))
359    return I;
360
361  ProgramState *newState = 0;
362  if (!freeStates.empty()) {
363    newState = freeStates.back();
364    freeStates.pop_back();
365  }
366  else {
367    newState = (ProgramState*) Alloc.Allocate<ProgramState>();
368  }
369  new (newState) ProgramState(State);
370  StateSet.InsertNode(newState, InsertPos);
371  recentlyAllocatedStates.push_back(newState);
372  return newState;
373}
374
375ProgramStateRef ProgramState::makeWithStore(const StoreRef &store) const {
376  ProgramState NewSt = *this;
377  NewSt.setStore(store);
378  return getStateManager().getPersistentState(NewSt);
379}
380
381void ProgramState::setStore(const StoreRef &newStore) {
382  Store newStoreStore = newStore.getStore();
383  if (newStoreStore)
384    stateMgr->getStoreManager().incrementReferenceCount(newStoreStore);
385  if (store)
386    stateMgr->getStoreManager().decrementReferenceCount(store);
387  store = newStoreStore;
388}
389
390//===----------------------------------------------------------------------===//
391//  State pretty-printing.
392//===----------------------------------------------------------------------===//
393
394void ProgramState::print(raw_ostream &Out,
395                         const char *NL, const char *Sep) const {
396  // Print the store.
397  ProgramStateManager &Mgr = getStateManager();
398  Mgr.getStoreManager().print(getStore(), Out, NL, Sep);
399
400  // Print out the environment.
401  Env.print(Out, NL, Sep);
402
403  // Print out the constraints.
404  Mgr.getConstraintManager().print(this, Out, NL, Sep);
405
406  // Print checker-specific data.
407  Mgr.getOwningEngine()->printState(Out, this, NL, Sep);
408}
409
410void ProgramState::printDOT(raw_ostream &Out) const {
411  print(Out, "\\l", "\\|");
412}
413
414void ProgramState::dump() const {
415  print(llvm::errs());
416}
417
418void ProgramState::printTaint(raw_ostream &Out,
419                              const char *NL, const char *Sep) const {
420  TaintMapImpl TM = get<TaintMap>();
421
422  if (!TM.isEmpty())
423    Out <<"Tainted Symbols:" << NL;
424
425  for (TaintMapImpl::iterator I = TM.begin(), E = TM.end(); I != E; ++I) {
426    Out << I->first << " : " << I->second << NL;
427  }
428}
429
430void ProgramState::dumpTaint() const {
431  printTaint(llvm::errs());
432}
433
434//===----------------------------------------------------------------------===//
435// Generic Data Map.
436//===----------------------------------------------------------------------===//
437
438void *const* ProgramState::FindGDM(void *K) const {
439  return GDM.lookup(K);
440}
441
442void*
443ProgramStateManager::FindGDMContext(void *K,
444                               void *(*CreateContext)(llvm::BumpPtrAllocator&),
445                               void (*DeleteContext)(void*)) {
446
447  std::pair<void*, void (*)(void*)>& p = GDMContexts[K];
448  if (!p.first) {
449    p.first = CreateContext(Alloc);
450    p.second = DeleteContext;
451  }
452
453  return p.first;
454}
455
456ProgramStateRef ProgramStateManager::addGDM(ProgramStateRef St, void *Key, void *Data){
457  ProgramState::GenericDataMap M1 = St->getGDM();
458  ProgramState::GenericDataMap M2 = GDMFactory.add(M1, Key, Data);
459
460  if (M1 == M2)
461    return St;
462
463  ProgramState NewSt = *St;
464  NewSt.GDM = M2;
465  return getPersistentState(NewSt);
466}
467
468ProgramStateRef ProgramStateManager::removeGDM(ProgramStateRef state, void *Key) {
469  ProgramState::GenericDataMap OldM = state->getGDM();
470  ProgramState::GenericDataMap NewM = GDMFactory.remove(OldM, Key);
471
472  if (NewM == OldM)
473    return state;
474
475  ProgramState NewState = *state;
476  NewState.GDM = NewM;
477  return getPersistentState(NewState);
478}
479
480void ScanReachableSymbols::anchor() { }
481
482bool ScanReachableSymbols::scan(nonloc::CompoundVal val) {
483  for (nonloc::CompoundVal::iterator I=val.begin(), E=val.end(); I!=E; ++I)
484    if (!scan(*I))
485      return false;
486
487  return true;
488}
489
490bool ScanReachableSymbols::scan(const SymExpr *sym) {
491  unsigned &isVisited = visited[sym];
492  if (isVisited)
493    return true;
494  isVisited = 1;
495
496  if (!visitor.VisitSymbol(sym))
497    return false;
498
499  // TODO: should be rewritten using SymExpr::symbol_iterator.
500  switch (sym->getKind()) {
501    case SymExpr::RegionValueKind:
502    case SymExpr::ConjuredKind:
503    case SymExpr::DerivedKind:
504    case SymExpr::ExtentKind:
505    case SymExpr::MetadataKind:
506      break;
507    case SymExpr::CastSymbolKind:
508      return scan(cast<SymbolCast>(sym)->getOperand());
509    case SymExpr::SymIntKind:
510      return scan(cast<SymIntExpr>(sym)->getLHS());
511    case SymExpr::IntSymKind:
512      return scan(cast<IntSymExpr>(sym)->getRHS());
513    case SymExpr::SymSymKind: {
514      const SymSymExpr *x = cast<SymSymExpr>(sym);
515      return scan(x->getLHS()) && scan(x->getRHS());
516    }
517  }
518  return true;
519}
520
521bool ScanReachableSymbols::scan(SVal val) {
522  if (loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&val))
523    return scan(X->getRegion());
524
525  if (nonloc::LocAsInteger *X = dyn_cast<nonloc::LocAsInteger>(&val))
526    return scan(X->getLoc());
527
528  if (SymbolRef Sym = val.getAsSymbol())
529    return scan(Sym);
530
531  if (const SymExpr *Sym = val.getAsSymbolicExpression())
532    return scan(Sym);
533
534  if (nonloc::CompoundVal *X = dyn_cast<nonloc::CompoundVal>(&val))
535    return scan(*X);
536
537  return true;
538}
539
540bool ScanReachableSymbols::scan(const MemRegion *R) {
541  if (isa<MemSpaceRegion>(R))
542    return true;
543
544  unsigned &isVisited = visited[R];
545  if (isVisited)
546    return true;
547  isVisited = 1;
548
549  // If this is a symbolic region, visit the symbol for the region.
550  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
551    if (!visitor.VisitSymbol(SR->getSymbol()))
552      return false;
553
554  // If this is a subregion, also visit the parent regions.
555  if (const SubRegion *SR = dyn_cast<SubRegion>(R))
556    if (!scan(SR->getSuperRegion()))
557      return false;
558
559  // Now look at the binding to this region (if any).
560  if (!scan(state->getSValAsScalarOrLoc(R)))
561    return false;
562
563  // Now look at the subregions.
564  if (!SRM.get())
565    SRM.reset(state->getStateManager().getStoreManager().
566                                           getSubRegionMap(state->getStore()));
567
568  return SRM->iterSubRegions(R, *this);
569}
570
571bool ProgramState::scanReachableSymbols(SVal val, SymbolVisitor& visitor) const {
572  ScanReachableSymbols S(this, visitor);
573  return S.scan(val);
574}
575
576bool ProgramState::scanReachableSymbols(const SVal *I, const SVal *E,
577                                   SymbolVisitor &visitor) const {
578  ScanReachableSymbols S(this, visitor);
579  for ( ; I != E; ++I) {
580    if (!S.scan(*I))
581      return false;
582  }
583  return true;
584}
585
586bool ProgramState::scanReachableSymbols(const MemRegion * const *I,
587                                   const MemRegion * const *E,
588                                   SymbolVisitor &visitor) const {
589  ScanReachableSymbols S(this, visitor);
590  for ( ; I != E; ++I) {
591    if (!S.scan(*I))
592      return false;
593  }
594  return true;
595}
596
597ProgramStateRef ProgramState::addTaint(const Stmt *S,
598                                           const LocationContext *LCtx,
599                                           TaintTagType Kind) const {
600  if (const Expr *E = dyn_cast_or_null<Expr>(S))
601    S = E->IgnoreParens();
602
603  SymbolRef Sym = getSVal(S, LCtx).getAsSymbol();
604  if (Sym)
605    return addTaint(Sym, Kind);
606
607  const MemRegion *R = getSVal(S, LCtx).getAsRegion();
608  addTaint(R, Kind);
609
610  // Cannot add taint, so just return the state.
611  return this;
612}
613
614ProgramStateRef ProgramState::addTaint(const MemRegion *R,
615                                           TaintTagType Kind) const {
616  if (const SymbolicRegion *SR = dyn_cast_or_null<SymbolicRegion>(R))
617    return addTaint(SR->getSymbol(), Kind);
618  return this;
619}
620
621ProgramStateRef ProgramState::addTaint(SymbolRef Sym,
622                                           TaintTagType Kind) const {
623  // If this is a symbol cast, remove the cast before adding the taint. Taint
624  // is cast agnostic.
625  while (const SymbolCast *SC = dyn_cast<SymbolCast>(Sym))
626    Sym = SC->getOperand();
627
628  ProgramStateRef NewState = set<TaintMap>(Sym, Kind);
629  assert(NewState);
630  return NewState;
631}
632
633bool ProgramState::isTainted(const Stmt *S, const LocationContext *LCtx,
634                             TaintTagType Kind) const {
635  if (const Expr *E = dyn_cast_or_null<Expr>(S))
636    S = E->IgnoreParens();
637
638  SVal val = getSVal(S, LCtx);
639  return isTainted(val, Kind);
640}
641
642bool ProgramState::isTainted(SVal V, TaintTagType Kind) const {
643  if (const SymExpr *Sym = V.getAsSymExpr())
644    return isTainted(Sym, Kind);
645  if (const MemRegion *Reg = V.getAsRegion())
646    return isTainted(Reg, Kind);
647  return false;
648}
649
650bool ProgramState::isTainted(const MemRegion *Reg, TaintTagType K) const {
651  if (!Reg)
652    return false;
653
654  // Element region (array element) is tainted if either the base or the offset
655  // are tainted.
656  if (const ElementRegion *ER = dyn_cast<ElementRegion>(Reg))
657    return isTainted(ER->getSuperRegion(), K) || isTainted(ER->getIndex(), K);
658
659  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(Reg))
660    return isTainted(SR->getSymbol(), K);
661
662  if (const SubRegion *ER = dyn_cast<SubRegion>(Reg))
663    return isTainted(ER->getSuperRegion(), K);
664
665  return false;
666}
667
668bool ProgramState::isTainted(SymbolRef Sym, TaintTagType Kind) const {
669  if (!Sym)
670    return false;
671
672  // Traverse all the symbols this symbol depends on to see if any are tainted.
673  bool Tainted = false;
674  for (SymExpr::symbol_iterator SI = Sym->symbol_begin(), SE =Sym->symbol_end();
675       SI != SE; ++SI) {
676    assert(isa<SymbolData>(*SI));
677    const TaintTagType *Tag = get<TaintMap>(*SI);
678    Tainted = (Tag && *Tag == Kind);
679
680    // If this is a SymbolDerived with a tainted parent, it's also tainted.
681    if (const SymbolDerived *SD = dyn_cast<SymbolDerived>(*SI))
682      Tainted = Tainted || isTainted(SD->getParentSymbol(), Kind);
683
684    // If memory region is tainted, data is also tainted.
685    if (const SymbolRegionValue *SRV = dyn_cast<SymbolRegionValue>(*SI))
686      Tainted = Tainted || isTainted(SRV->getRegion(), Kind);
687
688    // If If this is a SymbolCast from a tainted value, it's also tainted.
689    if (const SymbolCast *SC = dyn_cast<SymbolCast>(*SI))
690      Tainted = Tainted || isTainted(SC->getOperand(), Kind);
691
692    if (Tainted)
693      return true;
694  }
695
696  return Tainted;
697}
698