ProgramState.cpp 22 KB

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