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
32 namespace clang {
33
34 class ASTContext;
35 class CastExpr;
36 class CompoundLiteralExpr;
37 class CXXBasePath;
38 class Decl;
39 class Expr;
40 class LocationContext;
41 class ObjCIvarDecl;
42 class StackFrameContext;
43
44 namespace ento {
45
46 class CallEvent;
47 class ProgramStateManager;
48 class ScanReachableSymbols;
49 class SymbolReaper;
50
51 using InvalidatedSymbols = llvm::DenseSet<SymbolRef>;
52
53 class StoreManager {
54 protected:
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
64 public:
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 store, Loc loc, QualType 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<SVal> getDefaultBinding(Store store, const 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.
getDefaultBinding(nonloc::LazyCompoundVal lcv)96 Optional<SVal> getDefaultBinding(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 store, Loc loc, SVal 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 store, const 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 store, const 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 ST, Loc 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.
getRegionManager()130 MemRegionManager& getRegionManager() { return MRMgr; }
131
getSValBuilder()132 SValBuilder& getSValBuilder() { return svalBuilder; }
133
getLValueVar(const VarDecl * VD,const LocationContext * LC)134 virtual Loc getLValueVar(const VarDecl *VD, const LocationContext *LC) {
135 return svalBuilder.makeLoc(MRMgr.getVarRegion(VD, LC));
136 }
137
getLValueCompoundLiteral(const CompoundLiteralExpr * CL,const LocationContext * LC)138 Loc getLValueCompoundLiteral(const CompoundLiteralExpr *CL,
139 const LocationContext *LC) {
140 return loc::MemRegionVal(MRMgr.getCompoundLiteralRegion(CL, LC));
141 }
142
143 virtual SVal getLValueIvar(const ObjCIvarDecl *decl, SVal base);
144
getLValueField(const FieldDecl * D,SVal Base)145 virtual SVal getLValueField(const FieldDecl *D, SVal Base) {
146 return getLValueFieldOrIvar(D, Base);
147 }
148
149 virtual SVal getLValueElement(QualType elementType, NonLoc offset, SVal Base);
150
151 /// ArrayToPointer - Used by ExprEngine::VistCast to handle implicit
152 /// conversions between arrays and pointers.
153 virtual SVal ArrayToPointer(Loc Array, QualType ElementTy) = 0;
154
155 /// Evaluates a chain of derived-to-base casts through the path specified in
156 /// \p Cast.
157 SVal evalDerivedToBase(SVal Derived, const CastExpr *Cast);
158
159 /// Evaluates a chain of derived-to-base casts through the specified path.
160 SVal evalDerivedToBase(SVal Derived, const CXXBasePath &CastPath);
161
162 /// Evaluates a derived-to-base cast through a single level of derivation.
163 SVal evalDerivedToBase(SVal Derived, QualType DerivedPtrType,
164 bool IsVirtual);
165
166 /// Attempts to do a down cast. Used to model BaseToDerived and C++
167 /// dynamic_cast.
168 /// The callback may result in the following 3 scenarios:
169 /// - Successful cast (ex: derived is subclass of base).
170 /// - Failed cast (ex: derived is definitely not a subclass of base).
171 /// The distinction of this case from the next one is necessary to model
172 /// dynamic_cast.
173 /// - We don't know (base is a symbolic region and we don't have
174 /// enough info to determine if the cast will succeed at run time).
175 /// The function returns an SVal representing the derived class; it's
176 /// valid only if Failed flag is set to false.
177 SVal attemptDownCast(SVal Base, QualType DerivedPtrType, bool &Failed);
178
179 const ElementRegion *GetElementZeroRegion(const SubRegion *R, QualType T);
180
181 /// castRegion - Used by ExprEngine::VisitCast to handle casts from
182 /// a MemRegion* to a specific location type. 'R' is the region being
183 /// casted and 'CastToTy' the result type of the cast.
184 Optional<const MemRegion *> castRegion(const MemRegion *region,
185 QualType CastToTy);
186
187 virtual StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx,
188 SymbolReaper &SymReaper) = 0;
189
190 virtual bool includedInBindings(Store store,
191 const MemRegion *region) const = 0;
192
193 /// If the StoreManager supports it, increment the reference count of
194 /// the specified Store object.
incrementReferenceCount(Store store)195 virtual void incrementReferenceCount(Store store) {}
196
197 /// If the StoreManager supports it, decrement the reference count of
198 /// the specified Store object. If the reference count hits 0, the memory
199 /// associated with the object is recycled.
decrementReferenceCount(Store store)200 virtual void decrementReferenceCount(Store store) {}
201
202 using InvalidatedRegions = SmallVector<const MemRegion *, 8>;
203
204 /// invalidateRegions - Clears out the specified regions from the store,
205 /// marking their values as unknown. Depending on the store, this may also
206 /// invalidate additional regions that may have changed based on accessing
207 /// the given regions. Optionally, invalidates non-static globals as well.
208 /// \param[in] store The initial store
209 /// \param[in] Values The values to invalidate.
210 /// \param[in] E The current statement being evaluated. Used to conjure
211 /// symbols to mark the values of invalidated regions.
212 /// \param[in] Count The current block count. Used to conjure
213 /// symbols to mark the values of invalidated regions.
214 /// \param[in] Call The call expression which will be used to determine which
215 /// globals should get invalidated.
216 /// \param[in,out] IS A set to fill with any symbols that are no longer
217 /// accessible. Pass \c NULL if this information will not be used.
218 /// \param[in] ITraits Information about invalidation for a particular
219 /// region/symbol.
220 /// \param[in,out] InvalidatedTopLevel A vector to fill with regions
221 //// explicitly being invalidated. Pass \c NULL if this
222 /// information will not be used.
223 /// \param[in,out] Invalidated A vector to fill with any regions being
224 /// invalidated. This should include any regions explicitly invalidated
225 /// even if they do not currently have bindings. Pass \c NULL if this
226 /// information will not be used.
227 virtual StoreRef invalidateRegions(Store store,
228 ArrayRef<SVal> Values,
229 const Expr *E, unsigned Count,
230 const LocationContext *LCtx,
231 const CallEvent *Call,
232 InvalidatedSymbols &IS,
233 RegionAndSymbolInvalidationTraits &ITraits,
234 InvalidatedRegions *InvalidatedTopLevel,
235 InvalidatedRegions *Invalidated) = 0;
236
237 /// enterStackFrame - Let the StoreManager to do something when execution
238 /// engine is about to execute into a callee.
239 StoreRef enterStackFrame(Store store,
240 const CallEvent &Call,
241 const StackFrameContext *CalleeCtx);
242
243 /// Finds the transitive closure of symbols within the given region.
244 ///
245 /// Returns false if the visitor aborted the scan.
246 virtual bool scanReachableSymbols(Store S, const MemRegion *R,
247 ScanReachableSymbols &Visitor) = 0;
248
249 virtual void printJson(raw_ostream &Out, Store S, const char *NL,
250 unsigned int Space, bool IsDot) const = 0;
251
252 class BindingsHandler {
253 public:
254 virtual ~BindingsHandler();
255
256 /// \return whether the iteration should continue.
257 virtual bool HandleBinding(StoreManager& SMgr, Store store,
258 const MemRegion *region, SVal val) = 0;
259 };
260
261 class FindUniqueBinding : public BindingsHandler {
262 SymbolRef Sym;
263 const MemRegion* Binding = nullptr;
264 bool First = true;
265
266 public:
FindUniqueBinding(SymbolRef sym)267 FindUniqueBinding(SymbolRef sym) : Sym(sym) {}
268
269 explicit operator bool() { return First && Binding; }
270
271 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
272 SVal val) override;
getRegion()273 const MemRegion *getRegion() { return Binding; }
274 };
275
276 /// iterBindings - Iterate over the bindings in the Store.
277 virtual void iterBindings(Store store, BindingsHandler& f) = 0;
278
279 protected:
280 const ElementRegion *MakeElementRegion(const SubRegion *baseRegion,
281 QualType pointeeTy,
282 uint64_t index = 0);
283
284 private:
285 SVal getLValueFieldOrIvar(const Decl *decl, SVal base);
286 };
287
StoreRef(Store store,StoreManager & smgr)288 inline StoreRef::StoreRef(Store store, StoreManager & smgr)
289 : store(store), mgr(smgr) {
290 if (store)
291 mgr.incrementReferenceCount(store);
292 }
293
StoreRef(const StoreRef & sr)294 inline StoreRef::StoreRef(const StoreRef &sr)
295 : store(sr.store), mgr(sr.mgr)
296 {
297 if (store)
298 mgr.incrementReferenceCount(store);
299 }
300
~StoreRef()301 inline StoreRef::~StoreRef() {
302 if (store)
303 mgr.decrementReferenceCount(store);
304 }
305
306 inline StoreRef &StoreRef::operator=(StoreRef const &newStore) {
307 assert(&newStore.mgr == &mgr);
308 if (store != newStore.store) {
309 mgr.incrementReferenceCount(newStore.store);
310 mgr.decrementReferenceCount(store);
311 store = newStore.getStore();
312 }
313 return *this;
314 }
315
316 // FIXME: Do we need to pass ProgramStateManager anymore?
317 std::unique_ptr<StoreManager>
318 CreateRegionStoreManager(ProgramStateManager &StMgr);
319 std::unique_ptr<StoreManager>
320 CreateFieldsOnlyRegionStoreManager(ProgramStateManager &StMgr);
321
322 } // namespace ento
323
324 } // namespace clang
325
326 #endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_STORE_H
327