Clang Project

clang_source_code/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
1//===- Store.h - Interface for maps from Locations to Values ----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9//  This file defined the types Store and StoreManager.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_STORE_H
14#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_STORE_H
15
16#include "clang/AST/Type.h"
17#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
20#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h"
22#include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
23#include "clang/Basic/LLVM.h"
24#include "llvm/ADT/ArrayRef.h"
25#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/Optional.h"
27#include "llvm/ADT/SmallVector.h"
28#include <cassert>
29#include <cstdint>
30#include <memory>
31
32namespace clang {
33
34class ASTContext;
35class CastExpr;
36class CompoundLiteralExpr;
37class CXXBasePath;
38class Decl;
39class Expr;
40class LocationContext;
41class ObjCIvarDecl;
42class StackFrameContext;
43
44namespace ento {
45
46class CallEvent;
47class ProgramStateManager;
48class ScanReachableSymbols;
49class SymbolReaper;
50
51using InvalidatedSymbols = llvm::DenseSet<SymbolRef>;
52
53class StoreManager {
54protected:
55  SValBuilder &svalBuilder;
56  ProgramStateManager &StateMgr;
57
58  /// MRMgr - Manages region objects associated with this StoreManager.
59  MemRegionManager &MRMgr;
60  ASTContext &Ctx;
61
62  StoreManager(ProgramStateManager &stateMgr);
63
64public:
65  virtual ~StoreManager() = default;
66
67  /// Return the value bound to specified location in a given state.
68  /// \param[in] store The store in which to make the lookup.
69  /// \param[in] loc The symbolic memory location.
70  /// \param[in] T An optional type that provides a hint indicating the
71  ///   expected type of the returned value.  This is used if the value is
72  ///   lazily computed.
73  /// \return The value bound to the location \c loc.
74  virtual SVal getBinding(Store storeLoc locQualType T = QualType()) = 0;
75
76  /// Return the default value bound to a region in a given store. The default
77  /// binding is the value of sub-regions that were not initialized separately
78  /// from their base region. For example, if the structure is zero-initialized
79  /// upon construction, this method retrieves the concrete zero value, even if
80  /// some or all fields were later overwritten manually. Default binding may be
81  /// an unknown, undefined, concrete, or symbolic value.
82  /// \param[in] store The store in which to make the lookup.
83  /// \param[in] R The region to find the default binding for.
84  /// \return The default value bound to the region in the store, if a default
85  /// binding exists.
86  virtual Optional<SValgetDefaultBinding(Store storeconst MemRegion *R) = 0;
87
88  /// Return the default value bound to a LazyCompoundVal. The default binding
89  /// is used to represent the value of any fields or elements within the
90  /// structure represented by the LazyCompoundVal which were not initialized
91  /// explicitly separately from the whole structure. Default binding may be an
92  /// unknown, undefined, concrete, or symbolic value.
93  /// \param[in] lcv The lazy compound value.
94  /// \return The default value bound to the LazyCompoundVal \c lcv, if a
95  /// default binding exists.
96  Optional<SValgetDefaultBinding(nonloc::LazyCompoundVal lcv) {
97    return getDefaultBinding(lcv.getStore(), lcv.getRegion());
98  }
99
100  /// Return a store with the specified value bound to the given location.
101  /// \param[in] store The store in which to make the binding.
102  /// \param[in] loc The symbolic memory location.
103  /// \param[in] val The value to bind to location \c loc.
104  /// \return A StoreRef object that contains the same
105  ///   bindings as \c store with the addition of having the value specified
106  ///   by \c val bound to the location given for \c loc.
107  virtual StoreRef Bind(Store storeLoc locSVal val) = 0;
108
109  /// Return a store with the specified value bound to all sub-regions of the
110  /// region. The region must not have previous bindings. If you need to
111  /// invalidate existing bindings, consider invalidateRegions().
112  virtual StoreRef BindDefaultInitial(Store storeconst MemRegion *R,
113                                      SVal V) = 0;
114
115  /// Return a store with in which all values within the given region are
116  /// reset to zero. This method is allowed to overwrite previous bindings.
117  virtual StoreRef BindDefaultZero(Store storeconst MemRegion *R) = 0;
118
119  /// Create a new store with the specified binding removed.
120  /// \param ST the original store, that is the basis for the new store.
121  /// \param L the location whose binding should be removed.
122  virtual StoreRef killBinding(Store STLoc L) = 0;
123
124  /// getInitialStore - Returns the initial "empty" store representing the
125  ///  value bindings upon entry to an analyzed function.
126  virtual StoreRef getInitialStore(const LocationContext *InitLoc) = 0;
127
128  /// getRegionManager - Returns the internal RegionManager object that is
129  ///  used to query and manipulate MemRegion objects.
130  MemRegionManagergetRegionManager() { return MRMgr; }
131
132  SValBuildergetSValBuilder() { return svalBuilder; }
133
134  virtual Loc getLValueVar(const VarDecl *VDconst LocationContext *LC) {
135    return svalBuilder.makeLoc(MRMgr.getVarRegion(VDLC));
136  }
137
138  Loc getLValueCompoundLiteral(const CompoundLiteralExpr *CL,
139                               const LocationContext *LC) {
140    return loc::MemRegionVal(MRMgr.getCompoundLiteralRegion(CLLC));
141  }
142
143  virtual SVal getLValueIvar(const ObjCIvarDecl *declSVal base);
144
145  virtual SVal getLValueField(const FieldDecl *DSVal Base) {
146    return getLValueFieldOrIvar(DBase);
147  }
148
149  virtual SVal getLValueElement(QualType elementTypeNonLoc offsetSVal Base);
150
151  // FIXME: This should soon be eliminated altogether; clients should deal with
152  // region extents directly.
153  virtual DefinedOrUnknownSVal getSizeInElements(ProgramStateRef state,
154                                                 const MemRegion *region,
155                                                 QualType EleTy) {
156    return UnknownVal();
157  }
158
159  /// ArrayToPointer - Used by ExprEngine::VistCast to handle implicit
160  ///  conversions between arrays and pointers.
161  virtual SVal ArrayToPointer(Loc ArrayQualType ElementTy) = 0;
162
163  /// Evaluates a chain of derived-to-base casts through the path specified in
164  /// \p Cast.
165  SVal evalDerivedToBase(SVal Derivedconst CastExpr *Cast);
166
167  /// Evaluates a chain of derived-to-base casts through the specified path.
168  SVal evalDerivedToBase(SVal Derivedconst CXXBasePath &CastPath);
169
170  /// Evaluates a derived-to-base cast through a single level of derivation.
171  SVal evalDerivedToBase(SVal DerivedQualType DerivedPtrType,
172                         bool IsVirtual);
173
174  /// Attempts to do a down cast. Used to model BaseToDerived and C++
175  ///        dynamic_cast.
176  /// The callback may result in the following 3 scenarios:
177  ///  - Successful cast (ex: derived is subclass of base).
178  ///  - Failed cast (ex: derived is definitely not a subclass of base).
179  ///    The distinction of this case from the next one is necessary to model
180  ///    dynamic_cast.
181  ///  - We don't know (base is a symbolic region and we don't have
182  ///    enough info to determine if the cast will succeed at run time).
183  /// The function returns an SVal representing the derived class; it's
184  /// valid only if Failed flag is set to false.
185  SVal attemptDownCast(SVal BaseQualType DerivedPtrTypebool &Failed);
186
187  const ElementRegion *GetElementZeroRegion(const SubRegion *RQualType T);
188
189  /// castRegion - Used by ExprEngine::VisitCast to handle casts from
190  ///  a MemRegion* to a specific location type.  'R' is the region being
191  ///  casted and 'CastToTy' the result type of the cast.
192  const MemRegion *castRegion(const MemRegion *regionQualType CastToTy);
193
194  virtual StoreRef removeDeadBindings(Store storeconst StackFrameContext *LCtx,
195                                      SymbolReaper &SymReaper) = 0;
196
197  virtual bool includedInBindings(Store store,
198                                  const MemRegion *regionconst = 0;
199
200  /// If the StoreManager supports it, increment the reference count of
201  /// the specified Store object.
202  virtual void incrementReferenceCount(Store store) {}
203
204  /// If the StoreManager supports it, decrement the reference count of
205  /// the specified Store object.  If the reference count hits 0, the memory
206  /// associated with the object is recycled.
207  virtual void decrementReferenceCount(Store store) {}
208
209  using InvalidatedRegions = SmallVector<const MemRegion *, 8>;
210
211  /// invalidateRegions - Clears out the specified regions from the store,
212  ///  marking their values as unknown. Depending on the store, this may also
213  ///  invalidate additional regions that may have changed based on accessing
214  ///  the given regions. Optionally, invalidates non-static globals as well.
215  /// \param[in] store The initial store
216  /// \param[in] Values The values to invalidate.
217  /// \param[in] E The current statement being evaluated. Used to conjure
218  ///   symbols to mark the values of invalidated regions.
219  /// \param[in] Count The current block count. Used to conjure
220  ///   symbols to mark the values of invalidated regions.
221  /// \param[in] Call The call expression which will be used to determine which
222  ///   globals should get invalidated.
223  /// \param[in,out] IS A set to fill with any symbols that are no longer
224  ///   accessible. Pass \c NULL if this information will not be used.
225  /// \param[in] ITraits Information about invalidation for a particular
226  ///   region/symbol.
227  /// \param[in,out] InvalidatedTopLevel A vector to fill with regions
228  ////  explicitly being invalidated. Pass \c NULL if this
229  ///   information will not be used.
230  /// \param[in,out] Invalidated A vector to fill with any regions being
231  ///   invalidated. This should include any regions explicitly invalidated
232  ///   even if they do not currently have bindings. Pass \c NULL if this
233  ///   information will not be used.
234  virtual StoreRef invalidateRegions(Store store,
235                                  ArrayRef<SValValues,
236                                  const Expr *Eunsigned Count,
237                                  const LocationContext *LCtx,
238                                  const CallEvent *Call,
239                                  InvalidatedSymbols &IS,
240                                  RegionAndSymbolInvalidationTraits &ITraits,
241                                  InvalidatedRegions *InvalidatedTopLevel,
242                                  InvalidatedRegions *Invalidated) = 0;
243
244  /// enterStackFrame - Let the StoreManager to do something when execution
245  /// engine is about to execute into a callee.
246  StoreRef enterStackFrame(Store store,
247                           const CallEvent &Call,
248                           const StackFrameContext *CalleeCtx);
249
250  /// Finds the transitive closure of symbols within the given region.
251  ///
252  /// Returns false if the visitor aborted the scan.
253  virtual bool scanReachableSymbols(Store Sconst MemRegion *R,
254                                    ScanReachableSymbols &Visitor) = 0;
255
256  virtual void print(Store storeraw_ostream &Outconst charnl) = 0;
257
258  class BindingsHandler {
259  public:
260    virtual ~BindingsHandler();
261
262    /// \return whether the iteration should continue.
263    virtual bool HandleBinding(StoreManagerSMgrStore store,
264                               const MemRegion *regionSVal val) = 0;
265  };
266
267  class FindUniqueBinding : public BindingsHandler {
268    SymbolRef Sym;
269    const MemRegionBinding = nullptr;
270    bool First = true;
271
272  public:
273    FindUniqueBinding(SymbolRef sym) : Sym(sym) {}
274
275    explicit operator bool() { return First && Binding; }
276
277    bool HandleBinding(StoreManagerSMgrStore storeconst MemRegionR,
278                       SVal val) override;
279    const MemRegion *getRegion() { return Binding; }
280  };
281
282  /// iterBindings - Iterate over the bindings in the Store.
283  virtual void iterBindings(Store storeBindingsHandlerf) = 0;
284
285protected:
286  const ElementRegion *MakeElementRegion(const SubRegion *baseRegion,
287                                         QualType pointeeTy,
288                                         uint64_t index = 0);
289
290  /// CastRetrievedVal - Used by subclasses of StoreManager to implement
291  ///  implicit casts that arise from loads from regions that are reinterpreted
292  ///  as another region.
293  SVal CastRetrievedVal(SVal valconst TypedValueRegion *region,
294                        QualType castTy);
295
296private:
297  SVal getLValueFieldOrIvar(const Decl *declSVal base);
298};
299
300inline StoreRef::StoreRef(Store storeStoreManager & smgr)
301    : store(store), mgr(smgr) {
302  if (store)
303    mgr.incrementReferenceCount(store);
304}
305
306inline StoreRef::StoreRef(const StoreRef &sr)
307    : store(sr.store), mgr(sr.mgr)
308{
309  if (store)
310    mgr.incrementReferenceCount(store);
311}
312
313inline StoreRef::~StoreRef() {
314  if (store)
315    mgr.decrementReferenceCount(store);
316}
317
318inline StoreRef &StoreRef::operator=(StoreRef const &newStore) {
319  assert(&newStore.mgr == &mgr);
320  if (store != newStore.store) {
321    mgr.incrementReferenceCount(newStore.store);
322    mgr.decrementReferenceCount(store);
323    store = newStore.getStore();
324  }
325  return *this;
326}
327
328// FIXME: Do we need to pass ProgramStateManager anymore?
329std::unique_ptr<StoreManager>
330CreateRegionStoreManager(ProgramStateManager &StMgr);
331std::unique_ptr<StoreManager>
332CreateFieldsOnlyRegionStoreManager(ProgramStateManager &StMgr);
333
334// namespace ento
335
336// namespace clang
337
338#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_STORE_H
339
clang::ento::StoreManager::svalBuilder
clang::ento::StoreManager::StateMgr
clang::ento::StoreManager::MRMgr
clang::ento::StoreManager::Ctx
clang::ento::StoreManager::getBinding
clang::ento::StoreManager::getDefaultBinding
clang::ento::StoreManager::getDefaultBinding
clang::ento::StoreManager::Bind
clang::ento::StoreManager::BindDefaultInitial
clang::ento::StoreManager::BindDefaultZero
clang::ento::StoreManager::killBinding
clang::ento::StoreManager::getInitialStore
clang::ento::StoreManager::getRegionManager
clang::ento::StoreManager::getSValBuilder
clang::ento::StoreManager::getLValueVar
clang::ento::StoreManager::getLValueCompoundLiteral
clang::ento::StoreManager::getLValueIvar
clang::ento::StoreManager::getLValueField
clang::ento::StoreManager::getLValueElement
clang::ento::StoreManager::getSizeInElements
clang::ento::StoreManager::ArrayToPointer
clang::ento::StoreManager::evalDerivedToBase
clang::ento::StoreManager::evalDerivedToBase
clang::ento::StoreManager::evalDerivedToBase
clang::ento::StoreManager::attemptDownCast
clang::ento::StoreManager::GetElementZeroRegion
clang::ento::StoreManager::castRegion
clang::ento::StoreManager::removeDeadBindings
clang::ento::StoreManager::includedInBindings
clang::ento::StoreManager::incrementReferenceCount
clang::ento::StoreManager::decrementReferenceCount
clang::ento::StoreManager::invalidateRegions
clang::ento::StoreManager::enterStackFrame
clang::ento::StoreManager::scanReachableSymbols
clang::ento::StoreManager::print
clang::ento::StoreManager::BindingsHandler
clang::ento::StoreManager::BindingsHandler::HandleBinding
clang::ento::StoreManager::FindUniqueBinding
clang::ento::StoreManager::FindUniqueBinding::Sym
clang::ento::StoreManager::FindUniqueBinding::Binding
clang::ento::StoreManager::FindUniqueBinding::First
clang::ento::StoreManager::FindUniqueBinding::HandleBinding
clang::ento::StoreManager::FindUniqueBinding::getRegion
clang::ento::StoreManager::iterBindings
clang::ento::StoreManager::MakeElementRegion
clang::ento::StoreManager::CastRetrievedVal
clang::ento::StoreManager::getLValueFieldOrIvar