1 //===--- BugReporter.h - Generate PathDiagnostics --------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines BugReporter, a utility class for generating
11 // PathDiagnostics for analyses based on ProgramState.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGREPORTER_H
16 #define LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGREPORTER_H
18 #include "clang/Basic/SourceLocation.h"
19 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
20 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h"
21 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
22 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
24 #include "llvm/ADT/DenseSet.h"
25 #include "llvm/ADT/FoldingSet.h"
26 #include "llvm/ADT/ImmutableSet.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/ilist.h"
29 #include "llvm/ADT/ilist_node.h"
34 class DiagnosticsEngine;
45 class BugReporterContext;
49 //===----------------------------------------------------------------------===//
50 // Interface for individual bug reports.
51 //===----------------------------------------------------------------------===//
53 /// This class provides an interface through which checkers can create
54 /// individual bug reports.
55 class BugReport : public llvm::ilist_node<BugReport> {
58 virtual void anchor();
60 virtual ~NodeResolver() {}
61 virtual const ExplodedNode*
62 getOriginalNode(const ExplodedNode *N) = 0;
65 typedef const SourceRange *ranges_iterator;
66 typedef SmallVector<std::unique_ptr<BugReporterVisitor>, 8> VisitorList;
67 typedef VisitorList::iterator visitor_iterator;
68 typedef SmallVector<StringRef, 2> ExtraTextList;
69 typedef SmallVector<const PathDiagnosticNotePiece *, 4> NoteList;
72 friend class BugReporter;
73 friend class BugReportEquivClass;
76 const Decl *DeclWithIssue;
77 std::string ShortDescription;
78 std::string Description;
79 PathDiagnosticLocation Location;
80 PathDiagnosticLocation UniqueingLocation;
81 const Decl *UniqueingDecl;
83 const ExplodedNode *ErrorNode;
84 SmallVector<SourceRange, 4> Ranges;
85 ExtraTextList ExtraText;
88 typedef llvm::DenseSet<SymbolRef> Symbols;
89 typedef llvm::DenseSet<const MemRegion *> Regions;
91 /// A (stack of) a set of symbols that are registered with this
92 /// report as being "interesting", and thus used to help decide which
93 /// diagnostics to include when constructing the final path diagnostic.
94 /// The stack is largely used by BugReporter when generating PathDiagnostics
95 /// for multiple PathDiagnosticConsumers.
96 SmallVector<Symbols *, 2> interestingSymbols;
98 /// A (stack of) set of regions that are registered with this report as being
99 /// "interesting", and thus used to help decide which diagnostics
100 /// to include when constructing the final path diagnostic.
101 /// The stack is largely used by BugReporter when generating PathDiagnostics
102 /// for multiple PathDiagnosticConsumers.
103 SmallVector<Regions *, 2> interestingRegions;
105 /// A set of location contexts that correspoind to call sites which should be
106 /// considered "interesting".
107 llvm::SmallSet<const LocationContext *, 2> InterestingLocationContexts;
109 /// A set of custom visitors which generate "event" diagnostics at
110 /// interesting points in the path.
111 VisitorList Callbacks;
113 /// Used for ensuring the visitors are only added once.
114 llvm::FoldingSet<BugReporterVisitor> CallbacksSet;
116 /// Used for clients to tell if the report's configuration has changed
117 /// since the last time they checked.
118 unsigned ConfigurationChangeToken;
120 /// When set, this flag disables all callstack pruning from a diagnostic
121 /// path. This is useful for some reports that want maximum fidelty
122 /// when reporting an issue.
125 /// Used to track unique reasons why a bug report might be invalid.
128 /// \sa removeInvalidation
129 typedef std::pair<const void *, const void *> InvalidationRecord;
131 /// If non-empty, this bug report is likely a false positive and should not be
132 /// shown to the user.
135 /// \sa removeInvalidation
136 llvm::SmallSet<InvalidationRecord, 4> Invalidations;
139 // Used internally by BugReporter.
140 Symbols &getInterestingSymbols();
141 Regions &getInterestingRegions();
143 void lazyInitializeInterestingSets();
144 void pushInterestingSymbolsAndRegions();
145 void popInterestingSymbolsAndRegions();
148 BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode)
149 : BT(bt), DeclWithIssue(nullptr), Description(desc), ErrorNode(errornode),
150 ConfigurationChangeToken(0), DoNotPrunePath(false) {}
152 BugReport(BugType& bt, StringRef shortDesc, StringRef desc,
153 const ExplodedNode *errornode)
154 : BT(bt), DeclWithIssue(nullptr), ShortDescription(shortDesc),
155 Description(desc), ErrorNode(errornode), ConfigurationChangeToken(0),
156 DoNotPrunePath(false) {}
158 BugReport(BugType &bt, StringRef desc, PathDiagnosticLocation l)
159 : BT(bt), DeclWithIssue(nullptr), Description(desc), Location(l),
160 ErrorNode(nullptr), ConfigurationChangeToken(0), DoNotPrunePath(false) {}
162 /// \brief Create a BugReport with a custom uniqueing location.
164 /// The reports that have the same report location, description, bug type, and
165 /// ranges are uniqued - only one of the equivalent reports will be presented
166 /// to the user. This method allows to rest the location which should be used
167 /// for uniquing reports. For example, memory leaks checker, could set this to
168 /// the allocation site, rather then the location where the bug is reported.
169 BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode,
170 PathDiagnosticLocation LocationToUnique, const Decl *DeclToUnique)
171 : BT(bt), DeclWithIssue(nullptr), Description(desc),
172 UniqueingLocation(LocationToUnique),
173 UniqueingDecl(DeclToUnique),
174 ErrorNode(errornode), ConfigurationChangeToken(0),
175 DoNotPrunePath(false) {}
177 virtual ~BugReport();
179 const BugType& getBugType() const { return BT; }
180 BugType& getBugType() { return BT; }
182 /// \brief True when the report has an execution path associated with it.
184 /// A report is said to be path-sensitive if it was thrown against a
185 /// particular exploded node in the path-sensitive analysis graph.
186 /// Path-sensitive reports have their intermediate path diagnostics
187 /// auto-generated, perhaps with the help of checker-defined visitors,
188 /// and may contain extra notes.
189 /// Path-insensitive reports consist only of a single warning message
190 /// in a specific location, and perhaps extra notes.
191 /// Path-sensitive checkers are allowed to throw path-insensitive reports.
192 bool isPathSensitive() const { return ErrorNode != nullptr; }
194 const ExplodedNode *getErrorNode() const { return ErrorNode; }
196 StringRef getDescription() const { return Description; }
198 StringRef getShortDescription(bool UseFallback = true) const {
199 if (ShortDescription.empty() && UseFallback)
201 return ShortDescription;
204 /// Indicates whether or not any path pruning should take place
205 /// when generating a PathDiagnostic from this BugReport.
206 bool shouldPrunePath() const { return !DoNotPrunePath; }
208 /// Disable all path pruning when generating a PathDiagnostic.
209 void disablePathPruning() { DoNotPrunePath = true; }
211 void markInteresting(SymbolRef sym);
212 void markInteresting(const MemRegion *R);
213 void markInteresting(SVal V);
214 void markInteresting(const LocationContext *LC);
216 bool isInteresting(SymbolRef sym);
217 bool isInteresting(const MemRegion *R);
218 bool isInteresting(SVal V);
219 bool isInteresting(const LocationContext *LC);
221 unsigned getConfigurationChangeToken() const {
222 return ConfigurationChangeToken;
225 /// Returns whether or not this report should be considered valid.
227 /// Invalid reports are those that have been classified as likely false
228 /// positives after the fact.
229 bool isValid() const {
230 return Invalidations.empty();
233 /// Marks the current report as invalid, meaning that it is probably a false
234 /// positive and should not be reported to the user.
236 /// The \p Tag and \p Data arguments are intended to be opaque identifiers for
237 /// this particular invalidation, where \p Tag represents the visitor
238 /// responsible for invalidation, and \p Data represents the reason this
239 /// visitor decided to invalidate the bug report.
241 /// \sa removeInvalidation
242 void markInvalid(const void *Tag, const void *Data) {
243 Invalidations.insert(std::make_pair(Tag, Data));
246 /// Reverses the effects of a previous invalidation.
249 void removeInvalidation(const void *Tag, const void *Data) {
250 Invalidations.erase(std::make_pair(Tag, Data));
253 /// Return the canonical declaration, be it a method or class, where
254 /// this issue semantically occurred.
255 const Decl *getDeclWithIssue() const;
257 /// Specifically set the Decl where an issue occurred. This isn't necessary
258 /// for BugReports that cover a path as it will be automatically inferred.
259 void setDeclWithIssue(const Decl *declWithIssue) {
260 DeclWithIssue = declWithIssue;
263 /// Add new item to the list of additional notes that need to be attached to
264 /// this path-insensitive report. If you want to add extra notes to a
265 /// path-sensitive report, you need to use a BugReporterVisitor because it
266 /// allows you to specify where exactly in the auto-generated path diagnostic
267 /// the extra note should appear.
268 void addNote(StringRef Msg, const PathDiagnosticLocation &Pos,
269 ArrayRef<SourceRange> Ranges = {}) {
270 auto *P = new PathDiagnosticNotePiece(Pos, Msg);
272 for (const auto &R : Ranges)
278 virtual const NoteList &getNotes() {
282 /// \brief This allows for addition of meta data to the diagnostic.
284 /// Currently, only the HTMLDiagnosticClient knows how to display it.
285 void addExtraText(StringRef S) {
286 ExtraText.push_back(S);
289 virtual const ExtraTextList &getExtraText() {
293 /// \brief Return the "definitive" location of the reported bug.
295 /// While a bug can span an entire path, usually there is a specific
296 /// location that can be used to identify where the key issue occurred.
297 /// This location is used by clients rendering diagnostics.
298 virtual PathDiagnosticLocation getLocation(const SourceManager &SM) const;
300 /// \brief Get the location on which the report should be uniqued.
301 PathDiagnosticLocation getUniqueingLocation() const {
302 return UniqueingLocation;
305 /// \brief Get the declaration containing the uniqueing location.
306 const Decl *getUniqueingDecl() const {
307 return UniqueingDecl;
310 const Stmt *getStmt() const;
312 /// \brief Add a range to a bug report.
314 /// Ranges are used to highlight regions of interest in the source code.
315 /// They should be at the same source code line as the BugReport location.
316 /// By default, the source range of the statement corresponding to the error
317 /// node will be used; add a single invalid range to specify absence of
319 void addRange(SourceRange R) {
320 assert((R.isValid() || Ranges.empty()) && "Invalid range can only be used "
321 "to specify that the report does not have a range.");
325 /// \brief Get the SourceRanges associated with the report.
326 virtual llvm::iterator_range<ranges_iterator> getRanges();
328 /// \brief Add custom or predefined bug report visitors to this report.
330 /// The visitors should be used when the default trace is not sufficient.
331 /// For example, they allow constructing a more elaborate trace.
332 /// \sa registerConditionVisitor(), registerTrackNullOrUndefValue(),
333 /// registerFindLastStore(), registerNilReceiverVisitor(), and
334 /// registerVarDeclsLastStore().
335 void addVisitor(std::unique_ptr<BugReporterVisitor> visitor);
337 /// Iterators through the custom diagnostic visitors.
338 visitor_iterator visitor_begin() { return Callbacks.begin(); }
339 visitor_iterator visitor_end() { return Callbacks.end(); }
341 /// Profile to identify equivalent bug reports for error report coalescing.
342 /// Reports are uniqued to ensure that we do not emit multiple diagnostics
344 virtual void Profile(llvm::FoldingSetNodeID& hash) const;
347 //===----------------------------------------------------------------------===//
348 // BugTypes (collections of related reports).
349 //===----------------------------------------------------------------------===//
351 class BugReportEquivClass : public llvm::FoldingSetNode {
352 /// List of *owned* BugReport objects.
353 llvm::ilist<BugReport> Reports;
355 friend class BugReporter;
356 void AddReport(std::unique_ptr<BugReport> R) {
357 Reports.push_back(R.release());
361 BugReportEquivClass(std::unique_ptr<BugReport> R) { AddReport(std::move(R)); }
362 ~BugReportEquivClass();
364 void Profile(llvm::FoldingSetNodeID& ID) const {
365 assert(!Reports.empty());
366 Reports.front().Profile(ID);
369 typedef llvm::ilist<BugReport>::iterator iterator;
370 typedef llvm::ilist<BugReport>::const_iterator const_iterator;
372 iterator begin() { return Reports.begin(); }
373 iterator end() { return Reports.end(); }
375 const_iterator begin() const { return Reports.begin(); }
376 const_iterator end() const { return Reports.end(); }
379 //===----------------------------------------------------------------------===//
380 // BugReporter and friends.
381 //===----------------------------------------------------------------------===//
383 class BugReporterData {
385 virtual ~BugReporterData();
386 virtual DiagnosticsEngine& getDiagnostic() = 0;
387 virtual ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() = 0;
388 virtual ASTContext &getASTContext() = 0;
389 virtual SourceManager& getSourceManager() = 0;
390 virtual AnalyzerOptions& getAnalyzerOptions() = 0;
393 /// BugReporter is a utility class for generating PathDiagnostics for analysis.
394 /// It collects the BugReports and BugTypes and knows how to generate
395 /// and flush the corresponding diagnostics.
398 enum Kind { BaseBRKind, GRBugReporterKind };
401 typedef llvm::ImmutableSet<BugType*> BugTypesTy;
402 BugTypesTy::Factory F;
408 /// Generate and flush the diagnostics for the given bug report.
409 void FlushReport(BugReportEquivClass& EQ);
411 /// Generate and flush the diagnostics for the given bug report
412 /// and PathDiagnosticConsumer.
413 void FlushReport(BugReport *exampleReport,
414 PathDiagnosticConsumer &PD,
415 ArrayRef<BugReport*> BugReports);
417 /// The set of bug reports tracked by the BugReporter.
418 llvm::FoldingSet<BugReportEquivClass> EQClasses;
419 /// A vector of BugReports for tracking the allocated pointers and cleanup.
420 std::vector<BugReportEquivClass *> EQClassesVector;
423 BugReporter(BugReporterData& d, Kind k) : BugTypes(F.getEmptySet()), kind(k),
427 BugReporter(BugReporterData& d) : BugTypes(F.getEmptySet()), kind(BaseBRKind),
429 virtual ~BugReporter();
431 /// \brief Generate and flush diagnostics for all bug reports.
434 Kind getKind() const { return kind; }
436 DiagnosticsEngine& getDiagnostic() {
437 return D.getDiagnostic();
440 ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() {
441 return D.getPathDiagnosticConsumers();
444 /// \brief Iterator over the set of BugTypes tracked by the BugReporter.
445 typedef BugTypesTy::iterator iterator;
446 iterator begin() { return BugTypes.begin(); }
447 iterator end() { return BugTypes.end(); }
449 /// \brief Iterator over the set of BugReports tracked by the BugReporter.
450 typedef llvm::FoldingSet<BugReportEquivClass>::iterator EQClasses_iterator;
451 EQClasses_iterator EQClasses_begin() { return EQClasses.begin(); }
452 EQClasses_iterator EQClasses_end() { return EQClasses.end(); }
454 ASTContext &getContext() { return D.getASTContext(); }
456 SourceManager& getSourceManager() { return D.getSourceManager(); }
458 AnalyzerOptions& getAnalyzerOptions() { return D.getAnalyzerOptions(); }
460 virtual bool generatePathDiagnostic(PathDiagnostic& pathDiagnostic,
461 PathDiagnosticConsumer &PC,
462 ArrayRef<BugReport *> &bugReports) {
466 bool RemoveUnneededCalls(PathPieces &pieces, BugReport *R);
468 void Register(BugType *BT);
470 /// \brief Add the given report to the set of reports tracked by BugReporter.
472 /// The reports are usually generated by the checkers. Further, they are
473 /// folded based on the profile value, which is done to coalesce similar
475 void emitReport(std::unique_ptr<BugReport> R);
477 void EmitBasicReport(const Decl *DeclWithIssue, const CheckerBase *Checker,
478 StringRef BugName, StringRef BugCategory,
479 StringRef BugStr, PathDiagnosticLocation Loc,
480 ArrayRef<SourceRange> Ranges = None);
482 void EmitBasicReport(const Decl *DeclWithIssue, CheckName CheckName,
483 StringRef BugName, StringRef BugCategory,
484 StringRef BugStr, PathDiagnosticLocation Loc,
485 ArrayRef<SourceRange> Ranges = None);
488 llvm::StringMap<BugType *> StrBugTypes;
490 /// \brief Returns a BugType that is associated with the given name and
492 BugType *getBugTypeForName(CheckName CheckName, StringRef name,
496 // FIXME: Get rid of GRBugReporter. It's the wrong abstraction.
497 class GRBugReporter : public BugReporter {
500 GRBugReporter(BugReporterData& d, ExprEngine& eng)
501 : BugReporter(d, GRBugReporterKind), Eng(eng) {}
503 ~GRBugReporter() override;
505 /// getEngine - Return the analysis engine used to analyze a given
506 /// function or method.
507 ExprEngine &getEngine() { return Eng; }
509 /// getGraph - Get the exploded graph created by the analysis engine
510 /// for the analyzed method or function.
511 ExplodedGraph &getGraph();
513 /// getStateManager - Return the state manager used by the analysis
515 ProgramStateManager &getStateManager();
517 /// Generates a path corresponding to one of the given bug reports.
519 /// Which report is used for path generation is not specified. The
520 /// bug reporter will try to pick the shortest path, but this is not
523 /// \return True if the report was valid and a path was generated,
524 /// false if the reports should be considered invalid.
525 bool generatePathDiagnostic(PathDiagnostic &PD, PathDiagnosticConsumer &PC,
526 ArrayRef<BugReport*> &bugReports) override;
528 /// classof - Used by isa<>, cast<>, and dyn_cast<>.
529 static bool classof(const BugReporter* R) {
530 return R->getKind() == GRBugReporterKind;
534 class BugReporterContext {
535 virtual void anchor();
538 BugReporterContext(GRBugReporter& br) : BR(br) {}
540 virtual ~BugReporterContext() {}
542 GRBugReporter& getBugReporter() { return BR; }
544 ExplodedGraph &getGraph() { return BR.getGraph(); }
546 ProgramStateManager& getStateManager() {
547 return BR.getStateManager();
550 SValBuilder& getSValBuilder() {
551 return getStateManager().getSValBuilder();
554 ASTContext &getASTContext() {
555 return BR.getContext();
558 SourceManager& getSourceManager() {
559 return BR.getSourceManager();
562 virtual BugReport::NodeResolver& getNodeResolver() = 0;
565 } // end GR namespace
567 } // end clang namespace