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