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