1 //== ProgramState.h - Path-sensitive "State" for tracking 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 defines the state of the program along the analysisa path.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATE_H
14 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATE_H
15
16 #include "clang/Basic/LLVM.h"
17 #include "clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/Environment.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
23 #include "llvm/ADT/FoldingSet.h"
24 #include "llvm/ADT/ImmutableMap.h"
25 #include "llvm/Support/Allocator.h"
26 #include <utility>
27
28 namespace llvm {
29 class APSInt;
30 }
31
32 namespace clang {
33 class ASTContext;
34
35 namespace ento {
36
37 class AnalysisManager;
38 class CallEvent;
39 class CallEventManager;
40
41 typedef std::unique_ptr<ConstraintManager>(*ConstraintManagerCreator)(
42 ProgramStateManager &, SubEngine *);
43 typedef std::unique_ptr<StoreManager>(*StoreManagerCreator)(
44 ProgramStateManager &);
45
46 //===----------------------------------------------------------------------===//
47 // ProgramStateTrait - Traits used by the Generic Data Map of a ProgramState.
48 //===----------------------------------------------------------------------===//
49
50 template <typename T> struct ProgramStatePartialTrait;
51
52 template <typename T> struct ProgramStateTrait {
53 typedef typename T::data_type data_type;
MakeVoidPtrProgramStateTrait54 static inline void *MakeVoidPtr(data_type D) { return (void*) D; }
MakeDataProgramStateTrait55 static inline data_type MakeData(void *const* P) {
56 return P ? (data_type) *P : (data_type) 0;
57 }
58 };
59
60 /// \class ProgramState
61 /// ProgramState - This class encapsulates:
62 ///
63 /// 1. A mapping from expressions to values (Environment)
64 /// 2. A mapping from locations to values (Store)
65 /// 3. Constraints on symbolic values (GenericDataMap)
66 ///
67 /// Together these represent the "abstract state" of a program.
68 ///
69 /// ProgramState is intended to be used as a functional object; that is,
70 /// once it is created and made "persistent" in a FoldingSet, its
71 /// values will never change.
72 class ProgramState : public llvm::FoldingSetNode {
73 public:
74 typedef llvm::ImmutableSet<llvm::APSInt*> IntSetTy;
75 typedef llvm::ImmutableMap<void*, void*> GenericDataMap;
76
77 private:
78 void operator=(const ProgramState& R) = delete;
79
80 friend class ProgramStateManager;
81 friend class ExplodedGraph;
82 friend class ExplodedNode;
83
84 ProgramStateManager *stateMgr;
85 Environment Env; // Maps a Stmt to its current SVal.
86 Store store; // Maps a location to its current value.
87 GenericDataMap GDM; // Custom data stored by a client of this class.
88 unsigned refCount;
89
90 /// makeWithStore - Return a ProgramState with the same values as the current
91 /// state with the exception of using the specified Store.
92 ProgramStateRef makeWithStore(const StoreRef &store) const;
93
94 void setStore(const StoreRef &storeRef);
95
96 public:
97 /// This ctor is used when creating the first ProgramState object.
98 ProgramState(ProgramStateManager *mgr, const Environment& env,
99 StoreRef st, GenericDataMap gdm);
100
101 /// Copy ctor - We must explicitly define this or else the "Next" ptr
102 /// in FoldingSetNode will also get copied.
103 ProgramState(const ProgramState &RHS);
104
105 ~ProgramState();
106
107 int64_t getID() const;
108
109 /// Return the ProgramStateManager associated with this state.
getStateManager()110 ProgramStateManager &getStateManager() const {
111 return *stateMgr;
112 }
113
114 AnalysisManager &getAnalysisManager() const;
115
116 /// Return the ConstraintManager.
117 ConstraintManager &getConstraintManager() const;
118
119 /// getEnvironment - Return the environment associated with this state.
120 /// The environment is the mapping from expressions to values.
getEnvironment()121 const Environment& getEnvironment() const { return Env; }
122
123 /// Return the store associated with this state. The store
124 /// is a mapping from locations to values.
getStore()125 Store getStore() const { return store; }
126
127
128 /// getGDM - Return the generic data map associated with this state.
getGDM()129 GenericDataMap getGDM() const { return GDM; }
130
setGDM(GenericDataMap gdm)131 void setGDM(GenericDataMap gdm) { GDM = gdm; }
132
133 /// Profile - Profile the contents of a ProgramState object for use in a
134 /// FoldingSet. Two ProgramState objects are considered equal if they
135 /// have the same Environment, Store, and GenericDataMap.
Profile(llvm::FoldingSetNodeID & ID,const ProgramState * V)136 static void Profile(llvm::FoldingSetNodeID& ID, const ProgramState *V) {
137 V->Env.Profile(ID);
138 ID.AddPointer(V->store);
139 V->GDM.Profile(ID);
140 }
141
142 /// Profile - Used to profile the contents of this object for inclusion
143 /// in a FoldingSet.
Profile(llvm::FoldingSetNodeID & ID)144 void Profile(llvm::FoldingSetNodeID& ID) const {
145 Profile(ID, this);
146 }
147
148 BasicValueFactory &getBasicVals() const;
149 SymbolManager &getSymbolManager() const;
150
151 //==---------------------------------------------------------------------==//
152 // Constraints on values.
153 //==---------------------------------------------------------------------==//
154 //
155 // Each ProgramState records constraints on symbolic values. These constraints
156 // are managed using the ConstraintManager associated with a ProgramStateManager.
157 // As constraints gradually accrue on symbolic values, added constraints
158 // may conflict and indicate that a state is infeasible (as no real values
159 // could satisfy all the constraints). This is the principal mechanism
160 // for modeling path-sensitivity in ExprEngine/ProgramState.
161 //
162 // Various "assume" methods form the interface for adding constraints to
163 // symbolic values. A call to 'assume' indicates an assumption being placed
164 // on one or symbolic values. 'assume' methods take the following inputs:
165 //
166 // (1) A ProgramState object representing the current state.
167 //
168 // (2) The assumed constraint (which is specific to a given "assume" method).
169 //
170 // (3) A binary value "Assumption" that indicates whether the constraint is
171 // assumed to be true or false.
172 //
173 // The output of "assume*" is a new ProgramState object with the added constraints.
174 // If no new state is feasible, NULL is returned.
175 //
176
177 /// Assumes that the value of \p cond is zero (if \p assumption is "false")
178 /// or non-zero (if \p assumption is "true").
179 ///
180 /// This returns a new state with the added constraint on \p cond.
181 /// If no new state is feasible, NULL is returned.
182 LLVM_NODISCARD ProgramStateRef assume(DefinedOrUnknownSVal cond,
183 bool assumption) const;
184
185 /// Assumes both "true" and "false" for \p cond, and returns both
186 /// corresponding states (respectively).
187 ///
188 /// This is more efficient than calling assume() twice. Note that one (but not
189 /// both) of the returned states may be NULL.
190 LLVM_NODISCARD std::pair<ProgramStateRef, ProgramStateRef>
191 assume(DefinedOrUnknownSVal cond) const;
192
193 LLVM_NODISCARD ProgramStateRef
194 assumeInBound(DefinedOrUnknownSVal idx, DefinedOrUnknownSVal upperBound,
195 bool assumption, QualType IndexType = QualType()) const;
196
197 /// Assumes that the value of \p Val is bounded with [\p From; \p To]
198 /// (if \p assumption is "true") or it is fully out of this range
199 /// (if \p assumption is "false").
200 ///
201 /// This returns a new state with the added constraint on \p cond.
202 /// If no new state is feasible, NULL is returned.
203 LLVM_NODISCARD ProgramStateRef assumeInclusiveRange(DefinedOrUnknownSVal Val,
204 const llvm::APSInt &From,
205 const llvm::APSInt &To,
206 bool assumption) const;
207
208 /// Assumes given range both "true" and "false" for \p Val, and returns both
209 /// corresponding states (respectively).
210 ///
211 /// This is more efficient than calling assume() twice. Note that one (but not
212 /// both) of the returned states may be NULL.
213 LLVM_NODISCARD std::pair<ProgramStateRef, ProgramStateRef>
214 assumeInclusiveRange(DefinedOrUnknownSVal Val, const llvm::APSInt &From,
215 const llvm::APSInt &To) const;
216
217 /// Check if the given SVal is not constrained to zero and is not
218 /// a zero constant.
219 ConditionTruthVal isNonNull(SVal V) const;
220
221 /// Check if the given SVal is constrained to zero or is a zero
222 /// constant.
223 ConditionTruthVal isNull(SVal V) const;
224
225 /// \return Whether values \p Lhs and \p Rhs are equal.
226 ConditionTruthVal areEqual(SVal Lhs, SVal Rhs) const;
227
228 /// Utility method for getting regions.
229 const VarRegion* getRegion(const VarDecl *D, const LocationContext *LC) const;
230
231 //==---------------------------------------------------------------------==//
232 // Binding and retrieving values to/from the environment and symbolic store.
233 //==---------------------------------------------------------------------==//
234
235 /// Create a new state by binding the value 'V' to the statement 'S' in the
236 /// state's environment.
237 LLVM_NODISCARD ProgramStateRef BindExpr(const Stmt *S,
238 const LocationContext *LCtx, SVal V,
239 bool Invalidate = true) const;
240
241 LLVM_NODISCARD ProgramStateRef bindLoc(Loc location, SVal V,
242 const LocationContext *LCtx,
243 bool notifyChanges = true) const;
244
245 LLVM_NODISCARD ProgramStateRef bindLoc(SVal location, SVal V,
246 const LocationContext *LCtx) const;
247
248 /// Initializes the region of memory represented by \p loc with an initial
249 /// value. Once initialized, all values loaded from any sub-regions of that
250 /// region will be equal to \p V, unless overwritten later by the program.
251 /// This method should not be used on regions that are already initialized.
252 /// If you need to indicate that memory contents have suddenly become unknown
253 /// within a certain region of memory, consider invalidateRegions().
254 LLVM_NODISCARD ProgramStateRef
255 bindDefaultInitial(SVal loc, SVal V, const LocationContext *LCtx) const;
256
257 /// Performs C++ zero-initialization procedure on the region of memory
258 /// represented by \p loc.
259 LLVM_NODISCARD ProgramStateRef
260 bindDefaultZero(SVal loc, const LocationContext *LCtx) const;
261
262 LLVM_NODISCARD ProgramStateRef killBinding(Loc LV) const;
263
264 /// Returns the state with bindings for the given regions
265 /// cleared from the store.
266 ///
267 /// Optionally invalidates global regions as well.
268 ///
269 /// \param Regions the set of regions to be invalidated.
270 /// \param E the expression that caused the invalidation.
271 /// \param BlockCount The number of times the current basic block has been
272 // visited.
273 /// \param CausesPointerEscape the flag is set to true when
274 /// the invalidation entails escape of a symbol (representing a
275 /// pointer). For example, due to it being passed as an argument in a
276 /// call.
277 /// \param IS the set of invalidated symbols.
278 /// \param Call if non-null, the invalidated regions represent parameters to
279 /// the call and should be considered directly invalidated.
280 /// \param ITraits information about special handling for a particular
281 /// region/symbol.
282 LLVM_NODISCARD ProgramStateRef
283 invalidateRegions(ArrayRef<const MemRegion *> Regions, const Expr *E,
284 unsigned BlockCount, const LocationContext *LCtx,
285 bool CausesPointerEscape, InvalidatedSymbols *IS = nullptr,
286 const CallEvent *Call = nullptr,
287 RegionAndSymbolInvalidationTraits *ITraits = nullptr) const;
288
289 LLVM_NODISCARD ProgramStateRef
290 invalidateRegions(ArrayRef<SVal> Regions, const Expr *E,
291 unsigned BlockCount, const LocationContext *LCtx,
292 bool CausesPointerEscape, InvalidatedSymbols *IS = nullptr,
293 const CallEvent *Call = nullptr,
294 RegionAndSymbolInvalidationTraits *ITraits = nullptr) const;
295
296 /// enterStackFrame - Returns the state for entry to the given stack frame,
297 /// preserving the current state.
298 LLVM_NODISCARD ProgramStateRef enterStackFrame(
299 const CallEvent &Call, const StackFrameContext *CalleeCtx) const;
300
301 /// Get the lvalue for a base class object reference.
302 Loc getLValue(const CXXBaseSpecifier &BaseSpec, const SubRegion *Super) const;
303
304 /// Get the lvalue for a base class object reference.
305 Loc getLValue(const CXXRecordDecl *BaseClass, const SubRegion *Super,
306 bool IsVirtual) const;
307
308 /// Get the lvalue for a variable reference.
309 Loc getLValue(const VarDecl *D, const LocationContext *LC) const;
310
311 Loc getLValue(const CompoundLiteralExpr *literal,
312 const LocationContext *LC) const;
313
314 /// Get the lvalue for an ivar reference.
315 SVal getLValue(const ObjCIvarDecl *decl, SVal base) const;
316
317 /// Get the lvalue for a field reference.
318 SVal getLValue(const FieldDecl *decl, SVal Base) const;
319
320 /// Get the lvalue for an indirect field reference.
321 SVal getLValue(const IndirectFieldDecl *decl, SVal Base) const;
322
323 /// Get the lvalue for an array index.
324 SVal getLValue(QualType ElementType, SVal Idx, SVal Base) const;
325
326 /// Returns the SVal bound to the statement 'S' in the state's environment.
327 SVal getSVal(const Stmt *S, const LocationContext *LCtx) const;
328
329 SVal getSValAsScalarOrLoc(const Stmt *Ex, const LocationContext *LCtx) const;
330
331 /// Return the value bound to the specified location.
332 /// Returns UnknownVal() if none found.
333 SVal getSVal(Loc LV, QualType T = QualType()) const;
334
335 /// Returns the "raw" SVal bound to LV before any value simplfication.
336 SVal getRawSVal(Loc LV, QualType T= QualType()) const;
337
338 /// Return the value bound to the specified location.
339 /// Returns UnknownVal() if none found.
340 SVal getSVal(const MemRegion* R, QualType T = QualType()) const;
341
342 /// Return the value bound to the specified location, assuming
343 /// that the value is a scalar integer or an enumeration or a pointer.
344 /// Returns UnknownVal() if none found or the region is not known to hold
345 /// a value of such type.
346 SVal getSValAsScalarOrLoc(const MemRegion *R) const;
347
348 using region_iterator = const MemRegion **;
349
350 /// Visits the symbols reachable from the given SVal using the provided
351 /// SymbolVisitor.
352 ///
353 /// This is a convenience API. Consider using ScanReachableSymbols class
354 /// directly when making multiple scans on the same state with the same
355 /// visitor to avoid repeated initialization cost.
356 /// \sa ScanReachableSymbols
357 bool scanReachableSymbols(SVal val, SymbolVisitor& visitor) const;
358
359 /// Visits the symbols reachable from the regions in the given
360 /// MemRegions range using the provided SymbolVisitor.
361 bool scanReachableSymbols(llvm::iterator_range<region_iterator> Reachable,
362 SymbolVisitor &visitor) const;
363
364 template <typename CB> CB scanReachableSymbols(SVal val) const;
365 template <typename CB> CB
366 scanReachableSymbols(llvm::iterator_range<region_iterator> Reachable) const;
367
368 //==---------------------------------------------------------------------==//
369 // Accessing the Generic Data Map (GDM).
370 //==---------------------------------------------------------------------==//
371
372 void *const* FindGDM(void *K) const;
373
374 template <typename T>
375 LLVM_NODISCARD ProgramStateRef
376 add(typename ProgramStateTrait<T>::key_type K) const;
377
378 template <typename T>
379 typename ProgramStateTrait<T>::data_type
get()380 get() const {
381 return ProgramStateTrait<T>::MakeData(FindGDM(ProgramStateTrait<T>::GDMIndex()));
382 }
383
384 template<typename T>
385 typename ProgramStateTrait<T>::lookup_type
get(typename ProgramStateTrait<T>::key_type key)386 get(typename ProgramStateTrait<T>::key_type key) const {
387 void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
388 return ProgramStateTrait<T>::Lookup(ProgramStateTrait<T>::MakeData(d), key);
389 }
390
391 template <typename T>
392 typename ProgramStateTrait<T>::context_type get_context() const;
393
394 template <typename T>
395 LLVM_NODISCARD ProgramStateRef
396 remove(typename ProgramStateTrait<T>::key_type K) const;
397
398 template <typename T>
399 LLVM_NODISCARD ProgramStateRef
400 remove(typename ProgramStateTrait<T>::key_type K,
401 typename ProgramStateTrait<T>::context_type C) const;
402
403 template <typename T> LLVM_NODISCARD ProgramStateRef remove() const;
404
405 template <typename T>
406 LLVM_NODISCARD ProgramStateRef
407 set(typename ProgramStateTrait<T>::data_type D) const;
408
409 template <typename T>
410 LLVM_NODISCARD ProgramStateRef
411 set(typename ProgramStateTrait<T>::key_type K,
412 typename ProgramStateTrait<T>::value_type E) const;
413
414 template <typename T>
415 LLVM_NODISCARD ProgramStateRef
416 set(typename ProgramStateTrait<T>::key_type K,
417 typename ProgramStateTrait<T>::value_type E,
418 typename ProgramStateTrait<T>::context_type C) const;
419
420 template<typename T>
contains(typename ProgramStateTrait<T>::key_type key)421 bool contains(typename ProgramStateTrait<T>::key_type key) const {
422 void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
423 return ProgramStateTrait<T>::Contains(ProgramStateTrait<T>::MakeData(d), key);
424 }
425
426 // Pretty-printing.
427 void printJson(raw_ostream &Out, const LocationContext *LCtx = nullptr,
428 const char *NL = "\n", unsigned int Space = 0,
429 bool IsDot = false) const;
430
431 void printDOT(raw_ostream &Out, const LocationContext *LCtx = nullptr,
432 unsigned int Space = 0) const;
433
434 void dump() const;
435
436 private:
437 friend void ProgramStateRetain(const ProgramState *state);
438 friend void ProgramStateRelease(const ProgramState *state);
439
440 /// \sa invalidateValues()
441 /// \sa invalidateRegions()
442 ProgramStateRef
443 invalidateRegionsImpl(ArrayRef<SVal> Values,
444 const Expr *E, unsigned BlockCount,
445 const LocationContext *LCtx,
446 bool ResultsInSymbolEscape,
447 InvalidatedSymbols *IS,
448 RegionAndSymbolInvalidationTraits *HTraits,
449 const CallEvent *Call) const;
450 };
451
452 //===----------------------------------------------------------------------===//
453 // ProgramStateManager - Factory object for ProgramStates.
454 //===----------------------------------------------------------------------===//
455
456 class ProgramStateManager {
457 friend class ProgramState;
458 friend void ProgramStateRelease(const ProgramState *state);
459 private:
460 /// Eng - The SubEngine that owns this state manager.
461 SubEngine *Eng; /* Can be null. */
462
463 EnvironmentManager EnvMgr;
464 std::unique_ptr<StoreManager> StoreMgr;
465 std::unique_ptr<ConstraintManager> ConstraintMgr;
466
467 ProgramState::GenericDataMap::Factory GDMFactory;
468
469 typedef llvm::DenseMap<void*,std::pair<void*,void (*)(void*)> > GDMContextsTy;
470 GDMContextsTy GDMContexts;
471
472 /// StateSet - FoldingSet containing all the states created for analyzing
473 /// a particular function. This is used to unique states.
474 llvm::FoldingSet<ProgramState> StateSet;
475
476 /// Object that manages the data for all created SVals.
477 std::unique_ptr<SValBuilder> svalBuilder;
478
479 /// Manages memory for created CallEvents.
480 std::unique_ptr<CallEventManager> CallEventMgr;
481
482 /// A BumpPtrAllocator to allocate states.
483 llvm::BumpPtrAllocator &Alloc;
484
485 /// A vector of ProgramStates that we can reuse.
486 std::vector<ProgramState *> freeStates;
487
488 public:
489 ProgramStateManager(ASTContext &Ctx,
490 StoreManagerCreator CreateStoreManager,
491 ConstraintManagerCreator CreateConstraintManager,
492 llvm::BumpPtrAllocator& alloc,
493 SubEngine *subeng);
494
495 ~ProgramStateManager();
496
497 ProgramStateRef getInitialState(const LocationContext *InitLoc);
498
getContext()499 ASTContext &getContext() { return svalBuilder->getContext(); }
getContext()500 const ASTContext &getContext() const { return svalBuilder->getContext(); }
501
getBasicVals()502 BasicValueFactory &getBasicVals() {
503 return svalBuilder->getBasicValueFactory();
504 }
505
getSValBuilder()506 SValBuilder &getSValBuilder() {
507 return *svalBuilder;
508 }
509
getSValBuilder()510 const SValBuilder &getSValBuilder() const {
511 return *svalBuilder;
512 }
513
getSymbolManager()514 SymbolManager &getSymbolManager() {
515 return svalBuilder->getSymbolManager();
516 }
getSymbolManager()517 const SymbolManager &getSymbolManager() const {
518 return svalBuilder->getSymbolManager();
519 }
520
getAllocator()521 llvm::BumpPtrAllocator& getAllocator() { return Alloc; }
522
getRegionManager()523 MemRegionManager& getRegionManager() {
524 return svalBuilder->getRegionManager();
525 }
getRegionManager()526 const MemRegionManager &getRegionManager() const {
527 return svalBuilder->getRegionManager();
528 }
529
getCallEventManager()530 CallEventManager &getCallEventManager() { return *CallEventMgr; }
531
getStoreManager()532 StoreManager &getStoreManager() { return *StoreMgr; }
getConstraintManager()533 ConstraintManager &getConstraintManager() { return *ConstraintMgr; }
getOwningEngine()534 SubEngine &getOwningEngine() { return *Eng; }
535
536 ProgramStateRef
537 removeDeadBindingsFromEnvironmentAndStore(ProgramStateRef St,
538 const StackFrameContext *LCtx,
539 SymbolReaper &SymReaper);
540
541 public:
542
ArrayToPointer(Loc Array,QualType ElementTy)543 SVal ArrayToPointer(Loc Array, QualType ElementTy) {
544 return StoreMgr->ArrayToPointer(Array, ElementTy);
545 }
546
547 // Methods that manipulate the GDM.
548 ProgramStateRef addGDM(ProgramStateRef St, void *Key, void *Data);
549 ProgramStateRef removeGDM(ProgramStateRef state, void *Key);
550
551 // Methods that query & manipulate the Store.
552
iterBindings(ProgramStateRef state,StoreManager::BindingsHandler & F)553 void iterBindings(ProgramStateRef state, StoreManager::BindingsHandler& F) {
554 StoreMgr->iterBindings(state->getStore(), F);
555 }
556
557 ProgramStateRef getPersistentState(ProgramState &Impl);
558 ProgramStateRef getPersistentStateWithGDM(ProgramStateRef FromState,
559 ProgramStateRef GDMState);
560
haveEqualConstraints(ProgramStateRef S1,ProgramStateRef S2)561 bool haveEqualConstraints(ProgramStateRef S1, ProgramStateRef S2) const {
562 return ConstraintMgr->haveEqualConstraints(S1, S2);
563 }
564
haveEqualEnvironments(ProgramStateRef S1,ProgramStateRef S2)565 bool haveEqualEnvironments(ProgramStateRef S1, ProgramStateRef S2) const {
566 return S1->Env == S2->Env;
567 }
568
haveEqualStores(ProgramStateRef S1,ProgramStateRef S2)569 bool haveEqualStores(ProgramStateRef S1, ProgramStateRef S2) const {
570 return S1->store == S2->store;
571 }
572
573 //==---------------------------------------------------------------------==//
574 // Generic Data Map methods.
575 //==---------------------------------------------------------------------==//
576 //
577 // ProgramStateManager and ProgramState support a "generic data map" that allows
578 // different clients of ProgramState objects to embed arbitrary data within a
579 // ProgramState object. The generic data map is essentially an immutable map
580 // from a "tag" (that acts as the "key" for a client) and opaque values.
581 // Tags/keys and values are simply void* values. The typical way that clients
582 // generate unique tags are by taking the address of a static variable.
583 // Clients are responsible for ensuring that data values referred to by a
584 // the data pointer are immutable (and thus are essentially purely functional
585 // data).
586 //
587 // The templated methods below use the ProgramStateTrait<T> class
588 // to resolve keys into the GDM and to return data values to clients.
589 //
590
591 // Trait based GDM dispatch.
592 template <typename T>
set(ProgramStateRef st,typename ProgramStateTrait<T>::data_type D)593 ProgramStateRef set(ProgramStateRef st, typename ProgramStateTrait<T>::data_type D) {
594 return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
595 ProgramStateTrait<T>::MakeVoidPtr(D));
596 }
597
598 template<typename T>
set(ProgramStateRef st,typename ProgramStateTrait<T>::key_type K,typename ProgramStateTrait<T>::value_type V,typename ProgramStateTrait<T>::context_type C)599 ProgramStateRef set(ProgramStateRef st,
600 typename ProgramStateTrait<T>::key_type K,
601 typename ProgramStateTrait<T>::value_type V,
602 typename ProgramStateTrait<T>::context_type C) {
603
604 return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
605 ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Set(st->get<T>(), K, V, C)));
606 }
607
608 template <typename T>
add(ProgramStateRef st,typename ProgramStateTrait<T>::key_type K,typename ProgramStateTrait<T>::context_type C)609 ProgramStateRef add(ProgramStateRef st,
610 typename ProgramStateTrait<T>::key_type K,
611 typename ProgramStateTrait<T>::context_type C) {
612 return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
613 ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Add(st->get<T>(), K, C)));
614 }
615
616 template <typename T>
remove(ProgramStateRef st,typename ProgramStateTrait<T>::key_type K,typename ProgramStateTrait<T>::context_type C)617 ProgramStateRef remove(ProgramStateRef st,
618 typename ProgramStateTrait<T>::key_type K,
619 typename ProgramStateTrait<T>::context_type C) {
620
621 return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
622 ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Remove(st->get<T>(), K, C)));
623 }
624
625 template <typename T>
remove(ProgramStateRef st)626 ProgramStateRef remove(ProgramStateRef st) {
627 return removeGDM(st, ProgramStateTrait<T>::GDMIndex());
628 }
629
630 void *FindGDMContext(void *index,
631 void *(*CreateContext)(llvm::BumpPtrAllocator&),
632 void (*DeleteContext)(void*));
633
634 template <typename T>
get_context()635 typename ProgramStateTrait<T>::context_type get_context() {
636 void *p = FindGDMContext(ProgramStateTrait<T>::GDMIndex(),
637 ProgramStateTrait<T>::CreateContext,
638 ProgramStateTrait<T>::DeleteContext);
639
640 return ProgramStateTrait<T>::MakeContext(p);
641 }
642 };
643
644
645 //===----------------------------------------------------------------------===//
646 // Out-of-line method definitions for ProgramState.
647 //===----------------------------------------------------------------------===//
648
getConstraintManager()649 inline ConstraintManager &ProgramState::getConstraintManager() const {
650 return stateMgr->getConstraintManager();
651 }
652
getRegion(const VarDecl * D,const LocationContext * LC)653 inline const VarRegion* ProgramState::getRegion(const VarDecl *D,
654 const LocationContext *LC) const
655 {
656 return getStateManager().getRegionManager().getVarRegion(D, LC);
657 }
658
assume(DefinedOrUnknownSVal Cond,bool Assumption)659 inline ProgramStateRef ProgramState::assume(DefinedOrUnknownSVal Cond,
660 bool Assumption) const {
661 if (Cond.isUnknown())
662 return this;
663
664 return getStateManager().ConstraintMgr
665 ->assume(this, Cond.castAs<DefinedSVal>(), Assumption);
666 }
667
668 inline std::pair<ProgramStateRef , ProgramStateRef >
assume(DefinedOrUnknownSVal Cond)669 ProgramState::assume(DefinedOrUnknownSVal Cond) const {
670 if (Cond.isUnknown())
671 return std::make_pair(this, this);
672
673 return getStateManager().ConstraintMgr
674 ->assumeDual(this, Cond.castAs<DefinedSVal>());
675 }
676
assumeInclusiveRange(DefinedOrUnknownSVal Val,const llvm::APSInt & From,const llvm::APSInt & To,bool Assumption)677 inline ProgramStateRef ProgramState::assumeInclusiveRange(
678 DefinedOrUnknownSVal Val, const llvm::APSInt &From, const llvm::APSInt &To,
679 bool Assumption) const {
680 if (Val.isUnknown())
681 return this;
682
683 assert(Val.getAs<NonLoc>() && "Only NonLocs are supported!");
684
685 return getStateManager().ConstraintMgr->assumeInclusiveRange(
686 this, Val.castAs<NonLoc>(), From, To, Assumption);
687 }
688
689 inline std::pair<ProgramStateRef, ProgramStateRef>
assumeInclusiveRange(DefinedOrUnknownSVal Val,const llvm::APSInt & From,const llvm::APSInt & To)690 ProgramState::assumeInclusiveRange(DefinedOrUnknownSVal Val,
691 const llvm::APSInt &From,
692 const llvm::APSInt &To) const {
693 if (Val.isUnknown())
694 return std::make_pair(this, this);
695
696 assert(Val.getAs<NonLoc>() && "Only NonLocs are supported!");
697
698 return getStateManager().ConstraintMgr->assumeInclusiveRangeDual(
699 this, Val.castAs<NonLoc>(), From, To);
700 }
701
bindLoc(SVal LV,SVal V,const LocationContext * LCtx)702 inline ProgramStateRef ProgramState::bindLoc(SVal LV, SVal V, const LocationContext *LCtx) const {
703 if (Optional<Loc> L = LV.getAs<Loc>())
704 return bindLoc(*L, V, LCtx);
705 return this;
706 }
707
getLValue(const CXXBaseSpecifier & BaseSpec,const SubRegion * Super)708 inline Loc ProgramState::getLValue(const CXXBaseSpecifier &BaseSpec,
709 const SubRegion *Super) const {
710 const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl();
711 return loc::MemRegionVal(
712 getStateManager().getRegionManager().getCXXBaseObjectRegion(
713 Base, Super, BaseSpec.isVirtual()));
714 }
715
getLValue(const CXXRecordDecl * BaseClass,const SubRegion * Super,bool IsVirtual)716 inline Loc ProgramState::getLValue(const CXXRecordDecl *BaseClass,
717 const SubRegion *Super,
718 bool IsVirtual) const {
719 return loc::MemRegionVal(
720 getStateManager().getRegionManager().getCXXBaseObjectRegion(
721 BaseClass, Super, IsVirtual));
722 }
723
getLValue(const VarDecl * VD,const LocationContext * LC)724 inline Loc ProgramState::getLValue(const VarDecl *VD,
725 const LocationContext *LC) const {
726 return getStateManager().StoreMgr->getLValueVar(VD, LC);
727 }
728
getLValue(const CompoundLiteralExpr * literal,const LocationContext * LC)729 inline Loc ProgramState::getLValue(const CompoundLiteralExpr *literal,
730 const LocationContext *LC) const {
731 return getStateManager().StoreMgr->getLValueCompoundLiteral(literal, LC);
732 }
733
getLValue(const ObjCIvarDecl * D,SVal Base)734 inline SVal ProgramState::getLValue(const ObjCIvarDecl *D, SVal Base) const {
735 return getStateManager().StoreMgr->getLValueIvar(D, Base);
736 }
737
getLValue(const FieldDecl * D,SVal Base)738 inline SVal ProgramState::getLValue(const FieldDecl *D, SVal Base) const {
739 return getStateManager().StoreMgr->getLValueField(D, Base);
740 }
741
getLValue(const IndirectFieldDecl * D,SVal Base)742 inline SVal ProgramState::getLValue(const IndirectFieldDecl *D,
743 SVal Base) const {
744 StoreManager &SM = *getStateManager().StoreMgr;
745 for (const auto *I : D->chain()) {
746 Base = SM.getLValueField(cast<FieldDecl>(I), Base);
747 }
748
749 return Base;
750 }
751
getLValue(QualType ElementType,SVal Idx,SVal Base)752 inline SVal ProgramState::getLValue(QualType ElementType, SVal Idx, SVal Base) const{
753 if (Optional<NonLoc> N = Idx.getAs<NonLoc>())
754 return getStateManager().StoreMgr->getLValueElement(ElementType, *N, Base);
755 return UnknownVal();
756 }
757
getSVal(const Stmt * Ex,const LocationContext * LCtx)758 inline SVal ProgramState::getSVal(const Stmt *Ex,
759 const LocationContext *LCtx) const{
760 return Env.getSVal(EnvironmentEntry(Ex, LCtx),
761 *getStateManager().svalBuilder);
762 }
763
764 inline SVal
getSValAsScalarOrLoc(const Stmt * S,const LocationContext * LCtx)765 ProgramState::getSValAsScalarOrLoc(const Stmt *S,
766 const LocationContext *LCtx) const {
767 if (const Expr *Ex = dyn_cast<Expr>(S)) {
768 QualType T = Ex->getType();
769 if (Ex->isGLValue() || Loc::isLocType(T) ||
770 T->isIntegralOrEnumerationType())
771 return getSVal(S, LCtx);
772 }
773
774 return UnknownVal();
775 }
776
getRawSVal(Loc LV,QualType T)777 inline SVal ProgramState::getRawSVal(Loc LV, QualType T) const {
778 return getStateManager().StoreMgr->getBinding(getStore(), LV, T);
779 }
780
getSVal(const MemRegion * R,QualType T)781 inline SVal ProgramState::getSVal(const MemRegion* R, QualType T) const {
782 return getStateManager().StoreMgr->getBinding(getStore(),
783 loc::MemRegionVal(R),
784 T);
785 }
786
getBasicVals()787 inline BasicValueFactory &ProgramState::getBasicVals() const {
788 return getStateManager().getBasicVals();
789 }
790
getSymbolManager()791 inline SymbolManager &ProgramState::getSymbolManager() const {
792 return getStateManager().getSymbolManager();
793 }
794
795 template<typename T>
add(typename ProgramStateTrait<T>::key_type K)796 ProgramStateRef ProgramState::add(typename ProgramStateTrait<T>::key_type K) const {
797 return getStateManager().add<T>(this, K, get_context<T>());
798 }
799
800 template <typename T>
get_context()801 typename ProgramStateTrait<T>::context_type ProgramState::get_context() const {
802 return getStateManager().get_context<T>();
803 }
804
805 template<typename T>
remove(typename ProgramStateTrait<T>::key_type K)806 ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K) const {
807 return getStateManager().remove<T>(this, K, get_context<T>());
808 }
809
810 template<typename T>
remove(typename ProgramStateTrait<T>::key_type K,typename ProgramStateTrait<T>::context_type C)811 ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K,
812 typename ProgramStateTrait<T>::context_type C) const {
813 return getStateManager().remove<T>(this, K, C);
814 }
815
816 template <typename T>
remove()817 ProgramStateRef ProgramState::remove() const {
818 return getStateManager().remove<T>(this);
819 }
820
821 template<typename T>
set(typename ProgramStateTrait<T>::data_type D)822 ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::data_type D) const {
823 return getStateManager().set<T>(this, D);
824 }
825
826 template<typename T>
set(typename ProgramStateTrait<T>::key_type K,typename ProgramStateTrait<T>::value_type E)827 ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
828 typename ProgramStateTrait<T>::value_type E) const {
829 return getStateManager().set<T>(this, K, E, get_context<T>());
830 }
831
832 template<typename T>
set(typename ProgramStateTrait<T>::key_type K,typename ProgramStateTrait<T>::value_type E,typename ProgramStateTrait<T>::context_type C)833 ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
834 typename ProgramStateTrait<T>::value_type E,
835 typename ProgramStateTrait<T>::context_type C) const {
836 return getStateManager().set<T>(this, K, E, C);
837 }
838
839 template <typename CB>
scanReachableSymbols(SVal val)840 CB ProgramState::scanReachableSymbols(SVal val) const {
841 CB cb(this);
842 scanReachableSymbols(val, cb);
843 return cb;
844 }
845
846 template <typename CB>
scanReachableSymbols(llvm::iterator_range<region_iterator> Reachable)847 CB ProgramState::scanReachableSymbols(
848 llvm::iterator_range<region_iterator> Reachable) const {
849 CB cb(this);
850 scanReachableSymbols(Reachable, cb);
851 return cb;
852 }
853
854 /// \class ScanReachableSymbols
855 /// A utility class that visits the reachable symbols using a custom
856 /// SymbolVisitor. Terminates recursive traversal when the visitor function
857 /// returns false.
858 class ScanReachableSymbols {
859 typedef llvm::DenseSet<const void*> VisitedItems;
860
861 VisitedItems visited;
862 ProgramStateRef state;
863 SymbolVisitor &visitor;
864 public:
ScanReachableSymbols(ProgramStateRef st,SymbolVisitor & v)865 ScanReachableSymbols(ProgramStateRef st, SymbolVisitor &v)
866 : state(std::move(st)), visitor(v) {}
867
868 bool scan(nonloc::LazyCompoundVal val);
869 bool scan(nonloc::CompoundVal val);
870 bool scan(SVal val);
871 bool scan(const MemRegion *R);
872 bool scan(const SymExpr *sym);
873 };
874
875 } // end ento namespace
876
877 } // end clang namespace
878
879 #endif
880