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