Coverage Report

Created: 2022-05-17 06:19

/Users/buildslave/jenkins/workspace/coverage/llvm-project/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
4.49M
      wasInlined(wasInlined) {
51
4.49M
    assert(Pred->getState() &&
52
4.49M
           "We should not call the checkers on an empty state.");
53
4.49M
  }
54
55
99.7k
  AnalysisManager &getAnalysisManager() {
56
99.7k
    return Eng.getAnalysisManager();
57
99.7k
  }
58
59
35.2k
  ConstraintManager &getConstraintManager() {
60
35.2k
    return Eng.getConstraintManager();
61
35.2k
  }
62
63
162
  StoreManager &getStoreManager() {
64
162
    return Eng.getStoreManager();
65
162
  }
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
232k
  ExplodedNode *getPredecessor() { return Pred; }
71
2.87M
  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
19.7k
  bool isDifferent() { return Changed; }
76
77
  /// Returns the number of times the current block has been visited
78
  /// along the analyzed path.
79
5.93k
  unsigned blockCount() const {
80
5.93k
    return NB.getContext().blockCount();
81
5.93k
  }
82
83
306k
  ASTContext &getASTContext() {
84
306k
    return Eng.getContext();
85
306k
  }
86
87
2.76k
  const ASTContext &getASTContext() const { return Eng.getContext(); }
88
89
776
  const LangOptions &getLangOpts() const {
90
776
    return Eng.getContext().getLangOpts();
91
776
  }
92
93
292k
  const LocationContext *getLocationContext() const {
94
292k
    return Pred->getLocationContext();
95
292k
  }
96
97
96.4k
  const StackFrameContext *getStackFrame() const {
98
96.4k
    return Pred->getStackFrame();
99
96.4k
  }
100
101
  /// Return true if the current LocationContext has no caller context.
102
62.0k
  bool inTopFrame() const { return getLocationContext()->inTopFrame();  }
103
104
19.6k
  BugReporter &getBugReporter() {
105
19.6k
    return Eng.getBugReporter();
106
19.6k
  }
107
108
2.18k
  const SourceManager &getSourceManager() {
109
2.18k
    return getBugReporter().getSourceManager();
110
2.18k
  }
111
112
60
  Preprocessor &getPreprocessor() { return getBugReporter().getPreprocessor(); }
113
114
72.1k
  SValBuilder &getSValBuilder() {
115
72.1k
    return Eng.getSValBuilder();
116
72.1k
  }
117
118
886
  SymbolManager &getSymbolManager() {
119
886
    return getSValBuilder().getSymbolManager();
120
886
  }
121
122
619
  ProgramStateManager &getStateManager() {
123
619
    return Eng.getStateManager();
124
619
  }
125
126
3.15k
  AnalysisDeclContext *getCurrentAnalysisDeclContext() const {
127
3.15k
    return Pred->getLocationContext()->getAnalysisDeclContext();
128
3.15k
  }
129
130
  /// Get the blockID.
131
440
  unsigned getBlockID() const {
132
440
    return NB.getContext().getBlock()->getBlockID();
133
440
  }
134
135
  /// If the given node corresponds to a PostStore program point,
136
  /// retrieve the location region as it was uttered in the code.
137
  ///
138
  /// This utility can be useful for generating extensive diagnostics, for
139
  /// example, for finding variables that the given symbol was assigned to.
140
7.19k
  static const MemRegion *getLocationRegionIfPostStore(const ExplodedNode *N) {
141
7.19k
    ProgramPoint L = N->getLocation();
142
7.19k
    if (Optional<PostStore> PSL = L.getAs<PostStore>())
143
373
      return reinterpret_cast<const MemRegion*>(PSL->getLocationValue());
144
6.82k
    return nullptr;
145
7.19k
  }
146
147
  /// Get the value of arbitrary expressions at this point in the path.
148
258k
  SVal getSVal(const Stmt *S) const {
149
258k
    return Pred->getSVal(S);
150
258k
  }
151
152
  /// Returns true if the value of \p E is greater than or equal to \p
153
  /// Val under unsigned comparison
154
  bool isGreaterOrEqual(const Expr *E, unsigned long long Val);
155
156
  /// Returns true if the value of \p E is negative.
157
  bool isNegative(const Expr *E);
