ProgramState.cpp revision 314564
1139823Simp//= ProgramState.cpp - Path-Sensitive "State" for tracking values --*- C++ -*--=
211150Swollman//
31541Srgrimes//                     The LLVM Compiler Infrastructure
41541Srgrimes//
51541Srgrimes// This file is distributed under the University of Illinois Open Source
61541Srgrimes// License. See LICENSE.TXT for details.
71541Srgrimes//
81541Srgrimes//===----------------------------------------------------------------------===//
91541Srgrimes//
101541Srgrimes//  This file implements ProgramState and ProgramStateManager.
111541Srgrimes//
121541Srgrimes//===----------------------------------------------------------------------===//
131541Srgrimes
141541Srgrimes#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
151541Srgrimes#include "clang/Analysis/CFG.h"
161541Srgrimes#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
171541Srgrimes#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
181541Srgrimes#include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
191541Srgrimes#include "clang/StaticAnalyzer/Core/PathSensitive/TaintManager.h"
201541Srgrimes#include "llvm/Support/raw_ostream.h"
211541Srgrimes
221541Srgrimesusing namespace clang;
231541Srgrimesusing namespace ento;
241541Srgrimes
251541Srgrimesnamespace clang { namespace  ento {
261541Srgrimes/// Increments the number of times this state is referenced.
271541Srgrimes
281541Srgrimesvoid ProgramStateRetain(const ProgramState *state) {
2911150Swollman  ++const_cast<ProgramState*>(state)->refCount;
3050477Speter}
311541Srgrimes
321541Srgrimes/// Decrement the number of times this state is referenced.
33125680Sbmsvoid ProgramStateRelease(const ProgramState *state) {
3454263Sshin  assert(state->refCount > 0);
35101106Srwatson  ProgramState *s = const_cast<ProgramState*>(state);
3629514Sjoerg  if (--s->refCount == 0) {
3729514Sjoerg    ProgramStateManager &Mgr = s->getStateManager();
381541Srgrimes    Mgr.StateSet.RemoveNode(s);
391541Srgrimes    s->~ProgramState();
4050673Sjlemon    Mgr.freeStates.push_back(s);
4112172Sphk  }
4212172Sphk}
431541Srgrimes}}
441541Srgrimes
45164033SrwatsonProgramState::ProgramState(ProgramStateManager *mgr, const Environment& env,
4648758Sgreen                 StoreRef st, GenericDataMap gdm)
471541Srgrimes  : stateMgr(mgr),
481541Srgrimes    Env(env),
491541Srgrimes    store(st.getStore()),
5075619Skris    GDM(gdm),
5134923Sbde    refCount(0) {
5292760Sjeff  stateMgr->getStoreManager().incrementReferenceCount(store);
531541Srgrimes}
541541Srgrimes
551541SrgrimesProgramState::ProgramState(const ProgramState &RHS)
561541Srgrimes    : llvm::FoldingSetNode(),
571541Srgrimes      stateMgr(RHS.stateMgr),
581541Srgrimes      Env(RHS.Env),
591541Srgrimes      store(RHS.store),
6055679Sshin      GDM(RHS.GDM),
6155679Sshin      refCount(0) {
6255679Sshin  stateMgr->getStoreManager().incrementReferenceCount(store);
631541Srgrimes}
6455679Sshin
6555679SshinProgramState::~ProgramState() {
6655679Sshin  if (store)
677090Sbde    stateMgr->getStoreManager().decrementReferenceCount(store);
681541Srgrimes}
6955679Sshin
7055679SshinProgramStateManager::ProgramStateManager(ASTContext &Ctx,
71148385Sume                                         StoreManagerCreator CreateSMgr,
72122922Sandre                                         ConstraintManagerCreator CreateCMgr,
7355679Sshin                                         llvm::BumpPtrAllocator &alloc,
74145360Sandre                                         SubEngine *SubEng)
751541Srgrimes  : Eng(SubEng), EnvMgr(alloc), GDMFactory(alloc),
761541Srgrimes    svalBuilder(createSimpleSValBuilder(alloc, Ctx, *this)),
771541Srgrimes    CallEventMgr(new CallEventManager(alloc)), Alloc(alloc) {
781541Srgrimes  StoreMgr = (*CreateSMgr)(*this);
791541Srgrimes  ConstraintMgr = (*CreateCMgr)(*this, SubEng);
8055679Sshin}
8155679Sshin
8255679Sshin
831541SrgrimesProgramStateManager::~ProgramStateManager() {
846283Swollman  for (GDMContextsTy::iterator I=GDMContexts.begin(), E=GDMContexts.end();
856283Swollman       I!=E; ++I)
866283Swollman    I->second.second(I->second.first);
8755679Sshin}
881541Srgrimes
8958698SjlemonProgramStateRef
9058698SjlemonProgramStateManager::removeDeadBindings(ProgramStateRef state,
91163606Srwatson                                   const StackFrameContext *LCtx,
92163606Srwatson                                   SymbolReaper& SymReaper) {
93162035Sglebius
94157478Sglebius  // This code essentially performs a "mark-and-sweep" of the VariableBindings.
95162767Ssilby  // The roots are any Block-level exprs and Decls that our liveness algorithm
96169608Sandre  // tells us are live.  We then see what Decls they may reference, and keep
97169608Sandre  // those around.  This code more than likely can be made faster, and the
98169608Sandre  // frequency of which this method is called should be experimented with
99169608Sandre  // for optimum performance.
100169608Sandre  ProgramState NewState = *state;
101169608Sandre
102169608Sandre  NewState.Env = EnvMgr.removeDeadBindings(NewState.Env, SymReaper, state);
103169608Sandre
104169608Sandre  // Clean up the store.
105169608Sandre  StoreRef newStore = StoreMgr->removeDeadBindings(NewState.getStore(), LCtx,
106169608Sandre                                                   SymReaper);
107162031Sglebius  NewState.setStore(newStore);
108162767Ssilby  SymReaper.setReapedStore(newStore);
109162767Ssilby
110162767Ssilby  ProgramStateRef Result = getPersistentState(NewState);
111162767Ssilby  return ConstraintMgr->removeDeadBindings(Result, SymReaper);
112162767Ssilby}
113162768Smaxim
114162768SmaximProgramStateRef ProgramState::bindLoc(Loc LV, SVal V, bool notifyChanges) const {
115162768Smaxim  ProgramStateManager &Mgr = getStateManager();
116162767Ssilby  ProgramStateRef newState = makeWithStore(Mgr.StoreMgr->Bind(getStore(),
117162767Ssilby                                                             LV, V));
118162767Ssilby  const MemRegion *MR = LV.getAsRegion();
119162767Ssilby  if (MR && Mgr.getOwningEngine() && notifyChanges)
120162767Ssilby    return Mgr.getOwningEngine()->processRegionChange(newState, MR);
121162767Ssilby
122162767Ssilby  return newState;
123162767Ssilby}
124162767Ssilby
125162031SglebiusProgramStateRef ProgramState::bindDefault(SVal loc, SVal V) const {
126162031Sglebius  ProgramStateManager &Mgr = getStateManager();
127162031Sglebius  const MemRegion *R = loc.castAs<loc::MemRegionVal>().getRegion();
128157478Sglebius  const StoreRef &newStore = Mgr.StoreMgr->BindDefault(getStore(), R, V);
129162031Sglebius  ProgramStateRef new_state = makeWithStore(newStore);
130162767Ssilby  return Mgr.getOwningEngine() ?
131162031Sglebius           Mgr.getOwningEngine()->processRegionChange(new_state, R) :
132162031Sglebius           new_state;
133170289Sdwmalone}
134162767Ssilby
135162767Ssilbytypedef ArrayRef<const MemRegion *> RegionList;
136162031Sglebiustypedef ArrayRef<SVal> ValueList;
137162035Sglebius
138162767SsilbyProgramStateRef
139162031SglebiusProgramState::invalidateRegions(RegionList Regions,
140162031Sglebius                             const Expr *E, unsigned Count,
141169541Sandre                             const LocationContext *LCtx,
142162031Sglebius                             bool CausedByPointerEscape,
143162031Sglebius                             InvalidatedSymbols *IS,
144162031Sglebius                             const CallEvent *Call,
145162031Sglebius                             RegionAndSymbolInvalidationTraits *ITraits) const {
146162151Sglebius  SmallVector<SVal, 8> Values;
147162151Sglebius  for (RegionList::const_iterator I = Regions.begin(),
148167721Sandre                                  End = Regions.end(); I != End; ++I)
149167721Sandre    Values.push_back(loc::MemRegionVal(*I));
150162151Sglebius
151169541Sandre  return invalidateRegionsImpl(Values, E, Count, LCtx, CausedByPointerEscape,
152169541Sandre                               IS, ITraits, Call);
153157927Sps}
154157927Sps
155162031SglebiusProgramStateRef
156162767SsilbyProgramState::invalidateRegions(ValueList Values,
157157927Sps                             const Expr *E, unsigned Count,
158157927Sps                             const LocationContext *LCtx,
1591541Srgrimes                             bool CausedByPointerEscape,
160169541Sandre                             InvalidatedSymbols *IS,
1611541Srgrimes                             const CallEvent *Call,
162169454Srwatson                             RegionAndSymbolInvalidationTraits *ITraits) const {
163162031Sglebius
164162031Sglebius  return invalidateRegionsImpl(Values, E, Count, LCtx, CausedByPointerEscape,
165157478Sglebius                               IS, ITraits, Call);
166157478Sglebius}
167162767Ssilby
168162031SglebiusProgramStateRef
169162031SglebiusProgramState::invalidateRegionsImpl(ValueList Values,
170169608Sandre                                    const Expr *E, unsigned Count,
1711541Srgrimes                                    const LocationContext *LCtx,
1721541Srgrimes                                    bool CausedByPointerEscape,
1731541Srgrimes                                    InvalidatedSymbols *IS,
174111145Sjlemon                                    RegionAndSymbolInvalidationTraits *ITraits,
175138410Srwatson                                    const CallEvent *Call) const {
176111145Sjlemon  ProgramStateManager &Mgr = getStateManager();
177111145Sjlemon  SubEngine* Eng = Mgr.getOwningEngine();
178111145Sjlemon
179157431Srwatson  InvalidatedSymbols Invalidated;
180111145Sjlemon  if (!IS)
181111145Sjlemon    IS = &Invalidated;
182162151Sglebius
183162111Sru  RegionAndSymbolInvalidationTraits ITraitsLocal;
184111145Sjlemon  if (!ITraits)
185111145Sjlemon    ITraits = &ITraitsLocal;
186169608Sandre
187162151Sglebius  if (Eng) {
188138020Srwatson    StoreManager::InvalidatedRegions TopLevelInvalidated;
189162151Sglebius    StoreManager::InvalidatedRegions Invalidated;
190162151Sglebius    const StoreRef &newStore
191162151Sglebius    = Mgr.StoreMgr->invalidateRegions(getStore(), Values, E, Count, LCtx, Call,
192162151Sglebius                                      *IS, *ITraits, &TopLevelInvalidated,
193162151Sglebius                                      &Invalidated);
194162151Sglebius
195162151Sglebius    ProgramStateRef newState = makeWithStore(newStore);
196112009Sjlemon
197112009Sjlemon    if (CausedByPointerEscape) {
198169608Sandre      newState = Eng->notifyCheckersOfPointerEscape(newState, IS,
199112009Sjlemon                                                    TopLevelInvalidated,
200157376Srwatson                                                    Invalidated, Call,
201157376Srwatson                                                    *ITraits);
202162151Sglebius    }
203112009Sjlemon
204112009Sjlemon    return Eng->processRegionChanges(newState, IS, TopLevelInvalidated,
205112009Sjlemon                                     Invalidated, Call);
206111145Sjlemon  }
207111145Sjlemon
208111145Sjlemon  const StoreRef &newStore =
209111145Sjlemon  Mgr.StoreMgr->invalidateRegions(getStore(), Values, E, Count, LCtx, Call,
210111145Sjlemon                                  *IS, *ITraits, nullptr, nullptr);
211111145Sjlemon  return makeWithStore(newStore);
212111145Sjlemon}
213111145Sjlemon
214111145SjlemonProgramStateRef ProgramState::killBinding(Loc LV) const {
215111145Sjlemon  assert(!LV.getAs<loc::MemRegionVal>() && "Use invalidateRegion instead.");
216133874Srwatson
217169477Sandre  Store OldStore = getStore();
218111145Sjlemon  const StoreRef &newStore =
219169477Sandre    getStateManager().StoreMgr->killBinding(OldStore, LV);
220169477Sandre
221111145Sjlemon  if (newStore.getStore() == OldStore)
222169477Sandre    return this;
223169477Sandre
224111145Sjlemon  return makeWithStore(newStore);
225111145Sjlemon}
226111145Sjlemon
227121850SsilbyProgramStateRef
228121884SsilbyProgramState::enterStackFrame(const CallEvent &Call,
229111145Sjlemon                              const StackFrameContext *CalleeCtx) const {
230112009Sjlemon  const StoreRef &NewStore =
231111145Sjlemon    getStateManager().StoreMgr->enterStackFrame(getStore(), Call, CalleeCtx);
232111145Sjlemon  return makeWithStore(NewStore);
233111145Sjlemon}
234111145Sjlemon
235111145SjlemonSVal ProgramState::getSValAsScalarOrLoc(const MemRegion *R) const {
236111145Sjlemon  // We only want to do fetches from regions that we can actually bind
237137139Sandre  // values.  For example, SymbolicRegions of type 'id<...>' cannot
238157376Srwatson  // have direct bindings (but their can be bindings on their subregions).
239157376Srwatson  if (!R->isBoundable())
240157376Srwatson    return UnknownVal();
241157376Srwatson
242157376Srwatson  if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
243160925Srwatson    QualType T = TR->getValueType();
244160925Srwatson    if (Loc::isLocType(T) || T->isIntegralOrEnumerationType())
245160925Srwatson      return getSVal(R);
246157376Srwatson  }
247111145Sjlemon
248111145Sjlemon  return UnknownVal();
249160925Srwatson}
250169347Srwatson
251130387SrwatsonSVal ProgramState::getSVal(Loc location, QualType T) const {
252111145Sjlemon  SVal V = getRawSVal(cast<Loc>(location), T);
253157376Srwatson
254114794Srwatson  // If 'V' is a symbolic value that is *perfectly* constrained to
255126351Srwatson  // be a constant value, use that value instead to lessen the burden
256157432Srwatson  // on later analysis stages (so we have less symbolic values to reason
257111145Sjlemon  // about).
258169608Sandre  if (!T.isNull()) {
259157376Srwatson    if (SymbolRef sym = V.getAsSymbol()) {
260157376Srwatson      if (const llvm::APSInt *Int = getStateManager()
261157376Srwatson                                    .getConstraintManager()
262157376Srwatson                                    .getSymVal(this, sym)) {
263157376Srwatson        // FIXME: Because we don't correctly model (yet) sign-extension
264157376Srwatson        // and truncation of symbolic values, we need to convert
265157376Srwatson        // the integer value to the correct signedness and bitwidth.
266157376Srwatson        //
267157376Srwatson        // This shows up in the following:
268157376Srwatson        //
269157376Srwatson        //   char foo();
270157376Srwatson        //   unsigned x = foo();
271157376Srwatson        //   if (x == 54)
272157376Srwatson        //     ...
273157376Srwatson        //
274157376Srwatson        //  The symbolic value stored to 'x' is actually the conjured
275111145Sjlemon        //  symbol for the call to foo(); the type of that symbol is 'char',
276111145Sjlemon        //  not unsigned.
277162064Sglebius        const llvm::APSInt &NewV = getBasicVals().Convert(T, *Int);
278121850Ssilby
279121884Ssilby        if (V.getAs<Loc>())
280121884Ssilby          return loc::ConcreteInt(NewV);
281121884Ssilby        else
282121884Ssilby          return nonloc::ConcreteInt(NewV);
283121884Ssilby      }
284121884Ssilby    }
285121884Ssilby  }
286121884Ssilby
287121884Ssilby  return V;
288121884Ssilby}
289121850Ssilby
290121850SsilbyProgramStateRef ProgramState::BindExpr(const Stmt *S,
291121850Ssilby                                           const LocationContext *LCtx,
292121850Ssilby                                           SVal V, bool Invalidate) const{
293121850Ssilby  Environment NewEnv =
294121850Ssilby    getStateManager().EnvMgr.bindExpr(Env, EnvironmentEntry(S, LCtx), V,
295121850Ssilby                                      Invalidate);
296121884Ssilby  if (NewEnv == Env)
297121884Ssilby    return this;
298121850Ssilby
299162064Sglebius  ProgramState NewSt = *this;
300121884Ssilby  NewSt.Env = NewEnv;
301121884Ssilby  return getStateManager().getPersistentState(NewSt);
302133874Srwatson}
303121884Ssilby
304139222SrwatsonProgramStateRef ProgramState::assumeInBound(DefinedOrUnknownSVal Idx,
305121850Ssilby                                      DefinedOrUnknownSVal UpperBound,
306139222Srwatson                                      bool Assumption,
307121850Ssilby                                      QualType indexTy) const {
308162064Sglebius  if (Idx.isUnknown() || UpperBound.isUnknown())
309121850Ssilby    return this;
310169608Sandre
311169608Sandre  // Build an expression for 0 <= Idx < UpperBound.
312169608Sandre  // This is the same as Idx + MIN < UpperBound + MIN, if overflow is allowed.
313169608Sandre  // FIXME: This should probably be part of SValBuilder.
314169608Sandre  ProgramStateManager &SM = getStateManager();
315169608Sandre  SValBuilder &svalBuilder = SM.getSValBuilder();
316169608Sandre  ASTContext &Ctx = svalBuilder.getContext();
317169608Sandre
318169608Sandre  // Get the offset: the minimum value of the array index type.
319169608Sandre  BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
320169608Sandre  // FIXME: This should be using ValueManager::ArrayindexTy...somehow.
321169608Sandre  if (indexTy.isNull())
322169608Sandre    indexTy = Ctx.IntTy;
323169608Sandre  nonloc::ConcreteInt Min(BVF.getMinValue(indexTy));
324169608Sandre
325169608Sandre  // Adjust the index.
326169608Sandre  SVal newIdx = svalBuilder.evalBinOpNN(this, BO_Add,
327169608Sandre                                        Idx.castAs<NonLoc>(), Min, indexTy);
328169608Sandre  if (newIdx.isUnknownOrUndef())
329169608Sandre    return this;
330169608Sandre
331169608Sandre  // Adjust the upper bound.
332169608Sandre  SVal newBound =
333169608Sandre    svalBuilder.evalBinOpNN(this, BO_Add, UpperBound.castAs<NonLoc>(),
334169608Sandre                            Min, indexTy);
335169608Sandre
336169608Sandre  if (newBound.isUnknownOrUndef())
337169608Sandre    return this;
338169608Sandre
339169608Sandre  // Build the actual comparison.
340169608Sandre  SVal inBound = svalBuilder.evalBinOpNN(this, BO_LT, newIdx.castAs<NonLoc>(),
341169608Sandre                                         newBound.castAs<NonLoc>(), Ctx.IntTy);
342169608Sandre  if (inBound.isUnknownOrUndef())
343169608Sandre    return this;
344169608Sandre
345169608Sandre  // Finally, let the constraint manager take care of it.
346169608Sandre  ConstraintManager &CM = SM.getConstraintManager();
347169608Sandre  return CM.assume(this, inBound.castAs<DefinedSVal>(), Assumption);
348169608Sandre}
349169608Sandre
350169608SandreConditionTruthVal ProgramState::isNull(SVal V) const {
351169608Sandre  if (V.isZeroConstant())
352169608Sandre    return true;
353169608Sandre
354169608Sandre  if (V.isConstant())
355169608Sandre    return false;
356169608Sandre
357169608Sandre  SymbolRef Sym = V.getAsSymbol(/* IncludeBaseRegion */ true);
358169608Sandre  if (!Sym)
359169608Sandre    return ConditionTruthVal();
360169608Sandre
361169608Sandre  return getStateManager().ConstraintMgr->isNull(this, Sym);
362169608Sandre}
363169608Sandre
364169608SandreProgramStateRef ProgramStateManager::getInitialState(const LocationContext *InitLoc) {
365169608Sandre  ProgramState State(this,
366169608Sandre                EnvMgr.getInitialEnvironment(),
367169608Sandre                StoreMgr->getInitialStore(InitLoc),
368169608Sandre                GDMFactory.getEmptyMap());
369169608Sandre
370169608Sandre  return getPersistentState(State);
371169608Sandre}
372169608Sandre
373169608SandreProgramStateRef ProgramStateManager::getPersistentStateWithGDM(
374169608Sandre                                                     ProgramStateRef FromState,
375169608Sandre                                                     ProgramStateRef GDMState) {
376169608Sandre  ProgramState NewState(*FromState);
377169608Sandre  NewState.GDM = GDMState->GDM;
378169608Sandre  return getPersistentState(NewState);
379169608Sandre}
380169608Sandre
381169608SandreProgramStateRef ProgramStateManager::getPersistentState(ProgramState &State) {
382169608Sandre
383169608Sandre  llvm::FoldingSetNodeID ID;
384169608Sandre  State.Profile(ID);
385169608Sandre  void *InsertPos;
386169608Sandre
387169608Sandre  if (ProgramState *I = StateSet.FindNodeOrInsertPos(ID, InsertPos))
388169608Sandre    return I;
389169608Sandre
390169608Sandre  ProgramState *newState = nullptr;
391169608Sandre  if (!freeStates.empty()) {
392169608Sandre    newState = freeStates.back();
393169608Sandre    freeStates.pop_back();
394169608Sandre  }
395169608Sandre  else {
396169608Sandre    newState = (ProgramState*) Alloc.Allocate<ProgramState>();
397169608Sandre  }
398169608Sandre  new (newState) ProgramState(State);
399169608Sandre  StateSet.InsertNode(newState, InsertPos);
400169608Sandre  return newState;
401169608Sandre}
402169608Sandre
403169608SandreProgramStateRef ProgramState::makeWithStore(const StoreRef &store) const {
404169608Sandre  ProgramState NewSt(*this);
405169608Sandre  NewSt.setStore(store);
406169608Sandre  return getStateManager().getPersistentState(NewSt);
407169608Sandre}
408169608Sandre
409169608Sandrevoid ProgramState::setStore(const StoreRef &newStore) {
410169608Sandre  Store newStoreStore = newStore.getStore();
411169608Sandre  if (newStoreStore)
412169608Sandre    stateMgr->getStoreManager().incrementReferenceCount(newStoreStore);
413169608Sandre  if (store)
414169608Sandre    stateMgr->getStoreManager().decrementReferenceCount(store);
415169635Soleg  store = newStoreStore;
416169608Sandre}
417169608Sandre
418169608Sandre//===----------------------------------------------------------------------===//
419169608Sandre//  State pretty-printing.
420169608Sandre//===----------------------------------------------------------------------===//
421169608Sandre
422169608Sandrevoid ProgramState::print(raw_ostream &Out,
423169635Soleg                         const char *NL, const char *Sep) const {
424169608Sandre  // Print the store.
425169608Sandre  ProgramStateManager &Mgr = getStateManager();
426169608Sandre  Mgr.getStoreManager().print(getStore(), Out, NL, Sep);
427169608Sandre
428169608Sandre  // Print out the environment.
429169608Sandre  Env.print(Out, NL, Sep);
430169608Sandre
431169608Sandre  // Print out the constraints.
432169608Sandre  Mgr.getConstraintManager().print(this, Out, NL, Sep);
433169608Sandre
434169608Sandre  // Print checker-specific data.
435169608Sandre  Mgr.getOwningEngine()->printState(Out, this, NL, Sep);
436169608Sandre}
437169608Sandre
438169608Sandrevoid ProgramState::printDOT(raw_ostream &Out) const {
439169608Sandre  print(Out, "\\l", "\\|");
440169608Sandre}
441169608Sandre
442169608SandreLLVM_DUMP_METHOD void ProgramState::dump() const {
443169608Sandre  print(llvm::errs());
444169608Sandre}
445169608Sandre
446169608Sandrevoid ProgramState::printTaint(raw_ostream &Out,
447169608Sandre                              const char *NL, const char *Sep) const {
448169608Sandre  TaintMapImpl TM = get<TaintMap>();
449169608Sandre
450169608Sandre  if (!TM.isEmpty())
451157376Srwatson    Out <<"Tainted Symbols:" << NL;
452112009Sjlemon
453111145Sjlemon  for (TaintMapImpl::iterator I = TM.begin(), E = TM.end(); I != E; ++I) {
454157376Srwatson    Out << I->first << " : " << I->second << NL;
455111145Sjlemon  }
456111145Sjlemon}
457157376Srwatson
458157386Srwatsonvoid ProgramState::dumpTaint() const {
459157376Srwatson  printTaint(llvm::errs());
460160549Srwatson}
461160549Srwatson
462157386Srwatson//===----------------------------------------------------------------------===//
463160549Srwatson// Generic Data Map.
464160549Srwatson//===----------------------------------------------------------------------===//
465157376Srwatson
466111145Sjlemonvoid *const* ProgramState::FindGDM(void *K) const {
467157376Srwatson  return GDM.lookup(K);
468157432Srwatson}
469169608Sandre
470138020Srwatsonvoid*
471138020SrwatsonProgramStateManager::FindGDMContext(void *K,
472111145Sjlemon                               void *(*CreateContext)(llvm::BumpPtrAllocator&),
473169608Sandre                               void (*DeleteContext)(void*)) {
474111145Sjlemon
475158009Srwatson  std::pair<void*, void (*)(void*)>& p = GDMContexts[K];
476157376Srwatson  if (!p.first) {
477157376Srwatson    p.first = CreateContext(Alloc);
478157386Srwatson    p.second = DeleteContext;
479160549Srwatson  }
480160549Srwatson
481160549Srwatson  return p.first;
482160549Srwatson}
483160549Srwatson
484160549SrwatsonProgramStateRef ProgramStateManager::addGDM(ProgramStateRef St, void *Key, void *Data){
485157386Srwatson  ProgramState::GenericDataMap M1 = St->getGDM();
486157386Srwatson  ProgramState::GenericDataMap M2 = GDMFactory.add(M1, Key, Data);
487160549Srwatson
488157386Srwatson  if (M1 == M2)
489157386Srwatson    return St;
490157386Srwatson
491157386Srwatson  ProgramState NewSt = *St;
492157386Srwatson  NewSt.GDM = M2;
493157386Srwatson  return getPersistentState(NewSt);
494157376Srwatson}
495157386Srwatson
496157386SrwatsonProgramStateRef ProgramStateManager::removeGDM(ProgramStateRef state, void *Key) {
497157386Srwatson  ProgramState::GenericDataMap OldM = state->getGDM();
498157386Srwatson  ProgramState::GenericDataMap NewM = GDMFactory.remove(OldM, Key);
499157386Srwatson
500157386Srwatson  if (NewM == OldM)
501157376Srwatson    return state;
502157386Srwatson
503157376Srwatson  ProgramState NewState = *state;
504157376Srwatson  NewState.GDM = NewM;
505157376Srwatson  return getPersistentState(NewState);
506157376Srwatson}
507157376Srwatson
508157376Srwatsonbool ScanReachableSymbols::scan(nonloc::LazyCompoundVal val) {
509157386Srwatson  bool wasVisited = !visited.insert(val.getCVData()).second;
510111145Sjlemon  if (wasVisited)
511126002Spjd    return true;
512126002Spjd
513112009Sjlemon  StoreManager &StoreMgr = state->getStateManager().getStoreManager();
514157376Srwatson  // FIXME: We don't really want to use getBaseRegion() here because pointer
515112009Sjlemon  // arithmetic doesn't apply, but scanReachableSymbols only accepts base
516111145Sjlemon  // regions right now.
517111145Sjlemon  const MemRegion *R = val.getRegion()->getBaseRegion();
518111145Sjlemon  return StoreMgr.scanReachableSymbols(val.getStore(), R, *this);
519126351Srwatson}
520111145Sjlemon
521111145Sjlemonbool ScanReachableSymbols::scan(nonloc::CompoundVal val) {
522111145Sjlemon  for (nonloc::CompoundVal::iterator I=val.begin(), E=val.end(); I!=E; ++I)
523111145Sjlemon    if (!scan(*I))
524111145Sjlemon      return false;
525111145Sjlemon
526111145Sjlemon  return true;
527168845Sandre}
528111145Sjlemon
529111145Sjlemonbool ScanReachableSymbols::scan(const SymExpr *sym) {
530111145Sjlemon  for (SymExpr::symbol_iterator SI = sym->symbol_begin(),
531111145Sjlemon                                SE = sym->symbol_end();
532111145Sjlemon       SI != SE; ++SI) {
533138020Srwatson    bool wasVisited = !visited.insert(*SI).second;
534138020Srwatson    if (wasVisited)
535151967Sandre      continue;
536111145Sjlemon
537111145Sjlemon    if (!visitor.VisitSymbol(*SI))
538111145Sjlemon      return false;
539111145Sjlemon  }
540114794Srwatson
541123607Srwatson  return true;
542114794Srwatson}
543114794Srwatson
544111153Sjlemonbool ScanReachableSymbols::scan(SVal val) {
545111145Sjlemon  if (Optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>())
546111145Sjlemon    return scan(X->getRegion());
547111145Sjlemon
548111145Sjlemon  if (Optional<nonloc::LazyCompoundVal> X =
549111145Sjlemon          val.getAs<nonloc::LazyCompoundVal>())
550111153Sjlemon    return scan(*X);
551111153Sjlemon
552111153Sjlemon  if (Optional<nonloc::LocAsInteger> X = val.getAs<nonloc::LocAsInteger>())
553111145Sjlemon    return scan(X->getLoc());
554111145Sjlemon
555111145Sjlemon  if (SymbolRef Sym = val.getAsSymbol())
556111145Sjlemon    return scan(Sym);
557111145Sjlemon
558168845Sandre  if (const SymExpr *Sym = val.getAsSymbolicExpression())
559133874Srwatson    return scan(Sym);
560133874Srwatson
561111145Sjlemon  if (Optional<nonloc::CompoundVal> X = val.getAs<nonloc::CompoundVal>())
562111145Sjlemon    return scan(*X);
563133874Srwatson
564111145Sjlemon  return true;
565168845Sandre}
566169477Sandre
567168845Sandrebool ScanReachableSymbols::scan(const MemRegion *R) {
568133874Srwatson  if (isa<MemSpaceRegion>(R))
569168845Sandre    return true;
570111145Sjlemon
571111145Sjlemon  bool wasVisited = !visited.insert(R).second;
572111145Sjlemon  if (wasVisited)
573111145Sjlemon    return true;
574111145Sjlemon
575111145Sjlemon  if (!visitor.VisitMemRegion(R))
576111145Sjlemon    return false;
577111145Sjlemon
578111145Sjlemon  // If this is a symbolic region, visit the symbol for the region.
579111145Sjlemon  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
580111145Sjlemon    if (!visitor.VisitSymbol(SR->getSymbol()))
581111145Sjlemon      return false;
582111153Sjlemon
583111145Sjlemon  // If this is a subregion, also visit the parent regions.
584111145Sjlemon  if (const SubRegion *SR = dyn_cast<SubRegion>(R)) {
585111145Sjlemon    const MemRegion *Super = SR->getSuperRegion();
586122922Sandre    if (!scan(Super))
587122922Sandre      return false;
588111145Sjlemon
589111153Sjlemon    // When we reach the topmost region, scan all symbols in it.
590111153Sjlemon    if (isa<MemSpaceRegion>(Super)) {
591111153Sjlemon      StoreManager &StoreMgr = state->getStateManager().getStoreManager();
592111145Sjlemon      if (!StoreMgr.scanReachableSymbols(state->getStore(), SR, *this))
593133874Srwatson        return false;
594111145Sjlemon    }
595111145Sjlemon  }
596111145Sjlemon
597124248Sandre  // Regions captured by a block are also implicitly reachable.
598124248Sandre  if (const BlockDataRegion *BDR = dyn_cast<BlockDataRegion>(R)) {
599122922Sandre    BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
600134793Sjmg                                              E = BDR->referenced_vars_end();
601134793Sjmg    for ( ; I != E; ++I) {
602111145Sjlemon      if (!scan(I.getCapturedRegion()))
603111145Sjlemon        return false;
604111145Sjlemon    }
605111145Sjlemon  }
606111145Sjlemon
607111145Sjlemon  return true;
608111145Sjlemon}
609111145Sjlemon
610169608Sandrebool ProgramState::scanReachableSymbols(SVal val, SymbolVisitor& visitor) const {
611169608Sandre  ScanReachableSymbols S(this, visitor);
612169608Sandre  return S.scan(val);
613169608Sandre}
614169608Sandre
615169608Sandrebool ProgramState::scanReachableSymbols(const SVal *I, const SVal *E,
616169608Sandre                                   SymbolVisitor &visitor) const {
617169608Sandre  ScanReachableSymbols S(this, visitor);
618169608Sandre  for ( ; I != E; ++I) {
619169608Sandre    if (!S.scan(*I))
620169608Sandre      return false;
621169608Sandre  }
622169608Sandre  return true;
623169608Sandre}
624169608Sandre
625169608Sandrebool ProgramState::scanReachableSymbols(const MemRegion * const *I,
626169608Sandre                                   const MemRegion * const *E,
627169608Sandre                                   SymbolVisitor &visitor) const {
628169608Sandre  ScanReachableSymbols S(this, visitor);
629169608Sandre  for ( ; I != E; ++I) {
630169608Sandre    if (!S.scan(*I))
631169608Sandre      return false;
632169608Sandre  }
633169608Sandre  return true;
634169608Sandre}
635169608Sandre
636169608SandreProgramStateRef ProgramState::addTaint(const Stmt *S,
637169608Sandre                                           const LocationContext *LCtx,
638169608Sandre                                           TaintTagType Kind) const {
639169608Sandre  if (const Expr *E = dyn_cast_or_null<Expr>(S))
640169608Sandre    S = E->IgnoreParens();
641169608Sandre
642169608Sandre  SymbolRef Sym = getSVal(S, LCtx).getAsSymbol();
643169608Sandre  if (Sym)
644169608Sandre    return addTaint(Sym, Kind);
645169608Sandre
646169608Sandre  const MemRegion *R = getSVal(S, LCtx).getAsRegion();
647169608Sandre  addTaint(R, Kind);
648
649  // Cannot add taint, so just return the state.
650  return this;
651}
652
653ProgramStateRef ProgramState::addTaint(const MemRegion *R,
654                                           TaintTagType Kind) const {
655  if (const SymbolicRegion *SR = dyn_cast_or_null<SymbolicRegion>(R))
656    return addTaint(SR->getSymbol(), Kind);
657  return this;
658}
659
660ProgramStateRef ProgramState::addTaint(SymbolRef Sym,
661                                           TaintTagType Kind) const {
662  // If this is a symbol cast, remove the cast before adding the taint. Taint
663  // is cast agnostic.
664  while (const SymbolCast *SC = dyn_cast<SymbolCast>(Sym))
665    Sym = SC->getOperand();
666
667  ProgramStateRef NewState = set<TaintMap>(Sym, Kind);
668  assert(NewState);
669  return NewState;
670}
671
672bool ProgramState::isTainted(const Stmt *S, const LocationContext *LCtx,
673                             TaintTagType Kind) const {
674  if (const Expr *E = dyn_cast_or_null<Expr>(S))
675    S = E->IgnoreParens();
676
677  SVal val = getSVal(S, LCtx);
678  return isTainted(val, Kind);
679}
680
681bool ProgramState::isTainted(SVal V, TaintTagType Kind) const {
682  if (const SymExpr *Sym = V.getAsSymExpr())
683    return isTainted(Sym, Kind);
684  if (const MemRegion *Reg = V.getAsRegion())
685    return isTainted(Reg, Kind);
686  return false;
687}
688
689bool ProgramState::isTainted(const MemRegion *Reg, TaintTagType K) const {
690  if (!Reg)
691    return false;
692
693  // Element region (array element) is tainted if either the base or the offset
694  // are tainted.
695  if (const ElementRegion *ER = dyn_cast<ElementRegion>(Reg))
696    return isTainted(ER->getSuperRegion(), K) || isTainted(ER->getIndex(), K);
697
698  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(Reg))
699    return isTainted(SR->getSymbol(), K);
700
701  if (const SubRegion *ER = dyn_cast<SubRegion>(Reg))
702    return isTainted(ER->getSuperRegion(), K);
703
704  return false;
705}
706
707bool ProgramState::isTainted(SymbolRef Sym, TaintTagType Kind) const {
708  if (!Sym)
709    return false;
710
711  // Traverse all the symbols this symbol depends on to see if any are tainted.
712  bool Tainted = false;
713  for (SymExpr::symbol_iterator SI = Sym->symbol_begin(), SE =Sym->symbol_end();
714       SI != SE; ++SI) {
715    if (!isa<SymbolData>(*SI))
716      continue;
717
718    const TaintTagType *Tag = get<TaintMap>(*SI);
719    Tainted = (Tag && *Tag == Kind);
720
721    // If this is a SymbolDerived with a tainted parent, it's also tainted.
722    if (const SymbolDerived *SD = dyn_cast<SymbolDerived>(*SI))
723      Tainted = Tainted || isTainted(SD->getParentSymbol(), Kind);
724
725    // If memory region is tainted, data is also tainted.
726    if (const SymbolRegionValue *SRV = dyn_cast<SymbolRegionValue>(*SI))
727      Tainted = Tainted || isTainted(SRV->getRegion(), Kind);
728
729    // If If this is a SymbolCast from a tainted value, it's also tainted.
730    if (const SymbolCast *SC = dyn_cast<SymbolCast>(*SI))
731      Tainted = Tainted || isTainted(SC->getOperand(), Kind);
732
733    if (Tainted)
734      return true;
735  }
736
737  return Tainted;
738}
739
740