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