ProgramState.cpp 28 KB

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