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