]> granicus.if.org Git - clang/blob - include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
Remove DiagBugReport by pulling it into its parent BugReport.
[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/PathSensitive/ProgramState.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/ImmutableList.h"
22 #include "llvm/ADT/ImmutableSet.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include <list>
25
26 namespace clang {
27
28 class ASTContext;
29 class Diagnostic;
30 class Stmt;
31 class ParentMap;
32
33 namespace ento {
34
35 class PathDiagnostic;
36 class PathDiagnosticPiece;
37 class PathDiagnosticClient;
38 class ExplodedNode;
39 class ExplodedGraph;
40 class BugReporter;
41 class BugReporterContext;
42 class ExprEngine;
43 class ProgramState;
44 class BugType;
45
46 //===----------------------------------------------------------------------===//
47 // Interface for individual bug reports.
48 //===----------------------------------------------------------------------===//
49
50 class BugReporterVisitor : public llvm::FoldingSetNode {
51 public:
52   virtual ~BugReporterVisitor();
53   virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
54                                          const ExplodedNode *PrevN,
55                                          BugReporterContext &BRC) = 0;
56
57   virtual bool isOwnedByReporterContext() { return true; }
58   virtual void Profile(llvm::FoldingSetNodeID &ID) const = 0;
59 };
60
61 class BugReport : public BugReporterVisitor {
62 public:
63   class NodeResolver {
64   public:
65     virtual ~NodeResolver() {}
66     virtual const ExplodedNode*
67             getOriginalNode(const ExplodedNode *N) = 0;
68   };
69
70   typedef void (*VisitorCreator)(BugReporterContext &BRcC, const void *data,
71                                  const ExplodedNode *N);
72   typedef const SourceRange *ranges_iterator;
73
74 protected:
75   friend class BugReporter;
76   friend class BugReportEquivClass;
77   typedef SmallVector<std::pair<VisitorCreator, const void*>, 2> Creators;
78
79   BugType& BT;
80   std::string ShortDescription;
81   std::string Description;
82   FullSourceLoc Location;
83   const ExplodedNode *ErrorNode;
84   SmallVector<SourceRange, 4> Ranges;
85   Creators creators;
86
87   /// Profile to identify equivalent bug reports for error report coalescing.
88   virtual void Profile(llvm::FoldingSetNodeID& hash) const;
89
90   const Stmt *getStmt() const;
91
92 public:
93   BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode)
94     : BT(bt), Description(desc), ErrorNode(errornode) {}
95
96   BugReport(BugType& bt, StringRef shortDesc, StringRef desc,
97             const ExplodedNode *errornode)
98   : BT(bt), ShortDescription(shortDesc), Description(desc),
99     ErrorNode(errornode) {}
100
101   BugReport(BugType& bt, StringRef desc, FullSourceLoc l)
102     : BT(bt), Description(desc), Location(l), ErrorNode(0) {}
103
104   virtual ~BugReport();
105
106   bool isOwnedByReporterContext() { return false; }
107
108   const BugType& getBugType() const { return BT; }
109   BugType& getBugType() { return BT; }
110
111   const ExplodedNode *getErrorNode() const { return ErrorNode; }
112
113   const StringRef getDescription() const { return Description; }
114
115   const StringRef getShortDescription() const {
116     return ShortDescription.empty() ? Description : ShortDescription;
117   }
118
119   /// \brief This allows for addition of meta data to the diagnostic.
120   ///
121   /// Currently, only the HTMLDiagnosticClient knows how to display it. 
122   virtual std::pair<const char**,const char**> getExtraDescriptiveText() {
123     return std::make_pair((const char**)0,(const char**)0);
124   }
125
126   /// Provide custom definition for the last diagnostic piece on the path.
127   virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
128                                           const ExplodedNode *N);
129
130   /// \brief Return the "definitive" location of the reported bug.
131   ///
132   ///  While a bug can span an entire path, usually there is a specific
133   ///  location that can be used to identify where the key issue occurred.
134   ///  This location is used by clients rendering diagnostics.
135   virtual SourceLocation getLocation() const;
136
137   /// \brief Add a range to a bug report.
138   ///
139   /// Ranges are used to highlight regions of interest in the source code.
140   /// They should be at the same source code line as the BugReport location.
141   void addRange(SourceRange R) {
142     assert(R.isValid());
143     Ranges.push_back(R);
144   }
145
146   /// \brief Get the SourceRanges associated with the report.
147   virtual std::pair<ranges_iterator, ranges_iterator> getRanges();
148
149   /// \brief Add custom or predefined bug report visitors to this report.
150   ///
151   /// The visitors should be used when the default trace is not sufficient.
152   /// For example, they allow constructing a more elaborate trace.
153   /// \sa registerConditionVisitor(), registerTrackNullOrUndefValue(),
154   /// registerFindLastStore(), registerNilReceiverVisitor(), and
155   /// registerVarDeclsLastStore().
156   void addVisitorCreator(VisitorCreator creator, const void *data) {
157     creators.push_back(std::make_pair(creator, data));
158   }
159
160   virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
161                                          const ExplodedNode *PrevN,
162                                          BugReporterContext &BR);
163
164   virtual void registerInitialVisitors(BugReporterContext &BRC,
165                                        const ExplodedNode *N) {}
166 };
167
168 //===----------------------------------------------------------------------===//
169 // BugTypes (collections of related reports).
170 //===----------------------------------------------------------------------===//
171
172 class BugReportEquivClass : public llvm::FoldingSetNode {
173   /// List of *owned* BugReport objects.
174   std::list<BugReport*> Reports;
175
176   friend class BugReporter;
177   void AddReport(BugReport* R) { Reports.push_back(R); }
178 public:
179   BugReportEquivClass(BugReport* R) { Reports.push_back(R); }
180   ~BugReportEquivClass();
181
182   void Profile(llvm::FoldingSetNodeID& ID) const {
183     assert(!Reports.empty());
184     (*Reports.begin())->Profile(ID);
185   }
186
187   class iterator {
188     std::list<BugReport*>::iterator impl;
189   public:
190     iterator(std::list<BugReport*>::iterator i) : impl(i) {}
191     iterator &operator++() { ++impl; return *this; }
192     bool operator==(const iterator &I) const { return I.impl == impl; }
193     bool operator!=(const iterator &I) const { return I.impl != impl; }
194     BugReport* operator*() const { return *impl; }
195     BugReport* operator->() const { return *impl; }
196   };
197
198   class const_iterator {
199     std::list<BugReport*>::const_iterator impl;
200   public:
201     const_iterator(std::list<BugReport*>::const_iterator i) : impl(i) {}
202     const_iterator &operator++() { ++impl; return *this; }
203     bool operator==(const const_iterator &I) const { return I.impl == impl; }
204     bool operator!=(const const_iterator &I) const { return I.impl != impl; }
205     const BugReport* operator*() const { return *impl; }
206     const BugReport* operator->() const { return *impl; }
207   };
208
209   iterator begin() { return iterator(Reports.begin()); }
210   iterator end() { return iterator(Reports.end()); }
211
212   const_iterator begin() const { return const_iterator(Reports.begin()); }
213   const_iterator end() const { return const_iterator(Reports.end()); }
214 };
215
216 //===----------------------------------------------------------------------===//
217 // BugReporter and friends.
218 //===----------------------------------------------------------------------===//
219
220 class BugReporterData {
221 public:
222   virtual ~BugReporterData();
223   virtual Diagnostic& getDiagnostic() = 0;
224   virtual PathDiagnosticClient* getPathDiagnosticClient() = 0;
225   virtual ASTContext &getASTContext() = 0;
226   virtual SourceManager& getSourceManager() = 0;
227 };
228
229 /// BugReporter is a utility class for generating PathDiagnostics for analysis.
230 /// It collects the BugReports and BugTypes and knows how to generate
231 /// and flush the corresponding diagnostics.
232 class BugReporter {
233 public:
234   enum Kind { BaseBRKind, GRBugReporterKind };
235
236 private:
237   typedef llvm::ImmutableSet<BugType*> BugTypesTy;
238   BugTypesTy::Factory F;
239   BugTypesTy BugTypes;
240
241   const Kind kind;
242   BugReporterData& D;
243
244   /// Generate and flush the diagnostics for the given bug report.
245   void FlushReport(BugReportEquivClass& EQ);
246
247   /// The set of bug reports tracked by the BugReporter.
248   llvm::FoldingSet<BugReportEquivClass> EQClasses;
249
250 protected:
251   BugReporter(BugReporterData& d, Kind k) : BugTypes(F.getEmptySet()), kind(k),
252                                             D(d) {}
253
254 public:
255   BugReporter(BugReporterData& d) : BugTypes(F.getEmptySet()), kind(BaseBRKind),
256                                     D(d) {}
257   virtual ~BugReporter();
258
259   /// \brief Generate and flush diagnostics for all bug reports.
260   void FlushReports();
261
262   Kind getKind() const { return kind; }
263
264   Diagnostic& getDiagnostic() {
265     return D.getDiagnostic();
266   }
267
268   PathDiagnosticClient* getPathDiagnosticClient() {
269     return D.getPathDiagnosticClient();
270   }
271
272   /// \brief Iterator over the set of BugTypes tracked by the BugReporter.
273   typedef BugTypesTy::iterator iterator;
274   iterator begin() { return BugTypes.begin(); }
275   iterator end() { return BugTypes.end(); }
276
277   /// \brief Iterator over the set of BugReports tracked by the BugReporter.
278   typedef llvm::FoldingSet<BugReportEquivClass>::iterator EQClasses_iterator;
279   EQClasses_iterator EQClasses_begin() { return EQClasses.begin(); }
280   EQClasses_iterator EQClasses_end() { return EQClasses.end(); }
281
282   ASTContext &getContext() { return D.getASTContext(); }
283
284   SourceManager& getSourceManager() { return D.getSourceManager(); }
285
286   virtual void GeneratePathDiagnostic(PathDiagnostic& pathDiagnostic,
287         SmallVectorImpl<BugReport *> &bugReports) {}
288
289   void Register(BugType *BT);
290
291   /// \brief Add the given report to the set of reports tracked by BugReporter.
292   ///
293   /// The reports are usually generated by the checkers. Further, they are
294   /// folded based on the profile value, which is done to coalesce similar
295   /// reports.
296   void EmitReport(BugReport *R);
297
298   void EmitBasicReport(StringRef BugName, StringRef BugStr,
299                        SourceLocation Loc,
300                        SourceRange* RangeBeg, unsigned NumRanges);
301
302   void EmitBasicReport(StringRef BugName, StringRef BugCategory,
303                        StringRef BugStr, SourceLocation Loc,
304                        SourceRange* RangeBeg, unsigned NumRanges);
305
306
307   void EmitBasicReport(StringRef BugName, StringRef BugStr,
308                        SourceLocation Loc) {
309     EmitBasicReport(BugName, BugStr, Loc, 0, 0);
310   }
311
312   void EmitBasicReport(StringRef BugName, StringRef BugCategory,
313                        StringRef BugStr, SourceLocation Loc) {
314     EmitBasicReport(BugName, BugCategory, BugStr, Loc, 0, 0);
315   }
316
317   void EmitBasicReport(StringRef BugName, StringRef BugStr,
318                        SourceLocation Loc, SourceRange R) {
319     EmitBasicReport(BugName, BugStr, Loc, &R, 1);
320   }
321
322   void EmitBasicReport(StringRef BugName, StringRef Category,
323                        StringRef BugStr, SourceLocation Loc,
324                        SourceRange R) {
325     EmitBasicReport(BugName, Category, BugStr, Loc, &R, 1);
326   }
327
328   static bool classof(const BugReporter* R) { return true; }
329
330 private:
331   llvm::StringMap<BugType *> StrBugTypes;
332
333   /// \brief Returns a BugType that is associated with the given name and
334   /// category.
335   BugType *getBugTypeForName(StringRef name, StringRef category);
336 };
337
338 // FIXME: Get rid of GRBugReporter.  It's the wrong abstraction.
339 class GRBugReporter : public BugReporter {
340   ExprEngine& Eng;
341   llvm::SmallSet<SymbolRef, 10> NotableSymbols;
342 public:
343   GRBugReporter(BugReporterData& d, ExprEngine& eng)
344     : BugReporter(d, GRBugReporterKind), Eng(eng) {}
345
346   virtual ~GRBugReporter();
347
348   /// getEngine - Return the analysis engine used to analyze a given
349   ///  function or method.
350   ExprEngine &getEngine() { return Eng; }
351
352   /// getGraph - Get the exploded graph created by the analysis engine
353   ///  for the analyzed method or function.
354   ExplodedGraph &getGraph();
355
356   /// getStateManager - Return the state manager used by the analysis
357   ///  engine.
358   ProgramStateManager &getStateManager();
359
360   virtual void GeneratePathDiagnostic(PathDiagnostic &pathDiagnostic,
361                      SmallVectorImpl<BugReport*> &bugReports);
362
363   void addNotableSymbol(SymbolRef Sym) {
364     NotableSymbols.insert(Sym);
365   }
366
367   bool isNotable(SymbolRef Sym) const {
368     return (bool) NotableSymbols.count(Sym);
369   }
370
371   /// classof - Used by isa<>, cast<>, and dyn_cast<>.
372   static bool classof(const BugReporter* R) {
373     return R->getKind() == GRBugReporterKind;
374   }
375 };
376
377 class BugReporterContext {
378   GRBugReporter &BR;
379   // Not the most efficient data structure, but we use an ImmutableList for the
380   // Callbacks because it is safe to make additions to list during iteration.
381   llvm::ImmutableList<BugReporterVisitor*>::Factory F;
382   llvm::ImmutableList<BugReporterVisitor*> Callbacks;
383   llvm::FoldingSet<BugReporterVisitor> CallbacksSet;
384 public:
385   BugReporterContext(GRBugReporter& br) : BR(br), Callbacks(F.getEmptyList()) {}
386   virtual ~BugReporterContext();
387
388   void addVisitor(BugReporterVisitor* visitor);
389
390   typedef llvm::ImmutableList<BugReporterVisitor*>::iterator visitor_iterator;
391   visitor_iterator visitor_begin() { return Callbacks.begin(); }
392   visitor_iterator visitor_end() { return Callbacks.end(); }
393
394   GRBugReporter& getBugReporter() { return BR; }
395
396   ExplodedGraph &getGraph() { return BR.getGraph(); }
397
398   void addNotableSymbol(SymbolRef Sym) {
399     // FIXME: For now forward to GRBugReporter.
400     BR.addNotableSymbol(Sym);
401   }
402
403   bool isNotable(SymbolRef Sym) const {
404     // FIXME: For now forward to GRBugReporter.
405     return BR.isNotable(Sym);
406   }
407
408   ProgramStateManager& getStateManager() {
409     return BR.getStateManager();
410   }
411
412   SValBuilder& getSValBuilder() {
413     return getStateManager().getSValBuilder();
414   }
415
416   ASTContext &getASTContext() {
417     return BR.getContext();
418   }
419
420   SourceManager& getSourceManager() {
421     return BR.getSourceManager();
422   }
423
424   virtual BugReport::NodeResolver& getNodeResolver() = 0;
425 };
426
427 //===----------------------------------------------------------------------===//
428 //===----------------------------------------------------------------------===//
429
430 namespace bugreporter {
431
432 const Stmt *GetDerefExpr(const ExplodedNode *N);
433 const Stmt *GetDenomExpr(const ExplodedNode *N);
434 const Stmt *GetCalleeExpr(const ExplodedNode *N);
435 const Stmt *GetRetValExpr(const ExplodedNode *N);
436
437 void registerConditionVisitor(BugReporterContext &BRC);
438
439 void registerTrackNullOrUndefValue(BugReporterContext &BRC, const void *stmt,
440                                    const ExplodedNode *N);
441
442 void registerFindLastStore(BugReporterContext &BRC, const void *memregion,
443                            const ExplodedNode *N);
444
445 void registerNilReceiverVisitor(BugReporterContext &BRC);  
446
447 void registerVarDeclsLastStore(BugReporterContext &BRC, const void *stmt,
448                                const ExplodedNode *N);
449
450 } // end namespace clang::bugreporter
451
452 //===----------------------------------------------------------------------===//
453
454 } // end GR namespace
455
456 } // end clang namespace
457
458 #endif