Coverage Report

Created: 2018-07-19 20:53

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
Line
Count
Source
1
//== CheckerContext.h - Context info for path-sensitive checkers--*- 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 CheckerContext that provides contextual info for
11
// path-sensitive checkers.
12
//
13
//===----------------------------------------------------------------------===//
14
15
#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CHECKERCONTEXT_H
16
#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CHECKERCONTEXT_H
17
18
#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
19
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
20
21
namespace clang {
22
namespace ento {
23
24
  /// Declares an immutable map of type \p NameTy, suitable for placement into
25
  /// the ProgramState. This is implementing using llvm::ImmutableMap.
26
  ///
27
  /// \code
28
  /// State = State->set<Name>(K, V);
29
  /// const Value *V = State->get<Name>(K); // Returns NULL if not in the map.
30
  /// State = State->remove<Name>(K);
31
  /// NameTy Map = State->get<Name>();
32
  /// \endcode
33
  ///
34
  /// The macro should not be used inside namespaces, or for traits that must
35
  /// be accessible from more than one translation unit.
36
  #define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value) \
37
    REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, \
38
                                     CLANG_ENTO_PROGRAMSTATE_MAP(Key, Value))
39
40
  /// Declares an immutable set of type \p NameTy, suitable for placement into
41
  /// the ProgramState. This is implementing using llvm::ImmutableSet.
42
  ///
43
  /// \code
44
  /// State = State->add<Name>(E);
45
  /// State = State->remove<Name>(E);
46
  /// bool Present = State->contains<Name>(E);
47
  /// NameTy Set = State->get<Name>();
48
  /// \endcode
49
  ///
50
  /// The macro should not be used inside namespaces, or for traits that must
51
  /// be accessible from more than one translation unit.
52
  #define REGISTER_SET_WITH_PROGRAMSTATE(Name, Elem) \
53
    REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, llvm::ImmutableSet<Elem>)
54
  
55
  /// Declares an immutable list of type \p NameTy, suitable for placement into
56
  /// the ProgramState. This is implementing using llvm::ImmutableList.
57
  ///
58
  /// \code
59
  /// State = State->add<Name>(E); // Adds to the /end/ of the list.
60
  /// bool Present = State->contains<Name>(E);
61
  /// NameTy List = State->get<Name>();
62
  /// \endcode
63
  ///
64
  /// The macro should not be used inside namespaces, or for traits that must
65
  /// be accessible from more than one translation unit.
66
  #define REGISTER_LIST_WITH_PROGRAMSTATE(Name, Elem) \
67
    REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, llvm::ImmutableList<Elem>)
