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