clang 23.0.0git
BugReporter.h
Go to the documentation of this file.
1//===- BugReporter.h - Generate PathDiagnostics -----------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines BugReporter, a utility class for generating
10// PathDiagnostics for analyses based on ProgramState.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGREPORTER_H
15#define LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGREPORTER_H
16
18#include "clang/Basic/LLVM.h"
29#include "llvm/ADT/ArrayRef.h"
30#include "llvm/ADT/FoldingSet.h"
31#include "llvm/ADT/ImmutableSet.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/Twine.h"
37#include "llvm/ADT/ilist.h"
38#include "llvm/ADT/ilist_node.h"
39#include "llvm/ADT/iterator_range.h"
40#include <cassert>
41#include <memory>
42#include <optional>
43#include <string>
44#include <utility>
45#include <vector>
46
47namespace clang {
48
49class AnalyzerOptions;
50class ASTContext;
51class Decl;
52class SourceManager;
53class Stmt;
54
55namespace ento {
56
57class BugType;
58class CheckerBase;
59class ExplodedGraph;
60class ExplodedNode;
61class ExprEngine;
62class MemRegion;
63
64//===----------------------------------------------------------------------===//
65// Interface for individual bug reports.
66//===----------------------------------------------------------------------===//
67
68/// A mapping from diagnostic consumers to the diagnostics they should
69/// consume.
71 llvm::DenseMap<PathDiagnosticConsumer *, std::unique_ptr<PathDiagnostic>>;
72
73/// Interface for classes constructing Stack hints.
74///
75/// If a PathDiagnosticEvent occurs in a different frame than the final
76/// diagnostic the hints can be used to summarize the effect of the call.
78public:
79 virtual ~StackHintGenerator() = 0;
80
81 /// Construct the Diagnostic message for the given ExplodedNode.
82 virtual std::string getMessage(const ExplodedNode *N) = 0;
83};
84
85/// Constructs a Stack hint for the given symbol.
86///
87/// The class knows how to construct the stack hint message based on
88/// traversing the CallExpr associated with the call and checking if the given
89/// symbol is returned or is one of the arguments.
90/// The hint can be customized by redefining 'getMessageForX()' methods.
92private:
93 SymbolRef Sym;
94 std::string Msg;
95
96public:
97 StackHintGeneratorForSymbol(SymbolRef S, StringRef M) : Sym(S), Msg(M) {}
98 ~StackHintGeneratorForSymbol() override = default;
99
100 /// Search the call expression for the symbol Sym and dispatch the
101 /// 'getMessageForX()' methods to construct a specific message.
102 std::string getMessage(const ExplodedNode *N) override;
103
104 /// Produces the message of the following form:
105 /// 'Msg via Nth parameter'
106 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex);
107
108 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
109 return Msg;
110 }
111
112 virtual std::string getMessageForSymbolNotFound() {
113 return Msg;
114 }
115};
116
117/// This class provides an interface through which checkers can create
118/// individual bug reports.
120public:
121 enum class Kind { Basic, PathSensitive };
122
123protected:
125 friend class BugReporter;
126
128 const BugType& BT;
129 std::string ShortDescription;
130 std::string Description;
131
135
136 BugReport(Kind kind, const BugType &bt, const llvm::Twine &desc)
137 : BugReport(kind, bt, "", desc) {}
138
139 BugReport(Kind K, const BugType &BT, const llvm::Twine &ShortDescription,
140 const llvm::Twine &Description)
142 Description(Description.str()) {}
143
144public:
145 virtual ~BugReport() = default;
146
147 Kind getKind() const { return K; }
148
149 const BugType& getBugType() const { return BT; }
150
151 /// A verbose warning message that is appropriate for displaying next to
152 /// the source code that introduces the problem. The description should be
153 /// at least a full sentence starting with a capital letter. The period at
154 /// the end of the warning is traditionally omitted. If the description
155 /// consists of multiple sentences, periods between the sentences are
156 /// encouraged, but the period at the end of the description is still omitted.
157 StringRef getDescription() const { return Description; }
158
159 /// A short general warning message that is appropriate for displaying in
160 /// the list of all reported bugs. It should describe what kind of bug is found
161 /// but does not need to try to go into details of that specific bug.
162 /// Grammatical conventions of getDescription() apply here as well.
163 StringRef getShortDescription(bool UseFallback = true) const {
164 if (ShortDescription.empty() && UseFallback)
165 return Description;
166 return ShortDescription;
167 }
168
169 /// The primary location of the bug report that points at the undesirable
170 /// behavior in the code. UIs should attach the warning description to this
171 /// location. The warning description should describe the bad behavior
172 /// at this location.
174
175 /// The smallest declaration that contains the bug location.
176 /// This is purely cosmetic; the declaration can be displayed to the user
177 /// but it does not affect whether the report is emitted.
178 virtual const Decl *getDeclWithIssue() const = 0;
179
180 /// Get the location on which the report should be uniqued. Two warnings are
181 /// considered to be equivalent whenever they have the same bug types,
182 /// descriptions, and uniqueing locations. Out of a class of equivalent
183 /// warnings only one gets displayed to the user. For most warnings the
184 /// uniqueing location coincides with their location, but sometimes
185 /// it makes sense to use different locations. For example, a leak
186 /// checker can place the warning at the location where the last reference
187 /// to the leaking resource is dropped but at the same time unique the warning
188 /// by where that resource is acquired (allocated).
190
191 /// Get the declaration that corresponds to (usually contains) the uniqueing
192 /// location. This is not actively used for uniqueing, i.e. otherwise
193 /// identical reports that have different uniqueing decls will be considered
194 /// equivalent.
195 virtual const Decl *getUniqueingDecl() const = 0;
196
197 /// Add new item to the list of additional notes that need to be attached to
198 /// this report. If the report is path-sensitive, these notes will not be
199 /// displayed as part of the execution path explanation, but will be displayed
200 /// separately. Use bug visitors if you need to add an extra path note.
201 void addNote(StringRef Msg, const PathDiagnosticLocation &Pos,
203 auto P = std::make_shared<PathDiagnosticNotePiece>(Pos, Msg);
204
205 for (const auto &R : Ranges)
206 P->addRange(R);
207
208 Notes.push_back(std::move(P));
209 }
210
214
215 /// Add a range to a bug report.
216 ///
217 /// Ranges are used to highlight regions of interest in the source code.
218 /// They should be at the same source code line as the BugReport location.
219 /// By default, the source range of the statement corresponding to the error
220 /// node will be used; add a single invalid range to specify absence of
221 /// ranges.
223 assert((R.isValid() || Ranges.empty()) && "Invalid range can only be used "
224 "to specify that the report does not have a range.");
225 Ranges.push_back(R);
226 }
227
228 /// Get the SourceRanges associated with the report.
230 return Ranges;
231 }
232
233 /// Add a fix-it hint to the bug report.
234 ///
235 /// Fix-it hints are the suggested edits to the code that would resolve
236 /// the problem explained by the bug report. Fix-it hints should be
237 /// as conservative as possible because it is not uncommon for the user
238 /// to blindly apply all fixits to their project. Note that it is very hard
239 /// to produce a good fix-it hint for most path-sensitive warnings.
240 void addFixItHint(const FixItHint &F) {
241 Fixits.push_back(F);
242 }
243
245
246 /// Reports are uniqued to ensure that we do not emit multiple diagnostics
247 /// for each bug.
248 virtual void Profile(llvm::FoldingSetNodeID& hash) const = 0;
249};
250
251class BasicBugReport : public BugReport {
252 PathDiagnosticLocation Location;
253 const Decl *DeclWithIssue = nullptr;
254
255public:
256 BasicBugReport(const BugType &bt, const llvm::Twine &desc,
258 : BugReport(Kind::Basic, bt, desc), Location(l) {}
259
260 BasicBugReport(const BugType &BT, const llvm::Twine &ShortDesc,
261 const llvm::Twine &Desc, PathDiagnosticLocation L)
262 : BugReport(Kind::Basic, BT, ShortDesc, Desc), Location(L) {}
263
264 static bool classof(const BugReport *R) {
265 return R->getKind() == Kind::Basic;
266 }
267
269 assert(Location.isValid());
270 return Location;
271 }
272
273 const Decl *getDeclWithIssue() const override {
274 return DeclWithIssue;
275 }
276
278 return getLocation();
279 }
280
281 const Decl *getUniqueingDecl() const override {
282 return getDeclWithIssue();
283 }
284
285 /// Specifically set the Decl where an issue occurred. This isn't necessary
286 /// for BugReports that cover a path as it will be automatically inferred.
287 void setDeclWithIssue(const Decl *declWithIssue) {
288 DeclWithIssue = declWithIssue;
289 }
290
291 void Profile(llvm::FoldingSetNodeID& hash) const override;
292};
293
295public:
297 using visitor_iterator = VisitorList::iterator;
298 using visitor_range = llvm::iterator_range<visitor_iterator>;
299
300protected:
301 /// The ExplodedGraph node against which the report was thrown. It corresponds
302 /// to the end of the execution path that demonstrates the bug.
303 const ExplodedNode *ErrorNode = nullptr;
304
305 /// The range that corresponds to ErrorNode's program point. It is usually
306 /// highlighted in the report.
308
309 /// Profile to identify equivalent bug reports for error report coalescing.
310
311 /// A (stack of) a set of symbols that are registered with this
312 /// report as being "interesting", and thus used to help decide which
313 /// diagnostics to include when constructing the final path diagnostic.
314 /// The stack is largely used by BugReporter when generating PathDiagnostics
315 /// for multiple PathDiagnosticConsumers.
316 llvm::DenseMap<SymbolRef, bugreporter::TrackingKind> InterestingSymbols;
317
318 /// A (stack of) set of regions that are registered with this report as being
319 /// "interesting", and thus used to help decide which diagnostics
320 /// to include when constructing the final path diagnostic.
321 /// The stack is largely used by BugReporter when generating PathDiagnostics
322 /// for multiple PathDiagnosticConsumers.
323 llvm::DenseMap<const MemRegion *, bugreporter::TrackingKind>
325
326 /// A set of stack frames that correspond to call sites which should be
327 /// considered "interesting".
329
330 /// A set of custom visitors which generate "event" diagnostics at
331 /// interesting points in the path.
333
334 /// Used for ensuring the visitors are only added once.
335 llvm::FoldingSet<BugReporterVisitor> CallbacksSet;
336
337 /// When set, this flag disables all callstack pruning from a diagnostic
338 /// path. This is useful for some reports that want maximum fidelty
339 /// when reporting an issue.
340 bool DoNotPrunePath = false;
341
342 /// Used to track unique reasons why a bug report might be invalid.
343 ///
344 /// \sa markInvalid
345 /// \sa removeInvalidation
346 using InvalidationRecord = std::pair<const void *, const void *>;
347
348 /// If non-empty, this bug report is likely a false positive and should not be
349 /// shown to the user.
350 ///
351 /// \sa markInvalid
352 /// \sa removeInvalidation
353 llvm::SmallSet<InvalidationRecord, 4> Invalidations;
354
355 /// Conditions we're already tracking.
357
358 /// Reports with different uniqueing locations are considered to be different
359 /// for the purposes of deduplication.
362
363 const Stmt *getStmt() const;
364
365 /// If an event occurs in a different frame than the final diagnostic,
366 /// supply a message that will be used to construct an extra hint on the
367 /// returns from all the calls on the stack from this event to the final
368 /// diagnostic.
369 // FIXME: Allow shared_ptr keys in DenseMap?
370 std::map<PathDiagnosticPieceRef, std::unique_ptr<StackHintGenerator>>
372
373public:
374 PathSensitiveBugReport(const BugType &bt, const llvm::Twine &desc,
375 const ExplodedNode *errorNode)
376 : PathSensitiveBugReport(bt, desc, desc, errorNode) {}
377
378 PathSensitiveBugReport(const BugType &bt, const llvm::Twine &shortDesc,
379 const llvm::Twine &desc, const ExplodedNode *errorNode)
380 : PathSensitiveBugReport(bt, shortDesc, desc, errorNode,
381 /*LocationToUnique*/ {},
382 /*DeclToUnique*/ nullptr) {}
383
384 /// Create a PathSensitiveBugReport with a custom uniqueing location.
385 ///
386 /// The reports that have the same report location, description, bug type, and
387 /// ranges are uniqued - only one of the equivalent reports will be presented
388 /// to the user. This method allows to rest the location which should be used
389 /// for uniquing reports. For example, memory leaks checker, could set this to
390 /// the allocation site, rather then the location where the bug is reported.
391 PathSensitiveBugReport(const BugType &bt, const llvm::Twine &desc,
392 const ExplodedNode *errorNode,
393 PathDiagnosticLocation LocationToUnique,
394 const Decl *DeclToUnique)
395 : PathSensitiveBugReport(bt, desc, desc, errorNode, LocationToUnique,
396 DeclToUnique) {}
397
398 PathSensitiveBugReport(const BugType &bt, const llvm::Twine &shortDesc,
399 const llvm::Twine &desc, const ExplodedNode *errorNode,
400 PathDiagnosticLocation LocationToUnique,
401 const Decl *DeclToUnique);
402
403 static bool classof(const BugReport *R) {
404 return R->getKind() == Kind::PathSensitive;
405 }
406
407 const ExplodedNode *getErrorNode() const { return ErrorNode; }
408
409 /// Indicates whether or not any path pruning should take place
410 /// when generating a PathDiagnostic from this BugReport.
411 bool shouldPrunePath() const { return !DoNotPrunePath; }
412
413 /// Disable all path pruning when generating a PathDiagnostic.
415
416 /// Get the location on which the report should be uniqued.
420
421 /// Get the declaration containing the uniqueing location.
422 const Decl *getUniqueingDecl() const override {
423 return UniqueingDecl;
424 }
425
426 const Decl *getDeclWithIssue() const override;
427
428 ArrayRef<SourceRange> getRanges() const override;
429
430 PathDiagnosticLocation getLocation() const override;
431
432 /// Marks a symbol as interesting. Different kinds of interestingness will
433 /// be processed differently by visitors (e.g. if the tracking kind is
434 /// condition, will append "will be used as a condition" to the message).
437
439
440 /// Marks a region as interesting. Different kinds of interestingness will
441 /// be processed differently by visitors (e.g. if the tracking kind is
442 /// condition, will append "will be used as a condition" to the message).
443 void markInteresting(
444 const MemRegion *R,
446
447 void markNotInteresting(const MemRegion *R);
448
449 /// Marks a symbolic value as interesting. Different kinds of interestingness
450 /// will be processed differently by visitors (e.g. if the tracking kind is
451 /// condition, will append "will be used as a condition" to the message).
454 void markInteresting(const StackFrame *SF);
455
456 bool isInteresting(SymbolRef sym) const;
457 bool isInteresting(const MemRegion *R) const;
458 bool isInteresting(SVal V) const;
459 bool isInteresting(const StackFrame *SF) const;
460
461 std::optional<bugreporter::TrackingKind>
463
464 std::optional<bugreporter::TrackingKind>
465 getInterestingnessKind(const MemRegion *R) const;
466
467 std::optional<bugreporter::TrackingKind> getInterestingnessKind(SVal V) const;
468
469 /// Returns whether or not this report should be considered valid.
470 ///
471 /// Invalid reports are those that have been classified as likely false
472 /// positives after the fact.
473 bool isValid() const {
474 return Invalidations.empty();
475 }
476
477 /// Marks the current report as invalid, meaning that it is probably a false
478 /// positive and should not be reported to the user.
479 ///
480 /// The \p Tag and \p Data arguments are intended to be opaque identifiers for
481 /// this particular invalidation, where \p Tag represents the visitor
482 /// responsible for invalidation, and \p Data represents the reason this
483 /// visitor decided to invalidate the bug report.
484 ///
485 /// \sa removeInvalidation
486 void markInvalid(const void *Tag, const void *Data) {
487 Invalidations.insert(std::make_pair(Tag, Data));
488 }
489
490 /// Profile to identify equivalent bug reports for error report coalescing.
491 /// Reports are uniqued to ensure that we do not emit multiple diagnostics
492 /// for each bug.
493 void Profile(llvm::FoldingSetNodeID &hash) const override;
494
495 /// Add custom or predefined bug report visitors to this report.
496 ///
497 /// The visitors should be used when the default trace is not sufficient.
498 /// For example, they allow constructing a more elaborate trace.
499 /// @{
500 void addVisitor(std::unique_ptr<BugReporterVisitor> visitor);
501
502 template <class VisitorType, class... Args>
503 void addVisitor(Args &&... ConstructorArgs) {
505 std::make_unique<VisitorType>(std::forward<Args>(ConstructorArgs)...));
506 }
507 /// @}
508
509 /// Remove all visitors attached to this bug report.
510 void clearVisitors();
511
512 /// Iterators through the custom diagnostic visitors.
516
517 /// Notes that the condition of the CFGBlock associated with \p Cond is
518 /// being tracked.
519 /// \returns false if the condition is already being tracked.
521 return TrackedConditions.insert(Cond).second;
522 }
523
525 std::unique_ptr<StackHintGenerator> StackHint) {
526 StackHints[Piece] = std::move(StackHint);
527 }
528
530 return StackHints.count(Piece) > 0;
531 }
532
533 /// Produce the hint for the given node. The node contains
534 /// information about the call for which the diagnostic can be generated.
535 std::string
537 const ExplodedNode *N) const {
538 auto I = StackHints.find(Piece);
539 if (I != StackHints.end())
540 return I->second->getMessage(N);
541 return "";
542 }
543};
544
545//===----------------------------------------------------------------------===//
546// BugTypes (collections of related reports).
547//===----------------------------------------------------------------------===//
548
549class BugReportEquivClass : public llvm::FoldingSetNode {
550 friend class BugReporter;
551
552 /// List of *owned* BugReport objects.
554
555 void AddReport(std::unique_ptr<BugReport> &&R) {
556 Reports.push_back(std::move(R));
557 }
558
559public:
560 BugReportEquivClass(std::unique_ptr<BugReport> R) { AddReport(std::move(R)); }
561
563
564 void Profile(llvm::FoldingSetNodeID& ID) const {
565 assert(!Reports.empty());
566 Reports.front()->Profile(ID);
567 }
568};
569
570//===----------------------------------------------------------------------===//
571// BugReporter and friends.
572//===----------------------------------------------------------------------===//
573
585
586/// BugReporter is a utility class for generating PathDiagnostics for analysis.
587/// It collects the BugReports and BugTypes and knows how to generate
588/// and flush the corresponding diagnostics.
589///
590/// The base class is used for generating path-insensitive
592private:
594
595 /// The top-level entry point for the issue to be reported.
596 const Decl *AnalysisEntryPoint = nullptr;
597
598 /// Generate and flush the diagnostics for the given bug report.
599 void FlushReport(BugReportEquivClass& EQ);
600
601 /// The set of bug reports tracked by the BugReporter.
602 llvm::FoldingSet<BugReportEquivClass> EQClasses;
603
604 /// A vector of BugReports for tracking the allocated pointers and cleanup.
605 std::vector<BugReportEquivClass *> EQClassesVector;
606
607 /// User-provided in-code suppressions.
608 BugSuppression UserSuppressions;
609
610public:
612 virtual ~BugReporter();
613
614 /// Generate and flush diagnostics for all bug reports.
615 void FlushReports();
616
619 return D.getPathDiagnosticConsumers();
620 }
621
622 /// Iterator over the set of BugReports tracked by the BugReporter.
623 using EQClasses_iterator = llvm::FoldingSet<BugReportEquivClass>::iterator;
624 llvm::iterator_range<EQClasses_iterator> equivalenceClasses() {
625 return EQClasses;
626 }
627
628 ASTContext &getContext() { return D.getASTContext(); }
629
630 const SourceManager &getSourceManager() { return D.getSourceManager(); }
631 const SourceManager &getSourceManager() const { return D.getSourceManager(); }
632
633 const AnalyzerOptions &getAnalyzerOptions() { return D.getAnalyzerOptions(); }
634
635 Preprocessor &getPreprocessor() { return D.getPreprocessor(); }
636 const Preprocessor &getPreprocessor() const { return D.getPreprocessor(); }
637
638 /// Get the top-level entry point for the issue to be reported.
639 const Decl *getAnalysisEntryPoint() const { return AnalysisEntryPoint; }
640
641 void setAnalysisEntryPoint(const Decl *EntryPoint) {
642 assert(EntryPoint);
643 AnalysisEntryPoint = EntryPoint;
644 }
645
646 /// Add the given report to the set of reports tracked by BugReporter.
647 ///
648 /// The reports are usually generated by the checkers. Further, they are
649 /// folded based on the profile value, which is done to coalesce similar
650 /// reports.
651 virtual void emitReport(std::unique_ptr<BugReport> R);
652
653 void EmitBasicReport(const Decl *DeclWithIssue,
654 const CheckerFrontend *Checker, StringRef BugName,
655 StringRef BugCategory, StringRef BugStr,
657 ArrayRef<SourceRange> Ranges = {},
658 ArrayRef<FixItHint> Fixits = {});
659
660 void EmitBasicReport(const Decl *DeclWithIssue, CheckerNameRef CheckerName,
661 StringRef BugName, StringRef BugCategory,
662 StringRef BugStr, PathDiagnosticLocation Loc,
663 ArrayRef<SourceRange> Ranges = {},
664 ArrayRef<FixItHint> Fixits = {});
665
666private:
667 llvm::StringMap<std::unique_ptr<BugType>> StrBugTypes;
668
669 /// Returns a BugType that is associated with the given name and
670 /// category.
671 BugType *getBugTypeForName(CheckerNameRef CheckerName, StringRef name,
672 StringRef category);
673
674 virtual BugReport *
675 findReportInEquivalenceClass(BugReportEquivClass &eqClass,
676 SmallVectorImpl<BugReport *> &bugReports) {
677 return eqClass.getReports()[0].get();
678 }
679
680protected:
681 /// Generate the diagnostics for the given bug report.
682 virtual std::unique_ptr<DiagnosticForConsumerMapTy>
684 BugReport *exampleReport,
685 ArrayRef<std::unique_ptr<PathDiagnosticConsumer>> consumers,
686 ArrayRef<BugReport *> bugReports);
687};
688
689/// GRBugReporter is used for generating path-sensitive reports.
691 ExprEngine& Eng;
692
693 BugReport *findReportInEquivalenceClass(
694 BugReportEquivClass &eqClass,
695 SmallVectorImpl<BugReport *> &bugReports) override;
696
697 /// Generate the diagnostics for the given bug report.
698 std::unique_ptr<DiagnosticForConsumerMapTy> generateDiagnosticForConsumerMap(
699 BugReport *exampleReport,
700 ArrayRef<std::unique_ptr<PathDiagnosticConsumer>> consumers,
701 ArrayRef<BugReport *> bugReports) override;
702
703public:
706
707 /// getGraph - Get the exploded graph created by the analysis engine
708 /// for the analyzed method or function.
709 const ExplodedGraph &getGraph() const;
710
711 /// getStateManager - Return the state manager used by the analysis
712 /// engine.
714
715 /// \p bugReports A set of bug reports within a *single* equivalence class
716 ///
717 /// \return A mapping from consumers to the corresponding diagnostics.
718 /// Iterates through the bug reports within a single equivalence class,
719 /// stops at a first non-invalidated report.
720 std::unique_ptr<DiagnosticForConsumerMapTy> generatePathDiagnostics(
721 ArrayRef<std::unique_ptr<PathDiagnosticConsumer>> consumers,
723
724 void emitReport(std::unique_ptr<BugReport> R) override;
725};
726
727
730
731 virtual void anchor();
732
733public:
735
736 virtual ~BugReporterContext() = default;
737
739 const PathSensitiveBugReporter &getBugReporter() const { return BR; }
740
742 return BR.getStateManager();
743 }
744
746 return BR.getContext();
747 }
748
750 return BR.getSourceManager();
751 }
752
754 return BR.getAnalyzerOptions();
755 }
756};
757
758/// The tag that carries some information with it.
759///
760/// It can be valuable to produce tags with some bits of information and later
761/// reuse them for a better diagnostic.
762///
763/// Please make sure that derived class' constructor is private and that the
764/// user can only create objects using DataTag::Factory. This also means that
765/// DataTag::Factory should be friend for every derived class.
766class DataTag : public ProgramPointTag {
767public:
768 StringRef getDebugTag() const override { return "Data Tag"; }
769
770 // Manage memory for DataTag objects.
771 class Factory {
772 std::vector<std::unique_ptr<DataTag>> Tags;
773
774 public:
775 template <class DataTagType, class... Args>
776 const DataTagType *make(Args &&... ConstructorArgs) {
777 // We cannot use std::make_unique because we cannot access the private
778 // constructor from inside it.
779 Tags.emplace_back(
780 new DataTagType(std::forward<Args>(ConstructorArgs)...));
781 return static_cast<DataTagType *>(Tags.back().get());
782 }
783 };
784
785protected:
786 DataTag(void *TagKind) : ProgramPointTag(TagKind) {}
787};
788
789/// The tag upon which the TagVisitor reacts. Add these in order to display
790/// additional PathDiagnosticEventPieces along the path.
791class NoteTag : public DataTag {
792public:
795
796private:
797 static int Kind;
798
799 const Callback Cb;
800 const bool IsPrunable;
801
802 NoteTag(Callback &&Cb, bool IsPrunable)
803 : DataTag(&Kind), Cb(std::move(Cb)), IsPrunable(IsPrunable) {}
804
805public:
806 static bool classof(const ProgramPointTag *T) {
807 return T->getTagKind() == &Kind;
808 }
809
810 std::optional<std::string> generateMessage(BugReporterContext &BRC,
811 PathSensitiveBugReport &R) const {
812 std::string Msg = Cb(BRC, R);
813 if (Msg.empty())
814 return std::nullopt;
815
816 return std::move(Msg);
817 }
818
819 StringRef getDebugTag() const override {
820 // TODO: Remember a few examples of generated messages
821 // and display them in the ExplodedGraph dump by
822 // returning them from this function.
823 return "Note Tag";
824 }
825
826 bool isPrunable() const { return IsPrunable; }
827
828 friend class Factory;
829 friend class TagVisitor;
830};
831
832} // namespace ento
833
834} // namespace clang
835
836#endif // LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGREPORTER_H
#define V(N, I)
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
Defines the clang::Preprocessor interface.
Defines the clang::SourceLocation class and associated facilities.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
Stores options for the analyzer from the command line.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2949
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
This represents one expression.
Definition Expr.h:112
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:81
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
ProgramPointTag(void *tagKind=nullptr)
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
It represents a stack frame of the call stack.
Stmt - This represents one statement.
Definition Stmt.h:86
PathDiagnosticLocation getLocation() const override
The primary location of the bug report that points at the undesirable behavior in the code.
const Decl * getDeclWithIssue() const override
The smallest declaration that contains the bug location.
PathDiagnosticLocation getUniqueingLocation() const override
Get the location on which the report should be uniqued.
void Profile(llvm::FoldingSetNodeID &hash) const override
Reports are uniqued to ensure that we do not emit multiple diagnostics for each bug.
BasicBugReport(const BugType &BT, const llvm::Twine &ShortDesc, const llvm::Twine &Desc, PathDiagnosticLocation L)
static bool classof(const BugReport *R)
const Decl * getUniqueingDecl() const override
Get the declaration that corresponds to (usually contains) the uniqueing location.
void setDeclWithIssue(const Decl *declWithIssue)
Specifically set the Decl where an issue occurred.
BasicBugReport(const BugType &bt, const llvm::Twine &desc, PathDiagnosticLocation l)
ArrayRef< std::unique_ptr< BugReport > > getReports() const
BugReportEquivClass(std::unique_ptr< BugReport > R)
void Profile(llvm::FoldingSetNodeID &ID) const
This class provides an interface through which checkers can create individual bug reports.
BugReport(Kind kind, const BugType &bt, const llvm::Twine &desc)
llvm::ArrayRef< FixItHint > getFixits() const
void addRange(SourceRange R)
Add a range to a bug report.
SmallVector< SourceRange, 4 > Ranges
std::string ShortDescription
void addNote(StringRef Msg, const PathDiagnosticLocation &Pos, ArrayRef< SourceRange > Ranges={})
Add new item to the list of additional notes that need to be attached to this report.
BugReport(Kind K, const BugType &BT, const llvm::Twine &ShortDescription, const llvm::Twine &Description)
virtual PathDiagnosticLocation getUniqueingLocation() const =0
Get the location on which the report should be uniqued.
virtual ~BugReport()=default
virtual PathDiagnosticLocation getLocation() const =0
The primary location of the bug report that points at the undesirable behavior in the code.
friend class BugReportEquivClass
virtual const Decl * getUniqueingDecl() const =0
Get the declaration that corresponds to (usually contains) the uniqueing location.
SmallVector< std::shared_ptr< PathDiagnosticNotePiece >, 4 > Notes
SmallVector< FixItHint, 4 > Fixits
ArrayRef< std::shared_ptr< PathDiagnosticNotePiece > > getNotes()
void addFixItHint(const FixItHint &F)
Add a fix-it hint to the bug report.
StringRef getDescription() const
A verbose warning message that is appropriate for displaying next to the source code that introduces ...
const BugType & BT
virtual void Profile(llvm::FoldingSetNodeID &hash) const =0
Reports are uniqued to ensure that we do not emit multiple diagnostics for each bug.
const BugType & getBugType() const
StringRef getShortDescription(bool UseFallback=true) const
A short general warning message that is appropriate for displaying in the list of all reported bugs.
friend class BugReporter
virtual ArrayRef< SourceRange > getRanges() const
Get the SourceRanges associated with the report.
virtual const Decl * getDeclWithIssue() const =0
The smallest declaration that contains the bug location.
ASTContext & getASTContext() const
BugReporterContext(PathSensitiveBugReporter &br)
ProgramStateManager & getStateManager() const
const SourceManager & getSourceManager() const
PathSensitiveBugReporter & getBugReporter()
virtual ~BugReporterContext()=default
const PathSensitiveBugReporter & getBugReporter() const
const AnalyzerOptions & getAnalyzerOptions() const
virtual ASTContext & getASTContext()=0
virtual ~BugReporterData()=default
virtual ArrayRef< std::unique_ptr< PathDiagnosticConsumer > > getPathDiagnosticConsumers()=0
virtual AnalyzerOptions & getAnalyzerOptions()=0
virtual SourceManager & getSourceManager()=0
virtual Preprocessor & getPreprocessor()=0
Preprocessor & getPreprocessor()
void FlushReports()
Generate and flush diagnostics for all bug reports.
BugReporter(BugReporterData &d)
const SourceManager & getSourceManager()
const Decl * getAnalysisEntryPoint() const
Get the top-level entry point for the issue to be reported.
ArrayRef< std::unique_ptr< PathDiagnosticConsumer > > getPathDiagnosticConsumers()
const SourceManager & getSourceManager() const
const Preprocessor & getPreprocessor() const
llvm::iterator_range< EQClasses_iterator > equivalenceClasses()
ASTContext & getContext()
void EmitBasicReport(const Decl *DeclWithIssue, const CheckerFrontend *Checker, StringRef BugName, StringRef BugCategory, StringRef BugStr, PathDiagnosticLocation Loc, ArrayRef< SourceRange > Ranges={}, ArrayRef< FixItHint > Fixits={})
virtual std::unique_ptr< DiagnosticForConsumerMapTy > generateDiagnosticForConsumerMap(BugReport *exampleReport, ArrayRef< std::unique_ptr< PathDiagnosticConsumer > > consumers, ArrayRef< BugReport * > bugReports)
Generate the diagnostics for the given bug report.
const AnalyzerOptions & getAnalyzerOptions()
virtual void emitReport(std::unique_ptr< BugReport > R)
Add the given report to the set of reports tracked by BugReporter.
llvm::FoldingSet< BugReportEquivClass >::iterator EQClasses_iterator
Iterator over the set of BugReports tracked by the BugReporter.
void setAnalysisEntryPoint(const Decl *EntryPoint)
The non-templated common ancestor of all the simple Checker<...> classes.
Definition Checker.h:553
A CheckerFrontend instance is what the user recognizes as "one checker": it has a public canonical na...
Definition Checker.h:526
Simple checker classes that implement one frontend (i.e.
Definition Checker.h:565
const DataTagType * make(Args &&... ConstructorArgs)
DataTag(void *TagKind)
StringRef getDebugTag() const override
The description of this program point which will be dumped for debugging purposes.
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:97
StringRef getDebugTag() const override
The description of this program point which will be dumped for debugging purposes.
friend class TagVisitor
static bool classof(const ProgramPointTag *T)
friend class Factory
bool isPrunable() const
std::function< std::string(BugReporterContext &, PathSensitiveBugReport &)> Callback
std::optional< std::string > generateMessage(BugReporterContext &BRC, PathSensitiveBugReport &R) const
void markInteresting(SymbolRef sym, bugreporter::TrackingKind TKind=bugreporter::TrackingKind::Thorough)
Marks a symbol as interesting.
void addVisitor(Args &&... ConstructorArgs)
SmallVector< std::unique_ptr< BugReporterVisitor >, 8 > VisitorList
PathDiagnosticLocation getUniqueingLocation() const override
Get the location on which the report should be uniqued.
VisitorList Callbacks
A set of custom visitors which generate "event" diagnostics at interesting points in the path.
std::string getCallStackMessage(PathDiagnosticPieceRef Piece, const ExplodedNode *N) const
Produce the hint for the given node.
PathDiagnosticLocation getLocation() const override
The primary location of the bug report that points at the undesirable behavior in the code.
PathSensitiveBugReport(const BugType &bt, const llvm::Twine &desc, const ExplodedNode *errorNode)
const Decl * getDeclWithIssue() const override
The smallest declaration that contains the bug location.
llvm::SmallPtrSet< const ExplodedNode *, 4 > TrackedConditions
Conditions we're already tracking.
std::map< PathDiagnosticPieceRef, std::unique_ptr< StackHintGenerator > > StackHints
If an event occurs in a different frame than the final diagnostic, supply a message that will be used...
PathSensitiveBugReport(const BugType &bt, const llvm::Twine &desc, const ExplodedNode *errorNode, PathDiagnosticLocation LocationToUnique, const Decl *DeclToUnique)
Create a PathSensitiveBugReport with a custom uniqueing location.
std::pair< const void *, const void * > InvalidationRecord
Used to track unique reasons why a bug report might be invalid.
bool shouldPrunePath() const
Indicates whether or not any path pruning should take place when generating a PathDiagnostic from thi...
PathDiagnosticLocation UniqueingLocation
Reports with different uniqueing locations are considered to be different for the purposes of dedupli...
ArrayRef< SourceRange > getRanges() const override
Get the SourceRanges associated with the report.
llvm::DenseMap< SymbolRef, bugreporter::TrackingKind > InterestingSymbols
Profile to identify equivalent bug reports for error report coalescing.
const Decl * getUniqueingDecl() const override
Get the declaration containing the uniqueing location.
llvm::SmallSet< InvalidationRecord, 4 > Invalidations
If non-empty, this bug report is likely a false positive and should not be shown to the user.
const ExplodedNode * getErrorNode() const
static bool classof(const BugReport *R)
llvm::SmallPtrSet< const StackFrame *, 2 > InterestingStackFrames
A set of stack frames that correspond to call sites which should be considered "interesting".
const ExplodedNode * ErrorNode
The ExplodedGraph node against which the report was thrown.
bool addTrackedCondition(const ExplodedNode *Cond)
Notes that the condition of the CFGBlock associated with Cond is being tracked.
visitor_iterator visitor_begin()
Iterators through the custom diagnostic visitors.
void addCallStackHint(PathDiagnosticPieceRef Piece, std::unique_ptr< StackHintGenerator > StackHint)
PathSensitiveBugReport(const BugType &bt, const llvm::Twine &shortDesc, const llvm::Twine &desc, const ExplodedNode *errorNode)
void markInvalid(const void *Tag, const void *Data)
Marks the current report as invalid, meaning that it is probably a false positive and should not be r...
void Profile(llvm::FoldingSetNodeID &hash) const override
Profile to identify equivalent bug reports for error report coalescing.
void clearVisitors()
Remove all visitors attached to this bug report.
bool hasCallStackHint(PathDiagnosticPieceRef Piece) const
void addVisitor(std::unique_ptr< BugReporterVisitor > visitor)
Add custom or predefined bug report visitors to this report.
bool isValid() const
Returns whether or not this report should be considered valid.
std::optional< bugreporter::TrackingKind > getInterestingnessKind(SymbolRef sym) const
bool DoNotPrunePath
When set, this flag disables all callstack pruning from a diagnostic path.
llvm::DenseMap< const MemRegion *, bugreporter::TrackingKind > InterestingRegions
A (stack of) set of regions that are registered with this report as being "interesting",...
llvm::iterator_range< visitor_iterator > visitor_range
bool isInteresting(SymbolRef sym) const
const SourceRange ErrorNodeRange
The range that corresponds to ErrorNode's program point.
VisitorList::iterator visitor_iterator
llvm::FoldingSet< BugReporterVisitor > CallbacksSet
Used for ensuring the visitors are only added once.
void disablePathPruning()
Disable all path pruning when generating a PathDiagnostic.
GRBugReporter is used for generating path-sensitive reports.
const ExplodedGraph & getGraph() const
getGraph - Get the exploded graph created by the analysis engine for the analyzed method or function.
void emitReport(std::unique_ptr< BugReport > R) override
Add the given report to the set of reports tracked by BugReporter.
std::unique_ptr< DiagnosticForConsumerMapTy > generatePathDiagnostics(ArrayRef< std::unique_ptr< PathDiagnosticConsumer > > consumers, ArrayRef< PathSensitiveBugReport * > &bugReports)
bugReports A set of bug reports within a single equivalence class
ProgramStateManager & getStateManager() const
getStateManager - Return the state manager used by the analysis engine.
PathSensitiveBugReporter(BugReporterData &d, ExprEngine &eng)
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:57
StackHintGeneratorForSymbol(SymbolRef S, StringRef M)
Definition BugReporter.h:97
std::string getMessage(const ExplodedNode *N) override
Search the call expression for the symbol Sym and dispatch the 'getMessageForX()' methods to construc...
virtual std::string getMessageForSymbolNotFound()
virtual std::string getMessageForReturn(const CallExpr *CallExpr)
virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex)
Produces the message of the following form: 'Msg via Nth parameter'.
~StackHintGeneratorForSymbol() override=default
Interface for classes constructing Stack hints.
Definition BugReporter.h:77
virtual std::string getMessage(const ExplodedNode *N)=0
Construct the Diagnostic message for the given ExplodedNode.
TrackingKind
Specifies the type of tracking for an expression.
@ Thorough
Default tracking kind – specifies that as much information should be gathered about the tracked expre...
const SymExpr * SymbolRef
Definition SymExpr.h:133
llvm::DenseMap< PathDiagnosticConsumer *, std::unique_ptr< PathDiagnostic > > DiagnosticForConsumerMapTy
A mapping from diagnostic consumers to the diagnostics they should consume.
Definition BugReporter.h:70
std::shared_ptr< PathDiagnosticPiece > PathDiagnosticPieceRef
The JSON file list parser is used to communicate input to InstallAPI.
Expr * Cond
};
int const char * function
Definition c++config.h:31