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_GR_BUGREPORTER
16 #define LLVM_CLANG_GR_BUGREPORTER
18 #include "clang/Basic/SourceLocation.h"
19 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h"
20 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/ilist.h"
24 #include "llvm/ADT/ilist_node.h"
25 #include "llvm/ADT/ImmutableSet.h"
26 #include "llvm/ADT/DenseSet.h"
31 class DiagnosticsEngine;
42 class BugReporterContext;
46 //===----------------------------------------------------------------------===//
47 // Interface for individual bug reports.
48 //===----------------------------------------------------------------------===//
50 /// This class provides an interface through which checkers can create
51 /// individual bug reports.
52 class BugReport : public llvm::ilist_node<BugReport> {
55 virtual void anchor();
57 virtual ~NodeResolver() {}
58 virtual const ExplodedNode*
59 getOriginalNode(const ExplodedNode *N) = 0;
62 typedef const SourceRange *ranges_iterator;
63 typedef SmallVector<BugReporterVisitor *, 8> VisitorList;
64 typedef VisitorList::iterator visitor_iterator;
65 typedef SmallVector<StringRef, 2> ExtraTextList;
68 friend class BugReporter;
69 friend class BugReportEquivClass;
72 const Decl *DeclWithIssue;
73 std::string ShortDescription;
74 std::string Description;
75 PathDiagnosticLocation Location;
76 PathDiagnosticLocation UniqueingLocation;
77 const ExplodedNode *ErrorNode;
78 SmallVector<SourceRange, 4> Ranges;
79 ExtraTextList ExtraText;
81 typedef llvm::DenseSet<SymbolRef> Symbols;
82 typedef llvm::DenseSet<const MemRegion *> Regions;
84 /// A (stack of) a set of symbols that are registered with this
85 /// report as being "interesting", and thus used to help decide which
86 /// diagnostics to include when constructing the final path diagnostic.
87 /// The stack is largely used by BugReporter when generating PathDiagnostics
88 /// for multiple PathDiagnosticConsumers.
89 llvm::SmallVector<Symbols *, 2> interestingSymbols;
91 /// A (stack of) set of regions that are registered with this report as being
92 /// "interesting", and thus used to help decide which diagnostics
93 /// to include when constructing the final path diagnostic.
94 /// The stack is largely used by BugReporter when generating PathDiagnostics
95 /// for multiple PathDiagnosticConsumers.
96 llvm::SmallVector<Regions *, 2> interestingRegions;
98 /// A set of custom visitors which generate "event" diagnostics at
99 /// interesting points in the path.
100 VisitorList Callbacks;
102 /// Used for ensuring the visitors are only added once.
103 llvm::FoldingSet<BugReporterVisitor> CallbacksSet;
105 /// Used for clients to tell if the report's configuration has changed
106 /// since the last time they checked.
107 unsigned ConfigurationChangeToken;
109 /// When set, this flag disables all callstack pruning from a diagnostic
110 /// path. This is useful for some reports that want maximum fidelty
111 /// when reporting an issue.
115 // Used internally by BugReporter.
116 Symbols &getInterestingSymbols();
117 Regions &getInterestingRegions();
119 void lazyInitializeInterestingSets();
120 void pushInterestingSymbolsAndRegions();
121 void popInterestingSymbolsAndRegions();
124 BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode)
125 : BT(bt), DeclWithIssue(0), Description(desc), ErrorNode(errornode),
126 ConfigurationChangeToken(0), DoNotPrunePath(false) {}
128 BugReport(BugType& bt, StringRef shortDesc, StringRef desc,
129 const ExplodedNode *errornode)
130 : BT(bt), DeclWithIssue(0), ShortDescription(shortDesc), Description(desc),
131 ErrorNode(errornode), ConfigurationChangeToken(0),
132 DoNotPrunePath(false) {}
134 BugReport(BugType& bt, StringRef desc, PathDiagnosticLocation l)
135 : BT(bt), DeclWithIssue(0), Description(desc), Location(l), ErrorNode(0),
136 ConfigurationChangeToken(0),
137 DoNotPrunePath(false) {}
139 /// \brief Create a BugReport with a custom uniqueing location.
141 /// The reports that have the same report location, description, bug type, and
142 /// ranges are uniqued - only one of the equivalent reports will be presented
143 /// to the user. This method allows to rest the location which should be used
144 /// for uniquing reports. For example, memory leaks checker, could set this to
145 /// the allocation site, rather then the location where the bug is reported.
146 BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode,
147 PathDiagnosticLocation LocationToUnique)
148 : BT(bt), DeclWithIssue(0), Description(desc),
149 UniqueingLocation(LocationToUnique),
150 ErrorNode(errornode), ConfigurationChangeToken(0) {}
152 virtual ~BugReport();
154 const BugType& getBugType() const { return BT; }
155 BugType& getBugType() { return BT; }
157 const ExplodedNode *getErrorNode() const { return ErrorNode; }
159 const StringRef getDescription() const { return Description; }
161 const StringRef getShortDescription() const {
162 return ShortDescription.empty() ? Description : ShortDescription;
165 /// Indicates whether or not any path pruning should take place
166 /// when generating a PathDiagnostic from this BugReport.
167 bool shouldPrunePath() const { return !DoNotPrunePath; }
169 /// Disable all path pruning when generating a PathDiagnostic.
170 void disablePathPruning() { DoNotPrunePath = true; }
172 void markInteresting(SymbolRef sym);
173 void markInteresting(const MemRegion *R);
174 void markInteresting(SVal V);
176 bool isInteresting(SymbolRef sym);
177 bool isInteresting(const MemRegion *R);
178 bool isInteresting(SVal V);
180 unsigned getConfigurationChangeToken() const {
181 return ConfigurationChangeToken;
184 /// Return the canonical declaration, be it a method or class, where
185 /// this issue semantically occurred.
186 const Decl *getDeclWithIssue() const;
188 /// Specifically set the Decl where an issue occurred. This isn't necessary
189 /// for BugReports that cover a path as it will be automatically inferred.
190 void setDeclWithIssue(const Decl *declWithIssue) {
191 DeclWithIssue = declWithIssue;
194 /// \brief This allows for addition of meta data to the diagnostic.
196 /// Currently, only the HTMLDiagnosticClient knows how to display it.
197 void addExtraText(StringRef S) {
198 ExtraText.push_back(S);
201 virtual const ExtraTextList &getExtraText() {
205 /// \brief Return the "definitive" location of the reported bug.
207 /// While a bug can span an entire path, usually there is a specific
208 /// location that can be used to identify where the key issue occurred.
209 /// This location is used by clients rendering diagnostics.
210 virtual PathDiagnosticLocation getLocation(const SourceManager &SM) const;
212 const Stmt *getStmt() const;
214 /// \brief Add a range to a bug report.
216 /// Ranges are used to highlight regions of interest in the source code.
217 /// They should be at the same source code line as the BugReport location.
218 /// By default, the source range of the statement corresponding to the error
219 /// node will be used; add a single invalid range to specify absence of
221 void addRange(SourceRange R) {
222 assert((R.isValid() || Ranges.empty()) && "Invalid range can only be used "
223 "to specify that the report does not have a range.");
227 /// \brief Get the SourceRanges associated with the report.
228 virtual std::pair<ranges_iterator, ranges_iterator> getRanges();
230 /// \brief Add custom or predefined bug report visitors to this report.
232 /// The visitors should be used when the default trace is not sufficient.
233 /// For example, they allow constructing a more elaborate trace.
234 /// \sa registerConditionVisitor(), registerTrackNullOrUndefValue(),
235 /// registerFindLastStore(), registerNilReceiverVisitor(), and
236 /// registerVarDeclsLastStore().
237 void addVisitor(BugReporterVisitor *visitor);
239 /// Iterators through the custom diagnostic visitors.
240 visitor_iterator visitor_begin() { return Callbacks.begin(); }
241 visitor_iterator visitor_end() { return Callbacks.end(); }
243 /// Profile to identify equivalent bug reports for error report coalescing.
244 /// Reports are uniqued to ensure that we do not emit multiple diagnostics
246 virtual void Profile(llvm::FoldingSetNodeID& hash) const;
249 } // end ento namespace
250 } // end clang namespace
253 template<> struct ilist_traits<clang::ento::BugReport>
254 : public ilist_default_traits<clang::ento::BugReport> {
255 clang::ento::BugReport *createSentinel() const {
256 return static_cast<clang::ento::BugReport *>(&Sentinel);
258 void destroySentinel(clang::ento::BugReport *) const {}
260 clang::ento::BugReport *provideInitialHead() const {
261 return createSentinel();
263 clang::ento::BugReport *ensureHead(clang::ento::BugReport *) const {
264 return createSentinel();
267 mutable ilist_half_node<clang::ento::BugReport> Sentinel;
274 //===----------------------------------------------------------------------===//
275 // BugTypes (collections of related reports).
276 //===----------------------------------------------------------------------===//
278 class BugReportEquivClass : public llvm::FoldingSetNode {
279 /// List of *owned* BugReport objects.
280 llvm::ilist<BugReport> Reports;
282 friend class BugReporter;
283 void AddReport(BugReport* R) { Reports.push_back(R); }
285 BugReportEquivClass(BugReport* R) { Reports.push_back(R); }
286 ~BugReportEquivClass();
288 void Profile(llvm::FoldingSetNodeID& ID) const {
289 assert(!Reports.empty());
290 Reports.front().Profile(ID);
293 typedef llvm::ilist<BugReport>::iterator iterator;
294 typedef llvm::ilist<BugReport>::const_iterator const_iterator;
296 iterator begin() { return Reports.begin(); }
297 iterator end() { return Reports.end(); }
299 const_iterator begin() const { return Reports.begin(); }
300 const_iterator end() const { return Reports.end(); }
303 //===----------------------------------------------------------------------===//
304 // BugReporter and friends.
305 //===----------------------------------------------------------------------===//
307 class BugReporterData {
309 virtual ~BugReporterData();
310 virtual DiagnosticsEngine& getDiagnostic() = 0;
311 virtual ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() = 0;
312 virtual ASTContext &getASTContext() = 0;
313 virtual SourceManager& getSourceManager() = 0;
316 /// BugReporter is a utility class for generating PathDiagnostics for analysis.
317 /// It collects the BugReports and BugTypes and knows how to generate
318 /// and flush the corresponding diagnostics.
321 enum Kind { BaseBRKind, GRBugReporterKind };
324 typedef llvm::ImmutableSet<BugType*> BugTypesTy;
325 BugTypesTy::Factory F;
331 /// Generate and flush the diagnostics for the given bug report.
332 void FlushReport(BugReportEquivClass& EQ);
334 /// Generate and flush the diagnostics for the given bug report
335 /// and PathDiagnosticConsumer.
336 void FlushReport(BugReport *exampleReport,
337 PathDiagnosticConsumer &PD,
338 ArrayRef<BugReport*> BugReports);
340 /// The set of bug reports tracked by the BugReporter.
341 llvm::FoldingSet<BugReportEquivClass> EQClasses;
342 /// A vector of BugReports for tracking the allocated pointers and cleanup.
343 std::vector<BugReportEquivClass *> EQClassesVector;
346 BugReporter(BugReporterData& d, Kind k) : BugTypes(F.getEmptySet()), kind(k),
350 BugReporter(BugReporterData& d) : BugTypes(F.getEmptySet()), kind(BaseBRKind),
352 virtual ~BugReporter();
354 /// \brief Generate and flush diagnostics for all bug reports.
357 Kind getKind() const { return kind; }
359 DiagnosticsEngine& getDiagnostic() {
360 return D.getDiagnostic();
363 ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() {
364 return D.getPathDiagnosticConsumers();
367 /// \brief Iterator over the set of BugTypes tracked by the BugReporter.
368 typedef BugTypesTy::iterator iterator;
369 iterator begin() { return BugTypes.begin(); }
370 iterator end() { return BugTypes.end(); }
372 /// \brief Iterator over the set of BugReports tracked by the BugReporter.
373 typedef llvm::FoldingSet<BugReportEquivClass>::iterator EQClasses_iterator;
374 EQClasses_iterator EQClasses_begin() { return EQClasses.begin(); }
375 EQClasses_iterator EQClasses_end() { return EQClasses.end(); }
377 ASTContext &getContext() { return D.getASTContext(); }
379 SourceManager& getSourceManager() { return D.getSourceManager(); }
381 virtual void GeneratePathDiagnostic(PathDiagnostic& pathDiagnostic,
382 PathDiagnosticConsumer &PC,
383 ArrayRef<BugReport *> &bugReports) {}
385 void Register(BugType *BT);
387 /// \brief Add the given report to the set of reports tracked by BugReporter.
389 /// The reports are usually generated by the checkers. Further, they are
390 /// folded based on the profile value, which is done to coalesce similar
392 void EmitReport(BugReport *R);
394 void EmitBasicReport(const Decl *DeclWithIssue,
395 StringRef BugName, StringRef BugCategory,
396 StringRef BugStr, PathDiagnosticLocation Loc,
397 SourceRange* RangeBeg, unsigned NumRanges);
399 void EmitBasicReport(const Decl *DeclWithIssue,
400 StringRef BugName, StringRef BugCategory,
401 StringRef BugStr, PathDiagnosticLocation Loc) {
402 EmitBasicReport(DeclWithIssue, BugName, BugCategory, BugStr, Loc, 0, 0);
405 void EmitBasicReport(const Decl *DeclWithIssue,
406 StringRef BugName, StringRef Category,
407 StringRef BugStr, PathDiagnosticLocation Loc,
409 EmitBasicReport(DeclWithIssue, BugName, Category, BugStr, Loc, &R, 1);
412 static bool classof(const BugReporter* R) { return true; }
415 llvm::StringMap<BugType *> StrBugTypes;
417 /// \brief Returns a BugType that is associated with the given name and
419 BugType *getBugTypeForName(StringRef name, StringRef category);
422 // FIXME: Get rid of GRBugReporter. It's the wrong abstraction.
423 class GRBugReporter : public BugReporter {
426 GRBugReporter(BugReporterData& d, ExprEngine& eng)
427 : BugReporter(d, GRBugReporterKind), Eng(eng) {}
429 virtual ~GRBugReporter();
431 /// getEngine - Return the analysis engine used to analyze a given
432 /// function or method.
433 ExprEngine &getEngine() { return Eng; }
435 /// getGraph - Get the exploded graph created by the analysis engine
436 /// for the analyzed method or function.
437 ExplodedGraph &getGraph();
439 /// getStateManager - Return the state manager used by the analysis
441 ProgramStateManager &getStateManager();
443 virtual void GeneratePathDiagnostic(PathDiagnostic &pathDiagnostic,
444 PathDiagnosticConsumer &PC,
445 ArrayRef<BugReport*> &bugReports);
447 /// classof - Used by isa<>, cast<>, and dyn_cast<>.
448 static bool classof(const BugReporter* R) {
449 return R->getKind() == GRBugReporterKind;
453 class BugReporterContext {
454 virtual void anchor();
457 BugReporterContext(GRBugReporter& br) : BR(br) {}
459 virtual ~BugReporterContext() {}
461 GRBugReporter& getBugReporter() { return BR; }
463 ExplodedGraph &getGraph() { return BR.getGraph(); }
465 ProgramStateManager& getStateManager() {
466 return BR.getStateManager();
469 SValBuilder& getSValBuilder() {
470 return getStateManager().getSValBuilder();
473 ASTContext &getASTContext() {
474 return BR.getContext();
477 SourceManager& getSourceManager() {
478 return BR.getSourceManager();
481 virtual BugReport::NodeResolver& getNodeResolver() = 0;
484 } // end GR namespace
486 } // end clang namespace