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/LLVM.h"
19 #include "clang/Basic/SourceLocation.h"
20 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.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 "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.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"
47 class AnalyzerOptions;
50 class DiagnosticsEngine;
51 class LocationContext;
65 //===----------------------------------------------------------------------===//
66 // Interface for individual bug reports.
67 //===----------------------------------------------------------------------===//
69 /// A mapping from diagnostic consumers to the diagnostics they should
71 using DiagnosticForConsumerMapTy =
72 llvm::DenseMap<PathDiagnosticConsumer *, std::unique_ptr<PathDiagnostic>>;
74 /// This class provides an interface through which checkers can create
75 /// individual bug reports.
76 class BugReport : public llvm::ilist_node<BugReport> {
79 virtual void anchor();
82 virtual ~NodeResolver() = default;
84 virtual const ExplodedNode*
85 getOriginalNode(const ExplodedNode *N) = 0;
88 using ranges_iterator = const SourceRange *;
89 using VisitorList = SmallVector<std::unique_ptr<BugReporterVisitor>, 8>;
90 using visitor_iterator = VisitorList::iterator;
91 using ExtraTextList = SmallVector<StringRef, 2>;
92 using NoteList = SmallVector<std::shared_ptr<PathDiagnosticNotePiece>, 4>;
95 friend class BugReportEquivClass;
96 friend class BugReporter;
99 const Decl *DeclWithIssue = nullptr;
100 std::string ShortDescription;
101 std::string Description;
102 PathDiagnosticLocation Location;
103 PathDiagnosticLocation UniqueingLocation;
104 const Decl *UniqueingDecl;
106 const ExplodedNode *ErrorNode = nullptr;
107 SmallVector<SourceRange, 4> Ranges;
108 ExtraTextList ExtraText;
111 using Symbols = llvm::DenseSet<SymbolRef>;
112 using Regions = llvm::DenseSet<const MemRegion *>;
114 /// A (stack of) a set of symbols that are registered with this
115 /// report as being "interesting", and thus used to help decide which
116 /// diagnostics to include when constructing the final path diagnostic.
117 /// The stack is largely used by BugReporter when generating PathDiagnostics
118 /// for multiple PathDiagnosticConsumers.
119 SmallVector<Symbols *, 2> interestingSymbols;
121 /// A (stack of) set of regions that are registered with this report as being
122 /// "interesting", and thus used to help decide which diagnostics
123 /// to include when constructing the final path diagnostic.
124 /// The stack is largely used by BugReporter when generating PathDiagnostics
125 /// for multiple PathDiagnosticConsumers.
126 SmallVector<Regions *, 2> interestingRegions;
128 /// A set of location contexts that correspoind to call sites which should be
129 /// considered "interesting".
130 llvm::SmallSet<const LocationContext *, 2> InterestingLocationContexts;
132 /// A set of custom visitors which generate "event" diagnostics at
133 /// interesting points in the path.
134 VisitorList Callbacks;
136 /// Used for ensuring the visitors are only added once.
137 llvm::FoldingSet<BugReporterVisitor> CallbacksSet;
139 /// When set, this flag disables all callstack pruning from a diagnostic
140 /// path. This is useful for some reports that want maximum fidelty
141 /// when reporting an issue.
142 bool DoNotPrunePath = false;
144 /// Used to track unique reasons why a bug report might be invalid.
147 /// \sa removeInvalidation
148 using InvalidationRecord = std::pair<const void *, const void *>;
150 /// If non-empty, this bug report is likely a false positive and should not be
151 /// shown to the user.
154 /// \sa removeInvalidation
155 llvm::SmallSet<InvalidationRecord, 4> Invalidations;
158 // Used internally by BugReporter.
159 Symbols &getInterestingSymbols();
160 Regions &getInterestingRegions();
162 void lazyInitializeInterestingSets();
163 void pushInterestingSymbolsAndRegions();
164 void popInterestingSymbolsAndRegions();
167 BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode)
168 : BT(bt), Description(desc), ErrorNode(errornode) {}
170 BugReport(BugType& bt, StringRef shortDesc, StringRef desc,
171 const ExplodedNode *errornode)
172 : BT(bt), ShortDescription(shortDesc), Description(desc),
173 ErrorNode(errornode) {}
175 BugReport(BugType &bt, StringRef desc, PathDiagnosticLocation l)
176 : BT(bt), Description(desc), Location(l) {}
178 /// Create a BugReport with a custom uniqueing location.
180 /// The reports that have the same report location, description, bug type, and
181 /// ranges are uniqued - only one of the equivalent reports will be presented
182 /// to the user. This method allows to rest the location which should be used
183 /// for uniquing reports. For example, memory leaks checker, could set this to
184 /// the allocation site, rather then the location where the bug is reported.
185 BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode,
186 PathDiagnosticLocation LocationToUnique, const Decl *DeclToUnique)
187 : BT(bt), Description(desc), UniqueingLocation(LocationToUnique),
188 UniqueingDecl(DeclToUnique), ErrorNode(errornode) {}
190 virtual ~BugReport();
192 const BugType& getBugType() const { return BT; }
193 BugType& getBugType() { return BT; }
195 /// True when the report has an execution path associated with it.
197 /// A report is said to be path-sensitive if it was thrown against a
198 /// particular exploded node in the path-sensitive analysis graph.
199 /// Path-sensitive reports have their intermediate path diagnostics
200 /// auto-generated, perhaps with the help of checker-defined visitors,
201 /// and may contain extra notes.
202 /// Path-insensitive reports consist only of a single warning message
203 /// in a specific location, and perhaps extra notes.
204 /// Path-sensitive checkers are allowed to throw path-insensitive reports.
205 bool isPathSensitive() const { return ErrorNode != nullptr; }
207 const ExplodedNode *getErrorNode() const { return ErrorNode; }
209 StringRef getDescription() const { return Description; }
211 StringRef getShortDescription(bool UseFallback = true) const {
212 if (ShortDescription.empty() && UseFallback)
214 return ShortDescription;
217 /// Indicates whether or not any path pruning should take place
218 /// when generating a PathDiagnostic from this BugReport.
219 bool shouldPrunePath() const { return !DoNotPrunePath; }
221 /// Disable all path pruning when generating a PathDiagnostic.
222 void disablePathPruning() { DoNotPrunePath = true; }
224 void markInteresting(SymbolRef sym);
225 void markInteresting(const MemRegion *R);
226 void markInteresting(SVal V);
227 void markInteresting(const LocationContext *LC);
229 bool isInteresting(SymbolRef sym);
230 bool isInteresting(const MemRegion *R);
231 bool isInteresting(SVal V);
232 bool isInteresting(const LocationContext *LC);
234 /// Returns whether or not this report should be considered valid.
236 /// Invalid reports are those that have been classified as likely false
237 /// positives after the fact.
238 bool isValid() const {
239 return Invalidations.empty();
242 /// Marks the current report as invalid, meaning that it is probably a false
243 /// positive and should not be reported to the user.
245 /// The \p Tag and \p Data arguments are intended to be opaque identifiers for
246 /// this particular invalidation, where \p Tag represents the visitor
247 /// responsible for invalidation, and \p Data represents the reason this
248 /// visitor decided to invalidate the bug report.
250 /// \sa removeInvalidation
251 void markInvalid(const void *Tag, const void *Data) {
252 Invalidations.insert(std::make_pair(Tag, Data));
255 /// Return the canonical declaration, be it a method or class, where
256 /// this issue semantically occurred.
257 const Decl *getDeclWithIssue() const;
259 /// Specifically set the Decl where an issue occurred. This isn't necessary
260 /// for BugReports that cover a path as it will be automatically inferred.
261 void setDeclWithIssue(const Decl *declWithIssue) {
262 DeclWithIssue = declWithIssue;
265 /// Add new item to the list of additional notes that need to be attached to
266 /// this path-insensitive report. If you want to add extra notes to a
267 /// path-sensitive report, you need to use a BugReporterVisitor because it
268 /// allows you to specify where exactly in the auto-generated path diagnostic
269 /// the extra note should appear.
270 void addNote(StringRef Msg, const PathDiagnosticLocation &Pos,
271 ArrayRef<SourceRange> Ranges) {
272 auto P = std::make_shared<PathDiagnosticNotePiece>(Pos, Msg);
274 for (const auto &R : Ranges)
277 Notes.push_back(std::move(P));
280 // FIXME: Instead of making an override, we could have default-initialized
281 // Ranges with {}, however it crashes the MSVC 2013 compiler.
282 void addNote(StringRef Msg, const PathDiagnosticLocation &Pos) {
283 std::vector<SourceRange> Ranges;
284 addNote(Msg, Pos, Ranges);
287 virtual const NoteList &getNotes() {
291 /// This allows for addition of meta data to the diagnostic.
293 /// Currently, only the HTMLDiagnosticClient knows how to display it.
294 void addExtraText(StringRef S) {
295 ExtraText.push_back(S);
298 virtual const ExtraTextList &getExtraText() {
302 /// Return the "definitive" location of the reported bug.
304 /// While a bug can span an entire path, usually there is a specific
305 /// location that can be used to identify where the key issue occurred.
306 /// This location is used by clients rendering diagnostics.
307 virtual PathDiagnosticLocation getLocation(const SourceManager &SM) const;
309 /// Get the location on which the report should be uniqued.
310 PathDiagnosticLocation getUniqueingLocation() const {
311 return UniqueingLocation;
314 /// Get the declaration containing the uniqueing location.
315 const Decl *getUniqueingDecl() const {
316 return UniqueingDecl;
319 const Stmt *getStmt() const;
321 /// Add a range to a bug report.
323 /// Ranges are used to highlight regions of interest in the source code.
324 /// They should be at the same source code line as the BugReport location.
325 /// By default, the source range of the statement corresponding to the error
326 /// node will be used; add a single invalid range to specify absence of
328 void addRange(SourceRange R) {
329 assert((R.isValid() || Ranges.empty()) && "Invalid range can only be used "
330 "to specify that the report does not have a range.");
334 /// Get the SourceRanges associated with the report.
335 virtual llvm::iterator_range<ranges_iterator> getRanges();
337 /// Add custom or predefined bug report visitors to this report.
339 /// The visitors should be used when the default trace is not sufficient.
340 /// For example, they allow constructing a more elaborate trace.
341 /// \sa registerConditionVisitor(), registerTrackNullOrUndefValue(),
342 /// registerFindLastStore(), registerNilReceiverVisitor(), and
343 /// registerVarDeclsLastStore().
344 void addVisitor(std::unique_ptr<BugReporterVisitor> visitor);
346 /// Remove all visitors attached to this bug report.
347 void clearVisitors();
349 /// Iterators through the custom diagnostic visitors.
350 visitor_iterator visitor_begin() { return Callbacks.begin(); }
351 visitor_iterator visitor_end() { return Callbacks.end(); }
353 /// Profile to identify equivalent bug reports for error report coalescing.
354 /// Reports are uniqued to ensure that we do not emit multiple diagnostics
356 virtual void Profile(llvm::FoldingSetNodeID& hash) const;
359 //===----------------------------------------------------------------------===//
360 // BugTypes (collections of related reports).
361 //===----------------------------------------------------------------------===//
363 class BugReportEquivClass : public llvm::FoldingSetNode {
364 friend class BugReporter;
366 /// List of *owned* BugReport objects.
367 llvm::ilist<BugReport> Reports;
369 void AddReport(std::unique_ptr<BugReport> R) {
370 Reports.push_back(R.release());
374 BugReportEquivClass(std::unique_ptr<BugReport> R) { AddReport(std::move(R)); }
375 ~BugReportEquivClass();
377 void Profile(llvm::FoldingSetNodeID& ID) const {
378 assert(!Reports.empty());
379 Reports.front().Profile(ID);
382 using iterator = llvm::ilist<BugReport>::iterator;
383 using const_iterator = llvm::ilist<BugReport>::const_iterator;
385 iterator begin() { return Reports.begin(); }
386 iterator end() { return Reports.end(); }
388 const_iterator begin() const { return Reports.begin(); }
389 const_iterator end() const { return Reports.end(); }
392 //===----------------------------------------------------------------------===//
393 // BugReporter and friends.
394 //===----------------------------------------------------------------------===//
396 class BugReporterData {
398 virtual ~BugReporterData();
400 virtual DiagnosticsEngine& getDiagnostic() = 0;
401 virtual ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() = 0;
402 virtual ASTContext &getASTContext() = 0;
403 virtual SourceManager &getSourceManager() = 0;
404 virtual AnalyzerOptions &getAnalyzerOptions() = 0;
407 /// BugReporter is a utility class for generating PathDiagnostics for analysis.
408 /// It collects the BugReports and BugTypes and knows how to generate
409 /// and flush the corresponding diagnostics.
411 /// The base class is used for generating path-insensitive
414 enum Kind { BaseBRKind, GRBugReporterKind };
417 using BugTypesTy = llvm::ImmutableSet<BugType *>;
419 BugTypesTy::Factory F;
425 /// Generate and flush the diagnostics for the given bug report.
426 void FlushReport(BugReportEquivClass& EQ);
428 /// Generate the diagnostics for the given bug report.
429 std::unique_ptr<DiagnosticForConsumerMapTy>
430 generateDiagnosticForConsumerMap(BugReport *exampleReport,
431 ArrayRef<PathDiagnosticConsumer *> consumers,
432 ArrayRef<BugReport *> bugReports);
434 /// The set of bug reports tracked by the BugReporter.
435 llvm::FoldingSet<BugReportEquivClass> EQClasses;
437 /// A vector of BugReports for tracking the allocated pointers and cleanup.
438 std::vector<BugReportEquivClass *> EQClassesVector;
441 BugReporter(BugReporterData& d, Kind k)
442 : BugTypes(F.getEmptySet()), kind(k), D(d) {}
445 BugReporter(BugReporterData& d)
446 : BugTypes(F.getEmptySet()), kind(BaseBRKind), D(d) {}
447 virtual ~BugReporter();
449 /// Generate and flush diagnostics for all bug reports.
452 Kind getKind() const { return kind; }
454 DiagnosticsEngine& getDiagnostic() {
455 return D.getDiagnostic();
458 ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() {
459 return D.getPathDiagnosticConsumers();
462 /// Iterator over the set of BugTypes tracked by the BugReporter.
463 using iterator = BugTypesTy::iterator;
464 iterator begin() { return BugTypes.begin(); }
465 iterator end() { return BugTypes.end(); }
467 /// Iterator over the set of BugReports tracked by the BugReporter.
468 using EQClasses_iterator = llvm::FoldingSet<BugReportEquivClass>::iterator;
469 EQClasses_iterator EQClasses_begin() { return EQClasses.begin(); }
470 EQClasses_iterator EQClasses_end() { return EQClasses.end(); }
472 ASTContext &getContext() { return D.getASTContext(); }
474 SourceManager &getSourceManager() { return D.getSourceManager(); }
476 AnalyzerOptions &getAnalyzerOptions() { return D.getAnalyzerOptions(); }
478 virtual std::unique_ptr<DiagnosticForConsumerMapTy>
479 generatePathDiagnostics(ArrayRef<PathDiagnosticConsumer *> consumers,
480 ArrayRef<BugReport *> &bugReports) {
484 void Register(BugType *BT);
486 /// Add the given report to the set of reports tracked by BugReporter.
488 /// The reports are usually generated by the checkers. Further, they are
489 /// folded based on the profile value, which is done to coalesce similar
491 void emitReport(std::unique_ptr<BugReport> R);
493 void EmitBasicReport(const Decl *DeclWithIssue, const CheckerBase *Checker,
494 StringRef BugName, StringRef BugCategory,
495 StringRef BugStr, PathDiagnosticLocation Loc,
496 ArrayRef<SourceRange> Ranges = None);
498 void EmitBasicReport(const Decl *DeclWithIssue, CheckName CheckName,
499 StringRef BugName, StringRef BugCategory,
500 StringRef BugStr, PathDiagnosticLocation Loc,
501 ArrayRef<SourceRange> Ranges = None);
504 llvm::StringMap<BugType *> StrBugTypes;
506 /// Returns a BugType that is associated with the given name and
508 BugType *getBugTypeForName(CheckName CheckName, StringRef name,
512 /// GRBugReporter is used for generating path-sensitive reports.
513 class GRBugReporter : public BugReporter {
517 GRBugReporter(BugReporterData& d, ExprEngine& eng)
518 : BugReporter(d, GRBugReporterKind), Eng(eng) {}
520 ~GRBugReporter() override;
522 /// getGraph - Get the exploded graph created by the analysis engine
523 /// for the analyzed method or function.
524 ExplodedGraph &getGraph();
526 /// getStateManager - Return the state manager used by the analysis
528 ProgramStateManager &getStateManager();
530 /// \p bugReports A set of bug reports within a *single* equivalence class
532 /// \return A mapping from consumers to the corresponding diagnostics.
533 /// Iterates through the bug reports within a single equivalence class,
534 /// stops at a first non-invalidated report.
535 std::unique_ptr<DiagnosticForConsumerMapTy>
536 generatePathDiagnostics(ArrayRef<PathDiagnosticConsumer *> consumers,
537 ArrayRef<BugReport *> &bugReports) override;
539 /// classof - Used by isa<>, cast<>, and dyn_cast<>.
540 static bool classof(const BugReporter* R) {
541 return R->getKind() == GRBugReporterKind;
546 class NodeMapClosure : public BugReport::NodeResolver {
547 InterExplodedGraphMap &M;
550 NodeMapClosure(InterExplodedGraphMap &m) : M(m) {}
552 const ExplodedNode *getOriginalNode(const ExplodedNode *N) override {
557 class BugReporterContext {
561 virtual void anchor();
564 BugReporterContext(GRBugReporter &br, InterExplodedGraphMap &Backmap)
565 : BR(br), NMC(Backmap) {}
567 virtual ~BugReporterContext() = default;
569 GRBugReporter& getBugReporter() { return BR; }
571 ExplodedGraph &getGraph() { return BR.getGraph(); }
573 ProgramStateManager& getStateManager() {
574 return BR.getStateManager();
577 SValBuilder &getSValBuilder() {
578 return getStateManager().getSValBuilder();
581 ASTContext &getASTContext() {
582 return BR.getContext();
585 SourceManager& getSourceManager() {
586 return BR.getSourceManager();
589 AnalyzerOptions &getAnalyzerOptions() {
590 return BR.getAnalyzerOptions();
593 NodeMapClosure& getNodeResolver() { return NMC; }
600 #endif // LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGREPORTER_H