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