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/AnalysisManager.h"
  14. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  15. #include "clang/Analysis/CFG.h"
  16. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  17. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  18. #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/TaintManager.h"
  20. #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h"
  21. #include "llvm/Support/raw_ostream.h"
  22. using namespace clang;
  23. using namespace ento;
  24. namespace clang { namespace ento {
  25. /// Increments the number of times this state is referenced.
  26. void ProgramStateRetain(const ProgramState *state) {
  27. ++const_cast<ProgramState*>(state)->refCount;
  28. }
  29. /// Decrement the number of times this state is referenced.
  30. void ProgramStateRelease(const ProgramState *state) {
  31. assert(state->refCount > 0);
  32. ProgramState *s = const_cast<ProgramState*>(state);
  33. if (--s->refCount == 0) {
  34. ProgramStateManager &Mgr = s->getStateManager();
  35. Mgr.StateSet.RemoveNode(s);
  36. s->~ProgramState();
  37. Mgr.freeStates.push_back(s);
  38. }
  39. }
  40. }}
  41. ProgramState::ProgramState(ProgramStateManager *mgr, const Environment& env,
  42. StoreRef st, GenericDataMap gdm)
  43. : stateMgr(mgr),
  44. Env(env),
  45. store(st.getStore()),
  46. GDM(gdm),
  47. refCount(0) {
  48. stateMgr->getStoreManager().incrementReferenceCount(store);
  49. }
  50. ProgramState::ProgramState(const ProgramState &RHS)
  51. : llvm::FoldingSetNode(),
  52. stateMgr(RHS.stateMgr),
  53. Env(RHS.Env),
  54. store(RHS.store),
  55. GDM(RHS.GDM),
  56. refCount(0) {
  57. stateMgr->getStoreManager().incrementReferenceCount(store);
  58. }
  59. ProgramState::~ProgramState() {
  60. if (store)
  61. stateMgr->getStoreManager().decrementReferenceCount(store);
  62. }
  63. int64_t ProgramState::getID() const {
  64. return getStateManager().Alloc.identifyKnownAlignedObject<ProgramState>(this);
  65. }
  66. ProgramStateManager::ProgramStateManager(ASTContext &Ctx,
  67. StoreManagerCreator CreateSMgr,
  68. ConstraintManagerCreator CreateCMgr,
  69. llvm::BumpPtrAllocator &alloc,
  70. SubEngine *SubEng)
  71. : Eng(SubEng), EnvMgr(alloc), GDMFactory(alloc),
  72. svalBuilder(createSimpleSValBuilder(alloc, Ctx, *this)),
  73. CallEventMgr(new CallEventManager(alloc)), Alloc(alloc) {
  74. StoreMgr = (*CreateSMgr)(*this);
  75. ConstraintMgr = (*CreateCMgr)(*this, SubEng);
  76. }
  77. ProgramStateManager::~ProgramStateManager() {
  78. for (GDMContextsTy::iterator I=GDMContexts.begin(), E=GDMContexts.end();
  79. I!=E; ++I)
  80. I->second.second(I->second.first);
  81. }
  82. ProgramStateRef
  83. ProgramStateManager::removeDeadBindings(ProgramStateRef state,
  84. const StackFrameContext *LCtx,
  85. SymbolReaper& SymReaper) {
  86. // This code essentially performs a "mark-and-sweep" of the VariableBindings.
  87. // The roots are any Block-level exprs and Decls that our liveness algorithm
  88. // tells us are live. We then see what Decls they may reference, and keep
  89. // those around. This code more than likely can be made faster, and the
  90. // frequency of which this method is called should be experimented with
  91. // for optimum performance.
  92. ProgramState NewState = *state;
  93. NewState.Env = EnvMgr.removeDeadBindings(NewState.Env, SymReaper, state);
  94. // Clean up the store.
  95. StoreRef newStore = StoreMgr->removeDeadBindings(NewState.getStore(), LCtx,
  96. SymReaper);
  97. NewState.setStore(newStore);
  98. SymReaper.setReapedStore(newStore);
  99. ProgramStateRef Result = getPersistentState(NewState);
  100. return ConstraintMgr->removeDeadBindings(Result, SymReaper);
  101. }
  102. ProgramStateRef ProgramState::bindLoc(Loc LV,
  103. SVal V,
  104. const LocationContext *LCtx,
  105. bool notifyChanges) const {
  106. ProgramStateManager &Mgr = getStateManager();
  107. ProgramStateRef newState = makeWithStore(Mgr.StoreMgr->Bind(getStore(),
  108. LV, V));
  109. const MemRegion *MR = LV.getAsRegion();
  110. if (MR && notifyChanges)
  111. return Mgr.getOwningEngine().processRegionChange(newState, MR, LCtx);
  112. return newState;
  113. }
  114. ProgramStateRef
  115. ProgramState::bindDefaultInitial(SVal loc, SVal V,
  116. const LocationContext *LCtx) const {
  117. ProgramStateManager &Mgr = getStateManager();
  118. const MemRegion *R = loc.castAs<loc::MemRegionVal>().getRegion();
  119. const StoreRef &newStore = Mgr.StoreMgr->BindDefaultInitial(getStore(), R, V);
  120. ProgramStateRef new_state = makeWithStore(newStore);
  121. return Mgr.getOwningEngine().processRegionChange(new_state, R, LCtx);
  122. }
  123. ProgramStateRef
  124. ProgramState::bindDefaultZero(SVal loc, const LocationContext *LCtx) const {
  125. ProgramStateManager &Mgr = getStateManager();
  126. const MemRegion *R = loc.castAs<loc::MemRegionVal>().getRegion();
  127. const StoreRef &newStore = Mgr.StoreMgr->BindDefaultZero(getStore(), R);
  128. ProgramStateRef new_state = makeWithStore(newStore);
  129. return Mgr.getOwningEngine().processRegionChange(new_state, R, LCtx);
  130. }
  131. typedef ArrayRef<const MemRegion *> RegionList;
  132. typedef ArrayRef<SVal> ValueList;
  133. ProgramStateRef
  134. ProgramState::invalidateRegions(RegionList Regions,
  135. const Expr *E, unsigned Count,
  136. const LocationContext *LCtx,
  137. bool CausedByPointerEscape,
  138. InvalidatedSymbols *IS,
  139. const CallEvent *Call,
  140. RegionAndSymbolInvalidationTraits *ITraits) const {
  141. SmallVector<SVal, 8> Values;
  142. for (RegionList::const_iterator I = Regions.begin(),
  143. End = Regions.end(); I != End; ++I)
  144. Values.push_back(loc::MemRegionVal(*I));
  145. return invalidateRegionsImpl(Values, E, Count, LCtx, CausedByPointerEscape,
  146. IS, ITraits, Call);
  147. }
  148. ProgramStateRef
  149. ProgramState::invalidateRegions(ValueList Values,
  150. const Expr *E, unsigned Count,
  151. const LocationContext *LCtx,
  152. bool CausedByPointerEscape,
  153. InvalidatedSymbols *IS,
  154. const CallEvent *Call,
  155. RegionAndSymbolInvalidationTraits *ITraits) const {
  156. return invalidateRegionsImpl(Values, E, Count, LCtx, CausedByPointerEscape,
  157. IS, ITraits, Call);
  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. RegionAndSymbolInvalidationTraits *ITraits,
  166. const CallEvent *Call) const {
  167. ProgramStateManager &Mgr = getStateManager();
  168. SubEngine &Eng = Mgr.getOwningEngine();
  169. InvalidatedSymbols InvalidatedSyms;
  170. if (!IS)
  171. IS = &InvalidatedSyms;
  172. RegionAndSymbolInvalidationTraits ITraitsLocal;
  173. if (!ITraits)
  174. ITraits = &ITraitsLocal;
  175. StoreManager::InvalidatedRegions TopLevelInvalidated;
  176. StoreManager::InvalidatedRegions Invalidated;
  177. const StoreRef &newStore
  178. = Mgr.StoreMgr->invalidateRegions(getStore(), Values, E, Count, LCtx, Call,
  179. *IS, *ITraits, &TopLevelInvalidated,
  180. &Invalidated);
  181. ProgramStateRef newState = makeWithStore(newStore);
  182. if (CausedByPointerEscape) {
  183. newState = Eng.notifyCheckersOfPointerEscape(newState, IS,
  184. TopLevelInvalidated,
  185. Call,
  186. *ITraits);
  187. }
  188. return Eng.processRegionChanges(newState, IS, TopLevelInvalidated,
  189. Invalidated, LCtx, Call);
  190. }
  191. ProgramStateRef ProgramState::killBinding(Loc LV) const {
  192. assert(!LV.getAs<loc::MemRegionVal>() && "Use invalidateRegion instead.");
  193. Store OldStore = getStore();
  194. const StoreRef &newStore =
  195. getStateManager().StoreMgr->killBinding(OldStore, LV);
  196. if (newStore.getStore() == OldStore)
  197. return this;
  198. return makeWithStore(newStore);
  199. }
  200. ProgramStateRef
  201. ProgramState::enterStackFrame(const CallEvent &Call,
  202. const StackFrameContext *CalleeCtx) const {
  203. const StoreRef &NewStore =
  204. getStateManager().StoreMgr->enterStackFrame(getStore(), Call, CalleeCtx);
  205. return makeWithStore(NewStore);
  206. }
  207. SVal ProgramState::getSValAsScalarOrLoc(const MemRegion *R) const {
  208. // We only want to do fetches from regions that we can actually bind
  209. // values. For example, SymbolicRegions of type 'id<...>' cannot
  210. // have direct bindings (but their can be bindings on their subregions).
  211. if (!R->isBoundable())
  212. return UnknownVal();
  213. if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
  214. QualType T = TR->getValueType();
  215. if (Loc::isLocType(T) || T->isIntegralOrEnumerationType())
  216. return getSVal(R);
  217. }
  218. return UnknownVal();
  219. }
  220. SVal ProgramState::getSVal(Loc location, QualType T) const {
  221. SVal V = getRawSVal(location, T);
  222. // If 'V' is a symbolic value that is *perfectly* constrained to
  223. // be a constant value, use that value instead to lessen the burden
  224. // on later analysis stages (so we have less symbolic values to reason
  225. // about).
  226. // We only go into this branch if we can convert the APSInt value we have
  227. // to the type of T, which is not always the case (e.g. for void).
  228. if (!T.isNull() && (T->isIntegralOrEnumerationType() || Loc::isLocType(T))) {
  229. if (SymbolRef sym = V.getAsSymbol()) {
  230. if (const llvm::APSInt *Int = getStateManager()
  231. .getConstraintManager()
  232. .getSymVal(this, sym)) {
  233. // FIXME: Because we don't correctly model (yet) sign-extension
  234. // and truncation of symbolic values, we need to convert
  235. // the integer value to the correct signedness and bitwidth.
  236. //
  237. // This shows up in the following:
  238. //
  239. // char foo();
  240. // unsigned x = foo();
  241. // if (x == 54)
  242. // ...
  243. //
  244. // The symbolic value stored to 'x' is actually the conjured
  245. // symbol for the call to foo(); the type of that symbol is 'char',
  246. // not unsigned.
  247. const llvm::APSInt &NewV = getBasicVals().Convert(T, *Int);
  248. if (V.getAs<Loc>())
  249. return loc::ConcreteInt(NewV);
  250. else
  251. return nonloc::ConcreteInt(NewV);
  252. }
  253. }
  254. }
  255. return V;
  256. }
  257. ProgramStateRef ProgramState::BindExpr(const Stmt *S,
  258. const LocationContext *LCtx,
  259. SVal V, bool Invalidate) const{
  260. Environment NewEnv =
  261. getStateManager().EnvMgr.bindExpr(Env, EnvironmentEntry(S, LCtx), V,
  262. Invalidate);
  263. if (NewEnv == Env)
  264. return this;
  265. ProgramState NewSt = *this;
  266. NewSt.Env = NewEnv;
  267. return getStateManager().getPersistentState(NewSt);
  268. }
  269. ProgramStateRef ProgramState::assumeInBound(DefinedOrUnknownSVal Idx,
  270. DefinedOrUnknownSVal UpperBound,
  271. bool Assumption,
  272. QualType indexTy) const {
  273. if (Idx.isUnknown() || UpperBound.isUnknown())
  274. return this;
  275. // Build an expression for 0 <= Idx < UpperBound.
  276. // This is the same as Idx + MIN < UpperBound + MIN, if overflow is allowed.
  277. // FIXME: This should probably be part of SValBuilder.
  278. ProgramStateManager &SM = getStateManager();
  279. SValBuilder &svalBuilder = SM.getSValBuilder();
  280. ASTContext &Ctx = svalBuilder.getContext();
  281. // Get the offset: the minimum value of the array index type.
  282. BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
  283. if (indexTy.isNull())
  284. indexTy = svalBuilder.getArrayIndexType();
  285. nonloc::ConcreteInt Min(BVF.getMinValue(indexTy));
  286. // Adjust the index.
  287. SVal newIdx = svalBuilder.evalBinOpNN(this, BO_Add,
  288. Idx.castAs<NonLoc>(), Min, indexTy);
  289. if (newIdx.isUnknownOrUndef())
  290. return this;
  291. // Adjust the upper bound.
  292. SVal newBound =
  293. svalBuilder.evalBinOpNN(this, BO_Add, UpperBound.castAs<NonLoc>(),
  294. Min, indexTy);
  295. if (newBound.isUnknownOrUndef())
  296. return this;
  297. // Build the actual comparison.
  298. SVal inBound = svalBuilder.evalBinOpNN(this, BO_LT, newIdx.castAs<NonLoc>(),
  299. newBound.castAs<NonLoc>(), Ctx.IntTy);
  300. if (inBound.isUnknownOrUndef())
  301. return this;
  302. // Finally, let the constraint manager take care of it.
  303. ConstraintManager &CM = SM.getConstraintManager();
  304. return CM.assume(this, inBound.castAs<DefinedSVal>(), Assumption);
  305. }
  306. ConditionTruthVal ProgramState::isNonNull(SVal V) const {
  307. ConditionTruthVal IsNull = isNull(V);
  308. if (IsNull.isUnderconstrained())
  309. return IsNull;
  310. return ConditionTruthVal(!IsNull.getValue());
  311. }
  312. ConditionTruthVal ProgramState::areEqual(SVal Lhs, SVal Rhs) const {
  313. return stateMgr->getSValBuilder().areEqual(this, Lhs, Rhs);
  314. }
  315. ConditionTruthVal ProgramState::isNull(SVal V) const {
  316. if (V.isZeroConstant())
  317. return true;
  318. if (V.isConstant())
  319. return false;
  320. SymbolRef Sym = V.getAsSymbol(/* IncludeBaseRegion */ true);
  321. if (!Sym)
  322. return ConditionTruthVal();
  323. return getStateManager().ConstraintMgr->isNull(this, Sym);
  324. }
  325. ProgramStateRef ProgramStateManager::getInitialState(const LocationContext *InitLoc) {
  326. ProgramState State(this,
  327. EnvMgr.getInitialEnvironment(),
  328. StoreMgr->getInitialStore(InitLoc),
  329. GDMFactory.getEmptyMap());
  330. return getPersistentState(State);
  331. }
  332. ProgramStateRef ProgramStateManager::getPersistentStateWithGDM(
  333. ProgramStateRef FromState,
  334. ProgramStateRef GDMState) {
  335. ProgramState NewState(*FromState);
  336. NewState.GDM = GDMState->GDM;
  337. return getPersistentState(NewState);
  338. }
  339. ProgramStateRef ProgramStateManager::getPersistentState(ProgramState &State) {
  340. llvm::FoldingSetNodeID ID;
  341. State.Profile(ID);
  342. void *InsertPos;
  343. if (ProgramState *I = StateSet.FindNodeOrInsertPos(ID, InsertPos))
  344. return I;
  345. ProgramState *newState = nullptr;
  346. if (!freeStates.empty()) {
  347. newState = freeStates.back();
  348. freeStates.pop_back();
  349. }
  350. else {
  351. newState = (ProgramState*) Alloc.Allocate<ProgramState>();
  352. }
  353. new (newState) ProgramState(State);
  354. StateSet.InsertNode(newState, InsertPos);
  355. return newState;
  356. }
  357. ProgramStateRef ProgramState::makeWithStore(const StoreRef &store) const {
  358. ProgramState NewSt(*this);
  359. NewSt.setStore(store);
  360. return getStateManager().getPersistentState(NewSt);
  361. }
  362. void ProgramState::setStore(const StoreRef &newStore) {
  363. Store newStoreStore = newStore.getStore();
  364. if (newStoreStore)
  365. stateMgr->getStoreManager().incrementReferenceCount(newStoreStore);
  366. if (store)
  367. stateMgr->getStoreManager().decrementReferenceCount(store);
  368. store = newStoreStore;
  369. }
  370. //===----------------------------------------------------------------------===//
  371. // State pretty-printing.
  372. //===----------------------------------------------------------------------===//
  373. void ProgramState::print(raw_ostream &Out,
  374. const char *NL, const char *Sep,
  375. const LocationContext *LC) const {
  376. // Print the store.
  377. ProgramStateManager &Mgr = getStateManager();
  378. const ASTContext &Context = getStateManager().getContext();
  379. Mgr.getStoreManager().print(getStore(), Out, NL);
  380. // Print out the environment.
  381. Env.print(Out, NL, Sep, Context, LC);
  382. // Print out the constraints.
  383. Mgr.getConstraintManager().print(this, Out, NL, Sep);
  384. // Print out the tracked dynamic types.
  385. printDynamicTypeInfo(this, Out, NL, Sep);
  386. // Print out tainted symbols.
  387. printTaint(Out, NL);
  388. // Print checker-specific data.
  389. Mgr.getOwningEngine().printState(Out, this, NL, Sep, LC);
  390. }
  391. void ProgramState::printDOT(raw_ostream &Out,
  392. const LocationContext *LC) const {
  393. print(Out, "\\l", "\\|", LC);
  394. }
  395. LLVM_DUMP_METHOD void ProgramState::dump() const {
  396. print(llvm::errs());
  397. }
  398. void ProgramState::printTaint(raw_ostream &Out,
  399. const char *NL) const {
  400. TaintMapImpl TM = get<TaintMap>();
  401. if (!TM.isEmpty())
  402. Out <<"Tainted symbols:" << NL;
  403. for (TaintMapImpl::iterator I = TM.begin(), E = TM.end(); I != E; ++I) {
  404. Out << I->first << " : " << I->second << NL;
  405. }
  406. }
  407. void ProgramState::dumpTaint() const {
  408. printTaint(llvm::errs());
  409. }
  410. AnalysisManager& ProgramState::getAnalysisManager() const {
  411. return stateMgr->getOwningEngine().getAnalysisManager();
  412. }
  413. //===----------------------------------------------------------------------===//
  414. // Generic Data Map.
  415. //===----------------------------------------------------------------------===//
  416. void *const* ProgramState::FindGDM(void *K) const {
  417. return GDM.lookup(K);
  418. }
  419. void*
  420. ProgramStateManager::FindGDMContext(void *K,
  421. void *(*CreateContext)(llvm::BumpPtrAllocator&),
  422. void (*DeleteContext)(void*)) {
  423. std::pair<void*, void (*)(void*)>& p = GDMContexts[K];
  424. if (!p.first) {
  425. p.first = CreateContext(Alloc);
  426. p.second = DeleteContext;
  427. }
  428. return p.first;
  429. }
  430. ProgramStateRef ProgramStateManager::addGDM(ProgramStateRef St, void *Key, void *Data){
  431. ProgramState::GenericDataMap M1 = St->getGDM();
  432. ProgramState::GenericDataMap M2 = GDMFactory.add(M1, Key, Data);
  433. if (M1 == M2)
  434. return St;
  435. ProgramState NewSt = *St;
  436. NewSt.GDM = M2;
  437. return getPersistentState(NewSt);
  438. }
  439. ProgramStateRef ProgramStateManager::removeGDM(ProgramStateRef state, void *Key) {
  440. ProgramState::GenericDataMap OldM = state->getGDM();
  441. ProgramState::GenericDataMap NewM = GDMFactory.remove(OldM, Key);
  442. if (NewM == OldM)
  443. return state;
  444. ProgramState NewState = *state;
  445. NewState.GDM = NewM;
  446. return getPersistentState(NewState);
  447. }
  448. bool ScanReachableSymbols::scan(nonloc::LazyCompoundVal val) {
  449. bool wasVisited = !visited.insert(val.getCVData()).second;
  450. if (wasVisited)
  451. return true;
  452. StoreManager &StoreMgr = state->getStateManager().getStoreManager();
  453. // FIXME: We don't really want to use getBaseRegion() here because pointer
  454. // arithmetic doesn't apply, but scanReachableSymbols only accepts base
  455. // regions right now.
  456. const MemRegion *R = val.getRegion()->getBaseRegion();
  457. return StoreMgr.scanReachableSymbols(val.getStore(), R, *this);
  458. }
  459. bool ScanReachableSymbols::scan(nonloc::CompoundVal val) {
  460. for (nonloc::CompoundVal::iterator I=val.begin(), E=val.end(); I!=E; ++I)
  461. if (!scan(*I))
  462. return false;
  463. return true;
  464. }
  465. bool ScanReachableSymbols::scan(const SymExpr *sym) {
  466. for (SymExpr::symbol_iterator SI = sym->symbol_begin(),
  467. SE = sym->symbol_end();
  468. SI != SE; ++SI) {
  469. bool wasVisited = !visited.insert(*SI).second;
  470. if (wasVisited)
  471. continue;
  472. if (!visitor.VisitSymbol(*SI))
  473. return false;
  474. }
  475. return true;
  476. }
  477. bool ScanReachableSymbols::scan(SVal val) {
  478. if (Optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>())
  479. return scan(X->getRegion());
  480. if (Optional<nonloc::LazyCompoundVal> X =
  481. val.getAs<nonloc::LazyCompoundVal>())
  482. return scan(*X);
  483. if (Optional<nonloc::LocAsInteger> X = val.getAs<nonloc::LocAsInteger>())
  484. return scan(X->getLoc());
  485. if (SymbolRef Sym = val.getAsSymbol())
  486. return scan(Sym);
  487. if (const SymExpr *Sym = val.getAsSymbolicExpression())
  488. return scan(Sym);
  489. if (Optional<nonloc::CompoundVal> X = val.getAs<nonloc::CompoundVal>())
  490. return scan(*X);
  491. return true;
  492. }
  493. bool ScanReachableSymbols::scan(const MemRegion *R) {
  494. if (isa<MemSpaceRegion>(R))
  495. return true;
  496. bool wasVisited = !visited.insert(R).second;
  497. if (wasVisited)
  498. return true;
  499. if (!visitor.VisitMemRegion(R))
  500. return false;
  501. // If this is a symbolic region, visit the symbol for the region.
  502. if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
  503. if (!visitor.VisitSymbol(SR->getSymbol()))
  504. return false;
  505. // If this is a subregion, also visit the parent regions.
  506. if (const SubRegion *SR = dyn_cast<SubRegion>(R)) {
  507. const MemRegion *Super = SR->getSuperRegion();
  508. if (!scan(Super))
  509. return false;
  510. // When we reach the topmost region, scan all symbols in it.
  511. if (isa<MemSpaceRegion>(Super)) {
  512. StoreManager &StoreMgr = state->getStateManager().getStoreManager();
  513. if (!StoreMgr.scanReachableSymbols(state->getStore(), SR, *this))
  514. return false;
  515. }
  516. }
  517. // Regions captured by a block are also implicitly reachable.
  518. if (const BlockDataRegion *BDR = dyn_cast<BlockDataRegion>(R)) {
  519. BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
  520. E = BDR->referenced_vars_end();
  521. for ( ; I != E; ++I) {
  522. if (!scan(I.getCapturedRegion()))
  523. return false;
  524. }
  525. }
  526. return true;
  527. }
  528. bool ProgramState::scanReachableSymbols(SVal val, SymbolVisitor& visitor) const {
  529. ScanReachableSymbols S(this, visitor);
  530. return S.scan(val);
  531. }
  532. bool ProgramState::scanReachableSymbols(
  533. llvm::iterator_range<region_iterator> Reachable,
  534. SymbolVisitor &visitor) const {
  535. ScanReachableSymbols S(this, visitor);
  536. for (const MemRegion *R : Reachable) {
  537. if (!S.scan(R))
  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. }