Coverage Report

Created: 2019-07-24 05:18

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