ProgramState.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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. #include "clang/Analysis/CFG.h"
  14. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  15. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  16. #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
  17. #include "clang/StaticAnalyzer/Core/PathSensitive/TaintManager.h"
  18. #include "llvm/Support/raw_ostream.h"
  19. using namespace clang;
  20. using namespace ento;
  21. // Give the vtable for ConstraintManager somewhere to live.
  22. // FIXME: Move this elsewhere.
  23. ConstraintManager::~ConstraintManager() {}
  24. namespace clang { namespace ento {
  25. /// Increments the number of times this state is referenced.
  26. void ProgramStateRetain(const ProgramState *state) {
  27. ++const_cast<ProgramState*>(state)->refCount;
  28. }
  29. /// Decrement the number of times this state is referenced.
  30. void ProgramStateRelease(const ProgramState *state) {
  31. assert(state->refCount > 0);
  32. ProgramState *s = const_cast<ProgramState*>(state);
  33. if (--s->refCount == 0) {
  34. ProgramStateManager &Mgr = s->getStateManager();
  35. Mgr.StateSet.RemoveNode(s);
  36. s->~ProgramState();
  37. Mgr.freeStates.push_back(s);
  38. }
  39. }
  40. }}
  41. ProgramState::ProgramState(ProgramStateManager *mgr, const Environment& env,
  42. StoreRef st, GenericDataMap gdm)
  43. : stateMgr(mgr),
  44. Env(env),
  45. store(st.getStore()),
  46. GDM(gdm),
  47. refCount(0) {
  48. stateMgr->getStoreManager().incrementReferenceCount(store);
  49. }
  50. ProgramState::ProgramState(const ProgramState &RHS)
  51. : llvm::FoldingSetNode(),
  52. stateMgr(RHS.stateMgr),
  53. Env(RHS.Env),
  54. store(RHS.store),
  55. GDM(RHS.GDM),
  56. refCount(0) {
  57. stateMgr->getStoreManager().incrementReferenceCount(store);
  58. }
  59. ProgramState::~ProgramState() {
  60. if (store)
  61. stateMgr->getStoreManager().decrementReferenceCount(store);
  62. }
  63. ProgramStateManager::~ProgramStateManager() {
  64. for (GDMContextsTy::iterator I=GDMContexts.begin(), E=GDMContexts.end();
  65. I!=E; ++I)
  66. I->second.second(I->second.first);
  67. }
  68. ProgramStateRef
  69. ProgramStateManager::removeDeadBindings(ProgramStateRef state,
  70. const StackFrameContext *LCtx,
  71. SymbolReaper& SymReaper) {
  72. // This code essentially performs a "mark-and-sweep" of the VariableBindings.
  73. // The roots are any Block-level exprs and Decls that our liveness algorithm
  74. // tells us are live. We then see what Decls they may reference, and keep
  75. // those around. This code more than likely can be made faster, and the
  76. // frequency of which this method is called should be experimented with
  77. // for optimum performance.
  78. ProgramState NewState = *state;
  79. NewState.Env = EnvMgr.removeDeadBindings(NewState.Env, SymReaper, state);
  80. // Clean up the store.
  81. StoreRef newStore = StoreMgr->removeDeadBindings(NewState.getStore(), LCtx,
  82. SymReaper);
  83. NewState.setStore(newStore);
  84. SymReaper.setReapedStore(newStore);
  85. return getPersistentState(NewState);
  86. }
  87. ProgramStateRef ProgramStateManager::MarshalState(ProgramStateRef state,
  88. const StackFrameContext *InitLoc) {
  89. // make up an empty state for now.
  90. ProgramState State(this,
  91. EnvMgr.getInitialEnvironment(),
  92. StoreMgr->getInitialStore(InitLoc),
  93. GDMFactory.getEmptyMap());
  94. return getPersistentState(State);
  95. }
  96. ProgramStateRef ProgramState::bindCompoundLiteral(const CompoundLiteralExpr *CL,
  97. const LocationContext *LC,
  98. SVal V) const {
  99. const StoreRef &newStore =
  100. getStateManager().StoreMgr->BindCompoundLiteral(getStore(), CL, LC, V);
  101. return makeWithStore(newStore);
  102. }
  103. ProgramStateRef ProgramState::bindDecl(const VarRegion* VR, SVal IVal) const {
  104. const StoreRef &newStore =
  105. getStateManager().StoreMgr->BindDecl(getStore(), VR, IVal);
  106. return makeWithStore(newStore);
  107. }
  108. ProgramStateRef ProgramState::bindDeclWithNoInit(const VarRegion* VR) const {
  109. const StoreRef &newStore =
  110. getStateManager().StoreMgr->BindDeclWithNoInit(getStore(), VR);
  111. return makeWithStore(newStore);
  112. }
  113. ProgramStateRef ProgramState::bindLoc(Loc LV, SVal V) const {
  114. ProgramStateManager &Mgr = getStateManager();
  115. ProgramStateRef newState = makeWithStore(Mgr.StoreMgr->Bind(getStore(),
  116. LV, V));
  117. const MemRegion *MR = LV.getAsRegion();
  118. if (MR && Mgr.getOwningEngine())
  119. return Mgr.getOwningEngine()->processRegionChange(newState, MR);
  120. return newState;
  121. }
  122. ProgramStateRef ProgramState::bindDefault(SVal loc, SVal V) const {
  123. ProgramStateManager &Mgr = getStateManager();
  124. const MemRegion *R = cast<loc::MemRegionVal>(loc).getRegion();
  125. const StoreRef &newStore = Mgr.StoreMgr->BindDefault(getStore(), R, V);
  126. ProgramStateRef new_state = makeWithStore(newStore);
  127. return Mgr.getOwningEngine() ?
  128. Mgr.getOwningEngine()->processRegionChange(new_state, R) :
  129. new_state;
  130. }
  131. ProgramStateRef
  132. ProgramState::invalidateRegions(ArrayRef<const MemRegion *> Regions,
  133. const Expr *E, unsigned Count,
  134. StoreManager::InvalidatedSymbols *IS,
  135. const CallOrObjCMessage *Call) const {
  136. if (!IS) {
  137. StoreManager::InvalidatedSymbols invalidated;
  138. return invalidateRegionsImpl(Regions, E, Count,
  139. invalidated, Call);
  140. }
  141. return invalidateRegionsImpl(Regions, E, Count, *IS, Call);
  142. }
  143. ProgramStateRef
  144. ProgramState::invalidateRegionsImpl(ArrayRef<const MemRegion *> Regions,
  145. const Expr *E, unsigned Count,
  146. StoreManager::InvalidatedSymbols &IS,
  147. const CallOrObjCMessage *Call) const {
  148. ProgramStateManager &Mgr = getStateManager();
  149. SubEngine* Eng = Mgr.getOwningEngine();
  150. if (Eng && Eng->wantsRegionChangeUpdate(this)) {
  151. StoreManager::InvalidatedRegions Invalidated;
  152. const StoreRef &newStore
  153. = Mgr.StoreMgr->invalidateRegions(getStore(), Regions, E, Count, IS,
  154. Call, &Invalidated);
  155. ProgramStateRef newState = makeWithStore(newStore);
  156. return Eng->processRegionChanges(newState, &IS, Regions, Invalidated);
  157. }
  158. const StoreRef &newStore =
  159. Mgr.StoreMgr->invalidateRegions(getStore(), Regions, E, Count, IS,
  160. Call, NULL);
  161. return makeWithStore(newStore);
  162. }
  163. ProgramStateRef ProgramState::unbindLoc(Loc LV) const {
  164. assert(!isa<loc::MemRegionVal>(LV) && "Use invalidateRegion instead.");
  165. Store OldStore = getStore();
  166. const StoreRef &newStore = getStateManager().StoreMgr->Remove(OldStore, LV);
  167. if (newStore.getStore() == OldStore)
  168. return this;
  169. return makeWithStore(newStore);
  170. }
  171. ProgramStateRef
  172. ProgramState::enterStackFrame(const LocationContext *callerCtx,
  173. const StackFrameContext *calleeCtx) const {
  174. const StoreRef &new_store =
  175. getStateManager().StoreMgr->enterStackFrame(this, callerCtx, calleeCtx);
  176. return makeWithStore(new_store);
  177. }
  178. SVal ProgramState::getSValAsScalarOrLoc(const MemRegion *R) const {
  179. // We only want to do fetches from regions that we can actually bind
  180. // values. For example, SymbolicRegions of type 'id<...>' cannot
  181. // have direct bindings (but their can be bindings on their subregions).
  182. if (!R->isBoundable())
  183. return UnknownVal();
  184. if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
  185. QualType T = TR->getValueType();
  186. if (Loc::isLocType(T) || T->isIntegerType())
  187. return getSVal(R);
  188. }
  189. return UnknownVal();
  190. }
  191. SVal ProgramState::getSVal(Loc location, QualType T) const {
  192. SVal V = getRawSVal(cast<Loc>(location), T);
  193. // If 'V' is a symbolic value that is *perfectly* constrained to
  194. // be a constant value, use that value instead to lessen the burden
  195. // on later analysis stages (so we have less symbolic values to reason
  196. // about).
  197. if (!T.isNull()) {
  198. if (SymbolRef sym = V.getAsSymbol()) {
  199. if (const llvm::APSInt *Int = getSymVal(sym)) {
  200. // FIXME: Because we don't correctly model (yet) sign-extension
  201. // and truncation of symbolic values, we need to convert
  202. // the integer value to the correct signedness and bitwidth.
  203. //
  204. // This shows up in the following:
  205. //
  206. // char foo();
  207. // unsigned x = foo();
  208. // if (x == 54)
  209. // ...
  210. //
  211. // The symbolic value stored to 'x' is actually the conjured
  212. // symbol for the call to foo(); the type of that symbol is 'char',
  213. // not unsigned.
  214. const llvm::APSInt &NewV = getBasicVals().Convert(T, *Int);
  215. if (isa<Loc>(V))
  216. return loc::ConcreteInt(NewV);
  217. else
  218. return nonloc::ConcreteInt(NewV);
  219. }
  220. }
  221. }
  222. return V;
  223. }
  224. ProgramStateRef ProgramState::BindExpr(const Stmt *S,
  225. const LocationContext *LCtx,
  226. SVal V, bool Invalidate) const{
  227. Environment NewEnv =
  228. getStateManager().EnvMgr.bindExpr(Env, EnvironmentEntry(S, LCtx), V,
  229. Invalidate);
  230. if (NewEnv == Env)
  231. return this;
  232. ProgramState NewSt = *this;
  233. NewSt.Env = NewEnv;
  234. return getStateManager().getPersistentState(NewSt);
  235. }
  236. ProgramStateRef
  237. ProgramState::bindExprAndLocation(const Stmt *S, const LocationContext *LCtx,
  238. SVal location,
  239. SVal V) const {
  240. Environment NewEnv =
  241. getStateManager().EnvMgr.bindExprAndLocation(Env,
  242. EnvironmentEntry(S, LCtx),
  243. location, V);
  244. if (NewEnv == Env)
  245. return this;
  246. ProgramState NewSt = *this;
  247. NewSt.Env = NewEnv;
  248. return getStateManager().getPersistentState(NewSt);
  249. }
  250. ProgramStateRef ProgramState::assumeInBound(DefinedOrUnknownSVal Idx,
  251. DefinedOrUnknownSVal UpperBound,
  252. bool Assumption,
  253. QualType indexTy) const {
  254. if (Idx.isUnknown() || UpperBound.isUnknown())
  255. return this;
  256. // Build an expression for 0 <= Idx < UpperBound.
  257. // This is the same as Idx + MIN < UpperBound + MIN, if overflow is allowed.
  258. // FIXME: This should probably be part of SValBuilder.
  259. ProgramStateManager &SM = getStateManager();
  260. SValBuilder &svalBuilder = SM.getSValBuilder();
  261. ASTContext &Ctx = svalBuilder.getContext();
  262. // Get the offset: the minimum value of the array index type.
  263. BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
  264. // FIXME: This should be using ValueManager::ArrayindexTy...somehow.
  265. if (indexTy.isNull())
  266. indexTy = Ctx.IntTy;
  267. nonloc::ConcreteInt Min(BVF.getMinValue(indexTy));
  268. // Adjust the index.
  269. SVal newIdx = svalBuilder.evalBinOpNN(this, BO_Add,
  270. cast<NonLoc>(Idx), Min, indexTy);
  271. if (newIdx.isUnknownOrUndef())
  272. return this;
  273. // Adjust the upper bound.
  274. SVal newBound =
  275. svalBuilder.evalBinOpNN(this, BO_Add, cast<NonLoc>(UpperBound),
  276. Min, indexTy);
  277. if (newBound.isUnknownOrUndef())
  278. return this;
  279. // Build the actual comparison.
  280. SVal inBound = svalBuilder.evalBinOpNN(this, BO_LT,
  281. cast<NonLoc>(newIdx), cast<NonLoc>(newBound),
  282. Ctx.IntTy);
  283. if (inBound.isUnknownOrUndef())
  284. return this;
  285. // Finally, let the constraint manager take care of it.
  286. ConstraintManager &CM = SM.getConstraintManager();
  287. return CM.assume(this, cast<DefinedSVal>(inBound), Assumption);
  288. }
  289. ProgramStateRef ProgramStateManager::getInitialState(const LocationContext *InitLoc) {
  290. ProgramState State(this,
  291. EnvMgr.getInitialEnvironment(),
  292. StoreMgr->getInitialStore(InitLoc),
  293. GDMFactory.getEmptyMap());
  294. return getPersistentState(State);
  295. }
  296. ProgramStateRef ProgramStateManager::getPersistentStateWithGDM(
  297. ProgramStateRef FromState,
  298. ProgramStateRef GDMState) {
  299. ProgramState NewState(*FromState);
  300. NewState.GDM = GDMState->GDM;
  301. return getPersistentState(NewState);
  302. }
  303. ProgramStateRef ProgramStateManager::getPersistentState(ProgramState &State) {
  304. llvm::FoldingSetNodeID ID;
  305. State.Profile(ID);
  306. void *InsertPos;
  307. if (ProgramState *I = StateSet.FindNodeOrInsertPos(ID, InsertPos))
  308. return I;
  309. ProgramState *newState = 0;
  310. if (!freeStates.empty()) {
  311. newState = freeStates.back();
  312. freeStates.pop_back();
  313. }
  314. else {
  315. newState = (ProgramState*) Alloc.Allocate<ProgramState>();
  316. }
  317. new (newState) ProgramState(State);
  318. StateSet.InsertNode(newState, InsertPos);
  319. return newState;
  320. }
  321. ProgramStateRef ProgramState::makeWithStore(const StoreRef &store) const {
  322. ProgramState NewSt(*this);
  323. NewSt.setStore(store);
  324. return getStateManager().getPersistentState(NewSt);
  325. }
  326. void ProgramState::setStore(const StoreRef &newStore) {
  327. Store newStoreStore = newStore.getStore();
  328. if (newStoreStore)
  329. stateMgr->getStoreManager().incrementReferenceCount(newStoreStore);
  330. if (store)
  331. stateMgr->getStoreManager().decrementReferenceCount(store);
  332. store = newStoreStore;
  333. }
  334. //===----------------------------------------------------------------------===//
  335. // State pretty-printing.
  336. //===----------------------------------------------------------------------===//
  337. void ProgramState::print(raw_ostream &Out,
  338. const char *NL, const char *Sep) const {
  339. // Print the store.
  340. ProgramStateManager &Mgr = getStateManager();
  341. Mgr.getStoreManager().print(getStore(), Out, NL, Sep);
  342. // Print out the environment.
  343. Env.print(Out, NL, Sep);
  344. // Print out the constraints.
  345. Mgr.getConstraintManager().print(this, Out, NL, Sep);
  346. // Print checker-specific data.
  347. Mgr.getOwningEngine()->printState(Out, this, NL, Sep);
  348. }
  349. void ProgramState::printDOT(raw_ostream &Out) const {
  350. print(Out, "\\l", "\\|");
  351. }
  352. void ProgramState::dump() const {
  353. print(llvm::errs());
  354. }
  355. void ProgramState::printTaint(raw_ostream &Out,
  356. const char *NL, const char *Sep) const {
  357. TaintMapImpl TM = get<TaintMap>();
  358. if (!TM.isEmpty())
  359. Out <<"Tainted Symbols:" << NL;
  360. for (TaintMapImpl::iterator I = TM.begin(), E = TM.end(); I != E; ++I) {
  361. Out << I->first << " : " << I->second << NL;
  362. }
  363. }
  364. void ProgramState::dumpTaint() const {
  365. printTaint(llvm::errs());
  366. }
  367. //===----------------------------------------------------------------------===//
  368. // Generic Data Map.
  369. //===----------------------------------------------------------------------===//
  370. void *const* ProgramState::FindGDM(void *K) const {
  371. return GDM.lookup(K);
  372. }
  373. void*
  374. ProgramStateManager::FindGDMContext(void *K,
  375. void *(*CreateContext)(llvm::BumpPtrAllocator&),
  376. void (*DeleteContext)(void*)) {
  377. std::pair<void*, void (*)(void*)>& p = GDMContexts[K];
  378. if (!p.first) {
  379. p.first = CreateContext(Alloc);
  380. p.second = DeleteContext;
  381. }
  382. return p.first;
  383. }
  384. ProgramStateRef ProgramStateManager::addGDM(ProgramStateRef St, void *Key, void *Data){
  385. ProgramState::GenericDataMap M1 = St->getGDM();
  386. ProgramState::GenericDataMap M2 = GDMFactory.add(M1, Key, Data);
  387. if (M1 == M2)
  388. return St;
  389. ProgramState NewSt = *St;
  390. NewSt.GDM = M2;
  391. return getPersistentState(NewSt);
  392. }
  393. ProgramStateRef ProgramStateManager::removeGDM(ProgramStateRef state, void *Key) {
  394. ProgramState::GenericDataMap OldM = state->getGDM();
  395. ProgramState::GenericDataMap NewM = GDMFactory.remove(OldM, Key);
  396. if (NewM == OldM)
  397. return state;
  398. ProgramState NewState = *state;
  399. NewState.GDM = NewM;
  400. return getPersistentState(NewState);
  401. }
  402. void ScanReachableSymbols::anchor() { }
  403. bool ScanReachableSymbols::scan(nonloc::CompoundVal val) {
  404. for (nonloc::CompoundVal::iterator I=val.begin(), E=val.end(); I!=E; ++I)
  405. if (!scan(*I))
  406. return false;
  407. return true;
  408. }
  409. bool ScanReachableSymbols::scan(const SymExpr *sym) {
  410. unsigned &isVisited = visited[sym];
  411. if (isVisited)
  412. return true;
  413. isVisited = 1;
  414. if (!visitor.VisitSymbol(sym))
  415. return false;
  416. // TODO: should be rewritten using SymExpr::symbol_iterator.
  417. switch (sym->getKind()) {
  418. case SymExpr::RegionValueKind:
  419. case SymExpr::ConjuredKind:
  420. case SymExpr::DerivedKind:
  421. case SymExpr::ExtentKind:
  422. case SymExpr::MetadataKind:
  423. break;
  424. case SymExpr::CastSymbolKind:
  425. return scan(cast<SymbolCast>(sym)->getOperand());
  426. case SymExpr::SymIntKind:
  427. return scan(cast<SymIntExpr>(sym)->getLHS());
  428. case SymExpr::IntSymKind:
  429. return scan(cast<IntSymExpr>(sym)->getRHS());
  430. case SymExpr::SymSymKind: {
  431. const SymSymExpr *x = cast<SymSymExpr>(sym);
  432. return scan(x->getLHS()) && scan(x->getRHS());
  433. }
  434. }
  435. return true;
  436. }
  437. bool ScanReachableSymbols::scan(SVal val) {
  438. if (loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&val))
  439. return scan(X->getRegion());
  440. if (nonloc::LocAsInteger *X = dyn_cast<nonloc::LocAsInteger>(&val))
  441. return scan(X->getLoc());
  442. if (SymbolRef Sym = val.getAsSymbol())
  443. return scan(Sym);
  444. if (const SymExpr *Sym = val.getAsSymbolicExpression())
  445. return scan(Sym);
  446. if (nonloc::CompoundVal *X = dyn_cast<nonloc::CompoundVal>(&val))
  447. return scan(*X);
  448. return true;
  449. }
  450. bool ScanReachableSymbols::scan(const MemRegion *R) {
  451. if (isa<MemSpaceRegion>(R))
  452. return true;
  453. unsigned &isVisited = visited[R];
  454. if (isVisited)
  455. return true;
  456. isVisited = 1;
  457. // If this is a symbolic region, visit the symbol for the region.
  458. if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
  459. if (!visitor.VisitSymbol(SR->getSymbol()))
  460. return false;
  461. // If this is a subregion, also visit the parent regions.
  462. if (const SubRegion *SR = dyn_cast<SubRegion>(R))
  463. if (!scan(SR->getSuperRegion()))
  464. return false;
  465. // Now look at the binding to this region (if any).
  466. if (!scan(state->getSValAsScalarOrLoc(R)))
  467. return false;
  468. // Now look at the subregions.
  469. if (!SRM.get())
  470. SRM.reset(state->getStateManager().getStoreManager().
  471. getSubRegionMap(state->getStore()));
  472. return SRM->iterSubRegions(R, *this);
  473. }
  474. bool ProgramState::scanReachableSymbols(SVal val, SymbolVisitor& visitor) const {
  475. ScanReachableSymbols S(this, visitor);
  476. return S.scan(val);
  477. }
  478. bool ProgramState::scanReachableSymbols(const SVal *I, const SVal *E,
  479. SymbolVisitor &visitor) const {
  480. ScanReachableSymbols S(this, visitor);
  481. for ( ; I != E; ++I) {
  482. if (!S.scan(*I))
  483. return false;
  484. }
  485. return true;
  486. }
  487. bool ProgramState::scanReachableSymbols(const MemRegion * const *I,
  488. const MemRegion * const *E,
  489. SymbolVisitor &visitor) const {
  490. ScanReachableSymbols S(this, visitor);
  491. for ( ; I != E; ++I) {
  492. if (!S.scan(*I))
  493. return false;
  494. }
  495. return true;
  496. }
  497. ProgramStateRef ProgramState::addTaint(const Stmt *S,
  498. const LocationContext *LCtx,
  499. TaintTagType Kind) const {
  500. if (const Expr *E = dyn_cast_or_null<Expr>(S))
  501. S = E->IgnoreParens();
  502. SymbolRef Sym = getSVal(S, LCtx).getAsSymbol();
  503. if (Sym)
  504. return addTaint(Sym, Kind);
  505. const MemRegion *R = getSVal(S, LCtx).getAsRegion();
  506. addTaint(R, Kind);
  507. // Cannot add taint, so just return the state.
  508. return this;
  509. }
  510. ProgramStateRef ProgramState::addTaint(const MemRegion *R,
  511. TaintTagType Kind) const {
  512. if (const SymbolicRegion *SR = dyn_cast_or_null<SymbolicRegion>(R))
  513. return addTaint(SR->getSymbol(), Kind);
  514. return this;
  515. }
  516. ProgramStateRef ProgramState::addTaint(SymbolRef Sym,
  517. TaintTagType Kind) const {
  518. // If this is a symbol cast, remove the cast before adding the taint. Taint
  519. // is cast agnostic.
  520. while (const SymbolCast *SC = dyn_cast<SymbolCast>(Sym))
  521. Sym = SC->getOperand();
  522. ProgramStateRef NewState = set<TaintMap>(Sym, Kind);
  523. assert(NewState);
  524. return NewState;
  525. }
  526. bool ProgramState::isTainted(const Stmt *S, const LocationContext *LCtx,
  527. TaintTagType Kind) const {
  528. if (const Expr *E = dyn_cast_or_null<Expr>(S))
  529. S = E->IgnoreParens();
  530. SVal val = getSVal(S, LCtx);
  531. return isTainted(val, Kind);
  532. }
  533. bool ProgramState::isTainted(SVal V, TaintTagType Kind) const {
  534. if (const SymExpr *Sym = V.getAsSymExpr())
  535. return isTainted(Sym, Kind);
  536. if (const MemRegion *Reg = V.getAsRegion())
  537. return isTainted(Reg, Kind);
  538. return false;
  539. }
  540. bool ProgramState::isTainted(const MemRegion *Reg, TaintTagType K) const {
  541. if (!Reg)
  542. return false;
  543. // Element region (array element) is tainted if either the base or the offset
  544. // are tainted.
  545. if (const ElementRegion *ER = dyn_cast<ElementRegion>(Reg))
  546. return isTainted(ER->getSuperRegion(), K) || isTainted(ER->getIndex(), K);
  547. if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(Reg))
  548. return isTainted(SR->getSymbol(), K);
  549. if (const SubRegion *ER = dyn_cast<SubRegion>(Reg))
  550. return isTainted(ER->getSuperRegion(), K);
  551. return false;
  552. }
  553. bool ProgramState::isTainted(SymbolRef Sym, TaintTagType Kind) const {
  554. if (!Sym)
  555. return false;
  556. // Traverse all the symbols this symbol depends on to see if any are tainted.
  557. bool Tainted = false;
  558. for (SymExpr::symbol_iterator SI = Sym->symbol_begin(), SE =Sym->symbol_end();
  559. SI != SE; ++SI) {
  560. assert(isa<SymbolData>(*SI));
  561. const TaintTagType *Tag = get<TaintMap>(*SI);
  562. Tainted = (Tag && *Tag == Kind);
  563. // If this is a SymbolDerived with a tainted parent, it's also tainted.
  564. if (const SymbolDerived *SD = dyn_cast<SymbolDerived>(*SI))
  565. Tainted = Tainted || isTainted(SD->getParentSymbol(), Kind);
  566. // If memory region is tainted, data is also tainted.
  567. if (const SymbolRegionValue *SRV = dyn_cast<SymbolRegionValue>(*SI))
  568. Tainted = Tainted || isTainted(SRV->getRegion(), Kind);
  569. // If If this is a SymbolCast from a tainted value, it's also tainted.
  570. if (const SymbolCast *SC = dyn_cast<SymbolCast>(*SI))
  571. Tainted = Tainted || isTainted(SC->getOperand(), Kind);
  572. if (Tainted)
  573. return true;
  574. }
  575. return Tainted;
  576. }