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/AnalyzerOptions.h"
20 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h"
21 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
23 #include "llvm/ADT/DenseSet.h"
24 #include "llvm/ADT/FoldingSet.h"
25 #include "llvm/ADT/ImmutableSet.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/ilist.h"
28 #include "llvm/ADT/ilist_node.h"
33 class DiagnosticsEngine;
44 class BugReporterContext;
48 //===----------------------------------------------------------------------===//
49 // Interface for individual bug reports.
50 //===----------------------------------------------------------------------===//
52 /// This class provides an interface through which checkers can create
53 /// individual bug reports.
54 class BugReport : public llvm::ilist_node<BugReport> {
57 virtual void anchor();
59 virtual ~NodeResolver() {}
60 virtual const ExplodedNode*
61 getOriginalNode(const ExplodedNode *N) = 0;
64 typedef const SourceRange *ranges_iterator;
65 typedef SmallVector<BugReporterVisitor *, 8> VisitorList;
66 typedef VisitorList::iterator visitor_iterator;
67 typedef SmallVector<StringRef, 2> ExtraTextList;
70 friend class BugReporter;
71 friend class BugReportEquivClass;
74 const Decl *DeclWithIssue;
75 std::string ShortDescription;
76 std::string Description;
77 PathDiagnosticLocation Location;
78 PathDiagnosticLocation UniqueingLocation;
79 const Decl *UniqueingDecl;
81 const ExplodedNode *ErrorNode;
82 SmallVector<SourceRange, 4> Ranges;
83 ExtraTextList ExtraText;
85 typedef llvm::DenseSet<SymbolRef> Symbols;
86 typedef llvm::DenseSet<const MemRegion *> Regions;
88 /// A (stack of) a set of symbols that are registered with this
89 /// report as being "interesting", and thus used to help decide which
90 /// diagnostics to include when constructing the final path diagnostic.
91 /// The stack is largely used by BugReporter when generating PathDiagnostics
92 /// for multiple PathDiagnosticConsumers.
93 SmallVector<Symbols *, 2> interestingSymbols;
95 /// A (stack of) set of regions that are registered with this report as being
96 /// "interesting", and thus used to help decide which diagnostics
97 /// to include when constructing the final path diagnostic.
98 /// The stack is largely used by BugReporter when generating PathDiagnostics
99 /// for multiple PathDiagnosticConsumers.
100 SmallVector<Regions *, 2> interestingRegions;
102 /// A set of location contexts that correspoind to call sites which should be
103 /// considered "interesting".
104 llvm::SmallSet<const LocationContext *, 2> InterestingLocationContexts;
106 /// A set of custom visitors which generate "event" diagnostics at
107 /// interesting points in the path.
108 VisitorList Callbacks;
110 /// Used for ensuring the visitors are only added once.
111 llvm::FoldingSet<BugReporterVisitor> CallbacksSet;
113 /// Used for clients to tell if the report's configuration has changed
114 /// since the last time they checked.
115 unsigned ConfigurationChangeToken;
117 /// When set, this flag disables all callstack pruning from a diagnostic
118 /// path. This is useful for some reports that want maximum fidelty
119 /// when reporting an issue.
122 /// Used to track unique reasons why a bug report might be invalid.
125 /// \sa removeInvalidation
126 typedef std::pair<const void *, const void *> InvalidationRecord;
128 /// If non-empty, this bug report is likely a false positive and should not be
129 /// shown to the user.
132 /// \sa removeInvalidation
133 llvm::SmallSet<InvalidationRecord, 4> Invalidations;
136 // Used internally by BugReporter.
137 Symbols &getInterestingSymbols();
138 Regions &getInterestingRegions();
140 void lazyInitializeInterestingSets();
141 void pushInterestingSymbolsAndRegions();
142 void popInterestingSymbolsAndRegions();
145 BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode)
146 : BT(bt), DeclWithIssue(0), Description(desc), ErrorNode(errornode),
147 ConfigurationChangeToken(0), DoNotPrunePath(false) {}
149 BugReport(BugType& bt, StringRef shortDesc, StringRef desc,
150 const ExplodedNode *errornode)
151 : BT(bt), DeclWithIssue(0), ShortDescription(shortDesc), Description(desc),
152 ErrorNode(errornode), ConfigurationChangeToken(0),
153 DoNotPrunePath(false) {}
155 BugReport(BugType& bt, StringRef desc, PathDiagnosticLocation l)
156 : BT(bt), DeclWithIssue(0), Description(desc), Location(l), ErrorNode(0),
157 ConfigurationChangeToken(0),
158 DoNotPrunePath(false) {}
160 /// \brief Create a BugReport with a custom uniqueing location.
162 /// The reports that have the same report location, description, bug type, and
163 /// ranges are uniqued - only one of the equivalent reports will be presented
164 /// to the user. This method allows to rest the location which should be used
165 /// for uniquing reports. For example, memory leaks checker, could set this to
166 /// the allocation site, rather then the location where the bug is reported.
167 BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode,
168 PathDiagnosticLocation LocationToUnique, const Decl *DeclToUnique)
169 : BT(bt), DeclWithIssue(0), Description(desc),
170 UniqueingLocation(LocationToUnique),
171 UniqueingDecl(DeclToUnique),
172 ErrorNode(errornode), ConfigurationChangeToken(0),
173 DoNotPrunePath(false) {}
175 virtual ~BugReport();
177 const BugType& getBugType() const { return BT; }
178 BugType& getBugType() { return BT; }
180 const ExplodedNode *getErrorNode() const { return ErrorNode; }
182 const StringRef getDescription() const { return Description; }
184 const StringRef getShortDescription(bool UseFallback = true) const {
185 if (ShortDescription.empty() && UseFallback)
187 return ShortDescription;
190 /// Indicates whether or not any path pruning should take place
191 /// when generating a PathDiagnostic from this BugReport.
192 bool shouldPrunePath() const { return !DoNotPrunePath; }
194 /// Disable all path pruning when generating a PathDiagnostic.
195 void disablePathPruning() { DoNotPrunePath = true; }
197 void markInteresting(SymbolRef sym);
198 void markInteresting(const MemRegion *R);
199 void markInteresting(SVal V);
200 void markInteresting(const LocationContext *LC);
202 bool isInteresting(SymbolRef sym);
203 bool isInteresting(const MemRegion *R);
204 bool isInteresting(SVal V);
205 bool isInteresting(const LocationContext *LC);
207 unsigned getConfigurationChangeToken() const {
208 return ConfigurationChangeToken;
211 /// Returns whether or not this report should be considered valid.
213 /// Invalid reports are those that have been classified as likely false
214 /// positives after the fact.
215 bool isValid() const {
216 return Invalidations.empty();
219 /// Marks the current report as invalid, meaning that it is probably a false
220 /// positive and should not be reported to the user.
222 /// The \p Tag and \p Data arguments are intended to be opaque identifiers for
223 /// this particular invalidation, where \p Tag represents the visitor
224 /// responsible for invalidation, and \p Data represents the reason this
225 /// visitor decided to invalidate the bug report.
227 /// \sa removeInvalidation
228 void markInvalid(const void *Tag, const void *Data) {
229 Invalidations.insert(std::make_pair(Tag, Data));
232 /// Reverses the effects of a previous invalidation.
235 void removeInvalidation(const void *Tag, const void *Data) {
236 Invalidations.erase(std::make_pair(Tag, Data));
239 /// Return the canonical declaration, be it a method or class, where
240 /// this issue semantically occurred.
241 const Decl *getDeclWithIssue() const;
243 /// Specifically set the Decl where an issue occurred. This isn't necessary
244 /// for BugReports that cover a path as it will be automatically inferred.
245 void setDeclWithIssue(const Decl *declWithIssue) {
246 DeclWithIssue = declWithIssue;
249 /// \brief This allows for addition of meta data to the diagnostic.
251 /// Currently, only the HTMLDiagnosticClient knows how to display it.
252 void addExtraText(StringRef S) {
253 ExtraText.push_back(S);
256 virtual const ExtraTextList &getExtraText() {
260 /// \brief Return the "definitive" location of the reported bug.
262 /// While a bug can span an entire path, usually there is a specific
263 /// location that can be used to identify where the key issue occurred.
264 /// This location is used by clients rendering diagnostics.
265 virtual PathDiagnosticLocation getLocation(const SourceManager &SM) const;
267 /// \brief Get the location on which the report should be uniqued.
268 PathDiagnosticLocation getUniqueingLocation() const {
269 return UniqueingLocation;
272 /// \brief Get the declaration containing the uniqueing location.
273 const Decl *getUniqueingDecl() const {
274 return UniqueingDecl;
277 const Stmt *getStmt() const;
279 /// \brief Add a range to a bug report.
281 /// Ranges are used to highlight regions of interest in the source code.
282 /// They should be at the same source code line as the BugReport location.
283 /// By default, the source range of the statement corresponding to the error
284 /// node will be used; add a single invalid range to specify absence of
286 void addRange(SourceRange R) {
287 assert((R.isValid() || Ranges.empty()) && "Invalid range can only be used "
288 "to specify that the report does not have a range.");
292 /// \brief Get the SourceRanges associated with the report.
293 virtual std::pair<ranges_iterator, ranges_iterator> getRanges();
295 /// \brief Add custom or predefined bug report visitors to this report.
297 /// The visitors should be used when the default trace is not sufficient.
298 /// For example, they allow constructing a more elaborate trace.
299 /// \sa registerConditionVisitor(), registerTrackNullOrUndefValue(),
300 /// registerFindLastStore(), registerNilReceiverVisitor(), and
301 /// registerVarDeclsLastStore().
302 void addVisitor(BugReporterVisitor *visitor);
304 /// Iterators through the custom diagnostic visitors.
305 visitor_iterator visitor_begin() { return Callbacks.begin(); }
306 visitor_iterator visitor_end() { return Callbacks.end(); }
308 /// Profile to identify equivalent bug reports for error report coalescing.
309 /// Reports are uniqued to ensure that we do not emit multiple diagnostics
311 virtual void Profile(llvm::FoldingSetNodeID& hash) const;
314 } // end ento namespace
315 } // end clang namespace
318 template<> struct ilist_traits<clang::ento::BugReport>
319 : public ilist_default_traits<clang::ento::BugReport> {
320 clang::ento::BugReport *createSentinel() const {
321 return static_cast<clang::ento::BugReport *>(&Sentinel);
323 void destroySentinel(clang::ento::BugReport *) const {}
325 clang::ento::BugReport *provideInitialHead() const {
326 return createSentinel();
328 clang::ento::BugReport *ensureHead(clang::ento::BugReport *) const {
329 return createSentinel();
332 mutable ilist_half_node<clang::ento::BugReport> Sentinel;
339 //===----------------------------------------------------------------------===//
340 // BugTypes (collections of related reports).
341 //===----------------------------------------------------------------------===//
343 class BugReportEquivClass : public llvm::FoldingSetNode {
344 /// List of *owned* BugReport objects.
345 llvm::ilist<BugReport> Reports;
347 friend class BugReporter;
348 void AddReport(BugReport* R) { Reports.push_back(R); }
350 BugReportEquivClass(BugReport* R) { Reports.push_back(R); }
351 ~BugReportEquivClass();
353 void Profile(llvm::FoldingSetNodeID& ID) const {
354 assert(!Reports.empty());
355 Reports.front().Profile(ID);
358 typedef llvm::ilist<BugReport>::iterator iterator;
359 typedef llvm::ilist<BugReport>::const_iterator const_iterator;
361 iterator begin() { return Reports.begin(); }
362 iterator end() { return Reports.end(); }
364 const_iterator begin() const { return Reports.begin(); }
365 const_iterator end() const { return Reports.end(); }
368 //===----------------------------------------------------------------------===//
369 // BugReporter and friends.
370 //===----------------------------------------------------------------------===//
372 class BugReporterData {
374 virtual ~BugReporterData();
375 virtual DiagnosticsEngine& getDiagnostic() = 0;
376 virtual ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() = 0;
377 virtual ASTContext &getASTContext() = 0;
378 virtual SourceManager& getSourceManager() = 0;
379 virtual AnalyzerOptions& getAnalyzerOptions() = 0;
382 /// BugReporter is a utility class for generating PathDiagnostics for analysis.
383 /// It collects the BugReports and BugTypes and knows how to generate
384 /// and flush the corresponding diagnostics.
387 enum Kind { BaseBRKind, GRBugReporterKind };
390 typedef llvm::ImmutableSet<BugType*> BugTypesTy;
391 BugTypesTy::Factory F;
397 /// Generate and flush the diagnostics for the given bug report.
398 void FlushReport(BugReportEquivClass& EQ);
400 /// Generate and flush the diagnostics for the given bug report
401 /// and PathDiagnosticConsumer.
402 void FlushReport(BugReport *exampleReport,
403 PathDiagnosticConsumer &PD,
404 ArrayRef<BugReport*> BugReports);
406 /// The set of bug reports tracked by the BugReporter.
407 llvm::FoldingSet<BugReportEquivClass> EQClasses;
408 /// A vector of BugReports for tracking the allocated pointers and cleanup.
409 std::vector<BugReportEquivClass *> EQClassesVector;
412 BugReporter(BugReporterData& d, Kind k) : BugTypes(F.getEmptySet()), kind(k),
416 BugReporter(BugReporterData& d) : BugTypes(F.getEmptySet()), kind(BaseBRKind),
418 virtual ~BugReporter();
420 /// \brief Generate and flush diagnostics for all bug reports.
423 Kind getKind() const { return kind; }
425 DiagnosticsEngine& getDiagnostic() {
426 return D.getDiagnostic();
429 ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() {
430 return D.getPathDiagnosticConsumers();
433 /// \brief Iterator over the set of BugTypes tracked by the BugReporter.
434 typedef BugTypesTy::iterator iterator;
435 iterator begin() { return BugTypes.begin(); }
436 iterator end() { return BugTypes.end(); }
438 /// \brief Iterator over the set of BugReports tracked by the BugReporter.
439 typedef llvm::FoldingSet<BugReportEquivClass>::iterator EQClasses_iterator;
440 EQClasses_iterator EQClasses_begin() { return EQClasses.begin(); }
441 EQClasses_iterator EQClasses_end() { return EQClasses.end(); }
443 ASTContext &getContext() { return D.getASTContext(); }
445 SourceManager& getSourceManager() { return D.getSourceManager(); }
447 AnalyzerOptions& getAnalyzerOptions() { return D.getAnalyzerOptions(); }
449 virtual bool generatePathDiagnostic(PathDiagnostic& pathDiagnostic,
450 PathDiagnosticConsumer &PC,
451 ArrayRef<BugReport *> &bugReports) {
455 bool RemoveUnneededCalls(PathPieces &pieces, BugReport *R);
457 void Register(BugType *BT);
459 /// \brief Add the given report to the set of reports tracked by BugReporter.
461 /// The reports are usually generated by the checkers. Further, they are
462 /// folded based on the profile value, which is done to coalesce similar
464 void emitReport(BugReport *R);
466 void EmitBasicReport(const Decl *DeclWithIssue,
467 StringRef BugName, StringRef BugCategory,
468 StringRef BugStr, PathDiagnosticLocation Loc,
469 ArrayRef<SourceRange> Ranges = None);
472 llvm::StringMap<BugType *> StrBugTypes;
474 /// \brief Returns a BugType that is associated with the given name and
476 BugType *getBugTypeForName(StringRef name, StringRef category);
479 // FIXME: Get rid of GRBugReporter. It's the wrong abstraction.
480 class GRBugReporter : public BugReporter {
483 GRBugReporter(BugReporterData& d, ExprEngine& eng)
484 : BugReporter(d, GRBugReporterKind), Eng(eng) {}
486 virtual ~GRBugReporter();
488 /// getEngine - Return the analysis engine used to analyze a given
489 /// function or method.
490 ExprEngine &getEngine() { return Eng; }
492 /// getGraph - Get the exploded graph created by the analysis engine
493 /// for the analyzed method or function.
494 ExplodedGraph &getGraph();
496 /// getStateManager - Return the state manager used by the analysis
498 ProgramStateManager &getStateManager();
500 /// Generates a path corresponding to one of the given bug reports.
502 /// Which report is used for path generation is not specified. The
503 /// bug reporter will try to pick the shortest path, but this is not
506 /// \return True if the report was valid and a path was generated,
507 /// false if the reports should be considered invalid.
508 virtual bool generatePathDiagnostic(PathDiagnostic &PD,
509 PathDiagnosticConsumer &PC,
510 ArrayRef<BugReport*> &bugReports);
512 /// classof - Used by isa<>, cast<>, and dyn_cast<>.
513 static bool classof(const BugReporter* R) {
514 return R->getKind() == GRBugReporterKind;
518 class BugReporterContext {
519 virtual void anchor();
522 BugReporterContext(GRBugReporter& br) : BR(br) {}
524 virtual ~BugReporterContext() {}
526 GRBugReporter& getBugReporter() { return BR; }
528 ExplodedGraph &getGraph() { return BR.getGraph(); }
530 ProgramStateManager& getStateManager() {
531 return BR.getStateManager();
534 SValBuilder& getSValBuilder() {
535 return getStateManager().getSValBuilder();
538 ASTContext &getASTContext() {
539 return BR.getContext();
542 SourceManager& getSourceManager() {
543 return BR.getSourceManager();
546 virtual BugReport::NodeResolver& getNodeResolver() = 0;
549 } // end GR namespace
551 } // end clang namespace