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 std::string ShortDescription;
73 std::string Description;
74 PathDiagnosticLocation Location;
75 PathDiagnosticLocation UniqueingLocation;
76 const ExplodedNode *ErrorNode;
77 SmallVector<SourceRange, 4> Ranges;
78 ExtraTextList ExtraText;
80 typedef llvm::DenseSet<SymbolRef> Symbols;
81 typedef llvm::DenseSet<const MemRegion *> Regions;
83 /// A set of symbols that are registered with this report as being
84 /// "interesting", and thus used to help decide which diagnostics
85 /// to include when constructing the final path diagnostic.
86 Symbols interestingSymbols;
88 /// A set of regions that are registered with this report as being
89 /// "interesting", and thus used to help decide which diagnostics
90 /// to include when constructing the final path diagnostic.
91 Regions interestingRegions;
93 /// A set of custom visitors which generate "event" diagnostics at
94 /// interesting points in the path.
95 VisitorList Callbacks;
97 /// Used for ensuring the visitors are only added once.
98 llvm::FoldingSet<BugReporterVisitor> CallbacksSet;
100 /// Used for clients to tell if the report's configuration has changed
101 /// since the last time they checked.
102 unsigned ConfigurationChangeToken;
105 BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode)
106 : BT(bt), Description(desc), ErrorNode(errornode),
107 ConfigurationChangeToken(0) {}
109 BugReport(BugType& bt, StringRef shortDesc, StringRef desc,
110 const ExplodedNode *errornode)
111 : BT(bt), ShortDescription(shortDesc), Description(desc),
112 ErrorNode(errornode), ConfigurationChangeToken(0) {}
114 BugReport(BugType& bt, StringRef desc, PathDiagnosticLocation l)
115 : BT(bt), Description(desc), Location(l), ErrorNode(0),
116 ConfigurationChangeToken(0) {}
118 /// \brief Create a BugReport with a custom uniqueing location.
120 /// The reports that have the same report location, description, bug type, and
121 /// ranges are uniqued - only one of the equivalent reports will be presented
122 /// to the user. This method allows to rest the location which should be used
123 /// for uniquing reports. For example, memory leaks checker, could set this to
124 /// the allocation site, rather then the location where the bug is reported.
125 BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode,
126 PathDiagnosticLocation LocationToUnique)
127 : BT(bt), Description(desc), UniqueingLocation(LocationToUnique),
128 ErrorNode(errornode), ConfigurationChangeToken(0) {}
130 virtual ~BugReport();
132 const BugType& getBugType() const { return BT; }
133 BugType& getBugType() { return BT; }
135 const ExplodedNode *getErrorNode() const { return ErrorNode; }
137 const StringRef getDescription() const { return Description; }
139 const StringRef getShortDescription() const {
140 return ShortDescription.empty() ? Description : ShortDescription;
143 void markInteresting(SymbolRef sym);
144 void markInteresting(const MemRegion *R);
145 void markInteresting(SVal V);
147 bool isInteresting(SymbolRef sym) const;
148 bool isInteresting(const MemRegion *R) const;
149 bool isInteresting(SVal V) const;
151 unsigned getConfigurationChangeToken() const {
152 return ConfigurationChangeToken;
155 /// \brief This allows for addition of meta data to the diagnostic.
157 /// Currently, only the HTMLDiagnosticClient knows how to display it.
158 void addExtraText(StringRef S) {
159 ExtraText.push_back(S);
162 virtual const ExtraTextList &getExtraText() {
166 /// \brief Return the "definitive" location of the reported bug.
168 /// While a bug can span an entire path, usually there is a specific
169 /// location that can be used to identify where the key issue occurred.
170 /// This location is used by clients rendering diagnostics.
171 virtual PathDiagnosticLocation getLocation(const SourceManager &SM) const;
173 const Stmt *getStmt() const;
175 /// \brief Add a range to a bug report.
177 /// Ranges are used to highlight regions of interest in the source code.
178 /// They should be at the same source code line as the BugReport location.
179 /// By default, the source range of the statement corresponding to the error
180 /// node will be used; add a single invalid range to specify absence of
182 void addRange(SourceRange R) {
183 assert((R.isValid() || Ranges.empty()) && "Invalid range can only be used "
184 "to specify that the report does not have a range.");
188 /// \brief Get the SourceRanges associated with the report.
189 virtual std::pair<ranges_iterator, ranges_iterator> getRanges();
191 /// \brief Add custom or predefined bug report visitors to this report.
193 /// The visitors should be used when the default trace is not sufficient.
194 /// For example, they allow constructing a more elaborate trace.
195 /// \sa registerConditionVisitor(), registerTrackNullOrUndefValue(),
196 /// registerFindLastStore(), registerNilReceiverVisitor(), and
197 /// registerVarDeclsLastStore().
198 void addVisitor(BugReporterVisitor *visitor);
200 /// Iterators through the custom diagnostic visitors.
201 visitor_iterator visitor_begin() { return Callbacks.begin(); }
202 visitor_iterator visitor_end() { return Callbacks.end(); }
204 /// Profile to identify equivalent bug reports for error report coalescing.
205 /// Reports are uniqued to ensure that we do not emit multiple diagnostics
207 virtual void Profile(llvm::FoldingSetNodeID& hash) const;
210 } // end ento namespace
211 } // end clang namespace
214 template<> struct ilist_traits<clang::ento::BugReport>
215 : public ilist_default_traits<clang::ento::BugReport> {
216 clang::ento::BugReport *createSentinel() const {
217 return static_cast<clang::ento::BugReport *>(&Sentinel);
219 void destroySentinel(clang::ento::BugReport *) const {}
221 clang::ento::BugReport *provideInitialHead() const {
222 return createSentinel();
224 clang::ento::BugReport *ensureHead(clang::ento::BugReport *) const {
225 return createSentinel();
228 mutable ilist_half_node<clang::ento::BugReport> Sentinel;
235 //===----------------------------------------------------------------------===//
236 // BugTypes (collections of related reports).
237 //===----------------------------------------------------------------------===//
239 class BugReportEquivClass : public llvm::FoldingSetNode {
240 /// List of *owned* BugReport objects.
241 llvm::ilist<BugReport> Reports;
243 friend class BugReporter;
244 void AddReport(BugReport* R) { Reports.push_back(R); }
246 BugReportEquivClass(BugReport* R) { Reports.push_back(R); }
247 ~BugReportEquivClass();
249 void Profile(llvm::FoldingSetNodeID& ID) const {
250 assert(!Reports.empty());
251 Reports.front().Profile(ID);
254 typedef llvm::ilist<BugReport>::iterator iterator;
255 typedef llvm::ilist<BugReport>::const_iterator const_iterator;
257 iterator begin() { return Reports.begin(); }
258 iterator end() { return Reports.end(); }
260 const_iterator begin() const { return Reports.begin(); }
261 const_iterator end() const { return Reports.end(); }
264 //===----------------------------------------------------------------------===//
265 // BugReporter and friends.
266 //===----------------------------------------------------------------------===//
268 class BugReporterData {
270 virtual ~BugReporterData();
271 virtual DiagnosticsEngine& getDiagnostic() = 0;
272 virtual PathDiagnosticConsumer* getPathDiagnosticConsumer() = 0;
273 virtual ASTContext &getASTContext() = 0;
274 virtual SourceManager& getSourceManager() = 0;
277 /// BugReporter is a utility class for generating PathDiagnostics for analysis.
278 /// It collects the BugReports and BugTypes and knows how to generate
279 /// and flush the corresponding diagnostics.
282 enum Kind { BaseBRKind, GRBugReporterKind };
285 typedef llvm::ImmutableSet<BugType*> BugTypesTy;
286 BugTypesTy::Factory F;
292 /// Generate and flush the diagnostics for the given bug report.
293 void FlushReport(BugReportEquivClass& EQ);
295 /// The set of bug reports tracked by the BugReporter.
296 llvm::FoldingSet<BugReportEquivClass> EQClasses;
297 /// A vector of BugReports for tracking the allocated pointers and cleanup.
298 std::vector<BugReportEquivClass *> EQClassesVector;
301 BugReporter(BugReporterData& d, Kind k) : BugTypes(F.getEmptySet()), kind(k),
305 BugReporter(BugReporterData& d) : BugTypes(F.getEmptySet()), kind(BaseBRKind),
307 virtual ~BugReporter();
309 /// \brief Generate and flush diagnostics for all bug reports.
312 Kind getKind() const { return kind; }
314 DiagnosticsEngine& getDiagnostic() {
315 return D.getDiagnostic();
318 PathDiagnosticConsumer* getPathDiagnosticConsumer() {
319 return D.getPathDiagnosticConsumer();
322 /// \brief Iterator over the set of BugTypes tracked by the BugReporter.
323 typedef BugTypesTy::iterator iterator;
324 iterator begin() { return BugTypes.begin(); }
325 iterator end() { return BugTypes.end(); }
327 /// \brief Iterator over the set of BugReports tracked by the BugReporter.
328 typedef llvm::FoldingSet<BugReportEquivClass>::iterator EQClasses_iterator;
329 EQClasses_iterator EQClasses_begin() { return EQClasses.begin(); }
330 EQClasses_iterator EQClasses_end() { return EQClasses.end(); }
332 ASTContext &getContext() { return D.getASTContext(); }
334 SourceManager& getSourceManager() { return D.getSourceManager(); }
336 virtual void GeneratePathDiagnostic(PathDiagnostic& pathDiagnostic,
337 SmallVectorImpl<BugReport *> &bugReports) {}
339 void Register(BugType *BT);
341 /// \brief Add the given report to the set of reports tracked by BugReporter.
343 /// The reports are usually generated by the checkers. Further, they are
344 /// folded based on the profile value, which is done to coalesce similar
346 void EmitReport(BugReport *R);
348 void EmitBasicReport(StringRef BugName, StringRef BugStr,
349 PathDiagnosticLocation Loc,
350 SourceRange* RangeBeg, unsigned NumRanges);
352 void EmitBasicReport(StringRef BugName, StringRef BugCategory,
353 StringRef BugStr, PathDiagnosticLocation Loc,
354 SourceRange* RangeBeg, unsigned NumRanges);
357 void EmitBasicReport(StringRef BugName, StringRef BugStr,
358 PathDiagnosticLocation Loc) {
359 EmitBasicReport(BugName, BugStr, Loc, 0, 0);
362 void EmitBasicReport(StringRef BugName, StringRef BugCategory,
363 StringRef BugStr, PathDiagnosticLocation Loc) {
364 EmitBasicReport(BugName, BugCategory, BugStr, Loc, 0, 0);
367 void EmitBasicReport(StringRef BugName, StringRef BugStr,
368 PathDiagnosticLocation Loc, SourceRange R) {
369 EmitBasicReport(BugName, BugStr, Loc, &R, 1);
372 void EmitBasicReport(StringRef BugName, StringRef Category,
373 StringRef BugStr, PathDiagnosticLocation Loc,
375 EmitBasicReport(BugName, Category, BugStr, Loc, &R, 1);
378 static bool classof(const BugReporter* R) { return true; }
381 llvm::StringMap<BugType *> StrBugTypes;
383 /// \brief Returns a BugType that is associated with the given name and
385 BugType *getBugTypeForName(StringRef name, StringRef category);
388 // FIXME: Get rid of GRBugReporter. It's the wrong abstraction.
389 class GRBugReporter : public BugReporter {
392 GRBugReporter(BugReporterData& d, ExprEngine& eng)
393 : BugReporter(d, GRBugReporterKind), Eng(eng) {}
395 virtual ~GRBugReporter();
397 /// getEngine - Return the analysis engine used to analyze a given
398 /// function or method.
399 ExprEngine &getEngine() { return Eng; }
401 /// getGraph - Get the exploded graph created by the analysis engine
402 /// for the analyzed method or function.
403 ExplodedGraph &getGraph();
405 /// getStateManager - Return the state manager used by the analysis
407 ProgramStateManager &getStateManager();
409 virtual void GeneratePathDiagnostic(PathDiagnostic &pathDiagnostic,
410 SmallVectorImpl<BugReport*> &bugReports);
412 /// classof - Used by isa<>, cast<>, and dyn_cast<>.
413 static bool classof(const BugReporter* R) {
414 return R->getKind() == GRBugReporterKind;
418 class BugReporterContext {
419 virtual void anchor();
422 BugReporterContext(GRBugReporter& br) : BR(br) {}
424 virtual ~BugReporterContext() {}
426 GRBugReporter& getBugReporter() { return BR; }
428 ExplodedGraph &getGraph() { return BR.getGraph(); }
430 ProgramStateManager& getStateManager() {
431 return BR.getStateManager();
434 SValBuilder& getSValBuilder() {
435 return getStateManager().getSValBuilder();
438 ASTContext &getASTContext() {
439 return BR.getContext();
442 SourceManager& getSourceManager() {
443 return BR.getSourceManager();
446 virtual BugReport::NodeResolver& getNodeResolver() = 0;
449 } // end GR namespace
451 } // end clang namespace