Bug Summary

File:tools/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIBugReporter.cpp
Warning:line 101, column 29
Access to field 'CurrentState' results in a dereference of a null pointer (loaded from variable 'Req')

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name MPIBugReporter.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/lib/StaticAnalyzer/Checkers -I /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/StaticAnalyzer/Checkers -I /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn345461/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/lib/StaticAnalyzer/Checkers -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-10-27-211344-32123-1 -x c++ /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIBugReporter.cpp -faddrsig

/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIBugReporter.cpp

1//===-- MPIBugReporter.cpp - bug reporter -----------------------*- 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/// \file
11/// This file defines prefabricated reports which are emitted in
12/// case of MPI related bugs, detected by path-sensitive analysis.
13///
14//===----------------------------------------------------------------------===//
15
16#include "MPIBugReporter.h"
17#include "MPIChecker.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
19
20namespace clang {
21namespace ento {
22namespace mpi {
23
24void MPIBugReporter::reportDoubleNonblocking(
25 const CallEvent &MPICallEvent, const ento::mpi::Request &Req,
26 const MemRegion *const RequestRegion,
27 const ExplodedNode *const ExplNode,
28 BugReporter &BReporter) const {
29
30 std::string ErrorText;
31 ErrorText = "Double nonblocking on request " +
32 RequestRegion->getDescriptiveName() + ". ";
33
34 auto Report = llvm::make_unique<BugReport>(*DoubleNonblockingBugType,
35 ErrorText, ExplNode);
36
37 Report->addRange(MPICallEvent.getSourceRange());
38 SourceRange Range = RequestRegion->sourceRange();
39
40 if (Range.isValid())
41 Report->addRange(Range);
42
43 Report->addVisitor(llvm::make_unique<RequestNodeVisitor>(
44 RequestRegion, "Request is previously used by nonblocking call here. "));
45 Report->markInteresting(RequestRegion);
46
47 BReporter.emitReport(std::move(Report));
48}
49
50void MPIBugReporter::reportMissingWait(
51 const ento::mpi::Request &Req, const MemRegion *const RequestRegion,
52 const ExplodedNode *const ExplNode,
53 BugReporter &BReporter) const {
54 std::string ErrorText{"Request " + RequestRegion->getDescriptiveName() +
55 " has no matching wait. "};
56
57 auto Report =
58 llvm::make_unique<BugReport>(*MissingWaitBugType, ErrorText, ExplNode);
59
60 SourceRange Range = RequestRegion->sourceRange();
61 if (Range.isValid())
62 Report->addRange(Range);
63 Report->addVisitor(llvm::make_unique<RequestNodeVisitor>(
64 RequestRegion, "Request is previously used by nonblocking call here. "));
65 Report->markInteresting(RequestRegion);
66
67 BReporter.emitReport(std::move(Report));
68}
69
70void MPIBugReporter::reportUnmatchedWait(
71 const CallEvent &CE, const clang::ento::MemRegion *const RequestRegion,
72 const ExplodedNode *const ExplNode,
73 BugReporter &BReporter) const {
74 std::string ErrorText{"Request " + RequestRegion->getDescriptiveName() +
75 " has no matching nonblocking call. "};
76
77 auto Report =
78 llvm::make_unique<BugReport>(*UnmatchedWaitBugType, ErrorText, ExplNode);
79
80 Report->addRange(CE.getSourceRange());
81 SourceRange Range = RequestRegion->sourceRange();
82 if (Range.isValid())
83 Report->addRange(Range);
84
85 BReporter.emitReport(std::move(Report));
86}
87
88std::shared_ptr<PathDiagnosticPiece>
89MPIBugReporter::RequestNodeVisitor::VisitNode(const ExplodedNode *N,
90 BugReporterContext &BRC,
91 BugReport &BR) {
92
93 if (IsNodeFound)
1
Assuming the condition is false
2
Taking false branch
94 return nullptr;
95
96 const Request *const Req = N->getState()->get<RequestMap>(RequestRegion);
3
Calling 'ProgramState::get'
10
Returning from 'ProgramState::get'
11
'Req' initialized here
97 const Request *const PrevReq =
98 N->getFirstPred()->getState()->get<RequestMap>(RequestRegion);
99
100 // Check if request was previously unused or in a different state.
101 if ((Req && !PrevReq) || (Req->CurrentState != PrevReq->CurrentState)) {
12
Assuming 'Req' is null
13
Access to field 'CurrentState' results in a dereference of a null pointer (loaded from variable 'Req')
102 IsNodeFound = true;
103
104 ProgramPoint P = N->getFirstPred()->getLocation();
105 PathDiagnosticLocation L =
106 PathDiagnosticLocation::create(P, BRC.getSourceManager());
107
108 return std::make_shared<PathDiagnosticEventPiece>(L, ErrorText);
109 }
110
111 return nullptr;
112}
113
114} // end of namespace: mpi
115} // end of namespace: ento
116} // end of namespace: clang

