Coverage Report

Created: 2020-02-15 09:57

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
Line
Count
Source (jump to first uncovered line)
1
//===- BugReporter.h - Generate PathDiagnostics -----------------*- 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 BugReporter, a utility class for generating
10
//  PathDiagnostics for analyses based on ProgramState.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#ifndef LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGREPORTER_H
15
#define LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGREPORTER_H
16
17
#include "clang/Analysis/PathDiagnostic.h"
18
#include "clang/Basic/LLVM.h"
19
#include "clang/Basic/SourceLocation.h"
20
#include "clang/Lex/Preprocessor.h"
21
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
22
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
23
#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
24
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
25
#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
26
#include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
27
#include "llvm/ADT/ArrayRef.h"
28
#include "llvm/ADT/DenseSet.h"
29
#include "llvm/ADT/FoldingSet.h"
30
#include "llvm/ADT/ImmutableSet.h"
31
#include "llvm/ADT/None.h"
32
#include "llvm/ADT/SmallSet.h"
33
#include "llvm/ADT/SmallVector.h"
34
#include "llvm/ADT/StringMap.h"
35
#include "llvm/ADT/StringRef.h"
36
#include "llvm/ADT/ilist.h"
37
#include "llvm/ADT/ilist_node.h"
38
#include "llvm/ADT/iterator_range.h"
39
#include <cassert>
40
#include <memory>
41
#include <string>
42
#include <utility>
43
#include <vector>
44
45
namespace clang {
46
47
class AnalyzerOptions;
48
class ASTContext;
49
class Decl;
50
class DiagnosticsEngine;
51
class LocationContext;
52
class SourceManager;
53
class Stmt;
54
55
namespace ento {
56
57
class BugType;
58
class CheckerBase;
59
class ExplodedGraph;
60
class ExplodedNode;
61
class ExprEngine;
62
class MemRegion;
63
class SValBuilder;
64
65
//===----------------------------------------------------------------------===//
66
// Interface for individual bug reports.
67
//===----------------------------------------------------------------------===//
68
69
/// A mapping from diagnostic consumers to the diagnostics they should
70
/// consume.
71
using DiagnosticForConsumerMapTy =
72
    llvm::DenseMap<PathDiagnosticConsumer *, std::unique_ptr<PathDiagnostic>>;
73
74
/// Interface for classes constructing Stack hints.
75
///
76
/// If a PathDiagnosticEvent occurs in a different frame than the final
77
/// diagnostic the hints can be used to summarize the effect of the call.
78
class StackHintGenerator {
79
public:
80
  virtual ~StackHintGenerator() = 0;
81
82
  /// Construct the Diagnostic message for the given ExplodedNode.
83
  virtual std::string getMessage(const ExplodedNode *N) = 0;
84
};
85
86
/// Constructs a Stack hint for the given symbol.
87
///
88
/// The class knows how to construct the stack hint message based on
89
/// traversing the CallExpr associated with the call and checking if the given
90
/// symbol is returned or is one of the arguments.
91
/// The hint can be customized by redefining 'getMessageForX()' methods.
92
class StackHintGeneratorForSymbol : public StackHintGenerator {
93
private:
94
  SymbolRef Sym;
95
  std::string Msg;
96
97
public:
98
683
  StackHintGeneratorForSymbol(SymbolRef S, StringRef M) : Sym(S), Msg(M) {}
99
683
  ~StackHintGeneratorForSymbol() override = default;
100
101
  /// Search the call expression for the symbol Sym and dispatch the
102
  /// 'getMessageForX()' methods to construct a specific message.
103
  std::string getMessage(const ExplodedNode *N) override;
104
105
  /// Produces the message of the following form:
106
  ///   'Msg via Nth parameter'
107
  virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex);
108
109
7
  virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
110
7
    return Msg;
111
7
  }
112
113
6
  virtual std::string getMessageForSymbolNotFound() {
114
6
    return Msg;
115
6
  }
116
};
117
118
/// This class provides an interface through which checkers can create
119
/// individual bug reports.
120
class BugReport {
121
public:
122
  enum class Kind { Basic, PathSensitive };
123
124
protected:
125
  friend class BugReportEquivClass;
126
  friend class BugReporter;
127
128
  Kind K;
129
  const BugType& BT;
130
  std::string ShortDescription;
131
  std::string Description;
132
133
  SmallVector<SourceRange, 4> Ranges;
134
  SmallVector<std::shared_ptr<PathDiagnosticNotePiece>, 4> Notes;
135
  SmallVector<FixItHint, 4> Fixits;
136
137
  BugReport(Kind kind, const BugType &bt, StringRef desc)
138
14.1k
      : K(kind), BT(bt), Description(desc) {}
139
140
  BugReport(Kind K, const BugType &BT, StringRef ShortDescription,
141
            StringRef Description)
142
      : K(K), BT(BT), ShortDescription(ShortDescription),
143
32
        Description(Description) {}
144
145
public:
146
14.2k
  virtual ~BugReport() = default;
147
148
81.1k
  Kind getKind() const { return K; }
149
150
61.3k
  const BugType& getBugType() const { return BT; }
151
152
  /// A verbose warning message that is appropriate for displaying next to
153
  /// the source code that introduces the problem. The description should be
154
  /// at least a full sentence starting with a capital letter. The period at
155
  /// the end of the warning is traditionally omitted. If the description
156
  /// consists of multiple sentences, periods between the sentences are
157
  /// encouraged, but the period at the end of the description is still omitted.
158
38.5k
  StringRef getDescription() const { return Description; }
159
160
  /// A short general warning message that is appropriate for displaying in
161
  /// the list of all reported bugs. It should describe what kind of bug is found
162
  /// but does not need to try to go into details of that specific bug.
163
  /// Grammatical conventions of getDescription() apply here as well.
164
24.6k
  StringRef getShortDescription(bool UseFallback = true) const {
165
24.6k
    if (ShortDescription.empty() && 
UseFallback24.6k
)
166
0
      return Description;
167
24.6k
    return ShortDescription;
168
24.6k
  }
169
170
  /// The primary location of the bug report that points at the undesirable
171
  /// behavior in the code. UIs should attach the warning description to this
172
  /// location. The warning description should describe the bad behavior
173
  /// at this location.
174
  virtual PathDiagnosticLocation getLocation() const = 0;
175
176
  /// The smallest declaration that contains the bug location.
177
  /// This is purely cosmetic; the declaration can be displayed to the user
178
  /// but it does not affect whether the report is emitted.
179
  virtual const Decl *getDeclWithIssue() const = 0;
180
181
  /// Get the location on which the report should be uniqued. Two warnings are
182
  /// considered to be equivalent whenever they have the same bug types,
183
  /// descriptions, and uniqueing locations. Out of a class of equivalent
184
  /// warnings only one gets displayed to the user. For most warnings the
185
  /// uniqueing location coincides with their location, but sometimes
186
  /// it makes sense to use different locations. For example, a leak
187
  /// checker can place the warning at the location where the last reference
188
  /// to the leaking resource is dropped but at the same time unique the warning
189
  /// by where that resource is acquired (allocated).
190
  virtual PathDiagnosticLocation getUniqueingLocation() const = 0;
191
192
  /// Get the declaration that corresponds to (usually contains) the uniqueing
193
  /// location. This is not actively used for uniqueing, i.e. otherwise
194
  /// identical reports that have different uniqueing decls will be considered
195
  /// equivalent.
196
  virtual const Decl *getUniqueingDecl() const = 0;
197
198
  /// Add new item to the list of additional notes that need to be attached to
199
  /// this report. If the report is path-sensitive, these notes will not be
200
  /// displayed as part of the execution path explanation, but will be displayed
201
  /// separately. Use bug visitors if you need to add an extra path note.
202
  void addNote(StringRef Msg, const PathDiagnosticLocation &Pos,
203
166
               ArrayRef<SourceRange> Ranges = {}) {
204
166
    auto P = std::make_shared<PathDiagnosticNotePiece>(Pos, Msg);
205
166
206
166
    for (const auto &R : Ranges)
207
19
      P->addRange(R);
208
166
209
166
    Notes.push_back(std::move(P));
210
166
  }
211
212
27.5k
  ArrayRef<std::shared_ptr<PathDiagnosticNotePiece>> getNotes() {
213
27.5k
    return Notes;
214
27.5k
  }
215
216
  /// Add a range to a bug report.
217
  ///
218
  /// Ranges are used to highlight regions of interest in the source code.
219
  /// They should be at the same source code line as the BugReport location.
220
  /// By default, the source range of the statement corresponding to the error
221
  /// node will be used; add a single invalid range to specify absence of
222
  /// ranges.
223
4.24k
  void addRange(SourceRange R) {
224
4.24k
    assert((R.isValid() || Ranges.empty()) && "Invalid range can only be used "
225
4.24k
                           "to specify that the report does not have a range.");
226
4.24k
    Ranges.push_back(R);
227
4.24k
  }
228
229
  /// Get the SourceRanges associated with the report.
230
1.22k
  virtual ArrayRef<SourceRange> getRanges() const {
231
1.22k
    return Ranges;
232
1.22k
  }
233
234
  /// Add a fix-it hint to the bug report.
235
  ///
236
  /// Fix-it hints are the suggested edits to the code that would resolve
237
  /// the problem explained by the bug report. Fix-it hints should be
238
  /// as conservative as possible because it is not uncommon for the user
239
  /// to blindly apply all fixits to their project. Note that it is very hard
240
  /// to produce a good fix-it hint for most path-sensitive warnings.
241
12
  void addFixItHint(const FixItHint &F) {
242
12
    Fixits.push_back(F);
243
12
  }
244
245
13.7k
  llvm::ArrayRef<FixItHint> getFixits() const { return Fixits; }
246
247
  /// Reports are uniqued to ensure that we do not emit multiple diagnostics
248
  /// for each bug.
249
  virtual void Profile(llvm::FoldingSetNodeID& hash) const = 0;
250
};
251
252
class BasicBugReport : public BugReport {
253
  PathDiagnosticLocation Location;
254
  const Decl *DeclWithIssue = nullptr;
255
256
public:
257
  BasicBugReport(const BugType &bt, StringRef desc, PathDiagnosticLocation l)
258
1.22k
      : BugReport(Kind::Basic, bt, desc), Location(l) {}
259
260
13.2k
  static bool classof(const BugReport *R) {
261
13.2k
    return R->getKind() == Kind::Basic;
262
13.2k
  }
263
264
3.66k
  PathDiagnosticLocation getLocation() const override {
265
3.66k
    assert(Location.isValid());
266
3.66k
    return Location;
267
3.66k
  }
268
269
2.44k
  const Decl *getDeclWithIssue() const override {
270
2.44k
    return DeclWithIssue;
271
2.44k
  }
272
273
1.22k
  PathDiagnosticLocation getUniqueingLocation() const override {
274
1.22k
    return getLocation();
275
1.22k
  }
276
277
1.22k
  const Decl *getUniqueingDecl() const override {
278
1.22k
    return getDeclWithIssue();
279
1.22k
  }
280
281
  /// Specifically set the Decl where an issue occurred. This isn't necessary
282
  /// for BugReports that cover a path as it will be automatically inferred.
283
1.21k
  void setDeclWithIssue(const Decl *declWithIssue) {
284
1.21k
    DeclWithIssue = declWithIssue;
285
1.21k
  }
286
287
  void Profile(llvm::FoldingSetNodeID& hash) const override;
288
};
289
290
class PathSensitiveBugReport : public BugReport {
291
public:
292
  using VisitorList = SmallVector<std::unique_ptr<BugReporterVisitor>, 8>;
293
  using visitor_iterator = VisitorList::iterator;
294
  using visitor_range = llvm::iterator_range<visitor_iterator>;
295
296
protected:
297
  /// The ExplodedGraph node against which the report was thrown. It corresponds
298
  /// to the end of the execution path that demonstrates the bug.
299
  const ExplodedNode *ErrorNode = nullptr;
300
301
  /// The range that corresponds to ErrorNode's program point. It is usually
302
  /// highlighted in the report.
303
  const SourceRange ErrorNodeRange;
304
305
  /// Profile to identify equivalent bug reports for error report coalescing.
306
307
  /// A (stack of) a set of symbols that are registered with this
308
  /// report as being "interesting", and thus used to help decide which
309
  /// diagnostics to include when constructing the final path diagnostic.
310
  /// The stack is largely used by BugReporter when generating PathDiagnostics
311
  /// for multiple PathDiagnosticConsumers.
312
  llvm::DenseMap<SymbolRef, bugreporter::TrackingKind> InterestingSymbols;
313
314
  /// A (stack of) set of regions that are registered with this report as being
315
  /// "interesting", and thus used to help decide which diagnostics
316
  /// to include when constructing the final path diagnostic.
317
  /// The stack is largely used by BugReporter when generating PathDiagnostics
318
  /// for multiple PathDiagnosticConsumers.
319
  llvm::DenseMap<const MemRegion *, bugreporter::TrackingKind>
320
      InterestingRegions;
321
322
  /// A set of location contexts that correspoind to call sites which should be
323
  /// considered "interesting".
324
  llvm::SmallSet<const LocationContext *, 2> InterestingLocationContexts;
325
326
  /// A set of custom visitors which generate "event" diagnostics at
327
  /// interesting points in the path.
328
  VisitorList Callbacks;
329
330
  /// Used for ensuring the visitors are only added once.
331
  llvm::FoldingSet<BugReporterVisitor> CallbacksSet;
332
333
  /// When set, this flag disables all callstack pruning from a diagnostic
334
  /// path.  This is useful for some reports that want maximum fidelty
335
  /// when reporting an issue.
336
  bool DoNotPrunePath = false;
337
338
  /// Used to track unique reasons why a bug report might be invalid.
339
  ///
340
  /// \sa markInvalid
341
  /// \sa removeInvalidation
342
  using InvalidationRecord = std::pair<const void *, const void *>;
343
344
  /// If non-empty, this bug report is likely a false positive and should not be
345
  /// shown to the user.
346
  ///
347
  /// \sa markInvalid
348
  /// \sa removeInvalidation
349
  llvm::SmallSet<InvalidationRecord, 4> Invalidations;
350
351
  /// Conditions we're already tracking.
352
  llvm::SmallSet<const ExplodedNode *, 4> TrackedConditions;
353
354
  /// Reports with different uniqueing locations are considered to be different
355
  /// for the purposes of deduplication.
356
  PathDiagnosticLocation UniqueingLocation;
357
  const Decl *UniqueingDecl;
358
359
  const Stmt *getStmt() const;
360
361
  /// If an event occurs in a different frame than the final diagnostic,
362
  /// supply a message that will be used to construct an extra hint on the
363
  /// returns from all the calls on the stack from this event to the final
364
  /// diagnostic.
365
  // FIXME: Allow shared_ptr keys in DenseMap?
366
  std::map<PathDiagnosticPieceRef, std::unique_ptr<StackHintGenerator>>
367
      StackHints;
368
369
public:
370
  PathSensitiveBugReport(const BugType &bt, StringRef desc,
371
                         const ExplodedNode *errorNode)
372
      : BugReport(Kind::PathSensitive, bt, desc), ErrorNode(errorNode),
373
        ErrorNodeRange(getStmt() ? getStmt()->getSourceRange()
374
12.2k
                                 : SourceRange()) {}
375
376
  PathSensitiveBugReport(const BugType &bt, StringRef shortDesc, StringRef desc,
377
                         const ExplodedNode *errorNode)
378
      : BugReport(Kind::PathSensitive, bt, shortDesc, desc),
379
        ErrorNode(errorNode),
380
        ErrorNodeRange(getStmt() ? getStmt()->getSourceRange()
381
32
                                 : SourceRange()) {}
382
383
  /// Create a PathSensitiveBugReport with a custom uniqueing location.
384
  ///
385
  /// The reports that have the same report location, description, bug type, and
386
  /// ranges are uniqued - only one of the equivalent reports will be presented
387
  /// to the user. This method allows to rest the location which should be used
388
  /// for uniquing reports. For example, memory leaks checker, could set this to
389
  /// the allocation site, rather then the location where the bug is reported.
390
  PathSensitiveBugReport(const BugType &bt, StringRef desc,
391
                         const ExplodedNode *errorNode,
392
                         PathDiagnosticLocation LocationToUnique,
393
                         const Decl *DeclToUnique)
394
      : BugReport(Kind::PathSensitive, bt, desc), ErrorNode(errorNode),
395
        ErrorNodeRange(getStmt() ? getStmt()->getSourceRange() : SourceRange()),
396
670
        UniqueingLocation(LocationToUnique), UniqueingDecl(DeclToUnique) {
397
670
    assert(errorNode);
398
670
  }
399
400
52.4k
  static bool classof(const BugReport *R) {
401
52.4k
    return R->getKind() == Kind::PathSensitive;
402
52.4k
  }
403
404
105k
  const ExplodedNode *getErrorNode() const { return ErrorNode; }
405
406
  /// Indicates whether or not any path pruning should take place
407
  /// when generating a PathDiagnostic from this BugReport.
408
1.62k
  bool shouldPrunePath() const { return !DoNotPrunePath; }
409
410
  /// Disable all path pruning when generating a PathDiagnostic.
411
6
  void disablePathPruning() { DoNotPrunePath = true; }
412
413
  /// Get the location on which the report should be uniqued.
414
37.6k
  PathDiagnosticLocation getUniqueingLocation() const override {
415
37.6k
    return UniqueingLocation;
416
37.6k
  }
417
418
  /// Get the declaration containing the uniqueing location.
419
23.4k
  const Decl *getUniqueingDecl() const override {
420
23.4k
    return UniqueingDecl;
421
23.4k
  }
422
423
  const Decl *getDeclWithIssue() const override;
424
425
  ArrayRef<SourceRange> getRanges() const override;
426
427
  PathDiagnosticLocation getLocation() const override;
428
429
  /// Marks a symbol as interesting. Different kinds of interestingness will
430
  /// be processed differently by visitors (e.g. if the tracking kind is
431
  /// condition, will append "will be used as a condition" to the message).
432
  void markInteresting(SymbolRef sym, bugreporter::TrackingKind TKind =
433
                                          bugreporter::TrackingKind::Thorough);
434
435
  /// Marks a region as interesting. Different kinds of interestingness will
436
  /// be processed differently by visitors (e.g. if the tracking kind is
437
  /// condition, will append "will be used as a condition" to the message).
438
  void markInteresting(
439
      const MemRegion *R,
440
      bugreporter::TrackingKind TKind = bugreporter::TrackingKind::Thorough);
441
442
  /// Marks a symbolic value as interesting. Different kinds of interestingness
443
  /// will be processed differently by visitors (e.g. if the tracking kind is
444
  /// condition, will append "will be used as a condition" to the message).
445
  void markInteresting(SVal V, bugreporter::TrackingKind TKind =
446
                                   bugreporter::TrackingKind::Thorough);
447
  void markInteresting(const LocationContext *LC);
448
449
  bool isInteresting(SymbolRef sym) const;
450
  bool isInteresting(const MemRegion *R) const;
451
  bool isInteresting(SVal V) const;
452
  bool isInteresting(const LocationContext *LC) const;
453
454
  Optional<bugreporter::TrackingKind>
455
  getInterestingnessKind(SymbolRef sym) const;
456
457
  Optional<bugreporter::TrackingKind>
458
  getInterestingnessKind(const MemRegion *R) const;
459
460
  Optional<bugreporter::TrackingKind> getInterestingnessKind(SVal V) const;
461
462
  /// Returns whether or not this report should be considered valid.
463
  ///
464
  /// Invalid reports are those that have been classified as likely false
465
  /// positives after the fact.
466
1.31M
  bool isValid() const {
467
1.31M
    return Invalidations.empty();
468
1.31M
  }
469
470
  /// Marks the current report as invalid, meaning that it is probably a false
471
  /// positive and should not be reported to the user.
472
  ///
473
  /// The \p Tag and \p Data arguments are intended to be opaque identifiers for
474
  /// this particular invalidation, where \p Tag represents the visitor
475
  /// responsible for invalidation, and \p Data represents the reason this
476
  /// visitor decided to invalidate the bug report.
477
  ///
478
  /// \sa removeInvalidation
479
225
  void markInvalid(const void *Tag, const void *Data) {
480
225
    Invalidations.insert(std::make_pair(Tag, Data));
481
225
  }
482
483
  /// Profile to identify equivalent bug reports for error report coalescing.
484
  /// Reports are uniqued to ensure that we do not emit multiple diagnostics
485
  /// for each bug.
486
  void Profile(llvm::FoldingSetNodeID &hash) const override;
487
488
  /// Add custom or predefined bug report visitors to this report.
489
  ///
490
  /// The visitors should be used when the default trace is not sufficient.
491
  /// For example, they allow constructing a more elaborate trace.
492
  /// \sa registerConditionVisitor(), registerTrackNullOrUndefValue(),
493
  /// registerFindLastStore(), registerNilReceiverVisitor(), and
494
  /// registerVarDeclsLastStore().
495
  void addVisitor(std::unique_ptr<BugReporterVisitor> visitor);
496
497
  /// Remove all visitors attached to this bug report.
498
  void clearVisitors();
499
500
  /// Iterators through the custom diagnostic visitors.
501
1.27M
  visitor_iterator visitor_begin() { return Callbacks.begin(); }
502
1.27M
  visitor_iterator visitor_end() { return Callbacks.end(); }
503
1.27M
  visitor_range visitors() { return {visitor_begin(), visitor_end()}; }
504
505
  /// Notes that the condition of the CFGBlock associated with \p Cond is
506
  /// being tracked.
507
  /// \returns false if the condition is already being tracked.
508
1.28k
  bool addTrackedCondition(const ExplodedNode *Cond) {
509
1.28k
    return TrackedConditions.insert(Cond).second;
510
1.28k
  }
511
512
  void addCallStackHint(PathDiagnosticPieceRef Piece,
513
683
                        std::unique_ptr<StackHintGenerator> StackHint) {
514
683
    StackHints[Piece] = std::move(StackHint);
515
683
  }
516
517
2.71k
  bool hasCallStackHint(PathDiagnosticPieceRef Piece) const {
518
2.71k
    return StackHints.count(Piece) > 0;
519
2.71k
  }
520
521
  /// Produce the hint for the given node. The node contains
522
  /// information about the call for which the diagnostic can be generated.
523
  std::string
524
  getCallStackMessage(PathDiagnosticPieceRef Piece,
525
20
                      const ExplodedNode *N) const {
526
20
    auto I = StackHints.find(Piece);
527
20
    if (I != StackHints.end())
528
20
      return I->second->getMessage(N);
529
0
    return "";
530
0
  }
531
};
532
533
//===----------------------------------------------------------------------===//
534
// BugTypes (collections of related reports).
535
//===----------------------------------------------------------------------===//
536
537
class BugReportEquivClass : public llvm::FoldingSetNode {
538
  friend class BugReporter;
539
540
  /// List of *owned* BugReport objects.
541
  llvm::SmallVector<std::unique_ptr<BugReport>, 4> Reports;
542
543
14.2k
  void AddReport(std::unique_ptr<BugReport> &&R) {
544
14.2k
    Reports.push_back(std::move(R));
545
14.2k
  }
546
547
public:
548
13.2k
  BugReportEquivClass(std::unique_ptr<BugReport> R) { AddReport(std::move(R)); }
549
550
48.9k
  ArrayRef<std::unique_ptr<BugReport>> getReports() const { return Reports; }
551
552
1.25k
  void Profile(llvm::FoldingSetNodeID& ID) const {
553
1.25k
    assert(!Reports.empty());
554
1.25k
    Reports.front()->Profile(ID);
555
1.25k
  }
556
};
557
558
//===----------------------------------------------------------------------===//
559
// BugReporter and friends.
560
//===----------------------------------------------------------------------===//
561
562
class BugReporterData {
563
public:
564
1.25k
  virtual ~BugReporterData() = default;
565
566
  virtual ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() = 0;
567
  virtual ASTContext &getASTContext() = 0;
568
  virtual SourceManager &getSourceManager() = 0;
569
  virtual AnalyzerOptions &getAnalyzerOptions() = 0;
570
  virtual Preprocessor &getPreprocessor() = 0;
571
};
572
573
/// BugReporter is a utility class for generating PathDiagnostics for analysis.
574
/// It collects the BugReports and BugTypes and knows how to generate
575
/// and flush the corresponding diagnostics.
576
///
577
/// The base class is used for generating path-insensitive
578
class BugReporter {
579
private:
580
  BugReporterData& D;
581
582
  /// Generate and flush the diagnostics for the given bug report.
583
  void FlushReport(BugReportEquivClass& EQ);
584
585
  /// The set of bug reports tracked by the BugReporter.
586
  llvm::FoldingSet<BugReportEquivClass> EQClasses;
587
588
  /// A vector of BugReports for tracking the allocated pointers and cleanup.
589
  std::vector<BugReportEquivClass *> EQClassesVector;
590
591
public:
592
44.0k
  BugReporter(BugReporterData &d) : D(d) {}
593
  virtual ~BugReporter();
594
595
  /// Generate and flush diagnostics for all bug reports.
596
  void FlushReports();
597
598
13.2k
  ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() {
599
13.2k
    return D.getPathDiagnosticConsumers();
600
13.2k
  }
601
602
  /// Iterator over the set of BugReports tracked by the BugReporter.
603
  using EQClasses_iterator = llvm::FoldingSet<BugReportEquivClass>::iterator;
604
178
  EQClasses_iterator EQClasses_begin() { return EQClasses.begin(); }
605
178
  EQClasses_iterator EQClasses_end() { return EQClasses.end(); }
606
607
11.3k
  ASTContext &getContext() { return D.getASTContext(); }
608
609
300k
  const SourceManager &getSourceManager() { return D.getSourceManager(); }
610
611
63.6k
  const AnalyzerOptions &getAnalyzerOptions() { return D.getAnalyzerOptions(); }
612
613
19
  Preprocessor &getPreprocessor() { return D.getPreprocessor(); }
614
615
  /// Add the given report to the set of reports tracked by BugReporter.
616
  ///
617
  /// The reports are usually generated by the checkers. Further, they are
618
  /// folded based on the profile value, which is done to coalesce similar
619
  /// reports.
620
  virtual void emitReport(std::unique_ptr<BugReport> R);
621
622
  void EmitBasicReport(const Decl *DeclWithIssue, const CheckerBase *Checker,
623
                       StringRef BugName, StringRef BugCategory,
624
                       StringRef BugStr, PathDiagnosticLocation Loc,
625
                       ArrayRef<SourceRange> Ranges = None,
626
                       ArrayRef<FixItHint> Fixits = None);
627
628
  void EmitBasicReport(const Decl *DeclWithIssue, CheckerNameRef CheckerName,
629
                       StringRef BugName, StringRef BugCategory,
630
                       StringRef BugStr, PathDiagnosticLocation Loc,
631
                       ArrayRef<SourceRange> Ranges = None,
632
                       ArrayRef<FixItHint> Fixits = None);
633
634
private:
635
  llvm::StringMap<BugType *> StrBugTypes;
636
637
  /// Returns a BugType that is associated with the given name and
638
  /// category.
639
  BugType *getBugTypeForName(CheckerNameRef CheckerName, StringRef name,
640
                             StringRef category);
641
642
  virtual BugReport *
643
  findReportInEquivalenceClass(BugReportEquivClass &eqClass,
644
1.18k
                               SmallVectorImpl<BugReport *> &bugReports) {
645
1.18k
    return eqClass.getReports()[0].get();
646
1.18k
  }
647
648
protected:
649
  /// Generate the diagnostics for the given bug report.
650
  virtual std::unique_ptr<DiagnosticForConsumerMapTy>
651
  generateDiagnosticForConsumerMap(BugReport *exampleReport,
652
                                   ArrayRef<PathDiagnosticConsumer *> consumers,
653
                                   ArrayRef<BugReport *> bugReports);
654
};
655
656
/// GRBugReporter is used for generating path-sensitive reports.
657
class PathSensitiveBugReporter final : public BugReporter {
658
  ExprEngine& Eng;
659
660
  BugReport *findReportInEquivalenceClass(
661
      BugReportEquivClass &eqClass,
662
      SmallVectorImpl<BugReport *> &bugReports) override;
663
664
  /// Generate the diagnostics for the given bug report.
665
  std::unique_ptr<DiagnosticForConsumerMapTy>
666
  generateDiagnosticForConsumerMap(BugReport *exampleReport,
667
                                   ArrayRef<PathDiagnosticConsumer *> consumers,
668
                                   ArrayRef<BugReport *> bugReports) override;
669
public:
670
  PathSensitiveBugReporter(BugReporterData& d, ExprEngine& eng)
671
12.6k
      : BugReporter(d), Eng(eng) {}
672
673
  /// getGraph - Get the exploded graph created by the analysis engine
674
  ///  for the analyzed method or function.
675
  const ExplodedGraph &getGraph() const;
676
677
  /// getStateManager - Return the state manager used by the analysis
678
  ///  engine.
679
  ProgramStateManager &getStateManager() const;
680
681
  /// \p bugReports A set of bug reports within a *single* equivalence class
682
  ///
683
  /// \return A mapping from consumers to the corresponding diagnostics.
684
  /// Iterates through the bug reports within a single equivalence class,
685
  /// stops at a first non-invalidated report.
686
  std::unique_ptr<DiagnosticForConsumerMapTy> generatePathDiagnostics(
687
      ArrayRef<PathDiagnosticConsumer *> consumers,
688
      ArrayRef<PathSensitiveBugReport *> &bugReports);
689
690
  void emitReport(std::unique_ptr<BugReport> R) override;
691
};
692
693
694
class BugReporterContext {
695
  PathSensitiveBugReporter &BR;
696
697
  virtual void anchor();
698
699
public:
700
12.0k
  BugReporterContext(PathSensitiveBugReporter &br) : BR(br) {}
701
702
47.6k
  virtual ~BugReporterContext() = default;
703
704
0
  PathSensitiveBugReporter& getBugReporter() { return BR; }
705
706
33.6k
  ProgramStateManager& getStateManager() const {
707
33.6k
    return BR.getStateManager();
708
33.6k
  }
709
710
9.09k
  ASTContext &getASTContext() const {
711
9.09k
    return BR.getContext();
712
9.09k
  }
713
714
297k
  const SourceManager& getSourceManager() const {
715
297k
    return BR.getSourceManager();
716
297k
  }
717
718
26.1k
  const AnalyzerOptions &getAnalyzerOptions() const {
719
26.1k
    return BR.getAnalyzerOptions();
720
26.1k
  }
721
};
722
723
724
/// The tag upon which the TagVisitor reacts. Add these in order to display
725
/// additional PathDiagnosticEventPieces along the path.
726
class NoteTag : public ProgramPointTag {
727
public:
728
  using Callback =
729
      std::function<std::string(BugReporterContext &, BugReport &)>;
730
731
private:
732
  static int Kind;
733
734
  const Callback Cb;
735
  const bool IsPrunable;
736
737
  NoteTag(Callback &&Cb, bool IsPrunable)
738
238
      : ProgramPointTag(&Kind), Cb(std::move(Cb)), IsPrunable(IsPrunable) {}
739
740
public:
741
303k
  static bool classof(const ProgramPointTag *T) {
742
303k
    return T->getTagKind() == &Kind;
743
303k
  }
744
745
  Optional<std::string> generateMessage(BugReporterContext &BRC,
746
185
                                        BugReport &R) const {
747
185
    std::string Msg = Cb(BRC, R);
748
185
    if (Msg.empty())
749
2
      return None;
750
183
751
183
    return std::move(Msg);
752
183
  }
753
754
0
  StringRef getTagDescription() const override {
755
0
    // TODO: Remember a few examples of generated messages
756
0
    // and display them in the ExplodedGraph dump by
757
0
    // returning them from this function.
758
0
    return "Note Tag";
759
0
  }
760
761
183
  bool isPrunable() const { return IsPrunable; }
762
763
  // Manage memory for NoteTag objects.
764
  class Factory {
765
    std::vector<std::unique_ptr<NoteTag>> Tags;
766
767
  public:
768
238
    const NoteTag *makeNoteTag(Callback &&Cb, bool IsPrunable = false) {
769
238
      // We cannot use std::make_unique because we cannot access the private
770
238
      // constructor from inside it.
771
238
      std::unique_ptr<NoteTag> T(new NoteTag(std::move(Cb), IsPrunable));
772
238
      Tags.push_back(std::move(T));
773
238
      return Tags.back().get();
774
238
    }
775
  };
776
777
  friend class TagVisitor;
778
};
779
780
} // namespace ento
781
782
} // namespace clang
783
784
#endif // LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGREPORTER_H