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