ProgramState.cpp 27 KB

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