ProgramState.cpp 26 KB

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