158
159
  /// Generates a new transition in the program state graph
160
  /// (ExplodedGraph). Uses the default CheckerContext predecessor node.
161
  ///
162
  /// @param State The state of the generated node. If not specified, the state
163
  ///        will not be changed, but the new node will have the checker's tag.
164
  /// @param Tag The tag is used to uniquely identify the creation site. If no
165
  ///        tag is specified, a default tag, unique to the given checker,
166
  ///        will be used. Tags are used to prevent states generated at
167
  ///        different sites from caching out.
168
  ExplodedNode *addTransition(ProgramStateRef State = nullptr,
169
1.43M
                              const ProgramPointTag *Tag = nullptr) {
170
1.43M
    return addTransitionImpl(State ? 
State1.41M
:
getState()15.6k
, false, nullptr, Tag);
171
1.43M
  }
172
173
  /// Generates a new transition with the given predecessor.
174
  /// Allows checkers to generate a chain of nodes.
175
  ///
176
  /// @param State The state of the generated node.
177
  /// @param Pred The transition will be generated from the specified Pred node
178
  ///             to the newly generated node.
179
  /// @param Tag The tag to uniquely identify the creation site.
180
  ExplodedNode *addTransition(ProgramStateRef State, ExplodedNode *Pred,
181
192k
                              const ProgramPointTag *Tag = nullptr) {
182
192k
    return addTransitionImpl(State, false, Pred, Tag);
183
192k
  }
184
185
  /// Generate a sink node. Generating a sink stops exploration of the
186
  /// given path. To create a sink node for the purpose of reporting an error,
187
  /// checkers should use generateErrorNode() instead.
188
  ExplodedNode *generateSink(ProgramStateRef State, ExplodedNode *Pred,
189
7.77k
                             const ProgramPointTag *Tag = nullptr) {
190
7.77k
    return addTransitionImpl(State ? 
State6.27k
:
getState()1.49k
, true, Pred, Tag);
191
7.77k
  }
192
193
  /// Add a sink node to the current path of execution, halting analysis.
194
  void addSink(ProgramStateRef State = nullptr,
195
112
               const ProgramPointTag *Tag = nullptr) {
196
112
    if (!State)
197
88
      State = getState();
198
112
    addTransition(State, generateSink(State, getPredecessor()));
199
112
  }
200
201
  /// Generate a transition to a node that will be used to report
202
  /// an error. This node will be a sink. That is, it will stop exploration of
203
  /// the given path.
204
  ///
205
  /// @param State The state of the generated node.
206
  /// @param Tag The tag to uniquely identify the creation site. If null,
207
  ///        the default tag for the checker will be used.
208
  ExplodedNode *generateErrorNode(ProgramStateRef State = nullptr,
209
3.70k
                                  const ProgramPointTag *Tag = nullptr) {
210
3.70k
    return generateSink(State, Pred,
211
3.70k
                       (Tag ? 
Tag47
:
Location.getTag()3.65k
));
212
3.70k
  }
213
214
  /// Generate a transition to a node that will be used to report
215
  /// an error. This node will not be a sink. That is, exploration will
216
  /// continue along this path.
217
  ///
218
  /// @param State The state of the generated node.
219
  /// @param Tag The tag to uniquely identify the creation site. If null,
220
  ///        the default tag for the checker will be used.
221
  ExplodedNode *
222
  generateNonFatalErrorNode(ProgramStateRef State = nullptr,
223
16.0k
                            const ProgramPointTag *Tag = nullptr) {
224
16.0k
    return addTransition(State, (Tag ? 
Tag387
:
Location.getTag()15.7k
));
225
16.0k
  }
226
227
  /// Generate a transition to a node that will be used to report
228
  /// an error. This node will not be a sink. That is, exploration will
229
  /// continue along this path.
230
  ///
231
  /// @param State The state of the generated node.
232
  /// @param Pred The transition will be generated from the specified Pred node
233
  ///             to the newly generated node.
234
  /// @param Tag The tag to uniquely identify the creation site. If null,
235
  ///        the default tag for the checker will be used.
236
  ExplodedNode *
237
  generateNonFatalErrorNode(ProgramStateRef State,
238
                            ExplodedNode *Pred,
239
24
                            const ProgramPointTag *Tag = nullptr) {
240
24
    return addTransition(State, Pred, (Tag ? 
Tag0
: Location.getTag()));
241
24
  }
