ProgramState.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. //== ProgramState.h - 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 defines the state of the program along the analysisa path.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATE_H
  14. #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATE_H
  15. #include "clang/Basic/LLVM.h"
  16. #include "clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h"
  17. #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h"
  18. #include "clang/StaticAnalyzer/Core/PathSensitive/Environment.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
  20. #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
  21. #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
  22. #include "clang/StaticAnalyzer/Core/PathSensitive/TaintTag.h"
  23. #include "llvm/ADT/FoldingSet.h"
  24. #include "llvm/ADT/ImmutableMap.h"
  25. #include "llvm/ADT/PointerIntPair.h"
  26. #include "llvm/Support/Allocator.h"
  27. namespace llvm {
  28. class APSInt;
  29. }
  30. namespace clang {
  31. class ASTContext;
  32. namespace ento {
  33. class CallEvent;
  34. class CallEventManager;
  35. typedef std::unique_ptr<ConstraintManager>(*ConstraintManagerCreator)(
  36. ProgramStateManager &, SubEngine *);
  37. typedef std::unique_ptr<StoreManager>(*StoreManagerCreator)(
  38. ProgramStateManager &);
  39. //===----------------------------------------------------------------------===//
  40. // ProgramStateTrait - Traits used by the Generic Data Map of a ProgramState.
  41. //===----------------------------------------------------------------------===//
  42. template <typename T> struct ProgramStatePartialTrait;
  43. template <typename T> struct ProgramStateTrait {
  44. typedef typename T::data_type data_type;
  45. static inline void *MakeVoidPtr(data_type D) { return (void*) D; }
  46. static inline data_type MakeData(void *const* P) {
  47. return P ? (data_type) *P : (data_type) 0;
  48. }
  49. };
  50. /// \class ProgramState
  51. /// ProgramState - This class encapsulates:
  52. ///
  53. /// 1. A mapping from expressions to values (Environment)
  54. /// 2. A mapping from locations to values (Store)
  55. /// 3. Constraints on symbolic values (GenericDataMap)
  56. ///
  57. /// Together these represent the "abstract state" of a program.
  58. ///
  59. /// ProgramState is intended to be used as a functional object; that is,
  60. /// once it is created and made "persistent" in a FoldingSet, its
  61. /// values will never change.
  62. class ProgramState : public llvm::FoldingSetNode {
  63. public:
  64. typedef llvm::ImmutableSet<llvm::APSInt*> IntSetTy;
  65. typedef llvm::ImmutableMap<void*, void*> GenericDataMap;
  66. private:
  67. void operator=(const ProgramState& R) = delete;
  68. friend class ProgramStateManager;
  69. friend class ExplodedGraph;
  70. friend class ExplodedNode;
  71. ProgramStateManager *stateMgr;
  72. Environment Env; // Maps a Stmt to its current SVal.
  73. Store store; // Maps a location to its current value.
  74. GenericDataMap GDM; // Custom data stored by a client of this class.
  75. unsigned refCount;
  76. /// makeWithStore - Return a ProgramState with the same values as the current
  77. /// state with the exception of using the specified Store.
  78. ProgramStateRef makeWithStore(const StoreRef &store) const;
  79. void setStore(const StoreRef &storeRef);
  80. public:
  81. /// This ctor is used when creating the first ProgramState object.
  82. ProgramState(ProgramStateManager *mgr, const Environment& env,
  83. StoreRef st, GenericDataMap gdm);
  84. /// Copy ctor - We must explicitly define this or else the "Next" ptr
  85. /// in FoldingSetNode will also get copied.
  86. ProgramState(const ProgramState &RHS);
  87. ~ProgramState();
  88. /// Return the ProgramStateManager associated with this state.
  89. ProgramStateManager &getStateManager() const {
  90. return *stateMgr;
  91. }
  92. /// Return the ConstraintManager.
  93. ConstraintManager &getConstraintManager() const;
  94. /// getEnvironment - Return the environment associated with this state.
  95. /// The environment is the mapping from expressions to values.
  96. const Environment& getEnvironment() const { return Env; }
  97. /// Return the store associated with this state. The store
  98. /// is a mapping from locations to values.
  99. Store getStore() const { return store; }
  100. /// getGDM - Return the generic data map associated with this state.
  101. GenericDataMap getGDM() const { return GDM; }
  102. void setGDM(GenericDataMap gdm) { GDM = gdm; }
  103. /// Profile - Profile the contents of a ProgramState object for use in a
  104. /// FoldingSet. Two ProgramState objects are considered equal if they
  105. /// have the same Environment, Store, and GenericDataMap.
  106. static void Profile(llvm::FoldingSetNodeID& ID, const ProgramState *V) {
  107. V->Env.Profile(ID);
  108. ID.AddPointer(V->store);
  109. V->GDM.Profile(ID);
  110. }
  111. /// Profile - Used to profile the contents of this object for inclusion
  112. /// in a FoldingSet.
  113. void Profile(llvm::FoldingSetNodeID& ID) const {
  114. Profile(ID, this);
  115. }
  116. BasicValueFactory &getBasicVals() const;
  117. SymbolManager &getSymbolManager() const;
  118. //==---------------------------------------------------------------------==//
  119. // Constraints on values.
  120. //==---------------------------------------------------------------------==//
  121. //
  122. // Each ProgramState records constraints on symbolic values. These constraints
  123. // are managed using the ConstraintManager associated with a ProgramStateManager.
  124. // As constraints gradually accrue on symbolic values, added constraints
  125. // may conflict and indicate that a state is infeasible (as no real values
  126. // could satisfy all the constraints). This is the principal mechanism
  127. // for modeling path-sensitivity in ExprEngine/ProgramState.
  128. //
  129. // Various "assume" methods form the interface for adding constraints to
  130. // symbolic values. A call to 'assume' indicates an assumption being placed
  131. // on one or symbolic values. 'assume' methods take the following inputs:
  132. //
  133. // (1) A ProgramState object representing the current state.
  134. //
  135. // (2) The assumed constraint (which is specific to a given "assume" method).
  136. //
  137. // (3) A binary value "Assumption" that indicates whether the constraint is
  138. // assumed to be true or false.
  139. //
  140. // The output of "assume*" is a new ProgramState object with the added constraints.
  141. // If no new state is feasible, NULL is returned.
  142. //
  143. /// Assumes that the value of \p cond is zero (if \p assumption is "false")
  144. /// or non-zero (if \p assumption is "true").
  145. ///
  146. /// This returns a new state with the added constraint on \p cond.
  147. /// If no new state is feasible, NULL is returned.
  148. ProgramStateRef assume(DefinedOrUnknownSVal cond, bool assumption) const;
  149. /// Assumes both "true" and "false" for \p cond, and returns both
  150. /// corresponding states (respectively).
  151. ///
  152. /// This is more efficient than calling assume() twice. Note that one (but not
  153. /// both) of the returned states may be NULL.
  154. std::pair<ProgramStateRef, ProgramStateRef>
  155. assume(DefinedOrUnknownSVal cond) const;
  156. ProgramStateRef assumeInBound(DefinedOrUnknownSVal idx,
  157. DefinedOrUnknownSVal upperBound,
  158. bool assumption,
  159. QualType IndexType = QualType()) const;
  160. /// \brief Check if the given SVal is constrained to zero or is a zero
  161. /// constant.
  162. ConditionTruthVal isNull(SVal V) const;
  163. /// Utility method for getting regions.
  164. const VarRegion* getRegion(const VarDecl *D, const LocationContext *LC) const;
  165. //==---------------------------------------------------------------------==//
  166. // Binding and retrieving values to/from the environment and symbolic store.
  167. //==---------------------------------------------------------------------==//
  168. /// Create a new state by binding the value 'V' to the statement 'S' in the
  169. /// state's environment.
  170. ProgramStateRef BindExpr(const Stmt *S, const LocationContext *LCtx,
  171. SVal V, bool Invalidate = true) const;
  172. ProgramStateRef bindLoc(Loc location,
  173. SVal V,
  174. bool notifyChanges = true) const;
  175. ProgramStateRef bindLoc(SVal location, SVal V) const;
  176. ProgramStateRef bindDefault(SVal loc, SVal V) const;
  177. ProgramStateRef killBinding(Loc LV) const;
  178. /// \brief Returns the state with bindings for the given regions
  179. /// cleared from the store.
  180. ///
  181. /// Optionally invalidates global regions as well.
  182. ///
  183. /// \param Regions the set of regions to be invalidated.
  184. /// \param E the expression that caused the invalidation.
  185. /// \param BlockCount The number of times the current basic block has been
  186. // visited.
  187. /// \param CausesPointerEscape the flag is set to true when
  188. /// the invalidation entails escape of a symbol (representing a
  189. /// pointer). For example, due to it being passed as an argument in a
  190. /// call.
  191. /// \param IS the set of invalidated symbols.
  192. /// \param Call if non-null, the invalidated regions represent parameters to
  193. /// the call and should be considered directly invalidated.
  194. /// \param ITraits information about special handling for a particular
  195. /// region/symbol.
  196. ProgramStateRef
  197. invalidateRegions(ArrayRef<const MemRegion *> Regions, const Expr *E,
  198. unsigned BlockCount, const LocationContext *LCtx,
  199. bool CausesPointerEscape, InvalidatedSymbols *IS = nullptr,
  200. const CallEvent *Call = nullptr,
  201. RegionAndSymbolInvalidationTraits *ITraits = nullptr) const;
  202. ProgramStateRef
  203. invalidateRegions(ArrayRef<SVal> Regions, const Expr *E,
  204. unsigned BlockCount, const LocationContext *LCtx,
  205. bool CausesPointerEscape, InvalidatedSymbols *IS = nullptr,
  206. const CallEvent *Call = nullptr,
  207. RegionAndSymbolInvalidationTraits *ITraits = nullptr) const;
  208. /// enterStackFrame - Returns the state for entry to the given stack frame,
  209. /// preserving the current state.
  210. ProgramStateRef enterStackFrame(const CallEvent &Call,
  211. const StackFrameContext *CalleeCtx) const;
  212. /// Get the lvalue for a variable reference.
  213. Loc getLValue(const VarDecl *D, const LocationContext *LC) const;
  214. Loc getLValue(const CompoundLiteralExpr *literal,
  215. const LocationContext *LC) const;
  216. /// Get the lvalue for an ivar reference.
  217. SVal getLValue(const ObjCIvarDecl *decl, SVal base) const;
  218. /// Get the lvalue for a field reference.
  219. SVal getLValue(const FieldDecl *decl, SVal Base) const;
  220. /// Get the lvalue for an indirect field reference.
  221. SVal getLValue(const IndirectFieldDecl *decl, SVal Base) const;
  222. /// Get the lvalue for an array index.
  223. SVal getLValue(QualType ElementType, SVal Idx, SVal Base) const;
  224. /// Returns the SVal bound to the statement 'S' in the state's environment.
  225. SVal getSVal(const Stmt *S, const LocationContext *LCtx) const;
  226. SVal getSValAsScalarOrLoc(const Stmt *Ex, const LocationContext *LCtx) const;
  227. /// \brief Return the value bound to the specified location.
  228. /// Returns UnknownVal() if none found.
  229. SVal getSVal(Loc LV, QualType T = QualType()) const;
  230. /// Returns the "raw" SVal bound to LV before any value simplfication.
  231. SVal getRawSVal(Loc LV, QualType T= QualType()) const;
  232. /// \brief Return the value bound to the specified location.
  233. /// Returns UnknownVal() if none found.
  234. SVal getSVal(const MemRegion* R) const;
  235. SVal getSValAsScalarOrLoc(const MemRegion *R) const;
  236. /// \brief Visits the symbols reachable from the given SVal using the provided
  237. /// SymbolVisitor.
  238. ///
  239. /// This is a convenience API. Consider using ScanReachableSymbols class
  240. /// directly when making multiple scans on the same state with the same
  241. /// visitor to avoid repeated initialization cost.
  242. /// \sa ScanReachableSymbols
  243. bool scanReachableSymbols(SVal val, SymbolVisitor& visitor) const;
  244. /// \brief Visits the symbols reachable from the SVals in the given range
  245. /// using the provided SymbolVisitor.
  246. bool scanReachableSymbols(const SVal *I, const SVal *E,
  247. SymbolVisitor &visitor) const;
  248. /// \brief Visits the symbols reachable from the regions in the given
  249. /// MemRegions range using the provided SymbolVisitor.
  250. bool scanReachableSymbols(const MemRegion * const *I,
  251. const MemRegion * const *E,
  252. SymbolVisitor &visitor) const;
  253. template <typename CB> CB scanReachableSymbols(SVal val) const;
  254. template <typename CB> CB scanReachableSymbols(const SVal *beg,
  255. const SVal *end) const;
  256. template <typename CB> CB
  257. scanReachableSymbols(const MemRegion * const *beg,
  258. const MemRegion * const *end) const;
  259. /// Create a new state in which the statement is marked as tainted.
  260. ProgramStateRef addTaint(const Stmt *S, const LocationContext *LCtx,
  261. TaintTagType Kind = TaintTagGeneric) const;
  262. /// Create a new state in which the symbol is marked as tainted.
  263. ProgramStateRef addTaint(SymbolRef S,
  264. TaintTagType Kind = TaintTagGeneric) const;
  265. /// Create a new state in which the region symbol is marked as tainted.
  266. ProgramStateRef addTaint(const MemRegion *R,
  267. TaintTagType Kind = TaintTagGeneric) const;
  268. /// Check if the statement is tainted in the current state.
  269. bool isTainted(const Stmt *S, const LocationContext *LCtx,
  270. TaintTagType Kind = TaintTagGeneric) const;
  271. bool isTainted(SVal V, TaintTagType Kind = TaintTagGeneric) const;
  272. bool isTainted(SymbolRef Sym, TaintTagType Kind = TaintTagGeneric) const;
  273. bool isTainted(const MemRegion *Reg, TaintTagType Kind=TaintTagGeneric) const;
  274. //==---------------------------------------------------------------------==//
  275. // Accessing the Generic Data Map (GDM).
  276. //==---------------------------------------------------------------------==//
  277. void *const* FindGDM(void *K) const;
  278. template<typename T>
  279. ProgramStateRef add(typename ProgramStateTrait<T>::key_type K) const;
  280. template <typename T>
  281. typename ProgramStateTrait<T>::data_type
  282. get() const {
  283. return ProgramStateTrait<T>::MakeData(FindGDM(ProgramStateTrait<T>::GDMIndex()));
  284. }
  285. template<typename T>
  286. typename ProgramStateTrait<T>::lookup_type
  287. get(typename ProgramStateTrait<T>::key_type key) const {
  288. void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
  289. return ProgramStateTrait<T>::Lookup(ProgramStateTrait<T>::MakeData(d), key);
  290. }
  291. template <typename T>
  292. typename ProgramStateTrait<T>::context_type get_context() const;
  293. template<typename T>
  294. ProgramStateRef remove(typename ProgramStateTrait<T>::key_type K) const;
  295. template<typename T>
  296. ProgramStateRef remove(typename ProgramStateTrait<T>::key_type K,
  297. typename ProgramStateTrait<T>::context_type C) const;
  298. template <typename T>
  299. ProgramStateRef remove() const;
  300. template<typename T>
  301. ProgramStateRef set(typename ProgramStateTrait<T>::data_type D) const;
  302. template<typename T>
  303. ProgramStateRef set(typename ProgramStateTrait<T>::key_type K,
  304. typename ProgramStateTrait<T>::value_type E) const;
  305. template<typename T>
  306. ProgramStateRef set(typename ProgramStateTrait<T>::key_type K,
  307. typename ProgramStateTrait<T>::value_type E,
  308. typename ProgramStateTrait<T>::context_type C) const;
  309. template<typename T>
  310. bool contains(typename ProgramStateTrait<T>::key_type key) const {
  311. void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
  312. return ProgramStateTrait<T>::Contains(ProgramStateTrait<T>::MakeData(d), key);
  313. }
  314. // Pretty-printing.
  315. void print(raw_ostream &Out, const char *nl = "\n",
  316. const char *sep = "") const;
  317. void printDOT(raw_ostream &Out) const;
  318. void printTaint(raw_ostream &Out, const char *nl = "\n",
  319. const char *sep = "") const;
  320. void dump() const;
  321. void dumpTaint() const;
  322. private:
  323. friend void ProgramStateRetain(const ProgramState *state);
  324. friend void ProgramStateRelease(const ProgramState *state);
  325. /// \sa invalidateValues()
  326. /// \sa invalidateRegions()
  327. ProgramStateRef
  328. invalidateRegionsImpl(ArrayRef<SVal> Values,
  329. const Expr *E, unsigned BlockCount,
  330. const LocationContext *LCtx,
  331. bool ResultsInSymbolEscape,
  332. InvalidatedSymbols *IS,
  333. RegionAndSymbolInvalidationTraits *HTraits,
  334. const CallEvent *Call) const;
  335. };
  336. //===----------------------------------------------------------------------===//
  337. // ProgramStateManager - Factory object for ProgramStates.
  338. //===----------------------------------------------------------------------===//
  339. class ProgramStateManager {
  340. friend class ProgramState;
  341. friend void ProgramStateRelease(const ProgramState *state);
  342. private:
  343. /// Eng - The SubEngine that owns this state manager.
  344. SubEngine *Eng; /* Can be null. */
  345. EnvironmentManager EnvMgr;
  346. std::unique_ptr<StoreManager> StoreMgr;
  347. std::unique_ptr<ConstraintManager> ConstraintMgr;
  348. ProgramState::GenericDataMap::Factory GDMFactory;
  349. typedef llvm::DenseMap<void*,std::pair<void*,void (*)(void*)> > GDMContextsTy;
  350. GDMContextsTy GDMContexts;
  351. /// StateSet - FoldingSet containing all the states created for analyzing
  352. /// a particular function. This is used to unique states.
  353. llvm::FoldingSet<ProgramState> StateSet;
  354. /// Object that manages the data for all created SVals.
  355. std::unique_ptr<SValBuilder> svalBuilder;
  356. /// Manages memory for created CallEvents.
  357. std::unique_ptr<CallEventManager> CallEventMgr;
  358. /// A BumpPtrAllocator to allocate states.
  359. llvm::BumpPtrAllocator &Alloc;
  360. /// A vector of ProgramStates that we can reuse.
  361. std::vector<ProgramState *> freeStates;
  362. public:
  363. ProgramStateManager(ASTContext &Ctx,
  364. StoreManagerCreator CreateStoreManager,
  365. ConstraintManagerCreator CreateConstraintManager,
  366. llvm::BumpPtrAllocator& alloc,
  367. SubEngine *subeng);
  368. ~ProgramStateManager();
  369. ProgramStateRef getInitialState(const LocationContext *InitLoc);
  370. ASTContext &getContext() { return svalBuilder->getContext(); }
  371. const ASTContext &getContext() const { return svalBuilder->getContext(); }
  372. BasicValueFactory &getBasicVals() {
  373. return svalBuilder->getBasicValueFactory();
  374. }
  375. SValBuilder &getSValBuilder() {
  376. return *svalBuilder;
  377. }
  378. SymbolManager &getSymbolManager() {
  379. return svalBuilder->getSymbolManager();
  380. }
  381. const SymbolManager &getSymbolManager() const {
  382. return svalBuilder->getSymbolManager();
  383. }
  384. llvm::BumpPtrAllocator& getAllocator() { return Alloc; }
  385. MemRegionManager& getRegionManager() {
  386. return svalBuilder->getRegionManager();
  387. }
  388. const MemRegionManager& getRegionManager() const {
  389. return svalBuilder->getRegionManager();
  390. }
  391. CallEventManager &getCallEventManager() { return *CallEventMgr; }
  392. StoreManager& getStoreManager() { return *StoreMgr; }
  393. ConstraintManager& getConstraintManager() { return *ConstraintMgr; }
  394. SubEngine* getOwningEngine() { return Eng; }
  395. ProgramStateRef removeDeadBindings(ProgramStateRef St,
  396. const StackFrameContext *LCtx,
  397. SymbolReaper& SymReaper);
  398. public:
  399. SVal ArrayToPointer(Loc Array, QualType ElementTy) {
  400. return StoreMgr->ArrayToPointer(Array, ElementTy);
  401. }
  402. // Methods that manipulate the GDM.
  403. ProgramStateRef addGDM(ProgramStateRef St, void *Key, void *Data);
  404. ProgramStateRef removeGDM(ProgramStateRef state, void *Key);
  405. // Methods that query & manipulate the Store.
  406. void iterBindings(ProgramStateRef state, StoreManager::BindingsHandler& F) {
  407. StoreMgr->iterBindings(state->getStore(), F);
  408. }
  409. ProgramStateRef getPersistentState(ProgramState &Impl);
  410. ProgramStateRef getPersistentStateWithGDM(ProgramStateRef FromState,
  411. ProgramStateRef GDMState);
  412. bool haveEqualEnvironments(ProgramStateRef S1, ProgramStateRef S2) {
  413. return S1->Env == S2->Env;
  414. }
  415. bool haveEqualStores(ProgramStateRef S1, ProgramStateRef S2) {
  416. return S1->store == S2->store;
  417. }
  418. //==---------------------------------------------------------------------==//
  419. // Generic Data Map methods.
  420. //==---------------------------------------------------------------------==//
  421. //
  422. // ProgramStateManager and ProgramState support a "generic data map" that allows
  423. // different clients of ProgramState objects to embed arbitrary data within a
  424. // ProgramState object. The generic data map is essentially an immutable map
  425. // from a "tag" (that acts as the "key" for a client) and opaque values.
  426. // Tags/keys and values are simply void* values. The typical way that clients
  427. // generate unique tags are by taking the address of a static variable.
  428. // Clients are responsible for ensuring that data values referred to by a
  429. // the data pointer are immutable (and thus are essentially purely functional
  430. // data).
  431. //
  432. // The templated methods below use the ProgramStateTrait<T> class
  433. // to resolve keys into the GDM and to return data values to clients.
  434. //
  435. // Trait based GDM dispatch.
  436. template <typename T>
  437. ProgramStateRef set(ProgramStateRef st, typename ProgramStateTrait<T>::data_type D) {
  438. return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
  439. ProgramStateTrait<T>::MakeVoidPtr(D));
  440. }
  441. template<typename T>
  442. ProgramStateRef set(ProgramStateRef st,
  443. typename ProgramStateTrait<T>::key_type K,
  444. typename ProgramStateTrait<T>::value_type V,
  445. typename ProgramStateTrait<T>::context_type C) {
  446. return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
  447. ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Set(st->get<T>(), K, V, C)));
  448. }
  449. template <typename T>
  450. ProgramStateRef add(ProgramStateRef st,
  451. typename ProgramStateTrait<T>::key_type K,
  452. typename ProgramStateTrait<T>::context_type C) {
  453. return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
  454. ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Add(st->get<T>(), K, C)));
  455. }
  456. template <typename T>
  457. ProgramStateRef remove(ProgramStateRef st,
  458. typename ProgramStateTrait<T>::key_type K,
  459. typename ProgramStateTrait<T>::context_type C) {
  460. return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
  461. ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Remove(st->get<T>(), K, C)));
  462. }
  463. template <typename T>
  464. ProgramStateRef remove(ProgramStateRef st) {
  465. return removeGDM(st, ProgramStateTrait<T>::GDMIndex());
  466. }
  467. void *FindGDMContext(void *index,
  468. void *(*CreateContext)(llvm::BumpPtrAllocator&),
  469. void (*DeleteContext)(void*));
  470. template <typename T>
  471. typename ProgramStateTrait<T>::context_type get_context() {
  472. void *p = FindGDMContext(ProgramStateTrait<T>::GDMIndex(),
  473. ProgramStateTrait<T>::CreateContext,
  474. ProgramStateTrait<T>::DeleteContext);
  475. return ProgramStateTrait<T>::MakeContext(p);
  476. }
  477. void EndPath(ProgramStateRef St) {
  478. ConstraintMgr->EndPath(St);
  479. }
  480. };
  481. //===----------------------------------------------------------------------===//
  482. // Out-of-line method definitions for ProgramState.
  483. //===----------------------------------------------------------------------===//
  484. inline ConstraintManager &ProgramState::getConstraintManager() const {
  485. return stateMgr->getConstraintManager();
  486. }
  487. inline const VarRegion* ProgramState::getRegion(const VarDecl *D,
  488. const LocationContext *LC) const
  489. {
  490. return getStateManager().getRegionManager().getVarRegion(D, LC);
  491. }
  492. inline ProgramStateRef ProgramState::assume(DefinedOrUnknownSVal Cond,
  493. bool Assumption) const {
  494. if (Cond.isUnknown())
  495. return this;
  496. return getStateManager().ConstraintMgr
  497. ->assume(this, Cond.castAs<DefinedSVal>(), Assumption);
  498. }
  499. inline std::pair<ProgramStateRef , ProgramStateRef >
  500. ProgramState::assume(DefinedOrUnknownSVal Cond) const {
  501. if (Cond.isUnknown())
  502. return std::make_pair(this, this);
  503. return getStateManager().ConstraintMgr
  504. ->assumeDual(this, Cond.castAs<DefinedSVal>());
  505. }
  506. inline ProgramStateRef ProgramState::bindLoc(SVal LV, SVal V) const {
  507. if (Optional<Loc> L = LV.getAs<Loc>())
  508. return bindLoc(*L, V);
  509. return this;
  510. }
  511. inline Loc ProgramState::getLValue(const VarDecl *VD,
  512. const LocationContext *LC) const {
  513. return getStateManager().StoreMgr->getLValueVar(VD, LC);
  514. }
  515. inline Loc ProgramState::getLValue(const CompoundLiteralExpr *literal,
  516. const LocationContext *LC) const {
  517. return getStateManager().StoreMgr->getLValueCompoundLiteral(literal, LC);
  518. }
  519. inline SVal ProgramState::getLValue(const ObjCIvarDecl *D, SVal Base) const {
  520. return getStateManager().StoreMgr->getLValueIvar(D, Base);
  521. }
  522. inline SVal ProgramState::getLValue(const FieldDecl *D, SVal Base) const {
  523. return getStateManager().StoreMgr->getLValueField(D, Base);
  524. }
  525. inline SVal ProgramState::getLValue(const IndirectFieldDecl *D,
  526. SVal Base) const {
  527. StoreManager &SM = *getStateManager().StoreMgr;
  528. for (const auto *I : D->chain()) {
  529. Base = SM.getLValueField(cast<FieldDecl>(I), Base);
  530. }
  531. return Base;
  532. }
  533. inline SVal ProgramState::getLValue(QualType ElementType, SVal Idx, SVal Base) const{
  534. if (Optional<NonLoc> N = Idx.getAs<NonLoc>())
  535. return getStateManager().StoreMgr->getLValueElement(ElementType, *N, Base);
  536. return UnknownVal();
  537. }
  538. inline SVal ProgramState::getSVal(const Stmt *Ex,
  539. const LocationContext *LCtx) const{
  540. return Env.getSVal(EnvironmentEntry(Ex, LCtx),
  541. *getStateManager().svalBuilder);
  542. }
  543. inline SVal
  544. ProgramState::getSValAsScalarOrLoc(const Stmt *S,
  545. const LocationContext *LCtx) const {
  546. if (const Expr *Ex = dyn_cast<Expr>(S)) {
  547. QualType T = Ex->getType();
  548. if (Ex->isGLValue() || Loc::isLocType(T) ||
  549. T->isIntegralOrEnumerationType())
  550. return getSVal(S, LCtx);
  551. }
  552. return UnknownVal();
  553. }
  554. inline SVal ProgramState::getRawSVal(Loc LV, QualType T) const {
  555. return getStateManager().StoreMgr->getBinding(getStore(), LV, T);
  556. }
  557. inline SVal ProgramState::getSVal(const MemRegion* R) const {
  558. return getStateManager().StoreMgr->getBinding(getStore(),
  559. loc::MemRegionVal(R));
  560. }
  561. inline BasicValueFactory &ProgramState::getBasicVals() const {
  562. return getStateManager().getBasicVals();
  563. }
  564. inline SymbolManager &ProgramState::getSymbolManager() const {
  565. return getStateManager().getSymbolManager();
  566. }
  567. template<typename T>
  568. ProgramStateRef ProgramState::add(typename ProgramStateTrait<T>::key_type K) const {
  569. return getStateManager().add<T>(this, K, get_context<T>());
  570. }
  571. template <typename T>
  572. typename ProgramStateTrait<T>::context_type ProgramState::get_context() const {
  573. return getStateManager().get_context<T>();
  574. }
  575. template<typename T>
  576. ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K) const {
  577. return getStateManager().remove<T>(this, K, get_context<T>());
  578. }
  579. template<typename T>
  580. ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K,
  581. typename ProgramStateTrait<T>::context_type C) const {
  582. return getStateManager().remove<T>(this, K, C);
  583. }
  584. template <typename T>
  585. ProgramStateRef ProgramState::remove() const {
  586. return getStateManager().remove<T>(this);
  587. }
  588. template<typename T>
  589. ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::data_type D) const {
  590. return getStateManager().set<T>(this, D);
  591. }
  592. template<typename T>
  593. ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
  594. typename ProgramStateTrait<T>::value_type E) const {
  595. return getStateManager().set<T>(this, K, E, get_context<T>());
  596. }
  597. template<typename T>
  598. ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
  599. typename ProgramStateTrait<T>::value_type E,
  600. typename ProgramStateTrait<T>::context_type C) const {
  601. return getStateManager().set<T>(this, K, E, C);
  602. }
  603. template <typename CB>
  604. CB ProgramState::scanReachableSymbols(SVal val) const {
  605. CB cb(this);
  606. scanReachableSymbols(val, cb);
  607. return cb;
  608. }
  609. template <typename CB>
  610. CB ProgramState::scanReachableSymbols(const SVal *beg, const SVal *end) const {
  611. CB cb(this);
  612. scanReachableSymbols(beg, end, cb);
  613. return cb;
  614. }
  615. template <typename CB>
  616. CB ProgramState::scanReachableSymbols(const MemRegion * const *beg,
  617. const MemRegion * const *end) const {
  618. CB cb(this);
  619. scanReachableSymbols(beg, end, cb);
  620. return cb;
  621. }
  622. /// \class ScanReachableSymbols
  623. /// A Utility class that allows to visit the reachable symbols using a custom
  624. /// SymbolVisitor.
  625. class ScanReachableSymbols {
  626. typedef llvm::DenseSet<const void*> VisitedItems;
  627. VisitedItems visited;
  628. ProgramStateRef state;
  629. SymbolVisitor &visitor;
  630. public:
  631. ScanReachableSymbols(ProgramStateRef st, SymbolVisitor& v)
  632. : state(st), visitor(v) {}
  633. bool scan(nonloc::LazyCompoundVal val);
  634. bool scan(nonloc::CompoundVal val);
  635. bool scan(SVal val);
  636. bool scan(const MemRegion *R);
  637. bool scan(const SymExpr *sym);
  638. };
  639. } // end ento namespace
  640. } // end clang namespace
  641. #endif