]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
Merge bmake-20121111
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / 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   const Decl *DeclWithIssue;
73   std::string ShortDescription;
74   std::string Description;
75   PathDiagnosticLocation Location;
76   PathDiagnosticLocation UniqueingLocation;
77   const ExplodedNode *ErrorNode;
78   SmallVector<SourceRange, 4> Ranges;
79   ExtraTextList ExtraText;
80   
81   typedef llvm::DenseSet<SymbolRef> Symbols;
82   typedef llvm::DenseSet<const MemRegion *> Regions;
83
84   /// A (stack of) a set of symbols that are registered with this
85   /// report as being "interesting", and thus used to help decide which
86   /// diagnostics to include when constructing the final path diagnostic.
87   /// The stack is largely used by BugReporter when generating PathDiagnostics
88   /// for multiple PathDiagnosticConsumers.
89   llvm::SmallVector<Symbols *, 2> interestingSymbols;
90
91   /// A (stack of) set of regions that are registered with this report as being
92   /// "interesting", and thus used to help decide which diagnostics
93   /// to include when constructing the final path diagnostic.
94   /// The stack is largely used by BugReporter when generating PathDiagnostics
95   /// for multiple PathDiagnosticConsumers.
96   llvm::SmallVector<Regions *, 2> interestingRegions;
97
98   /// A set of custom visitors which generate "event" diagnostics at
99   /// interesting points in the path.
100   VisitorList Callbacks;
101
102   /// Used for ensuring the visitors are only added once.
103   llvm::FoldingSet<BugReporterVisitor> CallbacksSet;
104
105   /// Used for clients to tell if the report's configuration has changed
106   /// since the last time they checked.
107   unsigned ConfigurationChangeToken;
108   
109   /// When set, this flag disables all callstack pruning from a diagnostic
110   /// path.  This is useful for some reports that want maximum fidelty
111   /// when reporting an issue.
112   bool DoNotPrunePath;
113
114 private:
115   // Used internally by BugReporter.
116   Symbols &getInterestingSymbols();
117   Regions &getInterestingRegions();
118
119   void lazyInitializeInterestingSets();
120   void pushInterestingSymbolsAndRegions();
121   void popInterestingSymbolsAndRegions();
122
123 public:
124   BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode)
125     : BT(bt), DeclWithIssue(0), Description(desc), ErrorNode(errornode),
126       ConfigurationChangeToken(0), DoNotPrunePath(false) {}
127
128   BugReport(BugType& bt, StringRef shortDesc, StringRef desc,
129             const ExplodedNode *errornode)
130     : BT(bt), DeclWithIssue(0), ShortDescription(shortDesc), Description(desc),
131       ErrorNode(errornode), ConfigurationChangeToken(0),
132       DoNotPrunePath(false) {}
133
134   BugReport(BugType& bt, StringRef desc, PathDiagnosticLocation l)
135     : BT(bt), DeclWithIssue(0), Description(desc), Location(l), ErrorNode(0),
136       ConfigurationChangeToken(0),
137       DoNotPrunePath(false) {}
138
139   /// \brief Create a BugReport with a custom uniqueing location.
140   ///
141   /// The reports that have the same report location, description, bug type, and
142   /// ranges are uniqued - only one of the equivalent reports will be presented
143   /// to the user. This method allows to rest the location which should be used
144   /// for uniquing reports. For example, memory leaks checker, could set this to
145   /// the allocation site, rather then the location where the bug is reported.
146   BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode,
147             PathDiagnosticLocation LocationToUnique)
148     : BT(bt), DeclWithIssue(0), Description(desc),
149       UniqueingLocation(LocationToUnique),
150       ErrorNode(errornode), ConfigurationChangeToken(0) {}
151
152   virtual ~BugReport();
153
154   const BugType& getBugType() const { return BT; }
155   BugType& getBugType() { return BT; }
156
157   const ExplodedNode *getErrorNode() const { return ErrorNode; }
158
159   const StringRef getDescription() const { return Description; }
160
161   const StringRef getShortDescription() const {
162     return ShortDescription.empty() ? Description : ShortDescription;
163   }
164
165   /// Indicates whether or not any path pruning should take place
166   /// when generating a PathDiagnostic from this BugReport.
167   bool shouldPrunePath() const { return !DoNotPrunePath; }
168
169   /// Disable all path pruning when generating a PathDiagnostic.
170   void disablePathPruning() { DoNotPrunePath = true; }
171   
172   void markInteresting(SymbolRef sym);
173   void markInteresting(const MemRegion *R);
174   void markInteresting(SVal V);
175   
176   bool isInteresting(SymbolRef sym);
177   bool isInteresting(const MemRegion *R);
178   bool isInteresting(SVal V);
179
180   unsigned getConfigurationChangeToken() const {
181     return ConfigurationChangeToken;
182   }
183   
184   /// Return the canonical declaration, be it a method or class, where
185   /// this issue semantically occurred.
186   const Decl *getDeclWithIssue() const;
187   
188   /// Specifically set the Decl where an issue occurred.  This isn't necessary
189   /// for BugReports that cover a path as it will be automatically inferred.
190   void setDeclWithIssue(const Decl *declWithIssue) {
191     DeclWithIssue = declWithIssue;
192   }
193   
194   /// \brief This allows for addition of meta data to the diagnostic.
195   ///
196   /// Currently, only the HTMLDiagnosticClient knows how to display it. 
197   void addExtraText(StringRef S) {
198     ExtraText.push_back(S);
199   }
200
201   virtual const ExtraTextList &getExtraText() {
202     return ExtraText;
203   }
204
205   /// \brief Return the "definitive" location of the reported bug.
206   ///
207   ///  While a bug can span an entire path, usually there is a specific
208   ///  location that can be used to identify where the key issue occurred.
209   ///  This location is used by clients rendering diagnostics.
210   virtual PathDiagnosticLocation getLocation(const SourceManager &SM) const;
211
212   const Stmt *getStmt() const;
213
214   /// \brief Add a range to a bug report.
215   ///
216   /// Ranges are used to highlight regions of interest in the source code.
217   /// They should be at the same source code line as the BugReport location.
218   /// By default, the source range of the statement corresponding to the error
219   /// node will be used; add a single invalid range to specify absence of
220   /// ranges.
221   void addRange(SourceRange R) {
222     assert((R.isValid() || Ranges.empty()) && "Invalid range can only be used "
223                            "to specify that the report does not have a range.");
224     Ranges.push_back(R);
225   }
226
227   /// \brief Get the SourceRanges associated with the report.
228   virtual std::pair<ranges_iterator, ranges_iterator> getRanges();
229
230   /// \brief Add custom or predefined bug report visitors to this report.
231   ///
232   /// The visitors should be used when the default trace is not sufficient.
233   /// For example, they allow constructing a more elaborate trace.
234   /// \sa registerConditionVisitor(), registerTrackNullOrUndefValue(),
235   /// registerFindLastStore(), registerNilReceiverVisitor(), and
236   /// registerVarDeclsLastStore().
237   void addVisitor(BugReporterVisitor *visitor);
238
239         /// Iterators through the custom diagnostic visitors.
240   visitor_iterator visitor_begin() { return Callbacks.begin(); }
241   visitor_iterator visitor_end() { return Callbacks.end(); }
242
243   /// Profile to identify equivalent bug reports for error report coalescing.
244   /// Reports are uniqued to ensure that we do not emit multiple diagnostics
245   /// for each bug.
246   virtual void Profile(llvm::FoldingSetNodeID& hash) const;
247 };
248
249 } // end ento namespace
250 } // end clang namespace
251
252 namespace llvm {
253   template<> struct ilist_traits<clang::ento::BugReport>
254     : public ilist_default_traits<clang::ento::BugReport> {
255     clang::ento::BugReport *createSentinel() const {
256       return static_cast<clang::ento::BugReport *>(&Sentinel);
257     }
258     void destroySentinel(clang::ento::BugReport *) const {}
259
260     clang::ento::BugReport *provideInitialHead() const {
261       return createSentinel();
262     }
263     clang::ento::BugReport *ensureHead(clang::ento::BugReport *) const {
264       return createSentinel();
265     }
266   private:
267     mutable ilist_half_node<clang::ento::BugReport> Sentinel;
268   };
269 }
270
271 namespace clang {
272 namespace ento {
273
274 //===----------------------------------------------------------------------===//
275 // BugTypes (collections of related reports).
276 //===----------------------------------------------------------------------===//
277
278 class BugReportEquivClass : public llvm::FoldingSetNode {
279   /// List of *owned* BugReport objects.
280   llvm::ilist<BugReport> Reports;
281
282   friend class BugReporter;
283   void AddReport(BugReport* R) { Reports.push_back(R); }
284 public:
285   BugReportEquivClass(BugReport* R) { Reports.push_back(R); }
286   ~BugReportEquivClass();
287
288   void Profile(llvm::FoldingSetNodeID& ID) const {
289     assert(!Reports.empty());
290     Reports.front().Profile(ID);
291   }
292
293   typedef llvm::ilist<BugReport>::iterator iterator;
294   typedef llvm::ilist<BugReport>::const_iterator const_iterator;
295
296   iterator begin() { return Reports.begin(); }
297   iterator end() { return Reports.end(); }
298
299   const_iterator begin() const { return Reports.begin(); }
300   const_iterator end() const { return Reports.end(); }
301 };
302
303 //===----------------------------------------------------------------------===//
304 // BugReporter and friends.
305 //===----------------------------------------------------------------------===//
306
307 class BugReporterData {
308 public:
309   virtual ~BugReporterData();
310   virtual DiagnosticsEngine& getDiagnostic() = 0;
311   virtual ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() = 0;
312   virtual ASTContext &getASTContext() = 0;
313   virtual SourceManager& getSourceManager() = 0;
314 };
315
316 /// BugReporter is a utility class for generating PathDiagnostics for analysis.
317 /// It collects the BugReports and BugTypes and knows how to generate
318 /// and flush the corresponding diagnostics.
319 class BugReporter {
320 public:
321   enum Kind { BaseBRKind, GRBugReporterKind };
322
323 private:
324   typedef llvm::ImmutableSet<BugType*> BugTypesTy;
325   BugTypesTy::Factory F;
326   BugTypesTy BugTypes;
327
328   const Kind kind;
329   BugReporterData& D;
330
331   /// Generate and flush the diagnostics for the given bug report.
332   void FlushReport(BugReportEquivClass& EQ);
333
334   /// Generate and flush the diagnostics for the given bug report
335   /// and PathDiagnosticConsumer.
336   void FlushReport(BugReport *exampleReport,
337                    PathDiagnosticConsumer &PD,
338                    ArrayRef<BugReport*> BugReports);
339
340   /// The set of bug reports tracked by the BugReporter.
341   llvm::FoldingSet<BugReportEquivClass> EQClasses;
342   /// A vector of BugReports for tracking the allocated pointers and cleanup.
343   std::vector<BugReportEquivClass *> EQClassesVector;
344
345 protected:
346   BugReporter(BugReporterData& d, Kind k) : BugTypes(F.getEmptySet()), kind(k),
347                                             D(d) {}
348
349 public:
350   BugReporter(BugReporterData& d) : BugTypes(F.getEmptySet()), kind(BaseBRKind),
351                                     D(d) {}
352   virtual ~BugReporter();
353
354   /// \brief Generate and flush diagnostics for all bug reports.
355   void FlushReports();
356
357   Kind getKind() const { return kind; }
358
359   DiagnosticsEngine& getDiagnostic() {
360     return D.getDiagnostic();
361   }
362
363   ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() {
364     return D.getPathDiagnosticConsumers();
365   }
366
367   /// \brief Iterator over the set of BugTypes tracked by the BugReporter.
368   typedef BugTypesTy::iterator iterator;
369   iterator begin() { return BugTypes.begin(); }
370   iterator end() { return BugTypes.end(); }
371
372   /// \brief Iterator over the set of BugReports tracked by the BugReporter.
373   typedef llvm::FoldingSet<BugReportEquivClass>::iterator EQClasses_iterator;
374   EQClasses_iterator EQClasses_begin() { return EQClasses.begin(); }
375   EQClasses_iterator EQClasses_end() { return EQClasses.end(); }
376
377   ASTContext &getContext() { return D.getASTContext(); }
378
379   SourceManager& getSourceManager() { return D.getSourceManager(); }
380
381   virtual void GeneratePathDiagnostic(PathDiagnostic& pathDiagnostic,
382                                       PathDiagnosticConsumer &PC,
383                                       ArrayRef<BugReport *> &bugReports) {}
384
385   void Register(BugType *BT);
386
387   /// \brief Add the given report to the set of reports tracked by BugReporter.
388   ///
389   /// The reports are usually generated by the checkers. Further, they are
390   /// folded based on the profile value, which is done to coalesce similar
391   /// reports.
392   void EmitReport(BugReport *R);
393
394   void EmitBasicReport(const Decl *DeclWithIssue,
395                        StringRef BugName, StringRef BugCategory,
396                        StringRef BugStr, PathDiagnosticLocation Loc,
397                        SourceRange* RangeBeg, unsigned NumRanges);
398
399   void EmitBasicReport(const Decl *DeclWithIssue,
400                        StringRef BugName, StringRef BugCategory,
401                        StringRef BugStr, PathDiagnosticLocation Loc) {
402     EmitBasicReport(DeclWithIssue, BugName, BugCategory, BugStr, Loc, 0, 0);
403   }
404
405   void EmitBasicReport(const Decl *DeclWithIssue,
406                        StringRef BugName, StringRef Category,
407                        StringRef BugStr, PathDiagnosticLocation Loc,
408                        SourceRange R) {
409     EmitBasicReport(DeclWithIssue, BugName, Category, BugStr, Loc, &R, 1);
410   }
411
412   static bool classof(const BugReporter* R) { return true; }
413
414 private:
415   llvm::StringMap<BugType *> StrBugTypes;
416
417   /// \brief Returns a BugType that is associated with the given name and
418   /// category.
419   BugType *getBugTypeForName(StringRef name, StringRef category);
420 };
421
422 // FIXME: Get rid of GRBugReporter.  It's the wrong abstraction.
423 class GRBugReporter : public BugReporter {
424   ExprEngine& Eng;
425 public:
426   GRBugReporter(BugReporterData& d, ExprEngine& eng)
427     : BugReporter(d, GRBugReporterKind), Eng(eng) {}
428
429   virtual ~GRBugReporter();
430
431   /// getEngine - Return the analysis engine used to analyze a given
432   ///  function or method.
433   ExprEngine &getEngine() { return Eng; }
434
435   /// getGraph - Get the exploded graph created by the analysis engine
436   ///  for the analyzed method or function.
437   ExplodedGraph &getGraph();
438
439   /// getStateManager - Return the state manager used by the analysis
440   ///  engine.
441   ProgramStateManager &getStateManager();
442
443   virtual void GeneratePathDiagnostic(PathDiagnostic &pathDiagnostic,
444                                       PathDiagnosticConsumer &PC,
445                                       ArrayRef<BugReport*> &bugReports);
446
447   /// classof - Used by isa<>, cast<>, and dyn_cast<>.
448   static bool classof(const BugReporter* R) {
449     return R->getKind() == GRBugReporterKind;
450   }
451 };
452
453 class BugReporterContext {
454   virtual void anchor();
455   GRBugReporter &BR;
456 public:
457   BugReporterContext(GRBugReporter& br) : BR(br) {}
458
459   virtual ~BugReporterContext() {}
460
461   GRBugReporter& getBugReporter() { return BR; }
462
463   ExplodedGraph &getGraph() { return BR.getGraph(); }
464
465   ProgramStateManager& getStateManager() {
466     return BR.getStateManager();
467   }
468
469   SValBuilder& getSValBuilder() {
470     return getStateManager().getSValBuilder();
471   }
472
473   ASTContext &getASTContext() {
474     return BR.getContext();
475   }
476
477   SourceManager& getSourceManager() {
478     return BR.getSourceManager();
479   }
480
481   virtual BugReport::NodeResolver& getNodeResolver() = 0;
482 };
483
484 } // end GR namespace
485
486 } // end clang namespace
487
488 #endif