68
69
70
class CheckerContext {
71
  ExprEngine &Eng;
72
  /// The current exploded(symbolic execution) graph node.
73
  ExplodedNode *Pred;
74
  /// The flag is true if the (state of the execution) has been modified
75
  /// by the checker using this context. For example, a new transition has been
76
  /// added or a bug report issued.
77
  bool Changed;
78
  /// The tagged location, which is used to generate all new nodes.
79
  const ProgramPoint Location;
80
  NodeBuilder &NB;
81
82
public:
83
  /// If we are post visiting a call, this flag will be set if the
84
  /// call was inlined.  In all other cases it will be false.
85
  const bool wasInlined;
86
  
87
  CheckerContext(NodeBuilder &builder,
88
                 ExprEngine &eng,
89
                 ExplodedNode *pred,
90
                 const ProgramPoint &loc,
91
                 bool wasInlined = false)
92
    : Eng(eng),
93
      Pred(pred),
94
      Changed(false),
95
      Location(loc),
96
      NB(builder),
97
2.08M
      wasInlined(wasInlined) {
98
2.08M
    assert(Pred->getState() &&
99
2.08M
           "We should not call the checkers on an empty state.");
100
2.08M
  }
101
102
54.6k
  AnalysisManager &getAnalysisManager() {
103
54.6k
    return Eng.getAnalysisManager();
104
54.6k
  }
105
106
12.8k
  ConstraintManager &getConstraintManager() {
107
12.8k
    return Eng.getConstraintManager();
108
12.8k
  }
109
110
578
  StoreManager &getStoreManager() {
111
578
    return Eng.getStoreManager();
112
578
  }
113
  
114
  /// Returns the previous node in the exploded graph, which includes
115
  /// the state of the program before the checker ran. Note, checkers should
116
  /// not retain the node in their state since the nodes might get invalidated.
117
43.9k
  ExplodedNode *getPredecessor() { return Pred; }
118
795k
  const ProgramStateRef &getState() const { return Pred->getState(); }
119
120
  /// Check if the checker changed the state of the execution; ex: added
121
  /// a new transition or a bug report.
122
1.84k
  bool isDifferent() { return Changed; }
123
124
  /// Returns the number of times the current block has been visited
125
  /// along the analyzed path.
126
2.76k
  unsigned blockCount() const {
127
2.76k
    return NB.getContext().blockCount();
128
2.76k
  }
129
130
269k
  ASTContext &getASTContext() {
131
269k
    return Eng.getContext();
132
269k
  }
133
134
222
  const LangOptions &getLangOpts() const {
135
222
    return Eng.getContext().getLangOpts();
136
222
  }
137
138
105k
  const LocationContext *getLocationContext() const {
139
105k
    return Pred->getLocationContext();
140
105k
  }
141
142
50.8k
  const StackFrameContext *getStackFrame() const {
143
50.8k
    return Pred->getStackFrame();
144
50.8k
  }
145
146
  /// Return true if the current LocationContext has no caller context.
147
5.26k
  bool inTopFrame() const { return getLocationContext()->inTopFrame();  }
148
149
9.67k
  BugReporter &getBugReporter() {
150
9.67k
    return Eng.getBugReporter();
151
9.67k
  }
152
  
153
1.07k
  SourceManager &getSourceManager() {
154
1.07k
    return getBugReporter().getSourceManager();
155
1.07k
  }
156
157
24.6k
  SValBuilder &getSValBuilder() {
158
24.6k
    return Eng.getSValBuilder();
159
24.6k
  }
160
161
194
  SymbolManager &getSymbolManager() {
162
194
    return getSValBuilder().getSymbolManager();
163
194
  }
164
165
8.37k
  bool isObjCGCEnabled() const {
166
8.37k
    return Eng.isObjCGCEnabled();
167
8.37k
  }
168
169
317
  ProgramStateManager &getStateManager() {
170
317
    return Eng.getStateManager();
171
317
  }
172
173
2.30k
  AnalysisDeclContext *getCurrentAnalysisDeclContext() const {
174
2.30k
    return Pred->getLocationContext()->getAnalysisDeclContext();
175
2.30k
  }
176
177
  /// Get the blockID.
178
405
  unsigned getBlockID() const {
179
405
    return NB.getContext().getBlock()->getBlockID();
180
405
  }
181
182
  /// If the given node corresponds to a PostStore program point,
183
  /// retrieve the location region as it was uttered in the code.
184
  ///
185
  /// This utility can be useful for generating extensive diagnostics, for
186
  /// example, for finding variables that the given symbol was assigned to.
187
6.21k
  static const MemRegion *getLocationRegionIfPostStore(const ExplodedNode *N) {
188
6.21k
    ProgramPoint L = N->getLocation();
189
6.21k
    if (Optional<PostStore> PSL = L.getAs<PostStore>())
190
313
      return reinterpret_cast<const MemRegion*>(PSL->getLocationValue());
191
5.90k
    return nullptr;
192
5.90k
  }
193
194
  /// Get the value of arbitrary expressions at this point in the path.
195
183k
  SVal getSVal(const Stmt *S) const {
196
183k
    return Pred->getSVal(S);
197
183k
  }
198
199
  /// Returns true if the value of \p E is greater than or equal to \p
200
  /// Val under unsigned comparison
201
  bool isGreaterOrEqual(const Expr *E, unsigned long long Val);
202
203
  /// Returns true if the value of \p E is negative.
204
  bool isNegative(const Expr *E);
205
206
  /// Generates a new transition in the program state graph
207
  /// (ExplodedGraph). Uses the default CheckerContext predecessor node.
208
  ///
209
  /// @param State The state of the generated node. If not specified, the state
210
  ///        will not be changed, but the new node will have the checker's tag.
211
  /// @param Tag The tag is used to uniquely identify the creation site. If no
212
  ///        tag is specified, a default tag, unique to the given checker,
213
  ///        will be used. Tags are used to prevent states generated at
214
  ///        different sites from caching out.
215
  ExplodedNode *addTransition(ProgramStateRef State = nullptr,
216
393k
                              const ProgramPointTag *Tag = nullptr) {
217
393k
    return addTransitionImpl(State ? 
State387k
:
getState()6.33k
, false, nullptr, Tag);
218
393k
  }
219
220
  /// Generates a new transition with the given predecessor.
221
  /// Allows checkers to generate a chain of nodes.
222
  ///
223
  /// @param State The state of the generated node.
224
  /// @param Pred The transition will be generated from the specified Pred node
225
  ///             to the newly generated node.
226
  /// @param Tag The tag to uniquely identify the creation site.
227
  ExplodedNode *addTransition(ProgramStateRef State,
228
                              ExplodedNode *Pred,
229
26.0k
                              const ProgramPointTag *Tag = nullptr) {
230
26.0k
    return addTransitionImpl(State, false, Pred, Tag);
231
26.0k
  }
232
233
  /// Generate a sink node. Generating a sink stops exploration of the
234
  /// given path. To create a sink node for the purpose of reporting an error,
235
  /// checkers should use generateErrorNode() instead.
236
  ExplodedNode *generateSink(ProgramStateRef State, ExplodedNode *Pred,
237
5.95k
                             const ProgramPointTag *Tag = nullptr) {
238
5.95k
    return addTransitionImpl(State ? 
State5.02k
:
getState()930
, true, Pred, Tag);
239
5.95k
  }
240
241
  /// Generate a transition to a node that will be used to report
242
  /// an error. This node will be a sink. That is, it will stop exploration of
243
  /// the given path.
244
  ///
245
  /// @param State The state of the generated node.
246
  /// @param Tag The tag to uniquely identify the creation site. If null,
247
  ///        the default tag for the checker will be used.
248
  ExplodedNode *generateErrorNode(ProgramStateRef State = nullptr,
249
2.35k
                                  const ProgramPointTag *Tag = nullptr) {
250
2.35k
    return generateSink(State, Pred,
251
2.35k
                       (Tag ? 
Tag39
:
Location.getTag()2.31k
));
252
2.35k
  }
253
254
  /// Generate a transition to a node that will be used to report
255
  /// an error. This node will not be a sink. That is, exploration will
256
  /// continue along this path.
257
  ///
258
  /// @param State The state of the generated node.
259
  /// @param Tag The tag to uniquely identify the creation site. If null,
260
  ///        the default tag for the checker will be used.
261
  ExplodedNode *
262
  generateNonFatalErrorNode(ProgramStateRef State = nullptr,
263
6.70k
                            const ProgramPointTag *Tag = nullptr) {
264
6.70k
    return addTransition(State, (Tag ? 
Tag380
:
Location.getTag()6.32k
));
265
6.70k
  }
266
267
  /// Emit the diagnostics report.
268
3.71k
  void emitReport(std::unique_ptr<BugReport> R) {
269
3.71k
    Changed = true;
270
3.71k
    Eng.getBugReporter().emitReport(std::move(R));
271
3.71k
  }
272
273
  /// Returns the word that should be used to refer to the declaration
274
  /// in the report.
275
  StringRef getDeclDescription(const Decl *D);
276
277
  /// Get the declaration of the called function (path-sensitive).
278
  const FunctionDecl *getCalleeDecl(const CallExpr *CE) const;
279
280
  /// Get the name of the called function (path-sensitive).
281
  StringRef getCalleeName(const FunctionDecl *FunDecl) const;
282
283
  /// Get the identifier of the called function (path-sensitive).
284
  const IdentifierInfo *getCalleeIdentifier(const CallExpr *CE) const {
285
    const FunctionDecl *FunDecl = getCalleeDecl(CE);
286
    if (FunDecl)
287
      return FunDecl->getIdentifier();
288
    else
289
      return nullptr;
290
  }
291
292
  /// Get the name of the called function (path-sensitive).
293
12.9k
  StringRef getCalleeName(const CallExpr *CE) const {
294
12.9k
    const FunctionDecl *FunDecl = getCalleeDecl(CE);
295
12.9k
    return getCalleeName(FunDecl);
296
12.9k
  }
297
298
  /// Returns true if the callee is an externally-visible function in the
299
  /// top-level namespace, such as \c malloc.
300
  ///
301
  /// If a name is provided, the function must additionally match the given
302
  /// name.
303
  ///
304
  /// Note that this deliberately excludes C++ library functions in the \c std
305
  /// namespace, but will include C library functions accessed through the
306
  /// \c std namespace. This also does not check if the function is declared
307
  /// as 'extern "C"', or if it uses C++ name mangling.
308
  static bool isCLibraryFunction(const FunctionDecl *FD,
309
                                 StringRef Name = StringRef());
310
311
  /// Depending on wither the location corresponds to a macro, return 
312
  /// either the macro name or the token spelling.
313
  ///
314
  /// This could be useful when checkers' logic depends on whether a function
315
  /// is called with a given macro argument. For example:
316
  ///   s = socket(AF_INET,..)
317
  /// If AF_INET is a macro, the result should be treated as a source of taint.
318
  ///
319
  /// \sa clang::Lexer::getSpelling(), clang::Lexer::getImmediateMacroName().
320
  StringRef getMacroNameOrSpelling(SourceLocation &Loc);
321
322
private:
323
  ExplodedNode *addTransitionImpl(ProgramStateRef State,
324
                                 bool MarkAsSink,
325
                                 ExplodedNode *P = nullptr,
326
425k
                                 const ProgramPointTag *Tag = nullptr) {
327
425k
    // The analyzer may stop exploring if it sees a state it has previously
328
425k
    // visited ("cache out"). The early return here is a defensive check to
329
425k
    // prevent accidental caching out by checker API clients. Unless there is a
330
425k
    // tag or the client checker has requested that the generated node be
331
425k
    // marked as a sink, we assume that a client requesting a transition to a
332
425k
    // state that is the same as the predecessor state has made a mistake. We
333
425k
    // return the predecessor rather than cache out.
334
425k
    //
335
425k
    // TODO: We could potentially change the return to an assertion to alert
336
425k
    // clients to their mistake, but several checkers (including
337
425k
    // DereferenceChecker, CallAndMessageChecker, and DynamicTypePropagation)
338
425k
    // rely upon the defensive behavior and would need to be updated.
339
425k
    if (!State || (State == Pred->getState() && 
!Tag388k
&&
!MarkAsSink379k
))
340
378k
      return Pred;
341
46.9k
342
46.9k
    Changed = true;
343
46.9k
    const ProgramPoint &LocalLoc = (Tag ? 
Location.withTag(Tag)9.75k
:
Location37.2k
);
344
46.9k
    if (!P)
345
31.9k
      P = Pred;
346
46.9k
347
46.9k
    ExplodedNode *node;
348
46.9k
    if (MarkAsSink)
349
5.95k
      node = NB.generateSink(LocalLoc, State, P);
350
41.0k
    else
351
41.0k
      node = NB.generateNode(LocalLoc, State, P);
352
46.9k
    return node;
353
46.9k
  }
354
};
355
356
} // end GR namespace
357
358
} // end clang namespace
359
360
#endif