ProgramState.cpp 25 KB

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