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