/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h

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

/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h

1//ProgramStateTrait.h - Partial implementations of ProgramStateTrait -*- 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 partial implementations of template specializations of
11// the class ProgramStateTrait<>. ProgramStateTrait<> is used by ProgramState
12// to implement set/get methods for manipulating a ProgramState's
13// generic data map.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATETRAIT_H
18#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATETRAIT_H
19
20#include "llvm/ADT/ImmutableList.h"
21#include "llvm/ADT/ImmutableMap.h"
22#include "llvm/ADT/ImmutableSet.h"
23#include "llvm/Support/Allocator.h"
24#include <cstdint>
25
26namespace clang {
27namespace ento {
28
29 template <typename T> struct ProgramStatePartialTrait;
30
31 /// Declares a program state trait for type \p Type called \p Name, and
32 /// introduce a type named \c NameTy.
33 /// The macro should not be used inside namespaces.
34 #define REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, Type)namespace { class Name {}; using NameTy = Type; } namespace clang
{ namespace ento { template <> struct ProgramStateTrait
<Name> : public ProgramStatePartialTrait<NameTy> {
static void *GDMIndex() { static int Index; return &Index
; } }; } }
\
35 namespace { \
36 class Name {}; \
37 using Name ## Ty = Type; \
38 } \
39 namespace clang { \
40 namespace ento { \
41 template <> \
42 struct ProgramStateTrait<Name> \
43 : public ProgramStatePartialTrait<Name ## Ty> { \
44 static void *GDMIndex() { static int Index; return &Index; } \
45 }; \
46 } \
47 }
48
49 /// Declares a factory for objects of type \p Type in the program state
50 /// manager. The type must provide a ::Factory sub-class. Commonly used for
51 /// ImmutableMap, ImmutableSet, ImmutableList. The macro should not be used
52 /// inside namespaces.
53 #define REGISTER_FACTORY_WITH_PROGRAMSTATE(Type)namespace clang { namespace ento { template <> struct ProgramStateTrait
<Type> : public ProgramStatePartialTrait<Type> { static
void *GDMIndex() { static int Index; return &Index; } };
} }
\
54 namespace clang { \
55 namespace ento { \
56 template <> \
57 struct ProgramStateTrait<Type> \
58 : public ProgramStatePartialTrait<Type> { \
59 static void *GDMIndex() { static int Index; return &Index; } \
60 }; \
61 } \
62 }
63
64 /// Helper for registering a map trait.
65 ///
66 /// If the map type were written directly in the invocation of
67 /// REGISTER_TRAIT_WITH_PROGRAMSTATE, the comma in the template arguments
68 /// would be treated as a macro argument separator, which is wrong.
69 /// This allows the user to specify a map type in a way that the preprocessor
70 /// can deal with.
71 #define CLANG_ENTO_PROGRAMSTATE_MAP(Key, Value)llvm::ImmutableMap<Key, Value> llvm::ImmutableMap<Key, Value>
72
73 /// Declares an immutable map of type \p NameTy, suitable for placement into
74 /// the ProgramState. This is implementing using llvm::ImmutableMap.
75 ///
76 /// \code
77 /// State = State->set<Name>(K, V);
78 /// const Value *V = State->get<Name>(K); // Returns NULL if not in the map.
79 /// State = State->remove<Name>(K);
80 /// NameTy Map = State->get<Name>();
81 /// \endcode
82 ///
83 /// The macro should not be used inside namespaces, or for traits that must
84 /// be accessible from more than one translation unit.
85 #define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value)namespace { class Name {}; using NameTy = llvm::ImmutableMap<
Key, Value>; } namespace clang { namespace ento { template
<> struct ProgramStateTrait<Name> : public ProgramStatePartialTrait
<NameTy> { static void *GDMIndex() { static int Index; return
&Index; } }; } }
\
86 REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, \namespace { class Name {}; using NameTy = llvm::ImmutableMap<
Key, Value>; } namespace clang { namespace ento { template
<> struct ProgramStateTrait<Name> : public ProgramStatePartialTrait
<NameTy> { static void *GDMIndex() { static int Index; return
&Index; } }; } }
87 CLANG_ENTO_PROGRAMSTATE_MAP(Key, Value))namespace { class Name {}; using NameTy = llvm::ImmutableMap<
Key, Value>; } namespace clang { namespace ento { template
<> struct ProgramStateTrait<Name> : public ProgramStatePartialTrait
<NameTy> { static void *GDMIndex() { static int Index; return
&Index; } }; } }
88
89 /// Declares an immutable map type \p Name and registers the factory
90 /// for such maps in the program state, but does not add the map itself
91 /// to the program state. Useful for managing lifetime of maps that are used
92 /// as elements of other program state data structures.
93 #define REGISTER_MAP_FACTORY_WITH_PROGRAMSTATE(Name, Key, Value)using Name = llvm::ImmutableMap<Key, Value>; namespace clang
{ namespace ento { template <> struct ProgramStateTrait
<Name> : public ProgramStatePartialTrait<Name> { static
void *GDMIndex() { static int Index; return &Index; } };
} }
\
94 using Name = llvm::ImmutableMap<Key, Value>; \
95 REGISTER_FACTORY_WITH_PROGRAMSTATE(Name)namespace clang { namespace ento { template <> struct ProgramStateTrait
<Name> : public ProgramStatePartialTrait<Name> { static
void *GDMIndex() { static int Index; return &Index; } };
} }
96
97
98 /// Declares an immutable set of type \p NameTy, suitable for placement into
99 /// the ProgramState. This is implementing using llvm::ImmutableSet.
100 ///
101 /// \code
102 /// State = State->add<Name>(E);
103 /// State = State->remove<Name>(E);
104 /// bool Present = State->contains<Name>(E);
105 /// NameTy Set = State->get<Name>();
106 /// \endcode
107 ///
108 /// The macro should not be used inside namespaces, or for traits that must
109 /// be accessible from more than one translation unit.
110 #define REGISTER_SET_WITH_PROGRAMSTATE(Name, Elem)namespace { class Name {}; using NameTy = llvm::ImmutableSet<
Elem>; } namespace clang { namespace ento { template <>
struct ProgramStateTrait<Name> : public ProgramStatePartialTrait
<NameTy> { static void *GDMIndex() { static int Index; return
&Index; } }; } }
\
111 REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, llvm::ImmutableSet<Elem>)namespace { class Name {}; using NameTy = llvm::ImmutableSet<
Elem>; } namespace clang { namespace ento { template <>
struct ProgramStateTrait<Name> : public ProgramStatePartialTrait
<NameTy> { static void *GDMIndex() { static int Index; return
&Index; } }; } }
112
113 /// Declares an immutable set type \p Name and registers the factory
114 /// for such sets in the program state, but does not add the set itself
115 /// to the program state. Useful for managing lifetime of sets that are used
116 /// as elements of other program state data structures.
117 #define REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(Name, Elem)using Name = llvm::ImmutableSet<Elem>; namespace clang {
namespace ento { template <> struct ProgramStateTrait<
Name> : public ProgramStatePartialTrait<Name> { static
void *GDMIndex() { static int Index; return &Index; } };
} }
\
118 using Name = llvm::ImmutableSet<Elem>; \
119 REGISTER_FACTORY_WITH_PROGRAMSTATE(Name)namespace clang { namespace ento { template <> struct ProgramStateTrait
<Name> : public ProgramStatePartialTrait<Name> { static
void *GDMIndex() { static int Index; return &Index; } };
} }
120
121
122 /// Declares an immutable list type \p NameTy, suitable for placement into
123 /// the ProgramState. This is implementing using llvm::ImmutableList.
124 ///
125 /// \code
126 /// State = State->add<Name>(E); // Adds to the /end/ of the list.
127 /// bool Present = State->contains<Name>(E);
128 /// NameTy List = State->get<Name>();
129 /// \endcode
130 ///
131 /// The macro should not be used inside namespaces, or for traits that must
132 /// be accessible from more than one translation unit.
133 #define REGISTER_LIST_WITH_PROGRAMSTATE(Name, Elem)namespace { class Name {}; using NameTy = llvm::ImmutableList
<Elem>; } namespace clang { namespace ento { template <
> struct ProgramStateTrait<Name> : public ProgramStatePartialTrait
<NameTy> { static void *GDMIndex() { static int Index; return
&Index; } }; } }
\
134 REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, llvm::ImmutableList<Elem>)namespace { class Name {}; using NameTy = llvm::ImmutableList
<Elem>; } namespace clang { namespace ento { template <
> struct ProgramStateTrait<Name> : public ProgramStatePartialTrait
<NameTy> { static void *GDMIndex() { static int Index; return
&Index; } }; } }
135
136 /// Declares an immutable list of type \p Name and registers the factory
137 /// for such lists in the program state, but does not add the list itself
138 /// to the program state. Useful for managing lifetime of lists that are used
139 /// as elements of other program state data structures.
140 #define REGISTER_LIST_FACTORY_WITH_PROGRAMSTATE(Name, Elem)using Name = llvm::ImmutableList<Elem>; namespace clang
{ namespace ento { template <> struct ProgramStateTrait
<Name> : public ProgramStatePartialTrait<Name> { static
void *GDMIndex() { static int Index; return &Index; } };
} }
\
141 using Name = llvm::ImmutableList<Elem>; \
142 REGISTER_FACTORY_WITH_PROGRAMSTATE(Name)namespace clang { namespace ento { template <> struct ProgramStateTrait
<Name> : public ProgramStatePartialTrait<Name> { static
void *GDMIndex() { static int Index; return &Index; } };
} }
143
144
145 // Partial-specialization for ImmutableMap.
146 template <typename Key, typename Data, typename Info>
147 struct ProgramStatePartialTrait<llvm::ImmutableMap<Key, Data, Info>> {
148 using data_type = llvm::ImmutableMap<Key, Data, Info>;
149 using context_type = typename data_type::Factory &;
150 using key_type = Key;
151 using value_type = Data;
152 using lookup_type = const value_type *;
153
154 static data_type MakeData(void *const *p) {
155 return p ? data_type((typename data_type::TreeTy *) *p)
156 : data_type(nullptr);
157 }
158
159 static void *MakeVoidPtr(data_type B) {
160 return B.getRoot();
161 }
162
163 static lookup_type Lookup(data_type B, key_type K) {
164 return B.lookup(K);
5
Assigning value
6
Assigning value
7
Returning pointer
165 }
166
167 static data_type Set(data_type B, key_type K, value_type E,
168 context_type F) {
169 return F.add(B, K, E);
170 }
171
172 static data_type Remove(data_type B, key_type K, context_type F) {
173 return F.remove(B, K);
174 }
175
176 static bool Contains(data_type B, key_type K) {
177 return B.contains(K);
178 }
179
180 static context_type MakeContext(void *p) {
181 return *((typename data_type::Factory *) p);
182 }
183
184 static void *CreateContext(llvm::BumpPtrAllocator& Alloc) {
185 return new typename data_type::Factory(Alloc);
186 }
187
188 static void DeleteContext(void *Ctx) {
189 delete (typename data_type::Factory *) Ctx;
190 }
191 };
192
193 // Partial-specialization for ImmutableSet.
194 template <typename Key, typename Info>
195 struct ProgramStatePartialTrait<llvm::ImmutableSet<Key, Info>> {
196 using data_type = llvm::ImmutableSet<Key, Info>;
197 using context_type = typename data_type::Factory &;
198 using key_type = Key;
199
200 static data_type MakeData(void *const *p) {
201 return p ? data_type((typename data_type::TreeTy *) *p)
202 : data_type(nullptr);
203 }
204
205 static void *MakeVoidPtr(data_type B) {
206 return B.getRoot();
207 }
208
209 static data_type Add(data_type B, key_type K, context_type F) {
210 return F.add(B, K);
211 }
212
213 static data_type Remove(data_type B, key_type K, context_type F) {
214 return F.remove(B, K);
215 }
216
217 static bool Contains(data_type B, key_type K) {
218 return B.contains(K);
219 }
220
221 static context_type MakeContext(void *p) {
222 return *((typename data_type::Factory *) p);
223 }
224
225 static void *CreateContext(llvm::BumpPtrAllocator &Alloc) {
226 return new typename data_type::Factory(Alloc);
227 }
228
229 static void DeleteContext(void *Ctx) {
230 delete (typename data_type::Factory *) Ctx;
231 }
232 };
233
234 // Partial-specialization for ImmutableList.
235 template <typename T>
236 struct ProgramStatePartialTrait<llvm::ImmutableList<T>> {
237 using data_type = llvm::ImmutableList<T>;
238 using key_type = T;
239 using context_type = typename data_type::Factory &;
240
241 static data_type Add(data_type L, key_type K, context_type F) {
242 return F.add(K, L);
243 }
244
245 static bool Contains(data_type L, key_type K) {
246 return L.contains(K);
247 }
248
249 static data_type MakeData(void *const *p) {
250 return p ? data_type((const llvm::ImmutableListImpl<T> *) *p)
251 : data_type(nullptr);
252 }
253
254 static void *MakeVoidPtr(data_type D) {
255 return const_cast<llvm::ImmutableListImpl<T> *>(D.getInternalPointer());
256 }
257
258 static context_type MakeContext(void *p) {
259 return *((typename data_type::Factory *) p);
260 }
261
262 static void *CreateContext(llvm::BumpPtrAllocator &Alloc) {
263 return new typename data_type::Factory(Alloc);
264 }
265
266 static void DeleteContext(void *Ctx) {
267 delete (typename data_type::Factory *) Ctx;
268 }
269 };
270
271 // Partial specialization for bool.
272 template <> struct ProgramStatePartialTrait<bool> {
273 using data_type = bool;
274
275 static data_type MakeData(void *const *p) {
276 return p ? (data_type) (uintptr_t) *p
277 : data_type();
278 }
279
280 static void *MakeVoidPtr(data_type d) {
281 return (void *) (uintptr_t) d;
282 }
283 };
284
285 // Partial specialization for unsigned.
286 template <> struct ProgramStatePartialTrait<unsigned> {
287 using data_type = unsigned;
288
289 static data_type MakeData(void *const *p) {
290 return p ? (data_type) (uintptr_t) *p
291 : data_type();
292 }
293
294 static void *MakeVoidPtr(data_type d) {
295 return (void *) (uintptr_t) d;
296 }
297 };
298
299 // Partial specialization for void*.
300 template <> struct ProgramStatePartialTrait<void *> {
301 using data_type = void *;
302
303 static data_type MakeData(void *const *p) {
304 return p ? *p
305 : data_type();
306 }
307
308 static void *MakeVoidPtr(data_type d) {
309 return d;
310 }
311 };
312
313 // Partial specialization for const void *.
314 template <> struct ProgramStatePartialTrait<const void *> {
315 using data_type = const void *;
316
317 static data_type MakeData(void *const *p) {
318 return p ? *p : data_type();
319 }
320
321 static void *MakeVoidPtr(data_type d) {
322 return const_cast<void *>(d);
323 }
324 };
325
326} // namespace ento
327} // namespace clang
328
329#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATETRAIT_H