242
243
  /// Emit the diagnostics report.
244
5.89k
  void emitReport(std::unique_ptr<BugReport> R) {
245
5.89k
    Changed = true;
246
5.89k
    Eng.getBugReporter().emitReport(std::move(R));
247
5.89k
  }
248
249
  /// Produce a program point tag that displays an additional path note
250
  /// to the user. This is a lightweight alternative to the
251
  /// BugReporterVisitor mechanism: instead of visiting the bug report
252
  /// node-by-node to restore the sequence of events that led to discovering
253
  /// a bug, you can add notes as you add your transitions.
254
  ///
255
  /// @param Cb Callback with 'BugReporterContext &, BugReport &' parameters.
256
  /// @param IsPrunable Whether the note is prunable. It allows BugReporter
257
  ///        to omit the note from the report if it would make the displayed
258
  ///        bug path significantly shorter.
259
2.91k
  const NoteTag *getNoteTag(NoteTag::Callback &&Cb, bool IsPrunable = false) {
260
2.91k
    return Eng.getDataTags().make<NoteTag>(std::move(Cb), IsPrunable);
261
2.91k
  }
262
263
  /// A shorthand version of getNoteTag that doesn't require you to accept
264
  /// the 'BugReporterContext' argument when you don't need it.
265
  ///
266
  /// @param Cb Callback only with 'BugReport &' parameter.
267
  /// @param IsPrunable Whether the note is prunable. It allows BugReporter
268
  ///        to omit the note from the report if it would make the displayed
269
  ///        bug path significantly shorter.
270
  const NoteTag
271
  *getNoteTag(std::function<std::string(PathSensitiveBugReport &)> &&Cb,
272
1.88k
              bool IsPrunable = false) {
273
1.88k
    return getNoteTag(
274
1.88k
        [Cb](BugReporterContext &,
275
4.77k
             PathSensitiveBugReport &BR) { return Cb(BR); },
276
1.88k
        IsPrunable);
277
1.88k
  }
278
279
  /// A shorthand version of getNoteTag that doesn't require you to accept
280
  /// the arguments when you don't need it.
281
  ///
282
  /// @param Cb Callback without parameters.
283
  /// @param IsPrunable Whether the note is prunable. It allows BugReporter
284
  ///        to omit the note from the report if it would make the displayed
285
  ///        bug path significantly shorter.
286
  const NoteTag *getNoteTag(std::function<std::string()> &&Cb,
287
987
                            bool IsPrunable = false) {
288
987
    return getNoteTag([Cb](BugReporterContext &,
289
987
                           PathSensitiveBugReport &) 
{ return Cb(); }812
,
290
987
                      IsPrunable);
291
987
  }
292
293
  /// A shorthand version of getNoteTag that accepts a plain note.
294
  ///
295
  /// @param Note The note.
296
  /// @param IsPrunable Whether the note is prunable. It allows BugReporter
297
  ///        to omit the note from the report if it would make the displayed
298
  ///        bug path significantly shorter.
299
40
  const NoteTag *getNoteTag(StringRef Note, bool IsPrunable = false) {
300
40
    return getNoteTag(
301
40
        [Note](BugReporterContext &,
302
40
               PathSensitiveBugReport &) 
{ return std::string(Note); }13
,
303
40
        IsPrunable);
304
40
  }
305
306
  /// A shorthand version of getNoteTag that accepts a lambda with stream for
307
  /// note.
308
  ///
309
  /// @param Cb Callback with 'BugReport &' and 'llvm::raw_ostream &'.
310
  /// @param IsPrunable Whether the note is prunable. It allows BugReporter
311
  ///        to omit the note from the report if it would make the displayed
312
  ///        bug path significantly shorter.
313
  const NoteTag *getNoteTag(
314
      std::function<void(PathSensitiveBugReport &BR, llvm::raw_ostream &OS)> &&Cb,
315
462
      bool IsPrunable = false) {
316
462
    return getNoteTag(
317
496
        [Cb](PathSensitiveBugReport &BR) -> std::string {
318
496
          llvm::SmallString<128> Str;
319
496
          llvm::raw_svector_ostream OS(Str);
320
496
          Cb(BR, OS);
321
496
          return std::string(OS.str());
322
496
        },
323
462
        IsPrunable);
324
462
  }
