]> granicus.if.org Git - clang/blob - include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
Analyzer: Store BugReports directly in a ilist instead of adding another layer of...
[clang] / include / clang / StaticAnalyzer / Core / BugReporter / BugReporter.h
1 //===---  BugReporter.h - Generate PathDiagnostics --------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines BugReporter, a utility class for generating
11 //  PathDiagnostics for analyses based on ProgramState.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CLANG_GR_BUGREPORTER
16 #define LLVM_CLANG_GR_BUGREPORTER
17
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
28 namespace clang {
29
30 class ASTContext;
31 class DiagnosticsEngine;
32 class Stmt;
33 class ParentMap;
34
35 namespace ento {
36
37 class PathDiagnostic;
38 class ExplodedNode;
39 class ExplodedGraph;
40 class BugReport;
41 class BugReporter;
42 class BugReporterContext;
43 class ExprEngine;
44 class BugType;
45
46 //===----------------------------------------------------------------------===//
47 // Interface for individual bug reports.
48 //===----------------------------------------------------------------------===//
49
50 /// This class provides an interface through which checkers can create
51 /// individual bug reports.
52 class BugReport : public llvm::ilist_node<BugReport> {
53 public:  
54   class NodeResolver {
55     virtual void anchor();
56   public:
57     virtual ~NodeResolver() {}
58     virtual const ExplodedNode*
59             getOriginalNode(const ExplodedNode *N) = 0;
60   };
61
62   typedef const SourceRange *ranges_iterator;
63   typedef SmallVector<BugReporterVisitor *, 8> VisitorList;
64   typedef VisitorList::iterator visitor_iterator;
65   typedef SmallVector<StringRef, 2> ExtraTextList;
66
67 protected:
68   friend class BugReporter;
69   friend class BugReportEquivClass;
70
71   BugType& BT;
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;
79   
80   typedef llvm::DenseSet<SymbolRef> Symbols;
81   typedef llvm::DenseSet<const MemRegion *> Regions;
82
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;
87
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;
92
93   /// A set of custom visitors which generate "event" diagnostics at
94   /// interesting points in the path.
95   VisitorList Callbacks;
96
97   /// Used for ensuring the visitors are only added once.
98   llvm::FoldingSet<BugReporterVisitor> CallbacksSet;
99
100   /// Used for clients to tell if the report's configuration has changed
101   /// since the last time they checked.
102   unsigned ConfigurationChangeToken;
103
104 public:
105   BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode)
106     : BT(bt), Description(desc), ErrorNode(errornode),
107       ConfigurationChangeToken(0) {}
108
109   BugReport(BugType& bt, StringRef shortDesc, StringRef desc,
110             const ExplodedNode *errornode)
111     : BT(bt), ShortDescription(shortDesc), Description(desc),
112       ErrorNode(errornode), ConfigurationChangeToken(0) {}
113
114   BugReport(BugType& bt, StringRef desc, PathDiagnosticLocation l)
115     : BT(bt), Description(desc), Location(l), ErrorNode(0),
116       ConfigurationChangeToken(0) {}
117
118   /// \brief Create a BugReport with a custom uniqueing location.
119   ///
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) {}
129
130   virtual ~BugReport();
131
132   const BugType& getBugType() const { return BT; }
133   BugType& getBugType() { return BT; }
134
135   const ExplodedNode *getErrorNode() const { return ErrorNode; }
136
137   const StringRef getDescription() const { return Description; }
138
139   const StringRef getShortDescription() const {
140     return ShortDescription.empty() ? Description : ShortDescription;
141   }
142
143   void markInteresting(SymbolRef sym);
144   void markInteresting(const MemRegion *R);
145   void markInteresting(SVal V);
146   
147   bool isInteresting(SymbolRef sym) const;
148   bool isInteresting(const MemRegion *R) const;
149   bool isInteresting(SVal V) const;
150
151   unsigned getConfigurationChangeToken() const {
152     return ConfigurationChangeToken;
153   }
154   
155   /// \brief This allows for addition of meta data to the diagnostic.
156   ///
157   /// Currently, only the HTMLDiagnosticClient knows how to display it. 
158   void addExtraText(StringRef S) {
159     ExtraText.push_back(S);
160   }
161
162   virtual const ExtraTextList &getExtraText() {
163     return ExtraText;
164   }
165
166   /// \brief Return the "definitive" location of the reported bug.
167   ///
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;
172
173   const Stmt *getStmt() const;
174
175   /// \brief Add a range to a bug report.
176   ///
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
181   /// ranges.
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.");
185     Ranges.push_back(R);
186   }
187
188   /// \brief Get the SourceRanges associated with the report.
189   virtual std::pair<ranges_iterator, ranges_iterator> getRanges();
190
191   /// \brief Add custom or predefined bug report visitors to this report.
192   ///
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);
199
200         /// Iterators through the custom diagnostic visitors.
201   visitor_iterator visitor_begin() { return Callbacks.begin(); }
202   visitor_iterator visitor_end() { return Callbacks.end(); }
203
204   /// Profile to identify equivalent bug reports for error report coalescing.
205   /// Reports are uniqued to ensure that we do not emit multiple diagnostics
206   /// for each bug.
207   virtual void Profile(llvm::FoldingSetNodeID& hash) const;
208 };
209
210 } // end ento namespace
211 } // end clang namespace
212
213 namespace llvm {
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);
218     }
219     void destroySentinel(clang::ento::BugReport *) const {}
220
221     clang::ento::BugReport *provideInitialHead() const {
222       return createSentinel();
223     }
224     clang::ento::BugReport *ensureHead(clang::ento::BugReport *) const {
225       return createSentinel();
226     }
227   private:
228     mutable ilist_half_node<clang::ento::BugReport> Sentinel;
229   };
230 }
231
232 namespace clang {
233 namespace ento {
234
235 //===----------------------------------------------------------------------===//
236 // BugTypes (collections of related reports).
237 //===----------------------------------------------------------------------===//
238
239 class BugReportEquivClass : public llvm::FoldingSetNode {
240   /// List of *owned* BugReport objects.
241   llvm::ilist<BugReport> Reports;
242
243   friend class BugReporter;
244   void AddReport(BugReport* R) { Reports.push_back(R); }
245 public:
246   BugReportEquivClass(BugReport* R) { Reports.push_back(R); }
247   ~BugReportEquivClass();
248
249   void Profile(llvm::FoldingSetNodeID& ID) const {
250     assert(!Reports.empty());
251     Reports.front().Profile(ID);
252   }
253
254   typedef llvm::ilist<BugReport>::iterator iterator;
255   typedef llvm::ilist<BugReport>::const_iterator const_iterator;
256
257   iterator begin() { return Reports.begin(); }
258   iterator end() { return Reports.end(); }
259
260   const_iterator begin() const { return Reports.begin(); }
261   const_iterator end() const { return Reports.end(); }
262 };
263
264 //===----------------------------------------------------------------------===//
265 // BugReporter and friends.
266 //===----------------------------------------------------------------------===//
267
268 class BugReporterData {
269 public:
270   virtual ~BugReporterData();
271   virtual DiagnosticsEngine& getDiagnostic() = 0;
272   virtual PathDiagnosticConsumer* getPathDiagnosticConsumer() = 0;
273   virtual ASTContext &getASTContext() = 0;
274   virtual SourceManager& getSourceManager() = 0;
275 };
276
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.
280 class BugReporter {
281 public:
282   enum Kind { BaseBRKind, GRBugReporterKind };
283
284 private:
285   typedef llvm::ImmutableSet<BugType*> BugTypesTy;
286   BugTypesTy::Factory F;
287   BugTypesTy BugTypes;
288
289   const Kind kind;
290   BugReporterData& D;
291
292   /// Generate and flush the diagnostics for the given bug report.
293   void FlushReport(BugReportEquivClass& EQ);
294
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;
299
300 protected:
301   BugReporter(BugReporterData& d, Kind k) : BugTypes(F.getEmptySet()), kind(k),
302                                             D(d) {}
303
304 public:
305   BugReporter(BugReporterData& d) : BugTypes(F.getEmptySet()), kind(BaseBRKind),
306                                     D(d) {}
307   virtual ~BugReporter();
308
309   /// \brief Generate and flush diagnostics for all bug reports.
310   void FlushReports();
311
312   Kind getKind() const { return kind; }
313
314   DiagnosticsEngine& getDiagnostic() {
315     return D.getDiagnostic();
316   }
317
318   PathDiagnosticConsumer* getPathDiagnosticConsumer() {
319     return D.getPathDiagnosticConsumer();
320   }
321
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(); }
326
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(); }
331
332   ASTContext &getContext() { return D.getASTContext(); }
333
334   SourceManager& getSourceManager() { return D.getSourceManager(); }
335
336   virtual void GeneratePathDiagnostic(PathDiagnostic& pathDiagnostic,
337         SmallVectorImpl<BugReport *> &bugReports) {}
338
339   void Register(BugType *BT);
340
341   /// \brief Add the given report to the set of reports tracked by BugReporter.
342   ///
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
345   /// reports.
346   void EmitReport(BugReport *R);
347
348   void EmitBasicReport(StringRef BugName, StringRef BugStr,
349                        PathDiagnosticLocation Loc,
350                        SourceRange* RangeBeg, unsigned NumRanges);
351
352   void EmitBasicReport(StringRef BugName, StringRef BugCategory,
353                        StringRef BugStr, PathDiagnosticLocation Loc,
354                        SourceRange* RangeBeg, unsigned NumRanges);
355
356
357   void EmitBasicReport(StringRef BugName, StringRef BugStr,
358                        PathDiagnosticLocation Loc) {
359     EmitBasicReport(BugName, BugStr, Loc, 0, 0);
360   }
361
362   void EmitBasicReport(StringRef BugName, StringRef BugCategory,
363                        StringRef BugStr, PathDiagnosticLocation Loc) {
364     EmitBasicReport(BugName, BugCategory, BugStr, Loc, 0, 0);
365   }
366
367   void EmitBasicReport(StringRef BugName, StringRef BugStr,
368                        PathDiagnosticLocation Loc, SourceRange R) {
369     EmitBasicReport(BugName, BugStr, Loc, &R, 1);
370   }
371
372   void EmitBasicReport(StringRef BugName, StringRef Category,
373                        StringRef BugStr, PathDiagnosticLocation Loc,
374                        SourceRange R) {
375     EmitBasicReport(BugName, Category, BugStr, Loc, &R, 1);
376   }
377
378   static bool classof(const BugReporter* R) { return true; }
379
380 private:
381   llvm::StringMap<BugType *> StrBugTypes;
382
383   /// \brief Returns a BugType that is associated with the given name and
384   /// category.
385   BugType *getBugTypeForName(StringRef name, StringRef category);
386 };
387
388 // FIXME: Get rid of GRBugReporter.  It's the wrong abstraction.
389 class GRBugReporter : public BugReporter {
390   ExprEngine& Eng;
391 public:
392   GRBugReporter(BugReporterData& d, ExprEngine& eng)
393     : BugReporter(d, GRBugReporterKind), Eng(eng) {}
394
395   virtual ~GRBugReporter();
396
397   /// getEngine - Return the analysis engine used to analyze a given
398   ///  function or method.
399   ExprEngine &getEngine() { return Eng; }
400
401   /// getGraph - Get the exploded graph created by the analysis engine
402   ///  for the analyzed method or function.
403   ExplodedGraph &getGraph();
404
405   /// getStateManager - Return the state manager used by the analysis
406   ///  engine.
407   ProgramStateManager &getStateManager();
408
409   virtual void GeneratePathDiagnostic(PathDiagnostic &pathDiagnostic,
410                      SmallVectorImpl<BugReport*> &bugReports);
411
412   /// classof - Used by isa<>, cast<>, and dyn_cast<>.
413   static bool classof(const BugReporter* R) {
414     return R->getKind() == GRBugReporterKind;
415   }
416 };
417
418 class BugReporterContext {
419   virtual void anchor();
420   GRBugReporter &BR;
421 public:
422   BugReporterContext(GRBugReporter& br) : BR(br) {}
423
424   virtual ~BugReporterContext() {}
425
426   GRBugReporter& getBugReporter() { return BR; }
427
428   ExplodedGraph &getGraph() { return BR.getGraph(); }
429
430   ProgramStateManager& getStateManager() {
431     return BR.getStateManager();
432   }
433
434   SValBuilder& getSValBuilder() {
435     return getStateManager().getSValBuilder();
436   }
437
438   ASTContext &getASTContext() {
439     return BR.getContext();
440   }
441
442   SourceManager& getSourceManager() {
443     return BR.getSourceManager();
444   }
445
446   virtual BugReport::NodeResolver& getNodeResolver() = 0;
447 };
448
449 } // end GR namespace
450
451 } // end clang namespace
452
453 #endif