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"
27 #include "llvm/ADT/SmallSet.h"
32 class DiagnosticsEngine;
43 class BugReporterContext;
47 //===----------------------------------------------------------------------===//
48 // Interface for individual bug reports.
49 //===----------------------------------------------------------------------===//
51 /// This class provides an interface through which checkers can create
52 /// individual bug reports.
53 class BugReport : public llvm::ilist_node<BugReport> {
56 virtual void anchor();
58 virtual ~NodeResolver() {}
59 virtual const ExplodedNode*
60 getOriginalNode(const ExplodedNode *N) = 0;
63 typedef const SourceRange *ranges_iterator;
64 typedef SmallVector<BugReporterVisitor *, 8> VisitorList;
65 typedef VisitorList::iterator visitor_iterator;
66 typedef SmallVector<StringRef, 2> ExtraTextList;
69 friend class BugReporter;
70 friend class BugReportEquivClass;
73 const Decl *DeclWithIssue;
74 std::string ShortDescription;
75 std::string Description;
76 PathDiagnosticLocation Location;
77 PathDiagnosticLocation UniqueingLocation;
78 const ExplodedNode *ErrorNode;
79 SmallVector<SourceRange, 4> Ranges;
80 ExtraTextList ExtraText;
82 typedef llvm::DenseSet<SymbolRef> Symbols;
83 typedef llvm::DenseSet<const MemRegion *> Regions;
85 /// A (stack of) a set of symbols that are registered with this
86 /// report as being "interesting", and thus used to help decide which
87 /// diagnostics to include when constructing the final path diagnostic.
88 /// The stack is largely used by BugReporter when generating PathDiagnostics
89 /// for multiple PathDiagnosticConsumers.
90 llvm::SmallVector<Symbols *, 2> interestingSymbols;
92 /// A (stack of) set of regions that are registered with this report as being
93 /// "interesting", and thus used to help decide which diagnostics
94 /// to include when constructing the final path diagnostic.
95 /// The stack is largely used by BugReporter when generating PathDiagnostics
96 /// for multiple PathDiagnosticConsumers.
97 llvm::SmallVector<Regions *, 2> interestingRegions;
99 /// A set of location contexts that correspoind to call sites which should be
100 /// considered "interesting".
101 llvm::SmallSet<const LocationContext *, 2> InterestingLocationContexts;
103 /// A set of custom visitors which generate "event" diagnostics at
104 /// interesting points in the path.
105 VisitorList Callbacks;
107 /// Used for ensuring the visitors are only added once.
108 llvm::FoldingSet<BugReporterVisitor> CallbacksSet;
110 /// Used for clients to tell if the report's configuration has changed
111 /// since the last time they checked.
112 unsigned ConfigurationChangeToken;
114 /// When set, this flag disables all callstack pruning from a diagnostic
115 /// path. This is useful for some reports that want maximum fidelty
116 /// when reporting an issue.
120 // Used internally by BugReporter.
121 Symbols &getInterestingSymbols();
122 Regions &getInterestingRegions();
124 void lazyInitializeInterestingSets();
125 void pushInterestingSymbolsAndRegions();
126 void popInterestingSymbolsAndRegions();
129 BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode)
130 : BT(bt), DeclWithIssue(0), Description(desc), ErrorNode(errornode),
131 ConfigurationChangeToken(0), DoNotPrunePath(false) {}
133 BugReport(BugType& bt, StringRef shortDesc, StringRef desc,
134 const ExplodedNode *errornode)
135 : BT(bt), DeclWithIssue(0), ShortDescription(shortDesc), Description(desc),
136 ErrorNode(errornode), ConfigurationChangeToken(0),
137 DoNotPrunePath(false) {}
139 BugReport(BugType& bt, StringRef desc, PathDiagnosticLocation l)
140 : BT(bt), DeclWithIssue(0), Description(desc), Location(l), ErrorNode(0),
141 ConfigurationChangeToken(0),
142 DoNotPrunePath(false) {}
144 /// \brief Create a BugReport with a custom uniqueing location.
146 /// The reports that have the same report location, description, bug type, and
147 /// ranges are uniqued - only one of the equivalent reports will be presented
148 /// to the user. This method allows to rest the location which should be used
149 /// for uniquing reports. For example, memory leaks checker, could set this to
150 /// the allocation site, rather then the location where the bug is reported.
151 BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode,
152 PathDiagnosticLocation LocationToUnique)
153 : BT(bt), DeclWithIssue(0), Description(desc),
154 UniqueingLocation(LocationToUnique),
155 ErrorNode(errornode), ConfigurationChangeToken(0) {}
157 virtual ~BugReport();
159 const BugType& getBugType() const { return BT; }
160 BugType& getBugType() { return BT; }
162 const ExplodedNode *getErrorNode() const { return ErrorNode; }
164 const StringRef getDescription() const { return Description; }
166 const StringRef getShortDescription() const {
167 return ShortDescription.empty() ? Description : ShortDescription;
170 /// Indicates whether or not any path pruning should take place
171 /// when generating a PathDiagnostic from this BugReport.
172 bool shouldPrunePath() const { return !DoNotPrunePath; }
174 /// Disable all path pruning when generating a PathDiagnostic.
175 void disablePathPruning() { DoNotPrunePath = true; }
177 void markInteresting(SymbolRef sym);
178 void markInteresting(const MemRegion *R);
179 void markInteresting(SVal V);
180 void markInteresting(const LocationContext *LC);
182 bool isInteresting(SymbolRef sym);
183 bool isInteresting(const MemRegion *R);
184 bool isInteresting(SVal V);
185 bool isInteresting(const LocationContext *LC);
187 unsigned getConfigurationChangeToken() const {
188 return ConfigurationChangeToken;
191 /// Return the canonical declaration, be it a method or class, where
192 /// this issue semantically occurred.
193 const Decl *getDeclWithIssue() const;
195 /// Specifically set the Decl where an issue occurred. This isn't necessary
196 /// for BugReports that cover a path as it will be automatically inferred.
197 void setDeclWithIssue(const Decl *declWithIssue) {
198 DeclWithIssue = declWithIssue;
201 /// \brief This allows for addition of meta data to the diagnostic.
203 /// Currently, only the HTMLDiagnosticClient knows how to display it.
204 void addExtraText(StringRef S) {
205 ExtraText.push_back(S);
208 virtual const ExtraTextList &getExtraText() {
212 /// \brief Return the "definitive" location of the reported bug.
214 /// While a bug can span an entire path, usually there is a specific
215 /// location that can be used to identify where the key issue occurred.
216 /// This location is used by clients rendering diagnostics.
217 virtual PathDiagnosticLocation getLocation(const SourceManager &SM) const;
219 const Stmt *getStmt() const;
221 /// \brief Add a range to a bug report.
223 /// Ranges are used to highlight regions of interest in the source code.
224 /// They should be at the same source code line as the BugReport location.
225 /// By default, the source range of the statement corresponding to the error
226 /// node will be used; add a single invalid range to specify absence of
228 void addRange(SourceRange R) {
229 assert((R.isValid() || Ranges.empty()) && "Invalid range can only be used "
230 "to specify that the report does not have a range.");
234 /// \brief Get the SourceRanges associated with the report.
235 virtual std::pair<ranges_iterator, ranges_iterator> getRanges();
237 /// \brief Add custom or predefined bug report visitors to this report.
239 /// The visitors should be used when the default trace is not sufficient.
240 /// For example, they allow constructing a more elaborate trace.
241 /// \sa registerConditionVisitor(), registerTrackNullOrUndefValue(),
242 /// registerFindLastStore(), registerNilReceiverVisitor(), and
243 /// registerVarDeclsLastStore().
244 void addVisitor(BugReporterVisitor *visitor);
246 /// Iterators through the custom diagnostic visitors.
247 visitor_iterator visitor_begin() { return Callbacks.begin(); }
248 visitor_iterator visitor_end() { return Callbacks.end(); }
250 /// Profile to identify equivalent bug reports for error report coalescing.
251 /// Reports are uniqued to ensure that we do not emit multiple diagnostics
253 virtual void Profile(llvm::FoldingSetNodeID& hash) const;
256 } // end ento namespace
257 } // end clang namespace
260 template<> struct ilist_traits<clang::ento::BugReport>
261 : public ilist_default_traits<clang::ento::BugReport> {
262 clang::ento::BugReport *createSentinel() const {
263 return static_cast<clang::ento::BugReport *>(&Sentinel);
265 void destroySentinel(clang::ento::BugReport *) const {}
267 clang::ento::BugReport *provideInitialHead() const {
268 return createSentinel();
270 clang::ento::BugReport *ensureHead(clang::ento::BugReport *) const {
271 return createSentinel();
274 mutable ilist_half_node<clang::ento::BugReport> Sentinel;
281 //===----------------------------------------------------------------------===//
282 // BugTypes (collections of related reports).
283 //===----------------------------------------------------------------------===//
285 class BugReportEquivClass : public llvm::FoldingSetNode {
286 /// List of *owned* BugReport objects.
287 llvm::ilist<BugReport> Reports;
289 friend class BugReporter;
290 void AddReport(BugReport* R) { Reports.push_back(R); }
292 BugReportEquivClass(BugReport* R) { Reports.push_back(R); }
293 ~BugReportEquivClass();
295 void Profile(llvm::FoldingSetNodeID& ID) const {
296 assert(!Reports.empty());
297 Reports.front().Profile(ID);
300 typedef llvm::ilist<BugReport>::iterator iterator;
301 typedef llvm::ilist<BugReport>::const_iterator const_iterator;
303 iterator begin() { return Reports.begin(); }
304 iterator end() { return Reports.end(); }
306 const_iterator begin() const { return Reports.begin(); }
307 const_iterator end() const { return Reports.end(); }
310 //===----------------------------------------------------------------------===//
311 // BugReporter and friends.
312 //===----------------------------------------------------------------------===//
314 class BugReporterData {
316 virtual ~BugReporterData();
317 virtual DiagnosticsEngine& getDiagnostic() = 0;
318 virtual ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() = 0;
319 virtual ASTContext &getASTContext() = 0;
320 virtual SourceManager& getSourceManager() = 0;
323 /// BugReporter is a utility class for generating PathDiagnostics for analysis.
324 /// It collects the BugReports and BugTypes and knows how to generate
325 /// and flush the corresponding diagnostics.
328 enum Kind { BaseBRKind, GRBugReporterKind };
331 typedef llvm::ImmutableSet<BugType*> BugTypesTy;
332 BugTypesTy::Factory F;
338 /// Generate and flush the diagnostics for the given bug report.
339 void FlushReport(BugReportEquivClass& EQ);
341 /// Generate and flush the diagnostics for the given bug report
342 /// and PathDiagnosticConsumer.
343 void FlushReport(BugReport *exampleReport,
344 PathDiagnosticConsumer &PD,
345 ArrayRef<BugReport*> BugReports);
347 /// The set of bug reports tracked by the BugReporter.
348 llvm::FoldingSet<BugReportEquivClass> EQClasses;
349 /// A vector of BugReports for tracking the allocated pointers and cleanup.
350 std::vector<BugReportEquivClass *> EQClassesVector;
352 /// A map from PathDiagnosticPiece to the LocationContext of the inlined
353 /// function call it represents.
354 llvm::DenseMap<const PathDiagnosticCallPiece*,
355 const LocationContext*> LocationContextMap;
358 BugReporter(BugReporterData& d, Kind k) : BugTypes(F.getEmptySet()), kind(k),
362 BugReporter(BugReporterData& d) : BugTypes(F.getEmptySet()), kind(BaseBRKind),
364 virtual ~BugReporter();
366 /// \brief Generate and flush diagnostics for all bug reports.
369 Kind getKind() const { return kind; }
371 DiagnosticsEngine& getDiagnostic() {
372 return D.getDiagnostic();
375 ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() {
376 return D.getPathDiagnosticConsumers();
379 /// \brief Iterator over the set of BugTypes tracked by the BugReporter.
380 typedef BugTypesTy::iterator iterator;
381 iterator begin() { return BugTypes.begin(); }
382 iterator end() { return BugTypes.end(); }
384 /// \brief Iterator over the set of BugReports tracked by the BugReporter.
385 typedef llvm::FoldingSet<BugReportEquivClass>::iterator EQClasses_iterator;
386 EQClasses_iterator EQClasses_begin() { return EQClasses.begin(); }
387 EQClasses_iterator EQClasses_end() { return EQClasses.end(); }
389 ASTContext &getContext() { return D.getASTContext(); }
391 SourceManager& getSourceManager() { return D.getSourceManager(); }
393 virtual void GeneratePathDiagnostic(PathDiagnostic& pathDiagnostic,
394 PathDiagnosticConsumer &PC,
395 ArrayRef<BugReport *> &bugReports) {}
397 bool RemoveUneededCalls(PathPieces &pieces, BugReport *R);
399 void Register(BugType *BT);
401 /// \brief Add the given report to the set of reports tracked by BugReporter.
403 /// The reports are usually generated by the checkers. Further, they are
404 /// folded based on the profile value, which is done to coalesce similar
406 void EmitReport(BugReport *R);
408 void EmitBasicReport(const Decl *DeclWithIssue,
409 StringRef BugName, StringRef BugCategory,
410 StringRef BugStr, PathDiagnosticLocation Loc,
411 SourceRange* RangeBeg, unsigned NumRanges);
413 void EmitBasicReport(const Decl *DeclWithIssue,
414 StringRef BugName, StringRef BugCategory,
415 StringRef BugStr, PathDiagnosticLocation Loc) {
416 EmitBasicReport(DeclWithIssue, BugName, BugCategory, BugStr, Loc, 0, 0);
419 void EmitBasicReport(const Decl *DeclWithIssue,
420 StringRef BugName, StringRef Category,
421 StringRef BugStr, PathDiagnosticLocation Loc,
423 EmitBasicReport(DeclWithIssue, BugName, Category, BugStr, Loc, &R, 1);
426 static bool classof(const BugReporter* R) { return true; }
428 void addCallPieceLocationContextPair(const PathDiagnosticCallPiece *C,
429 const LocationContext *LC) {
430 LocationContextMap[C] = LC;
433 llvm::StringMap<BugType *> StrBugTypes;
435 /// \brief Returns a BugType that is associated with the given name and
437 BugType *getBugTypeForName(StringRef name, StringRef category);
440 // FIXME: Get rid of GRBugReporter. It's the wrong abstraction.
441 class GRBugReporter : public BugReporter {
444 GRBugReporter(BugReporterData& d, ExprEngine& eng)
445 : BugReporter(d, GRBugReporterKind), Eng(eng) {}
447 virtual ~GRBugReporter();
449 /// getEngine - Return the analysis engine used to analyze a given
450 /// function or method.
451 ExprEngine &getEngine() { return Eng; }
453 /// getGraph - Get the exploded graph created by the analysis engine
454 /// for the analyzed method or function.
455 ExplodedGraph &getGraph();
457 /// getStateManager - Return the state manager used by the analysis
459 ProgramStateManager &getStateManager();
461 virtual void GeneratePathDiagnostic(PathDiagnostic &pathDiagnostic,
462 PathDiagnosticConsumer &PC,
463 ArrayRef<BugReport*> &bugReports);
465 /// classof - Used by isa<>, cast<>, and dyn_cast<>.
466 static bool classof(const BugReporter* R) {
467 return R->getKind() == GRBugReporterKind;
471 class BugReporterContext {
472 virtual void anchor();
475 BugReporterContext(GRBugReporter& br) : BR(br) {}
477 virtual ~BugReporterContext() {}
479 GRBugReporter& getBugReporter() { return BR; }
481 ExplodedGraph &getGraph() { return BR.getGraph(); }
483 ProgramStateManager& getStateManager() {
484 return BR.getStateManager();
487 SValBuilder& getSValBuilder() {
488 return getStateManager().getSValBuilder();
491 ASTContext &getASTContext() {
492 return BR.getContext();
495 SourceManager& getSourceManager() {
496 return BR.getSourceManager();
499 virtual BugReport::NodeResolver& getNodeResolver() = 0;
502 } // end GR namespace
504 } // end clang namespace