325
326
  /// Returns the word that should be used to refer to the declaration
327
  /// in the report.
328
  StringRef getDeclDescription(const Decl *D);
329
330
  /// Get the declaration of the called function (path-sensitive).
331
  const FunctionDecl *getCalleeDecl(const CallExpr *CE) const;
332
333
  /// Get the name of the called function (path-sensitive).
334
  StringRef getCalleeName(const FunctionDecl *FunDecl) const;
335
336
  /// Get the identifier of the called function (path-sensitive).
337
0
  const IdentifierInfo *getCalleeIdentifier(const CallExpr *CE) const {
338
0
    const FunctionDecl *FunDecl = getCalleeDecl(CE);
339
0
    if (FunDecl)
340
0
      return FunDecl->getIdentifier();
341
0
    else
342
0
      return nullptr;
343
0
  }
344
345
  /// Get the name of the called function (path-sensitive).
346
50.1k
  StringRef getCalleeName(const CallExpr *CE) const {
347
50.1k
    const FunctionDecl *FunDecl = getCalleeDecl(CE);
348
50.1k
    return getCalleeName(FunDecl);
349
50.1k
  }
350
351
  /// Returns true if the callee is an externally-visible function in the
352
  /// top-level namespace, such as \c malloc.
353
  ///
354
  /// If a name is provided, the function must additionally match the given
355
  /// name.
356
  ///
357
  /// Note that this deliberately excludes C++ library functions in the \c std
358
  /// namespace, but will include C library functions accessed through the
359
  /// \c std namespace. This also does not check if the function is declared
360
  /// as 'extern "C"', or if it uses C++ name mangling.
361
  static bool isCLibraryFunction(const FunctionDecl *FD,
362
                                 StringRef Name = StringRef());
363
364
  /// Depending on wither the location corresponds to a macro, return
365
  /// either the macro name or the token spelling.
366
  ///
367
  /// This could be useful when checkers' logic depends on whether a function
368
  /// is called with a given macro argument. For example:
369
  ///   s = socket(AF_INET,..)
370
  /// If AF_INET is a macro, the result should be treated as a source of taint.
371
  ///
372
  /// \sa clang::Lexer::getSpelling(), clang::Lexer::getImmediateMacroName().
373
  StringRef getMacroNameOrSpelling(SourceLocation &Loc);
374
375
private:
376
  ExplodedNode *addTransitionImpl(ProgramStateRef State,
377
                                 bool MarkAsSink,
378
                                 ExplodedNode *P = nullptr,
379
1.63M
                                 const ProgramPointTag *Tag = nullptr) {
380
    // The analyzer may stop exploring if it sees a state it has previously
381
    // visited ("cache out"). The early return here is a defensive check to
382
    // prevent accidental caching out by checker API clients. Unless there is a
383
    // tag or the client checker has requested that the generated node be
384
    // marked as a sink, we assume that a client requesting a transition to a
385
    // state that is the same as the predecessor state has made a mistake. We
386
    // return the predecessor rather than cache out.
387
    //
388
    // TODO: We could potentially change the return to an assertion to alert
389
    // clients to their mistake, but several checkers (including
390
    // DereferenceChecker, CallAndMessageChecker, and DynamicTypePropagation)
391
    // rely upon the defensive behavior and would need to be updated.
392
1.63M
    if (!State || (State == Pred->getState() && 
!Tag1.56M
&&
!MarkAsSink1.54M
))
393
1.54M
      return Pred;
394
395
86.0k
    Changed = true;
396
86.0k
    const ProgramPoint &LocalLoc = (Tag ? 
Location.withTag(Tag)23.7k
:
Location62.2k
);
397
86.0k
    if (!P)
398
74.7k
      P = Pred;
399
400
86.0k
    ExplodedNode *node;
401
86.0k
    if (MarkAsSink)
402
7.77k
      node = NB.generateSink(LocalLoc, State, P);
403
78.2k
    else
404
78.2k
      node = NB.generateNode(LocalLoc, State, P);
405
86.0k
    return node;
406
1.63M
  }
407
};
408
409
} // end GR namespace
410
411
} // end clang namespace
412
413
#endif