]> granicus.if.org Git - clang/blob - include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
[analyzer] Re-apply r283092, attempt no.3, in small chunks this time.
[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_STATICANALYZER_CORE_BUGREPORTER_BUGREPORTER_H
16 #define LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGREPORTER_H
17
18 #include "clang/Basic/SourceLocation.h"
19 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
20 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h"
21 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
22 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
24 #include "llvm/ADT/DenseSet.h"
25 #include "llvm/ADT/FoldingSet.h"
26 #include "llvm/ADT/ImmutableSet.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/ilist.h"
29 #include "llvm/ADT/ilist_node.h"
30
31 namespace clang {
32
33 class ASTContext;
34 class DiagnosticsEngine;
35 class Stmt;
36 class ParentMap;
37
38 namespace ento {
39
40 class PathDiagnostic;
41 class ExplodedNode;
42 class ExplodedGraph;
43 class BugReport;
44 class BugReporter;
45 class BugReporterContext;
46 class ExprEngine;
47 class BugType;
48
49 //===----------------------------------------------------------------------===//
50 // Interface for individual bug reports.
51 //===----------------------------------------------------------------------===//
52
53 /// This class provides an interface through which checkers can create
54 /// individual bug reports.
55 class BugReport : public llvm::ilist_node<BugReport> {
56 public:  
57   class NodeResolver {
58     virtual void anchor();
59   public:
60     virtual ~NodeResolver() {}
61     virtual const ExplodedNode*
62             getOriginalNode(const ExplodedNode *N) = 0;
63   };
64
65   typedef const SourceRange *ranges_iterator;
66   typedef SmallVector<std::unique_ptr<BugReporterVisitor>, 8> VisitorList;
67   typedef VisitorList::iterator visitor_iterator;
68   typedef SmallVector<StringRef, 2> ExtraTextList;
69   typedef SmallVector<const PathDiagnosticNotePiece *, 4> NoteList;
70
71 protected:
72   friend class BugReporter;
73   friend class BugReportEquivClass;
74
75   BugType& BT;
76   const Decl *DeclWithIssue;
77   std::string ShortDescription;
78   std::string Description;
79   PathDiagnosticLocation Location;
80   PathDiagnosticLocation UniqueingLocation;
81   const Decl *UniqueingDecl;
82   
83   const ExplodedNode *ErrorNode;
84   SmallVector<SourceRange, 4> Ranges;
85   ExtraTextList ExtraText;
86   NoteList Notes;
87
88   typedef llvm::DenseSet<SymbolRef> Symbols;
89   typedef llvm::DenseSet<const MemRegion *> Regions;
90
91   /// A (stack of) a set of symbols that are registered with this
92   /// report as being "interesting", and thus used to help decide which
93   /// diagnostics to include when constructing the final path diagnostic.
94   /// The stack is largely used by BugReporter when generating PathDiagnostics
95   /// for multiple PathDiagnosticConsumers.
96   SmallVector<Symbols *, 2> interestingSymbols;
97
98   /// A (stack of) set of regions that are registered with this report as being
99   /// "interesting", and thus used to help decide which diagnostics
100   /// to include when constructing the final path diagnostic.
101   /// The stack is largely used by BugReporter when generating PathDiagnostics
102   /// for multiple PathDiagnosticConsumers.
103   SmallVector<Regions *, 2> interestingRegions;
104
105   /// A set of location contexts that correspoind to call sites which should be
106   /// considered "interesting".
107   llvm::SmallSet<const LocationContext *, 2> InterestingLocationContexts;
108
109   /// A set of custom visitors which generate "event" diagnostics at
110   /// interesting points in the path.
111   VisitorList Callbacks;
112
113   /// Used for ensuring the visitors are only added once.
114   llvm::FoldingSet<BugReporterVisitor> CallbacksSet;
115
116   /// Used for clients to tell if the report's configuration has changed
117   /// since the last time they checked.
118   unsigned ConfigurationChangeToken;
119   
120   /// When set, this flag disables all callstack pruning from a diagnostic
121   /// path.  This is useful for some reports that want maximum fidelty
122   /// when reporting an issue.
123   bool DoNotPrunePath;
124
125   /// Used to track unique reasons why a bug report might be invalid.
126   ///
127   /// \sa markInvalid
128   /// \sa removeInvalidation
129   typedef std::pair<const void *, const void *> InvalidationRecord;
130
131   /// If non-empty, this bug report is likely a false positive and should not be
132   /// shown to the user.
133   ///
134   /// \sa markInvalid
135   /// \sa removeInvalidation
136   llvm::SmallSet<InvalidationRecord, 4> Invalidations;
137
138 private:
139   // Used internally by BugReporter.
140   Symbols &getInterestingSymbols();
141   Regions &getInterestingRegions();
142
143   void lazyInitializeInterestingSets();
144   void pushInterestingSymbolsAndRegions();
145   void popInterestingSymbolsAndRegions();
146
147 public:
148   BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode)
149     : BT(bt), DeclWithIssue(nullptr), Description(desc), ErrorNode(errornode),
150       ConfigurationChangeToken(0), DoNotPrunePath(false) {}
151
152   BugReport(BugType& bt, StringRef shortDesc, StringRef desc,
153             const ExplodedNode *errornode)
154     : BT(bt), DeclWithIssue(nullptr), ShortDescription(shortDesc),
155       Description(desc), ErrorNode(errornode), ConfigurationChangeToken(0),
156       DoNotPrunePath(false) {}
157
158   BugReport(BugType &bt, StringRef desc, PathDiagnosticLocation l)
159     : BT(bt), DeclWithIssue(nullptr), Description(desc), Location(l),
160       ErrorNode(nullptr), ConfigurationChangeToken(0), DoNotPrunePath(false) {}
161
162   /// \brief Create a BugReport with a custom uniqueing location.
163   ///
164   /// The reports that have the same report location, description, bug type, and
165   /// ranges are uniqued - only one of the equivalent reports will be presented
166   /// to the user. This method allows to rest the location which should be used
167   /// for uniquing reports. For example, memory leaks checker, could set this to
168   /// the allocation site, rather then the location where the bug is reported.
169   BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode,
170             PathDiagnosticLocation LocationToUnique, const Decl *DeclToUnique)
171     : BT(bt), DeclWithIssue(nullptr), Description(desc),
172       UniqueingLocation(LocationToUnique),
173       UniqueingDecl(DeclToUnique),
174       ErrorNode(errornode), ConfigurationChangeToken(0),
175       DoNotPrunePath(false) {}
176
177   virtual ~BugReport();
178
179   const BugType& getBugType() const { return BT; }
180   BugType& getBugType() { return BT; }
181
182   /// \brief True when the report has an execution path associated with it.
183   ///
184   /// A report is said to be path-sensitive if it was thrown against a
185   /// particular exploded node in the path-sensitive analysis graph.
186   /// Path-sensitive reports have their intermediate path diagnostics
187   /// auto-generated, perhaps with the help of checker-defined visitors,
188   /// and may contain extra notes.
189   /// Path-insensitive reports consist only of a single warning message
190   /// in a specific location, and perhaps extra notes.
191   /// Path-sensitive checkers are allowed to throw path-insensitive reports.
192   bool isPathSensitive() const { return ErrorNode != nullptr; }
193
194   const ExplodedNode *getErrorNode() const { return ErrorNode; }
195
196   StringRef getDescription() const { return Description; }
197
198   StringRef getShortDescription(bool UseFallback = true) const {
199     if (ShortDescription.empty() && UseFallback)
200       return Description;
201     return ShortDescription;
202   }
203
204   /// Indicates whether or not any path pruning should take place
205   /// when generating a PathDiagnostic from this BugReport.
206   bool shouldPrunePath() const { return !DoNotPrunePath; }
207
208   /// Disable all path pruning when generating a PathDiagnostic.
209   void disablePathPruning() { DoNotPrunePath = true; }
210   
211   void markInteresting(SymbolRef sym);
212   void markInteresting(const MemRegion *R);
213   void markInteresting(SVal V);
214   void markInteresting(const LocationContext *LC);
215   
216   bool isInteresting(SymbolRef sym);
217   bool isInteresting(const MemRegion *R);
218   bool isInteresting(SVal V);
219   bool isInteresting(const LocationContext *LC);
220
221   unsigned getConfigurationChangeToken() const {
222     return ConfigurationChangeToken;
223   }
224
225   /// Returns whether or not this report should be considered valid.
226   ///
227   /// Invalid reports are those that have been classified as likely false
228   /// positives after the fact.
229   bool isValid() const {
230     return Invalidations.empty();
231   }
232
233   /// Marks the current report as invalid, meaning that it is probably a false
234   /// positive and should not be reported to the user.
235   ///
236   /// The \p Tag and \p Data arguments are intended to be opaque identifiers for
237   /// this particular invalidation, where \p Tag represents the visitor
238   /// responsible for invalidation, and \p Data represents the reason this
239   /// visitor decided to invalidate the bug report.
240   ///
241   /// \sa removeInvalidation
242   void markInvalid(const void *Tag, const void *Data) {
243     Invalidations.insert(std::make_pair(Tag, Data));
244   }
245
246   /// Reverses the effects of a previous invalidation.
247   ///
248   /// \sa markInvalid
249   void removeInvalidation(const void *Tag, const void *Data) {
250     Invalidations.erase(std::make_pair(Tag, Data));
251   }
252   
253   /// Return the canonical declaration, be it a method or class, where
254   /// this issue semantically occurred.
255   const Decl *getDeclWithIssue() const;
256   
257   /// Specifically set the Decl where an issue occurred.  This isn't necessary
258   /// for BugReports that cover a path as it will be automatically inferred.
259   void setDeclWithIssue(const Decl *declWithIssue) {
260     DeclWithIssue = declWithIssue;
261   }
262
263   /// Add new item to the list of additional notes that need to be attached to
264   /// this path-insensitive report. If you want to add extra notes to a
265   /// path-sensitive report, you need to use a BugReporterVisitor because it
266   /// allows you to specify where exactly in the auto-generated path diagnostic
267   /// the extra note should appear.
268   void addNote(StringRef Msg, const PathDiagnosticLocation &Pos,
269                     ArrayRef<SourceRange> Ranges = {}) {
270     auto *P = new PathDiagnosticNotePiece(Pos, Msg);
271
272     for (const auto &R : Ranges)
273       P->addRange(R);
274
275     Notes.push_back(P);
276   }
277
278   virtual const NoteList &getNotes() {
279     return Notes;
280   }
281
282   /// \brief This allows for addition of meta data to the diagnostic.
283   ///
284   /// Currently, only the HTMLDiagnosticClient knows how to display it. 
285   void addExtraText(StringRef S) {
286     ExtraText.push_back(S);
287   }
288
289   virtual const ExtraTextList &getExtraText() {
290     return ExtraText;
291   }
292
293   /// \brief Return the "definitive" location of the reported bug.
294   ///
295   ///  While a bug can span an entire path, usually there is a specific
296   ///  location that can be used to identify where the key issue occurred.
297   ///  This location is used by clients rendering diagnostics.
298   virtual PathDiagnosticLocation getLocation(const SourceManager &SM) const;
299
300   /// \brief Get the location on which the report should be uniqued.
301   PathDiagnosticLocation getUniqueingLocation() const {
302     return UniqueingLocation;
303   }
304   
305   /// \brief Get the declaration containing the uniqueing location.
306   const Decl *getUniqueingDecl() const {
307     return UniqueingDecl;
308   }
309
310   const Stmt *getStmt() const;
311
312   /// \brief Add a range to a bug report.
313   ///
314   /// Ranges are used to highlight regions of interest in the source code.
315   /// They should be at the same source code line as the BugReport location.
316   /// By default, the source range of the statement corresponding to the error
317   /// node will be used; add a single invalid range to specify absence of
318   /// ranges.
319   void addRange(SourceRange R) {
320     assert((R.isValid() || Ranges.empty()) && "Invalid range can only be used "
321                            "to specify that the report does not have a range.");
322     Ranges.push_back(R);
323   }
324
325   /// \brief Get the SourceRanges associated with the report.
326   virtual llvm::iterator_range<ranges_iterator> getRanges();
327
328   /// \brief Add custom or predefined bug report visitors to this report.
329   ///
330   /// The visitors should be used when the default trace is not sufficient.
331   /// For example, they allow constructing a more elaborate trace.
332   /// \sa registerConditionVisitor(), registerTrackNullOrUndefValue(),
333   /// registerFindLastStore(), registerNilReceiverVisitor(), and
334   /// registerVarDeclsLastStore().
335   void addVisitor(std::unique_ptr<BugReporterVisitor> visitor);
336
337   /// Iterators through the custom diagnostic visitors.
338   visitor_iterator visitor_begin() { return Callbacks.begin(); }
339   visitor_iterator visitor_end() { return Callbacks.end(); }
340
341   /// Profile to identify equivalent bug reports for error report coalescing.
342   /// Reports are uniqued to ensure that we do not emit multiple diagnostics
343   /// for each bug.
344   virtual void Profile(llvm::FoldingSetNodeID& hash) const;
345 };
346
347 //===----------------------------------------------------------------------===//
348 // BugTypes (collections of related reports).
349 //===----------------------------------------------------------------------===//
350
351 class BugReportEquivClass : public llvm::FoldingSetNode {
352   /// List of *owned* BugReport objects.
353   llvm::ilist<BugReport> Reports;
354
355   friend class BugReporter;
356   void AddReport(std::unique_ptr<BugReport> R) {
357     Reports.push_back(R.release());
358   }
359
360 public:
361   BugReportEquivClass(std::unique_ptr<BugReport> R) { AddReport(std::move(R)); }
362   ~BugReportEquivClass();
363
364   void Profile(llvm::FoldingSetNodeID& ID) const {
365     assert(!Reports.empty());
366     Reports.front().Profile(ID);
367   }
368
369   typedef llvm::ilist<BugReport>::iterator iterator;
370   typedef llvm::ilist<BugReport>::const_iterator const_iterator;
371
372   iterator begin() { return Reports.begin(); }
373   iterator end() { return Reports.end(); }
374
375   const_iterator begin() const { return Reports.begin(); }
376   const_iterator end() const { return Reports.end(); }
377 };
378
379 //===----------------------------------------------------------------------===//
380 // BugReporter and friends.
381 //===----------------------------------------------------------------------===//
382
383 class BugReporterData {
384 public:
385   virtual ~BugReporterData();
386   virtual DiagnosticsEngine& getDiagnostic() = 0;
387   virtual ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() = 0;
388   virtual ASTContext &getASTContext() = 0;
389   virtual SourceManager& getSourceManager() = 0;
390   virtual AnalyzerOptions& getAnalyzerOptions() = 0;
391 };
392
393 /// BugReporter is a utility class for generating PathDiagnostics for analysis.
394 /// It collects the BugReports and BugTypes and knows how to generate
395 /// and flush the corresponding diagnostics.
396 class BugReporter {
397 public:
398   enum Kind { BaseBRKind, GRBugReporterKind };
399
400 private:
401   typedef llvm::ImmutableSet<BugType*> BugTypesTy;
402   BugTypesTy::Factory F;
403   BugTypesTy BugTypes;
404
405   const Kind kind;
406   BugReporterData& D;
407
408   /// Generate and flush the diagnostics for the given bug report.
409   void FlushReport(BugReportEquivClass& EQ);
410
411   /// Generate and flush the diagnostics for the given bug report
412   /// and PathDiagnosticConsumer.
413   void FlushReport(BugReport *exampleReport,
414                    PathDiagnosticConsumer &PD,
415                    ArrayRef<BugReport*> BugReports);
416
417   /// The set of bug reports tracked by the BugReporter.
418   llvm::FoldingSet<BugReportEquivClass> EQClasses;
419   /// A vector of BugReports for tracking the allocated pointers and cleanup.
420   std::vector<BugReportEquivClass *> EQClassesVector;
421
422 protected:
423   BugReporter(BugReporterData& d, Kind k) : BugTypes(F.getEmptySet()), kind(k),
424                                             D(d) {}
425
426 public:
427   BugReporter(BugReporterData& d) : BugTypes(F.getEmptySet()), kind(BaseBRKind),
428                                     D(d) {}
429   virtual ~BugReporter();
430
431   /// \brief Generate and flush diagnostics for all bug reports.
432   void FlushReports();
433
434   Kind getKind() const { return kind; }
435
436   DiagnosticsEngine& getDiagnostic() {
437     return D.getDiagnostic();
438   }
439
440   ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() {
441     return D.getPathDiagnosticConsumers();
442   }
443
444   /// \brief Iterator over the set of BugTypes tracked by the BugReporter.
445   typedef BugTypesTy::iterator iterator;
446   iterator begin() { return BugTypes.begin(); }
447   iterator end() { return BugTypes.end(); }
448
449   /// \brief Iterator over the set of BugReports tracked by the BugReporter.
450   typedef llvm::FoldingSet<BugReportEquivClass>::iterator EQClasses_iterator;
451   EQClasses_iterator EQClasses_begin() { return EQClasses.begin(); }
452   EQClasses_iterator EQClasses_end() { return EQClasses.end(); }
453
454   ASTContext &getContext() { return D.getASTContext(); }
455
456   SourceManager& getSourceManager() { return D.getSourceManager(); }
457
458   AnalyzerOptions& getAnalyzerOptions() { return D.getAnalyzerOptions(); }
459
460   virtual bool generatePathDiagnostic(PathDiagnostic& pathDiagnostic,
461                                       PathDiagnosticConsumer &PC,
462                                       ArrayRef<BugReport *> &bugReports) {
463     return true;
464   }
465
466   bool RemoveUnneededCalls(PathPieces &pieces, BugReport *R);
467
468   void Register(BugType *BT);
469
470   /// \brief Add the given report to the set of reports tracked by BugReporter.
471   ///
472   /// The reports are usually generated by the checkers. Further, they are
473   /// folded based on the profile value, which is done to coalesce similar
474   /// reports.
475   void emitReport(std::unique_ptr<BugReport> R);
476
477   void EmitBasicReport(const Decl *DeclWithIssue, const CheckerBase *Checker,
478                        StringRef BugName, StringRef BugCategory,
479                        StringRef BugStr, PathDiagnosticLocation Loc,
480                        ArrayRef<SourceRange> Ranges = None);
481
482   void EmitBasicReport(const Decl *DeclWithIssue, CheckName CheckName,
483                        StringRef BugName, StringRef BugCategory,
484                        StringRef BugStr, PathDiagnosticLocation Loc,
485                        ArrayRef<SourceRange> Ranges = None);
486
487 private:
488   llvm::StringMap<BugType *> StrBugTypes;
489
490   /// \brief Returns a BugType that is associated with the given name and
491   /// category.
492   BugType *getBugTypeForName(CheckName CheckName, StringRef name,
493                              StringRef category);
494 };
495
496 // FIXME: Get rid of GRBugReporter.  It's the wrong abstraction.
497 class GRBugReporter : public BugReporter {
498   ExprEngine& Eng;
499 public:
500   GRBugReporter(BugReporterData& d, ExprEngine& eng)
501     : BugReporter(d, GRBugReporterKind), Eng(eng) {}
502
503   ~GRBugReporter() override;
504
505   /// getEngine - Return the analysis engine used to analyze a given
506   ///  function or method.
507   ExprEngine &getEngine() { return Eng; }
508
509   /// getGraph - Get the exploded graph created by the analysis engine
510   ///  for the analyzed method or function.
511   ExplodedGraph &getGraph();
512
513   /// getStateManager - Return the state manager used by the analysis
514   ///  engine.
515   ProgramStateManager &getStateManager();
516
517   /// Generates a path corresponding to one of the given bug reports.
518   ///
519   /// Which report is used for path generation is not specified. The
520   /// bug reporter will try to pick the shortest path, but this is not
521   /// guaranteed.
522   ///
523   /// \return True if the report was valid and a path was generated,
524   ///         false if the reports should be considered invalid.
525   bool generatePathDiagnostic(PathDiagnostic &PD, PathDiagnosticConsumer &PC,
526                               ArrayRef<BugReport*> &bugReports) override;
527
528   /// classof - Used by isa<>, cast<>, and dyn_cast<>.
529   static bool classof(const BugReporter* R) {
530     return R->getKind() == GRBugReporterKind;
531   }
532 };
533
534 class BugReporterContext {
535   virtual void anchor();
536   GRBugReporter &BR;
537 public:
538   BugReporterContext(GRBugReporter& br) : BR(br) {}
539
540   virtual ~BugReporterContext() {}
541
542   GRBugReporter& getBugReporter() { return BR; }
543
544   ExplodedGraph &getGraph() { return BR.getGraph(); }
545
546   ProgramStateManager& getStateManager() {
547     return BR.getStateManager();
548   }
549
550   SValBuilder& getSValBuilder() {
551     return getStateManager().getSValBuilder();
552   }
553
554   ASTContext &getASTContext() {
555     return BR.getContext();
556   }
557
558   SourceManager& getSourceManager() {
559     return BR.getSourceManager();
560   }
561
562   virtual BugReport::NodeResolver& getNodeResolver() = 0;
563 };
564
565 } // end GR namespace
566
567 } // end clang namespace
568
569 #endif