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.
119 /// Used to track unique reasons why a bug report might be invalid.
122 /// \sa removeInvalidation
123 typedef std::pair<const void *, const void *> InvalidationRecord;
125 /// If non-empty, this bug report is likely a false positive and should not be
126 /// shown to the user.
129 /// \sa removeInvalidation
130 llvm::SmallSet<InvalidationRecord, 4> Invalidations;
133 // Used internally by BugReporter.
134 Symbols &getInterestingSymbols();
135 Regions &getInterestingRegions();
137 void lazyInitializeInterestingSets();
138 void pushInterestingSymbolsAndRegions();
139 void popInterestingSymbolsAndRegions();
142 BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode)
143 : BT(bt), DeclWithIssue(0), Description(desc), ErrorNode(errornode),
144 ConfigurationChangeToken(0), DoNotPrunePath(false) {}
146 BugReport(BugType& bt, StringRef shortDesc, StringRef desc,
147 const ExplodedNode *errornode)
148 : BT(bt), DeclWithIssue(0), ShortDescription(shortDesc), Description(desc),
149 ErrorNode(errornode), ConfigurationChangeToken(0),
150 DoNotPrunePath(false) {}
152 BugReport(BugType& bt, StringRef desc, PathDiagnosticLocation l)
153 : BT(bt), DeclWithIssue(0), Description(desc), Location(l), ErrorNode(0),
154 ConfigurationChangeToken(0),
155 DoNotPrunePath(false) {}
157 /// \brief Create a BugReport with a custom uniqueing location.
159 /// The reports that have the same report location, description, bug type, and
160 /// ranges are uniqued - only one of the equivalent reports will be presented
161 /// to the user. This method allows to rest the location which should be used
162 /// for uniquing reports. For example, memory leaks checker, could set this to
163 /// the allocation site, rather then the location where the bug is reported.
164 BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode,
165 PathDiagnosticLocation LocationToUnique)
166 : BT(bt), DeclWithIssue(0), Description(desc),
167 UniqueingLocation(LocationToUnique),
168 ErrorNode(errornode), ConfigurationChangeToken(0),
169 DoNotPrunePath(false) {}
171 virtual ~BugReport();
173 const BugType& getBugType() const { return BT; }
174 BugType& getBugType() { return BT; }
176 const ExplodedNode *getErrorNode() const { return ErrorNode; }
178 const StringRef getDescription() const { return Description; }
180 const StringRef getShortDescription(bool UseFallback = true) const {
181 if (ShortDescription.empty() && UseFallback)
183 return ShortDescription;
186 /// Indicates whether or not any path pruning should take place
187 /// when generating a PathDiagnostic from this BugReport.
188 bool shouldPrunePath() const { return !DoNotPrunePath; }
190 /// Disable all path pruning when generating a PathDiagnostic.
191 void disablePathPruning() { DoNotPrunePath = true; }
193 void markInteresting(SymbolRef sym);
194 void markInteresting(const MemRegion *R);
195 void markInteresting(SVal V);
196 void markInteresting(const LocationContext *LC);
198 bool isInteresting(SymbolRef sym);
199 bool isInteresting(const MemRegion *R);
200 bool isInteresting(SVal V);
201 bool isInteresting(const LocationContext *LC);
203 unsigned getConfigurationChangeToken() const {
204 return ConfigurationChangeToken;
207 /// Returns whether or not this report should be considered valid.
209 /// Invalid reports are those that have been classified as likely false
210 /// positives after the fact.
211 bool isValid() const {
212 return Invalidations.empty();
215 /// Marks the current report as invalid, meaning that it is probably a false
216 /// positive and should not be reported to the user.
218 /// The \p Tag and \p Data arguments are intended to be opaque identifiers for
219 /// this particular invalidation, where \p Tag represents the visitor
220 /// responsible for invalidation, and \p Data represents the reason this
221 /// visitor decided to invalidate the bug report.
223 /// \sa removeInvalidation
224 void markInvalid(const void *Tag, const void *Data) {
225 Invalidations.insert(std::make_pair(Tag, Data));
228 /// Reverses the effects of a previous invalidation.
231 void removeInvalidation(const void *Tag, const void *Data) {
232 Invalidations.erase(std::make_pair(Tag, Data));
235 /// Return the canonical declaration, be it a method or class, where
236 /// this issue semantically occurred.
237 const Decl *getDeclWithIssue() const;
239 /// Specifically set the Decl where an issue occurred. This isn't necessary
240 /// for BugReports that cover a path as it will be automatically inferred.
241 void setDeclWithIssue(const Decl *declWithIssue) {
242 DeclWithIssue = declWithIssue;
245 /// \brief This allows for addition of meta data to the diagnostic.
247 /// Currently, only the HTMLDiagnosticClient knows how to display it.
248 void addExtraText(StringRef S) {
249 ExtraText.push_back(S);
252 virtual const ExtraTextList &getExtraText() {
256 /// \brief Return the "definitive" location of the reported bug.
258 /// While a bug can span an entire path, usually there is a specific
259 /// location that can be used to identify where the key issue occurred.
260 /// This location is used by clients rendering diagnostics.
261 virtual PathDiagnosticLocation getLocation(const SourceManager &SM) const;
263 const Stmt *getStmt() const;
265 /// \brief Add a range to a bug report.
267 /// Ranges are used to highlight regions of interest in the source code.
268 /// They should be at the same source code line as the BugReport location.
269 /// By default, the source range of the statement corresponding to the error
270 /// node will be used; add a single invalid range to specify absence of
272 void addRange(SourceRange R) {
273 assert((R.isValid() || Ranges.empty()) && "Invalid range can only be used "
274 "to specify that the report does not have a range.");
278 /// \brief Get the SourceRanges associated with the report.
279 virtual std::pair<ranges_iterator, ranges_iterator> getRanges();
281 /// \brief Add custom or predefined bug report visitors to this report.
283 /// The visitors should be used when the default trace is not sufficient.
284 /// For example, they allow constructing a more elaborate trace.
285 /// \sa registerConditionVisitor(), registerTrackNullOrUndefValue(),
286 /// registerFindLastStore(), registerNilReceiverVisitor(), and
287 /// registerVarDeclsLastStore().
288 void addVisitor(BugReporterVisitor *visitor);
290 /// Iterators through the custom diagnostic visitors.
291 visitor_iterator visitor_begin() { return Callbacks.begin(); }
292 visitor_iterator visitor_end() { return Callbacks.end(); }
294 /// Profile to identify equivalent bug reports for error report coalescing.
295 /// Reports are uniqued to ensure that we do not emit multiple diagnostics
297 virtual void Profile(llvm::FoldingSetNodeID& hash) const;
300 } // end ento namespace
301 } // end clang namespace
304 template<> struct ilist_traits<clang::ento::BugReport>
305 : public ilist_default_traits<clang::ento::BugReport> {
306 clang::ento::BugReport *createSentinel() const {
307 return static_cast<clang::ento::BugReport *>(&Sentinel);
309 void destroySentinel(clang::ento::BugReport *) const {}
311 clang::ento::BugReport *provideInitialHead() const {
312 return createSentinel();
314 clang::ento::BugReport *ensureHead(clang::ento::BugReport *) const {
315 return createSentinel();
318 mutable ilist_half_node<clang::ento::BugReport> Sentinel;
325 //===----------------------------------------------------------------------===//
326 // BugTypes (collections of related reports).
327 //===----------------------------------------------------------------------===//
329 class BugReportEquivClass : public llvm::FoldingSetNode {
330 /// List of *owned* BugReport objects.
331 llvm::ilist<BugReport> Reports;
333 friend class BugReporter;
334 void AddReport(BugReport* R) { Reports.push_back(R); }
336 BugReportEquivClass(BugReport* R) { Reports.push_back(R); }
337 ~BugReportEquivClass();
339 void Profile(llvm::FoldingSetNodeID& ID) const {
340 assert(!Reports.empty());
341 Reports.front().Profile(ID);
344 typedef llvm::ilist<BugReport>::iterator iterator;
345 typedef llvm::ilist<BugReport>::const_iterator const_iterator;
347 iterator begin() { return Reports.begin(); }
348 iterator end() { return Reports.end(); }
350 const_iterator begin() const { return Reports.begin(); }
351 const_iterator end() const { return Reports.end(); }
354 //===----------------------------------------------------------------------===//
355 // BugReporter and friends.
356 //===----------------------------------------------------------------------===//
358 class BugReporterData {
360 virtual ~BugReporterData();
361 virtual DiagnosticsEngine& getDiagnostic() = 0;
362 virtual ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() = 0;
363 virtual ASTContext &getASTContext() = 0;
364 virtual SourceManager& getSourceManager() = 0;
367 /// BugReporter is a utility class for generating PathDiagnostics for analysis.
368 /// It collects the BugReports and BugTypes and knows how to generate
369 /// and flush the corresponding diagnostics.
372 enum Kind { BaseBRKind, GRBugReporterKind };
375 typedef llvm::ImmutableSet<BugType*> BugTypesTy;
376 BugTypesTy::Factory F;
382 /// Generate and flush the diagnostics for the given bug report.
383 void FlushReport(BugReportEquivClass& EQ);
385 /// Generate and flush the diagnostics for the given bug report
386 /// and PathDiagnosticConsumer.
387 void FlushReport(BugReport *exampleReport,
388 PathDiagnosticConsumer &PD,
389 ArrayRef<BugReport*> BugReports);
391 /// The set of bug reports tracked by the BugReporter.
392 llvm::FoldingSet<BugReportEquivClass> EQClasses;
393 /// A vector of BugReports for tracking the allocated pointers and cleanup.
394 std::vector<BugReportEquivClass *> EQClassesVector;
396 /// A map from PathDiagnosticPiece to the LocationContext of the inlined
397 /// function call it represents.
398 llvm::DenseMap<const PathDiagnosticCallPiece*,
399 const LocationContext*> LocationContextMap;
402 BugReporter(BugReporterData& d, Kind k) : BugTypes(F.getEmptySet()), kind(k),
406 BugReporter(BugReporterData& d) : BugTypes(F.getEmptySet()), kind(BaseBRKind),
408 virtual ~BugReporter();
410 /// \brief Generate and flush diagnostics for all bug reports.
413 Kind getKind() const { return kind; }
415 DiagnosticsEngine& getDiagnostic() {
416 return D.getDiagnostic();
419 ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() {
420 return D.getPathDiagnosticConsumers();
423 /// \brief Iterator over the set of BugTypes tracked by the BugReporter.
424 typedef BugTypesTy::iterator iterator;
425 iterator begin() { return BugTypes.begin(); }
426 iterator end() { return BugTypes.end(); }
428 /// \brief Iterator over the set of BugReports tracked by the BugReporter.
429 typedef llvm::FoldingSet<BugReportEquivClass>::iterator EQClasses_iterator;
430 EQClasses_iterator EQClasses_begin() { return EQClasses.begin(); }
431 EQClasses_iterator EQClasses_end() { return EQClasses.end(); }
433 ASTContext &getContext() { return D.getASTContext(); }
435 SourceManager& getSourceManager() { return D.getSourceManager(); }
437 virtual bool generatePathDiagnostic(PathDiagnostic& pathDiagnostic,
438 PathDiagnosticConsumer &PC,
439 ArrayRef<BugReport *> &bugReports) {
443 bool RemoveUneededCalls(PathPieces &pieces, BugReport *R,
444 PathDiagnosticCallPiece *CallWithLoc = 0);
446 void Register(BugType *BT);
448 /// \brief Add the given report to the set of reports tracked by BugReporter.
450 /// The reports are usually generated by the checkers. Further, they are
451 /// folded based on the profile value, which is done to coalesce similar
453 void emitReport(BugReport *R);
455 void EmitBasicReport(const Decl *DeclWithIssue,
456 StringRef BugName, StringRef BugCategory,
457 StringRef BugStr, PathDiagnosticLocation Loc,
458 SourceRange* RangeBeg, unsigned NumRanges);
460 void EmitBasicReport(const Decl *DeclWithIssue,
461 StringRef BugName, StringRef BugCategory,
462 StringRef BugStr, PathDiagnosticLocation Loc) {
463 EmitBasicReport(DeclWithIssue, BugName, BugCategory, BugStr, Loc, 0, 0);
466 void EmitBasicReport(const Decl *DeclWithIssue,
467 StringRef BugName, StringRef Category,
468 StringRef BugStr, PathDiagnosticLocation Loc,
470 EmitBasicReport(DeclWithIssue, BugName, Category, BugStr, Loc, &R, 1);
473 void addCallPieceLocationContextPair(const PathDiagnosticCallPiece *C,
474 const LocationContext *LC) {
475 LocationContextMap[C] = LC;
478 llvm::StringMap<BugType *> StrBugTypes;
480 /// \brief Returns a BugType that is associated with the given name and
482 BugType *getBugTypeForName(StringRef name, StringRef category);
485 // FIXME: Get rid of GRBugReporter. It's the wrong abstraction.
486 class GRBugReporter : public BugReporter {
489 GRBugReporter(BugReporterData& d, ExprEngine& eng)
490 : BugReporter(d, GRBugReporterKind), Eng(eng) {}
492 virtual ~GRBugReporter();
494 /// getEngine - Return the analysis engine used to analyze a given
495 /// function or method.
496 ExprEngine &getEngine() { return Eng; }
498 /// getGraph - Get the exploded graph created by the analysis engine
499 /// for the analyzed method or function.
500 ExplodedGraph &getGraph();
502 /// getStateManager - Return the state manager used by the analysis
504 ProgramStateManager &getStateManager();
506 /// Generates a path corresponding to one of the given bug reports.
508 /// Which report is used for path generation is not specified. The
509 /// bug reporter will try to pick the shortest path, but this is not
512 /// \return True if the report was valid and a path was generated,
513 /// false if the reports should be considered invalid.
514 virtual bool generatePathDiagnostic(PathDiagnostic &PD,
515 PathDiagnosticConsumer &PC,
516 ArrayRef<BugReport*> &bugReports);
518 /// classof - Used by isa<>, cast<>, and dyn_cast<>.
519 static bool classof(const BugReporter* R) {
520 return R->getKind() == GRBugReporterKind;
524 class BugReporterContext {
525 virtual void anchor();
528 BugReporterContext(GRBugReporter& br) : BR(br) {}
530 virtual ~BugReporterContext() {}
532 GRBugReporter& getBugReporter() { return BR; }
534 ExplodedGraph &getGraph() { return BR.getGraph(); }
536 ProgramStateManager& getStateManager() {
537 return BR.getStateManager();
540 SValBuilder& getSValBuilder() {
541 return getStateManager().getSValBuilder();
544 ASTContext &getASTContext() {
545 return BR.getContext();
548 SourceManager& getSourceManager() {
549 return BR.getSourceManager();
552 virtual BugReport::NodeResolver& getNodeResolver() = 0;
555 } // end GR namespace
557 } // end clang namespace