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
45namespace clang {
46
47class AnalyzerOptions;
48class ASTContext;
49class Decl;
50class DiagnosticsEngine;
51class LocationContext;
52class SourceManager;
53class Stmt;
54
55namespace ento {
56
57class BugType;
58class CheckerBase;
59class ExplodedGraph;
60class ExplodedNode;
61class ExprEngine;
62class MemRegion;
63class SValBuilder;
64
65//===----------------------------------------------------------------------===//
66// Interface for individual bug reports.
67//===----------------------------------------------------------------------===//
68
69/// A mapping from diagnostic consumers to the diagnostics they should
70/// consume.
71using 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.
78class StackHintGenerator {
79public:
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.
92class StackHintGeneratorForSymbol : public StackHintGenerator {
93private:
94 SymbolRef Sym;
95 std::string Msg;
96
97public:
98 StackHintGeneratorForSymbol(SymbolRef S, StringRef M) : Sym(S), Msg(M) {}
99 ~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 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
110 return Msg;
111 }
112
113 virtual std::string getMessageForSymbolNotFound() {
114 return Msg;
115 }
116};
117
118/// This class provides an interface through which checkers can create
119/// individual bug reports.
120class BugReport {
121public:
122 enum class Kind { Basic, PathSensitive };
123
124protected:
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 : 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 Description(Description) {}
144
145public:
146 virtual ~BugReport() = default;
147
148 Kind getKind() const { return K; }
149
150 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 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 StringRef getShortDescription(bool UseFallback = true) const {
165 if (ShortDescription.empty() && UseFallback)
166 return Description;
167 return ShortDescription;
168 }
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 ArrayRef<SourceRange> Ranges = {}) {
204 auto P = std::make_shared<PathDiagnosticNotePiece>(Pos, Msg);
205
206 for (const auto &R : Ranges)
207 P->addRange(R);
208
209 Notes.push_back(std::move(P));
210 }
211
212 ArrayRef<std::shared_ptr<PathDiagnosticNotePiece>> getNotes() {
213 return Notes;
214 }
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 void addRange(SourceRange R) {
224 assert((R.isValid() || Ranges.empty()) && "Invalid range can only be used "
225 "to specify that the report does not have a range.");
226 Ranges.push_back(R);
227 }
228
229 /// Get the SourceRanges associated with the report.
230 virtual ArrayRef<SourceRange> getRanges() const {
231 return Ranges;
232 }
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 void addFixItHint(const FixItHint &F) {
242 Fixits.push_back(F);
243 }
244
245 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
252class BasicBugReport : public BugReport {
253 PathDiagnosticLocation Location;
254 const Decl *DeclWithIssue = nullptr;
255
256public:
257 BasicBugReport(const BugType &bt, StringRef desc, PathDiagnosticLocation l)
258 : BugReport(Kind::Basic, bt, desc), Location(l) {}
259
260 static bool classof(const BugReport *R) {
261 return R->getKind() == Kind::Basic;
262 }
263
264 PathDiagnosticLocation getLocation() const override {
265 assert(Location.isValid());
266 return Location;
267 }
268
269 const Decl *getDeclWithIssue() const override {
270 return DeclWithIssue;
271 }
272
273 PathDiagnosticLocation getUniqueingLocation() const override {
274 return getLocation();
275 }
276
277 const Decl *getUniqueingDecl() const override {
278 return getDeclWithIssue();
279 }
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 void setDeclWithIssue(const Decl *declWithIssue) {
284 DeclWithIssue = declWithIssue;
285 }
286
287 void Profile(llvm::FoldingSetNodeID& hash) const override;
288};
289
290class PathSensitiveBugReport : public BugReport {
291public:
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
296protected:
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
369public:
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 : 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 : 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 UniqueingLocation(LocationToUnique), UniqueingDecl(DeclToUnique) {
397 assert(errorNode);
398 }
399
400 static bool classof(const BugReport *R) {
401 return R->getKind() == Kind::PathSensitive;
402 }
403
404 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 bool shouldPrunePath() const { return !DoNotPrunePath; }
409
410 /// Disable all path pruning when generating a PathDiagnostic.
411 void disablePathPruning() { DoNotPrunePath = true; }
412
413 /// Get the location on which the report should be uniqued.
414 PathDiagnosticLocation getUniqueingLocation() const override {
415 return UniqueingLocation;
416 }
417
418 /// Get the declaration containing the uniqueing location.
419 const Decl *getUniqueingDecl() const override {
420 return UniqueingDecl;
421 }
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 bool isValid() const {
467 return Invalidations.empty();
468 }
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 void markInvalid(const void *Tag, const void *Data) {
480 Invalidations.insert(std::make_pair(Tag, Data));
481 }
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 visitor_iterator visitor_begin() { return Callbacks.begin(); }
502 visitor_iterator visitor_end() { return Callbacks.end(); }
503 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 bool addTrackedCondition(const ExplodedNode *Cond) {
509 return TrackedConditions.insert(Cond).second;
510 }
511
512 void addCallStackHint(PathDiagnosticPieceRef Piece,
513 std::unique_ptr<StackHintGenerator> StackHint) {
514 StackHints[Piece] = std::move(StackHint);
515 }
516
517 bool hasCallStackHint(PathDiagnosticPieceRef Piece) const {
518 return StackHints.count(Piece) > 0;
519 }
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 const ExplodedNode *N) const {
526 auto I = StackHints.find(Piece);
527 if (I != StackHints.end())
528 return I->second->getMessage(N);
529 return "";
530 }
531};
532
533//===----------------------------------------------------------------------===//
534// BugTypes (collections of related reports).
535//===----------------------------------------------------------------------===//
536
537class 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 void AddReport(std::unique_ptr<BugReport> &&R) {
544 Reports.push_back(std::move(R));
545 }
546
547public:
548 BugReportEquivClass(std::unique_ptr<BugReport> R) { AddReport(std::move(R)); }
549
550 ArrayRef<std::unique_ptr<BugReport>> getReports() const { return Reports; }
551
552 void Profile(llvm::FoldingSetNodeID& ID) const {
553 assert(!Reports.empty());
554 Reports.front()->Profile(ID);
555 }
556};
557
558//===----------------------------------------------------------------------===//
559// BugReporter and friends.
560//===----------------------------------------------------------------------===//
561
562class BugReporterData {
563public:
564 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
578class BugReporter {
579private:
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
591public:
592 BugReporter(BugReporterData &d) : D(d) {}
593 virtual ~BugReporter();
594
595 /// Generate and flush diagnostics for all bug reports.
596 void FlushReports();
597
598 ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() {
599 return D.getPathDiagnosticConsumers();
600 }
601
602 /// Iterator over the set of BugReports tracked by the BugReporter.
603 using EQClasses_iterator = llvm::FoldingSet<BugReportEquivClass>::iterator;
604 EQClasses_iterator EQClasses_begin() { return EQClasses.begin(); }
605 EQClasses_iterator EQClasses_end() { return EQClasses.end(); }
606
607 ASTContext &getContext() { return D.getASTContext(); }
608
609 const SourceManager &getSourceManager() { return D.getSourceManager(); }
610
611 const AnalyzerOptions &getAnalyzerOptions() { return D.getAnalyzerOptions(); }
612
613 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
634private:
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 SmallVectorImpl<BugReport *> &bugReports) {
645 return eqClass.getReports()[0].get();
646 }
647
648protected:
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.
657class 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;
669public:
670 PathSensitiveBugReporter(BugReporterData& d, ExprEngine& eng)
671 : 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
694class BugReporterContext {
695 PathSensitiveBugReporter &BR;
696
697 virtual void anchor();
698
699public:
700 BugReporterContext(PathSensitiveBugReporter &br) : BR(br) {}
701
702 virtual ~BugReporterContext() = default;
703
704 PathSensitiveBugReporter& getBugReporter() { return BR; }
705
706 ProgramStateManager& getStateManager() const {
707 return BR.getStateManager();
708 }
709
710 ASTContext &getASTContext() const {
711 return BR.getContext();
712 }
713
714 const SourceManager& getSourceManager() const {
715 return BR.getSourceManager();
716 }
717
718 const AnalyzerOptions &getAnalyzerOptions() const {
719 return BR.getAnalyzerOptions();
720 }
721};
722
723
724/// The tag upon which the TagVisitor reacts. Add these in order to display
725/// additional PathDiagnosticEventPieces along the path.
726class NoteTag : public ProgramPointTag {
727public:
728 using Callback =
729 std::function<std::string(BugReporterContext &,
730 PathSensitiveBugReport &)>;
731
732private:
733 static int Kind;
734
735 const Callback Cb;
736 const bool IsPrunable;
737
738 NoteTag(Callback &&Cb, bool IsPrunable)
739 : ProgramPointTag(&Kind), Cb(std::move(Cb)), IsPrunable(IsPrunable) {}
740
741public:
742 static bool classof(const ProgramPointTag *T) {
743 return T->getTagKind() == &Kind;
744 }
745
746 Optional<std::string> generateMessage(BugReporterContext &BRC,
747 PathSensitiveBugReport &R) const {
748 std::string Msg = Cb(BRC, R);
749 if (Msg.empty())
750 return None;
751
752 return std::move(Msg);
753 }
754
755 StringRef getTagDescription() const override {
756 // TODO: Remember a few examples of generated messages
757 // and display them in the ExplodedGraph dump by
758 // returning them from this function.
759 return "Note Tag";
760 }
761
762 bool isPrunable() const { return IsPrunable; }
763
764 // Manage memory for NoteTag objects.
765 class Factory {
766 std::vector<std::unique_ptr<NoteTag>> Tags;
767
768 public:
769 const NoteTag *makeNoteTag(Callback &&Cb, bool IsPrunable = false) {
770 // We cannot use std::make_unique because we cannot access the private
771 // constructor from inside it.
772 std::unique_ptr<NoteTag> T(new NoteTag(std::move(Cb), IsPrunable));
773 Tags.push_back(std::move(T));
774 return Tags.back().get();
775 }
776 };
777
778 friend class TagVisitor;
779};
780
781} // namespace ento
782
783} // namespace clang
784
785#endif // LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGREPORTER_H
786