ProgramState.cpp 24 KB

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