]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
Upgrade to 1.6.16
[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 #include "llvm/ADT/SmallSet.h"
28
29 namespace clang {
30
31 class ASTContext;
32 class DiagnosticsEngine;
33 class Stmt;
34 class ParentMap;
35
36 namespace ento {
37
38 class PathDiagnostic;
39 class ExplodedNode;
40 class ExplodedGraph;
41 class BugReport;
42 class BugReporter;
43 class BugReporterContext;
44 class ExprEngine;
45 class BugType;
46
47 //===----------------------------------------------------------------------===//
48 // Interface for individual bug reports.
49 //===----------------------------------------------------------------------===//
50
51 /// This class provides an interface through which checkers can create
52 /// individual bug reports.
53 class BugReport : public llvm::ilist_node<BugReport> {
54 public:  
55   class NodeResolver {
56     virtual void anchor();
57   public:
58     virtual ~NodeResolver() {}
59     virtual const ExplodedNode*
60             getOriginalNode(const ExplodedNode *N) = 0;
61   };
62
63   typedef const SourceRange *ranges_iterator;
64   typedef SmallVector<BugReporterVisitor *, 8> VisitorList;
65   typedef VisitorList::iterator visitor_iterator;
66   typedef SmallVector<StringRef, 2> ExtraTextList;
67
68 protected:
69   friend class BugReporter;
70   friend class BugReportEquivClass;
71
72   BugType& BT;
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;
81   
82   typedef llvm::DenseSet<SymbolRef> Symbols;
83   typedef llvm::DenseSet<const MemRegion *> Regions;
84
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;
91
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;
98
99   /// A set of location contexts that correspoind to call sites which should be
100   /// considered "interesting".
101   llvm::SmallSet<const LocationContext *, 2> InterestingLocationContexts;
102
103   /// A set of custom visitors which generate "event" diagnostics at
104   /// interesting points in the path.
105   VisitorList Callbacks;
106
107   /// Used for ensuring the visitors are only added once.
108   llvm::FoldingSet<BugReporterVisitor> CallbacksSet;
109
110   /// Used for clients to tell if the report's configuration has changed
111   /// since the last time they checked.
112   unsigned ConfigurationChangeToken;
113   
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.
117   bool DoNotPrunePath;
118
119   /// Used to track unique reasons why a bug report might be invalid.
120   ///
121   /// \sa markInvalid
122   /// \sa removeInvalidation
123   typedef std::pair<const void *, const void *> InvalidationRecord;
124
125   /// If non-empty, this bug report is likely a false positive and should not be
126   /// shown to the user.
127   ///
128   /// \sa markInvalid
129   /// \sa removeInvalidation
130   llvm::SmallSet<InvalidationRecord, 4> Invalidations;
131
132 private:
133   // Used internally by BugReporter.
134   Symbols &getInterestingSymbols();
135   Regions &getInterestingRegions();
136
137   void lazyInitializeInterestingSets();
138   void pushInterestingSymbolsAndRegions();
139   void popInterestingSymbolsAndRegions();
140
141 public:
142   BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode)
143     : BT(bt), DeclWithIssue(0), Description(desc), ErrorNode(errornode),
144       ConfigurationChangeToken(0), DoNotPrunePath(false) {}
145
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) {}
151
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) {}
156
157   /// \brief Create a BugReport with a custom uniqueing location.
158   ///
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) {}
170
171   virtual ~BugReport();
172
173   const BugType& getBugType() const { return BT; }
174   BugType& getBugType() { return BT; }
175
176   const ExplodedNode *getErrorNode() const { return ErrorNode; }
177
178   const StringRef getDescription() const { return Description; }
179
180   const StringRef getShortDescription(bool UseFallback = true) const {
181     if (ShortDescription.empty() && UseFallback)
182       return Description;
183     return ShortDescription;
184   }
185
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; }
189
190   /// Disable all path pruning when generating a PathDiagnostic.
191   void disablePathPruning() { DoNotPrunePath = true; }
192   
193   void markInteresting(SymbolRef sym);
194   void markInteresting(const MemRegion *R);
195   void markInteresting(SVal V);
196   void markInteresting(const LocationContext *LC);
197   
198   bool isInteresting(SymbolRef sym);
199   bool isInteresting(const MemRegion *R);
200   bool isInteresting(SVal V);
201   bool isInteresting(const LocationContext *LC);
202
203   unsigned getConfigurationChangeToken() const {
204     return ConfigurationChangeToken;
205   }
206
207   /// Returns whether or not this report should be considered valid.
208   ///
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();
213   }
214
215   /// Marks the current report as invalid, meaning that it is probably a false
216   /// positive and should not be reported to the user.
217   ///
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.
222   ///
223   /// \sa removeInvalidation
224   void markInvalid(const void *Tag, const void *Data) {
225     Invalidations.insert(std::make_pair(Tag, Data));
226   }
227
228   /// Reverses the effects of a previous invalidation.
229   ///
230   /// \sa markInvalid
231   void removeInvalidation(const void *Tag, const void *Data) {
232     Invalidations.erase(std::make_pair(Tag, Data));
233   }
234   
235   /// Return the canonical declaration, be it a method or class, where
236   /// this issue semantically occurred.
237   const Decl *getDeclWithIssue() const;
238   
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;
243   }
244   
245   /// \brief This allows for addition of meta data to the diagnostic.
246   ///
247   /// Currently, only the HTMLDiagnosticClient knows how to display it. 
248   void addExtraText(StringRef S) {
249     ExtraText.push_back(S);
250   }
251
252   virtual const ExtraTextList &getExtraText() {
253     return ExtraText;
254   }
255
256   /// \brief Return the "definitive" location of the reported bug.
257   ///
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;
262
263   const Stmt *getStmt() const;
264
265   /// \brief Add a range to a bug report.
266   ///
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
271   /// ranges.
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.");
275     Ranges.push_back(R);
276   }
277
278   /// \brief Get the SourceRanges associated with the report.
279   virtual std::pair<ranges_iterator, ranges_iterator> getRanges();
280
281   /// \brief Add custom or predefined bug report visitors to this report.
282   ///
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);
289
290         /// Iterators through the custom diagnostic visitors.
291   visitor_iterator visitor_begin() { return Callbacks.begin(); }
292   visitor_iterator visitor_end() { return Callbacks.end(); }
293
294   /// Profile to identify equivalent bug reports for error report coalescing.
295   /// Reports are uniqued to ensure that we do not emit multiple diagnostics
296   /// for each bug.
297   virtual void Profile(llvm::FoldingSetNodeID& hash) const;
298 };
299
300 } // end ento namespace
301 } // end clang namespace
302
303 namespace llvm {
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);
308     }
309     void destroySentinel(clang::ento::BugReport *) const {}
310
311     clang::ento::BugReport *provideInitialHead() const {
312       return createSentinel();
313     }
314     clang::ento::BugReport *ensureHead(clang::ento::BugReport *) const {
315       return createSentinel();
316     }
317   private:
318     mutable ilist_half_node<clang::ento::BugReport> Sentinel;
319   };
320 }
321
322 namespace clang {
323 namespace ento {
324
325 //===----------------------------------------------------------------------===//
326 // BugTypes (collections of related reports).
327 //===----------------------------------------------------------------------===//
328
329 class BugReportEquivClass : public llvm::FoldingSetNode {
330   /// List of *owned* BugReport objects.
331   llvm::ilist<BugReport> Reports;
332
333   friend class BugReporter;
334   void AddReport(BugReport* R) { Reports.push_back(R); }
335 public:
336   BugReportEquivClass(BugReport* R) { Reports.push_back(R); }
337   ~BugReportEquivClass();
338
339   void Profile(llvm::FoldingSetNodeID& ID) const {
340     assert(!Reports.empty());
341     Reports.front().Profile(ID);
342   }
343
344   typedef llvm::ilist<BugReport>::iterator iterator;
345   typedef llvm::ilist<BugReport>::const_iterator const_iterator;
346
347   iterator begin() { return Reports.begin(); }
348   iterator end() { return Reports.end(); }
349
350   const_iterator begin() const { return Reports.begin(); }
351   const_iterator end() const { return Reports.end(); }
352 };
353
354 //===----------------------------------------------------------------------===//
355 // BugReporter and friends.
356 //===----------------------------------------------------------------------===//
357
358 class BugReporterData {
359 public:
360   virtual ~BugReporterData();
361   virtual DiagnosticsEngine& getDiagnostic() = 0;
362   virtual ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() = 0;
363   virtual ASTContext &getASTContext() = 0;
364   virtual SourceManager& getSourceManager() = 0;
365 };
366
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.
370 class BugReporter {
371 public:
372   enum Kind { BaseBRKind, GRBugReporterKind };
373
374 private:
375   typedef llvm::ImmutableSet<BugType*> BugTypesTy;
376   BugTypesTy::Factory F;
377   BugTypesTy BugTypes;
378
379   const Kind kind;
380   BugReporterData& D;
381
382   /// Generate and flush the diagnostics for the given bug report.
383   void FlushReport(BugReportEquivClass& EQ);
384
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);
390
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;
395
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;
400
401 protected:
402   BugReporter(BugReporterData& d, Kind k) : BugTypes(F.getEmptySet()), kind(k),
403                                             D(d) {}
404
405 public:
406   BugReporter(BugReporterData& d) : BugTypes(F.getEmptySet()), kind(BaseBRKind),
407                                     D(d) {}
408   virtual ~BugReporter();
409
410   /// \brief Generate and flush diagnostics for all bug reports.
411   void FlushReports();
412
413   Kind getKind() const { return kind; }
414
415   DiagnosticsEngine& getDiagnostic() {
416     return D.getDiagnostic();
417   }
418
419   ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() {
420     return D.getPathDiagnosticConsumers();
421   }
422
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(); }
427
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(); }
432
433   ASTContext &getContext() { return D.getASTContext(); }
434
435   SourceManager& getSourceManager() { return D.getSourceManager(); }
436
437   virtual bool generatePathDiagnostic(PathDiagnostic& pathDiagnostic,
438                                       PathDiagnosticConsumer &PC,
439                                       ArrayRef<BugReport *> &bugReports) {
440     return true;
441   }
442
443   bool RemoveUneededCalls(PathPieces &pieces, BugReport *R,
444                           PathDiagnosticCallPiece *CallWithLoc = 0);
445
446   void Register(BugType *BT);
447
448   /// \brief Add the given report to the set of reports tracked by BugReporter.
449   ///
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
452   /// reports.
453   void emitReport(BugReport *R);
454
455   void EmitBasicReport(const Decl *DeclWithIssue,
456                        StringRef BugName, StringRef BugCategory,
457                        StringRef BugStr, PathDiagnosticLocation Loc,
458                        SourceRange* RangeBeg, unsigned NumRanges);
459
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);
464   }
465
466   void EmitBasicReport(const Decl *DeclWithIssue,
467                        StringRef BugName, StringRef Category,
468                        StringRef BugStr, PathDiagnosticLocation Loc,
469                        SourceRange R) {
470     EmitBasicReport(DeclWithIssue, BugName, Category, BugStr, Loc, &R, 1);
471   }
472
473   void addCallPieceLocationContextPair(const PathDiagnosticCallPiece *C,
474                                        const LocationContext *LC) {
475     LocationContextMap[C] = LC;
476   }
477 private:
478   llvm::StringMap<BugType *> StrBugTypes;
479
480   /// \brief Returns a BugType that is associated with the given name and
481   /// category.
482   BugType *getBugTypeForName(StringRef name, StringRef category);
483 };
484
485 // FIXME: Get rid of GRBugReporter.  It's the wrong abstraction.
486 class GRBugReporter : public BugReporter {
487   ExprEngine& Eng;
488 public:
489   GRBugReporter(BugReporterData& d, ExprEngine& eng)
490     : BugReporter(d, GRBugReporterKind), Eng(eng) {}
491
492   virtual ~GRBugReporter();
493
494   /// getEngine - Return the analysis engine used to analyze a given
495   ///  function or method.
496   ExprEngine &getEngine() { return Eng; }
497
498   /// getGraph - Get the exploded graph created by the analysis engine
499   ///  for the analyzed method or function.
500   ExplodedGraph &getGraph();
501
502   /// getStateManager - Return the state manager used by the analysis
503   ///  engine.
504   ProgramStateManager &getStateManager();
505
506   /// Generates a path corresponding to one of the given bug reports.
507   ///
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
510   /// guaranteed.
511   ///
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);
517
518   /// classof - Used by isa<>, cast<>, and dyn_cast<>.
519   static bool classof(const BugReporter* R) {
520     return R->getKind() == GRBugReporterKind;
521   }
522 };
523
524 class BugReporterContext {
525   virtual void anchor();
526   GRBugReporter &BR;
527 public:
528   BugReporterContext(GRBugReporter& br) : BR(br) {}
529
530   virtual ~BugReporterContext() {}
531
532   GRBugReporter& getBugReporter() { return BR; }
533
534   ExplodedGraph &getGraph() { return BR.getGraph(); }
535
536   ProgramStateManager& getStateManager() {
537     return BR.getStateManager();
538   }
539
540   SValBuilder& getSValBuilder() {
541     return getStateManager().getSValBuilder();
542   }
543
544   ASTContext &getASTContext() {
545     return BR.getContext();
546   }
547
548   SourceManager& getSourceManager() {
549     return BR.getSourceManager();
550   }
551
552   virtual BugReport::NodeResolver& getNodeResolver() = 0;
553 };
554
555 } // end GR namespace
556
557 } // end clang namespace
558
559 #endif