ProgramState.cpp 25 KB

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