clang 19.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 LocationContext;
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, StringRef desc)
137 : BugReport(kind, bt, "", desc) {}
138
140 StringRef Description)
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
212 return Notes;
213 }
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, StringRef desc, PathDiagnosticLocation l)
257 : BugReport(Kind::Basic, bt, desc), Location(l) {}
258
259 static bool classof(const BugReport *R) {
260 return R->getKind() == Kind::Basic;
261 }
262
264 assert(Location.isValid());
265 return Location;
266 }
267
268 const Decl *getDeclWithIssue() const override {
269 return DeclWithIssue;
270 }
271
273 return getLocation();
274 }
275
276 const Decl *getUniqueingDecl() const override {
277 return getDeclWithIssue();
278 }
279
280 /// Specifically set the Decl where an issue occurred. This isn't necessary
281 /// for BugReports that cover a path as it will be automatically inferred.
282 void setDeclWithIssue(const Decl *declWithIssue) {
283 DeclWithIssue = declWithIssue;
284 }
285
286 void Profile(llvm::FoldingSetNodeID& hash) const override;
287};
288
290public:
292 using visitor_iterator = VisitorList::iterator;
293 using visitor_range = llvm::iterator_range<visitor_iterator>;
294
295protected:
296 /// The ExplodedGraph node against which the report was thrown. It corresponds
297 /// to the end of the execution path that demonstrates the bug.
298 const ExplodedNode *ErrorNode = nullptr;
299
300 /// The range that corresponds to ErrorNode's program point. It is usually
301 /// highlighted in the report.
303
304 /// Profile to identify equivalent bug reports for error report coalescing.
305
306 /// A (stack of) a set of symbols that are registered with this
307 /// report as being "interesting", and thus used to help decide which
308 /// diagnostics to include when constructing the final path diagnostic.
309 /// The stack is largely used by BugReporter when generating PathDiagnostics
310 /// for multiple PathDiagnosticConsumers.
311 llvm::DenseMap<SymbolRef, bugreporter::TrackingKind> InterestingSymbols;
312
313 /// A (stack of) set of regions that are registered with this report as being
314 /// "interesting", and thus used to help decide which diagnostics
315 /// to include when constructing the final path diagnostic.
316 /// The stack is largely used by BugReporter when generating PathDiagnostics
317 /// for multiple PathDiagnosticConsumers.
318 llvm::DenseMap<const MemRegion *, bugreporter::TrackingKind>
320
321 /// A set of location contexts that correspoind to call sites which should be
322 /// considered "interesting".
323 llvm::SmallSet<const LocationContext *, 2> InterestingLocationContexts;
324
325 /// A set of custom visitors which generate "event" diagnostics at
326 /// interesting points in the path.
328
329 /// Used for ensuring the visitors are only added once.
330 llvm::FoldingSet<BugReporterVisitor> CallbacksSet;
331
332 /// When set, this flag disables all callstack pruning from a diagnostic
333 /// path. This is useful for some reports that want maximum fidelty
334 /// when reporting an issue.
335 bool DoNotPrunePath = false;
336
337 /// Used to track unique reasons why a bug report might be invalid.
338 ///
339 /// \sa markInvalid
340 /// \sa removeInvalidation
341 using InvalidationRecord = std::pair<const void *, const void *>;
342
343 /// If non-empty, this bug report is likely a false positive and should not be
344 /// shown to the user.
345 ///
346 /// \sa markInvalid
347 /// \sa removeInvalidation
348 llvm::SmallSet<InvalidationRecord, 4> Invalidations;
349
350 /// Conditions we're already tracking.
351 llvm::SmallSet<const ExplodedNode *, 4> TrackedConditions;
352
353 /// Reports with different uniqueing locations are considered to be different
354 /// for the purposes of deduplication.
357
358 const Stmt *getStmt() const;
359
360 /// If an event occurs in a different frame than the final diagnostic,
361 /// supply a message that will be used to construct an extra hint on the
362 /// returns from all the calls on the stack from this event to the final
363 /// diagnostic.
364 // FIXME: Allow shared_ptr keys in DenseMap?
365 std::map<PathDiagnosticPieceRef, std::unique_ptr<StackHintGenerator>>
367
368public:
369 PathSensitiveBugReport(const BugType &bt, StringRef desc,
370 const ExplodedNode *errorNode)
371 : PathSensitiveBugReport(bt, desc, desc, errorNode) {}
372
373 PathSensitiveBugReport(const BugType &bt, StringRef shortDesc, StringRef desc,
374 const ExplodedNode *errorNode)
375 : PathSensitiveBugReport(bt, shortDesc, desc, errorNode,
376 /*LocationToUnique*/ {},
377 /*DeclToUnique*/ nullptr) {}
378
379 /// Create a PathSensitiveBugReport with a custom uniqueing location.
380 ///
381 /// The reports that have the same report location, description, bug type, and
382 /// ranges are uniqued - only one of the equivalent reports will be presented
383 /// to the user. This method allows to rest the location which should be used
384 /// for uniquing reports. For example, memory leaks checker, could set this to
385 /// the allocation site, rather then the location where the bug is reported.
386 PathSensitiveBugReport(const BugType &bt, StringRef desc,
387 const ExplodedNode *errorNode,
388 PathDiagnosticLocation LocationToUnique,
389 const Decl *DeclToUnique)
390 : PathSensitiveBugReport(bt, desc, desc, errorNode, LocationToUnique,
391 DeclToUnique) {}
392
393 PathSensitiveBugReport(const BugType &bt, StringRef shortDesc, StringRef desc,
394 const ExplodedNode *errorNode,
395 PathDiagnosticLocation LocationToUnique,
396 const Decl *DeclToUnique);
397
398 static bool classof(const BugReport *R) {
399 return R->getKind() == Kind::PathSensitive;
400 }
401
402 const ExplodedNode *getErrorNode() const { return ErrorNode; }
403
404 /// Indicates whether or not any path pruning should take place
405 /// when generating a PathDiagnostic from this BugReport.
406 bool shouldPrunePath() const { return !DoNotPrunePath; }
407
408 /// Disable all path pruning when generating a PathDiagnostic.
410
411 /// Get the location on which the report should be uniqued.
413 return UniqueingLocation;
414 }
415
416 /// Get the declaration containing the uniqueing location.
417 const Decl *getUniqueingDecl() const override {
418 return UniqueingDecl;
419 }
420
421 const Decl *getDeclWithIssue() const override;
422
423 ArrayRef<SourceRange> getRanges() const override;
424
425 PathDiagnosticLocation getLocation() const override;
426
427 /// Marks a symbol as interesting. Different kinds of interestingness will
428 /// be processed differently by visitors (e.g. if the tracking kind is
429 /// condition, will append "will be used as a condition" to the message).
432
434
435 /// Marks a region as interesting. Different kinds of interestingness will
436 /// be processed differently by visitors (e.g. if the tracking kind is
437 /// condition, will append "will be used as a condition" to the message).
438 void markInteresting(
439 const MemRegion *R,
441
442 void markNotInteresting(const MemRegion *R);
443
444 /// Marks a symbolic value as interesting. Different kinds of interestingness
445 /// will be processed differently by visitors (e.g. if the tracking kind is
446 /// condition, will append "will be used as a condition" to the message).
449 void markInteresting(const LocationContext *LC);
450
451 bool isInteresting(SymbolRef sym) const;
452 bool isInteresting(const MemRegion *R) const;
453 bool isInteresting(SVal V) const;
454 bool isInteresting(const LocationContext *LC) const;
455
456 std::optional<bugreporter::TrackingKind>
458
459 std::optional<bugreporter::TrackingKind>
460 getInterestingnessKind(const MemRegion *R) const;
461
462 std::optional<bugreporter::TrackingKind> getInterestingnessKind(SVal V) const;
463
464 /// Returns whether or not this report should be considered valid.
465 ///
466 /// Invalid reports are those that have been classified as likely false
467 /// positives after the fact.
468 bool isValid() const {
469 return Invalidations.empty();
470 }
471
472 /// Marks the current report as invalid, meaning that it is probably a false
473 /// positive and should not be reported to the user.
474 ///
475 /// The \p Tag and \p Data arguments are intended to be opaque identifiers for
476 /// this particular invalidation, where \p Tag represents the visitor
477 /// responsible for invalidation, and \p Data represents the reason this
478 /// visitor decided to invalidate the bug report.
479 ///
480 /// \sa removeInvalidation
481 void markInvalid(const void *Tag, const void *Data) {
482 Invalidations.insert(std::make_pair(Tag, Data));
483 }
484
485 /// Profile to identify equivalent bug reports for error report coalescing.
486 /// Reports are uniqued to ensure that we do not emit multiple diagnostics
487 /// for each bug.
488 void Profile(llvm::FoldingSetNodeID &hash) const override;
489
490 /// Add custom or predefined bug report visitors to this report.
491 ///
492 /// The visitors should be used when the default trace is not sufficient.
493 /// For example, they allow constructing a more elaborate trace.
494 /// @{
495 void addVisitor(std::unique_ptr<BugReporterVisitor> visitor);
496
497 template <class VisitorType, class... Args>
498 void addVisitor(Args &&... ConstructorArgs) {
500 std::make_unique<VisitorType>(std::forward<Args>(ConstructorArgs)...));
501 }
502 /// @}
503
504 /// Remove all visitors attached to this bug report.
505 void clearVisitors();
506
507 /// Iterators through the custom diagnostic visitors.
511
512 /// Notes that the condition of the CFGBlock associated with \p Cond is
513 /// being tracked.
514 /// \returns false if the condition is already being tracked.
516 return TrackedConditions.insert(Cond).second;
517 }
518
520 std::unique_ptr<StackHintGenerator> StackHint) {
521 StackHints[Piece] = std::move(StackHint);
522 }
523
525 return StackHints.count(Piece) > 0;
526 }
527
528 /// Produce the hint for the given node. The node contains
529 /// information about the call for which the diagnostic can be generated.
530 std::string
532 const ExplodedNode *N) const {
533 auto I = StackHints.find(Piece);
534 if (I != StackHints.end())
535 return I->second->getMessage(N);
536 return "";
537 }
538};
539
540//===----------------------------------------------------------------------===//
541// BugTypes (collections of related reports).
542//===----------------------------------------------------------------------===//
543
544class BugReportEquivClass : public llvm::FoldingSetNode {
545 friend class BugReporter;
546
547 /// List of *owned* BugReport objects.
549
550 void AddReport(std::unique_ptr<BugReport> &&R) {
551 Reports.push_back(std::move(R));
552 }
553
554public:
555 BugReportEquivClass(std::unique_ptr<BugReport> R) { AddReport(std::move(R)); }
556
558
559 void Profile(llvm::FoldingSetNodeID& ID) const {
560 assert(!Reports.empty());
561 Reports.front()->Profile(ID);
562 }
563};
564
565//===----------------------------------------------------------------------===//
566// BugReporter and friends.
567//===----------------------------------------------------------------------===//
568
570public:
571 virtual ~BugReporterData() = default;
572
574 virtual ASTContext &getASTContext() = 0;
578};
579
580/// BugReporter is a utility class for generating PathDiagnostics for analysis.
581/// It collects the BugReports and BugTypes and knows how to generate
582/// and flush the corresponding diagnostics.
583///
584/// The base class is used for generating path-insensitive
586private:
588
589 /// The top-level entry point for the issue to be reported.
590 const Decl *AnalysisEntryPoint = nullptr;
591
592 /// Generate and flush the diagnostics for the given bug report.
593 void FlushReport(BugReportEquivClass& EQ);
594
595 /// The set of bug reports tracked by the BugReporter.
596 llvm::FoldingSet<BugReportEquivClass> EQClasses;
597
598 /// A vector of BugReports for tracking the allocated pointers and cleanup.
599 std::vector<BugReportEquivClass *> EQClassesVector;
600
601 /// User-provided in-code suppressions.
602 BugSuppression UserSuppressions;
603
604public:
606 virtual ~BugReporter();
607
608 /// Generate and flush diagnostics for all bug reports.
609 void FlushReports();
610
613 }
614
615 /// Iterator over the set of BugReports tracked by the BugReporter.
616 using EQClasses_iterator = llvm::FoldingSet<BugReportEquivClass>::iterator;
617 llvm::iterator_range<EQClasses_iterator> equivalenceClasses() {
618 return EQClasses;
619 }
620
622
624
626
628
629 /// Get the top-level entry point for the issue to be reported.
630 const Decl *getAnalysisEntryPoint() const { return AnalysisEntryPoint; }
631
632 void setAnalysisEntryPoint(const Decl *EntryPoint) {
633 assert(EntryPoint);
634 AnalysisEntryPoint = EntryPoint;
635 }
636
637 /// Add the given report to the set of reports tracked by BugReporter.
638 ///
639 /// The reports are usually generated by the checkers. Further, they are
640 /// folded based on the profile value, which is done to coalesce similar
641 /// reports.
642 virtual void emitReport(std::unique_ptr<BugReport> R);
643
644 void EmitBasicReport(const Decl *DeclWithIssue, const CheckerBase *Checker,
645 StringRef BugName, StringRef BugCategory,
646 StringRef BugStr, PathDiagnosticLocation Loc,
647 ArrayRef<SourceRange> Ranges = std::nullopt,
648 ArrayRef<FixItHint> Fixits = std::nullopt);
649
650 void EmitBasicReport(const Decl *DeclWithIssue, CheckerNameRef CheckerName,
651 StringRef BugName, StringRef BugCategory,
652 StringRef BugStr, PathDiagnosticLocation Loc,
653 ArrayRef<SourceRange> Ranges = std::nullopt,
654 ArrayRef<FixItHint> Fixits = std::nullopt);
655
656private:
657 llvm::StringMap<std::unique_ptr<BugType>> StrBugTypes;
658
659 /// Returns a BugType that is associated with the given name and
660 /// category.
661 BugType *getBugTypeForName(CheckerNameRef CheckerName, StringRef name,
662 StringRef category);
663
664 virtual BugReport *
665 findReportInEquivalenceClass(BugReportEquivClass &eqClass,
666 SmallVectorImpl<BugReport *> &bugReports) {
667 return eqClass.getReports()[0].get();
668 }
669
670protected:
671 /// Generate the diagnostics for the given bug report.
672 virtual std::unique_ptr<DiagnosticForConsumerMapTy>
673 generateDiagnosticForConsumerMap(BugReport *exampleReport,
675 ArrayRef<BugReport *> bugReports);
676};
677
678/// GRBugReporter is used for generating path-sensitive reports.
680 ExprEngine& Eng;
681
682 BugReport *findReportInEquivalenceClass(
683 BugReportEquivClass &eqClass,
684 SmallVectorImpl<BugReport *> &bugReports) override;
685
686 /// Generate the diagnostics for the given bug report.
687 std::unique_ptr<DiagnosticForConsumerMapTy>
688 generateDiagnosticForConsumerMap(BugReport *exampleReport,
690 ArrayRef<BugReport *> bugReports) override;
691public:
693 : BugReporter(d), Eng(eng) {}
694
695 /// getGraph - Get the exploded graph created by the analysis engine
696 /// for the analyzed method or function.
697 const ExplodedGraph &getGraph() const;
698
699 /// getStateManager - Return the state manager used by the analysis
700 /// engine.
702
703 /// \p bugReports A set of bug reports within a *single* equivalence class
704 ///
705 /// \return A mapping from consumers to the corresponding diagnostics.
706 /// Iterates through the bug reports within a single equivalence class,
707 /// stops at a first non-invalidated report.
708 std::unique_ptr<DiagnosticForConsumerMapTy> generatePathDiagnostics(
711
712 void emitReport(std::unique_ptr<BugReport> R) override;
713};
714
715
718
719 virtual void anchor();
720
721public:
723
724 virtual ~BugReporterContext() = default;
725
727 const PathSensitiveBugReporter &getBugReporter() const { return BR; }
728
730 return BR.getStateManager();
731 }
732
734 return BR.getContext();
735 }
736
738 return BR.getSourceManager();
739 }
740
742 return BR.getAnalyzerOptions();
743 }
744};
745
746/// The tag that carries some information with it.
747///
748/// It can be valuable to produce tags with some bits of information and later
749/// reuse them for a better diagnostic.
750///
751/// Please make sure that derived class' constuctor is private and that the user
752/// can only create objects using DataTag::Factory. This also means that
753/// DataTag::Factory should be friend for every derived class.
754class DataTag : public ProgramPointTag {
755public:
756 StringRef getTagDescription() const override { return "Data Tag"; }
757
758 // Manage memory for DataTag objects.
759 class Factory {
760 std::vector<std::unique_ptr<DataTag>> Tags;
761
762 public:
763 template <class DataTagType, class... Args>
764 const DataTagType *make(Args &&... ConstructorArgs) {
765 // We cannot use std::make_unique because we cannot access the private
766 // constructor from inside it.
767 Tags.emplace_back(
768 new DataTagType(std::forward<Args>(ConstructorArgs)...));
769 return static_cast<DataTagType *>(Tags.back().get());
770 }
771 };
772
773protected:
774 DataTag(void *TagKind) : ProgramPointTag(TagKind) {}
775};
776
777/// The tag upon which the TagVisitor reacts. Add these in order to display
778/// additional PathDiagnosticEventPieces along the path.
779class NoteTag : public DataTag {
780public:
781 using Callback = std::function<std::string(BugReporterContext &,
783
784private:
785 static int Kind;
786
787 const Callback Cb;
788 const bool IsPrunable;
789
790 NoteTag(Callback &&Cb, bool IsPrunable)
791 : DataTag(&Kind), Cb(std::move(Cb)), IsPrunable(IsPrunable) {}
792
793public:
794 static bool classof(const ProgramPointTag *T) {
795 return T->getTagKind() == &Kind;
796 }
797
798 std::optional<std::string> generateMessage(BugReporterContext &BRC,
799 PathSensitiveBugReport &R) const {
800 std::string Msg = Cb(BRC, R);
801 if (Msg.empty())
802 return std::nullopt;
803
804 return std::move(Msg);
805 }
806
807 StringRef getTagDescription() const override {
808 // TODO: Remember a few examples of generated messages
809 // and display them in the ExplodedGraph dump by
810 // returning them from this function.
811 return "Note Tag";
812 }
813
814 bool isPrunable() const { return IsPrunable; }
815
816 friend class Factory;
817 friend class TagVisitor;
818};
819
820} // namespace ento
821
822} // namespace clang
823
824#endif // LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGREPORTER_H
#define V(N, I)
Definition: ASTContext.h:3284
StringRef P
static char ID
Definition: Arena.cpp:183
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
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:182
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:2820
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
This represents one expression.
Definition: Expr.h:110
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
It wraps the AnalysisDeclContext to represent both the call stack with the help of StackFrameContext ...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128
ProgramPoints can be "tagged" as representing points specific to a given analysis entity.
Definition: ProgramPoint.h:38
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
bool isValid() const
Stmt - This represents one statement.
Definition: Stmt.h:84
BasicBugReport(const BugType &bt, StringRef desc, PathDiagnosticLocation l)
Definition: BugReporter.h:256
PathDiagnosticLocation getLocation() const override
The primary location of the bug report that points at the undesirable behavior in the code.
Definition: BugReporter.h:263
const Decl * getDeclWithIssue() const override
The smallest declaration that contains the bug location.
Definition: BugReporter.h:268
PathDiagnosticLocation getUniqueingLocation() const override
Get the location on which the report should be uniqued.
Definition: BugReporter.h:272
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)
Definition: BugReporter.h:259
const Decl * getUniqueingDecl() const override
Get the declaration that corresponds to (usually contains) the uniqueing location.
Definition: BugReporter.h:276
void setDeclWithIssue(const Decl *declWithIssue)
Specifically set the Decl where an issue occurred.
Definition: BugReporter.h:282
ArrayRef< std::unique_ptr< BugReport > > getReports() const
Definition: BugReporter.h:557
BugReportEquivClass(std::unique_ptr< BugReport > R)
Definition: BugReporter.h:555
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: BugReporter.h:559
This class provides an interface through which checkers can create individual bug reports.
Definition: BugReporter.h:119
llvm::ArrayRef< FixItHint > getFixits() const
Definition: BugReporter.h:244
void addRange(SourceRange R)
Add a range to a bug report.
Definition: BugReporter.h:222
SmallVector< SourceRange, 4 > Ranges
Definition: BugReporter.h:132
std::string ShortDescription
Definition: BugReporter.h:129
std::string Description
Definition: BugReporter.h:130
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.
Definition: BugReporter.h:201
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.
virtual const Decl * getUniqueingDecl() const =0
Get the declaration that corresponds to (usually contains) the uniqueing location.
SmallVector< std::shared_ptr< PathDiagnosticNotePiece >, 4 > Notes
Definition: BugReporter.h:133
SmallVector< FixItHint, 4 > Fixits
Definition: BugReporter.h:134
ArrayRef< std::shared_ptr< PathDiagnosticNotePiece > > getNotes()
Definition: BugReporter.h:211
BugReport(Kind kind, const BugType &bt, StringRef desc)
Definition: BugReporter.h:136
void addFixItHint(const FixItHint &F)
Add a fix-it hint to the bug report.
Definition: BugReporter.h:240
StringRef getDescription() const
A verbose warning message that is appropriate for displaying next to the source code that introduces ...
Definition: BugReporter.h:157
const BugType & BT
Definition: BugReporter.h:128
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
Definition: BugReporter.h:149
StringRef getShortDescription(bool UseFallback=true) const
A short general warning message that is appropriate for displaying in the list of all reported bugs.
Definition: BugReporter.h:163
Kind getKind() const
Definition: BugReporter.h:147
virtual ArrayRef< SourceRange > getRanges() const
Get the SourceRanges associated with the report.
Definition: BugReporter.h:229
virtual const Decl * getDeclWithIssue() const =0
The smallest declaration that contains the bug location.
BugReport(Kind K, const BugType &BT, StringRef ShortDescription, StringRef Description)
Definition: BugReporter.h:139
ASTContext & getASTContext() const
Definition: BugReporter.h:733
BugReporterContext(PathSensitiveBugReporter &br)
Definition: BugReporter.h:722
ProgramStateManager & getStateManager() const
Definition: BugReporter.h:729
const SourceManager & getSourceManager() const
Definition: BugReporter.h:737
PathSensitiveBugReporter & getBugReporter()
Definition: BugReporter.h:726
virtual ~BugReporterContext()=default
const PathSensitiveBugReporter & getBugReporter() const
Definition: BugReporter.h:727
const AnalyzerOptions & getAnalyzerOptions() const
Definition: BugReporter.h:741
virtual ASTContext & getASTContext()=0
virtual ~BugReporterData()=default
virtual AnalyzerOptions & getAnalyzerOptions()=0
virtual SourceManager & getSourceManager()=0
virtual Preprocessor & getPreprocessor()=0
virtual ArrayRef< PathDiagnosticConsumer * > getPathDiagnosticConsumers()=0
BugReporter is a utility class for generating PathDiagnostics for analysis.
Definition: BugReporter.h:585
virtual std::unique_ptr< DiagnosticForConsumerMapTy > generateDiagnosticForConsumerMap(BugReport *exampleReport, ArrayRef< PathDiagnosticConsumer * > consumers, ArrayRef< BugReport * > bugReports)
Generate the diagnostics for the given bug report.
Preprocessor & getPreprocessor()
Definition: BugReporter.h:627
void FlushReports()
Generate and flush diagnostics for all bug reports.
const SourceManager & getSourceManager()
Definition: BugReporter.h:623
const Decl * getAnalysisEntryPoint() const
Get the top-level entry point for the issue to be reported.
Definition: BugReporter.h:630
void EmitBasicReport(const Decl *DeclWithIssue, const CheckerBase *Checker, StringRef BugName, StringRef BugCategory, StringRef BugStr, PathDiagnosticLocation Loc, ArrayRef< SourceRange > Ranges=std::nullopt, ArrayRef< FixItHint > Fixits=std::nullopt)
llvm::iterator_range< EQClasses_iterator > equivalenceClasses()
Definition: BugReporter.h:617
ASTContext & getContext()
Definition: BugReporter.h:621
const AnalyzerOptions & getAnalyzerOptions()
Definition: BugReporter.h:625
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.
Definition: BugReporter.h:616
ArrayRef< PathDiagnosticConsumer * > getPathDiagnosticConsumers()
Definition: BugReporter.h:611
void setAnalysisEntryPoint(const Decl *EntryPoint)
Definition: BugReporter.h:632
This wrapper is used to ensure that only StringRefs originating from the CheckerRegistry are used as ...
const DataTagType * make(Args &&... ConstructorArgs)
Definition: BugReporter.h:764
The tag that carries some information with it.
Definition: BugReporter.h:754
DataTag(void *TagKind)
Definition: BugReporter.h:774
StringRef getTagDescription() const override
Definition: BugReporter.h:756
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:96
The tag upon which the TagVisitor reacts.
Definition: BugReporter.h:779
std::function< std::string(BugReporterContext &, PathSensitiveBugReport &)> Callback
Definition: BugReporter.h:782
static bool classof(const ProgramPointTag *T)
Definition: BugReporter.h:794
StringRef getTagDescription() const override
Definition: BugReporter.h:807
bool isPrunable() const
Definition: BugReporter.h:814
std::optional< std::string > generateMessage(BugReporterContext &BRC, PathSensitiveBugReport &R) const
Definition: BugReporter.h:798
llvm::SmallSet< const LocationContext *, 2 > InterestingLocationContexts
A set of location contexts that correspoind to call sites which should be considered "interesting".
Definition: BugReporter.h:323
void markInteresting(SymbolRef sym, bugreporter::TrackingKind TKind=bugreporter::TrackingKind::Thorough)
Marks a symbol as interesting.
void addVisitor(Args &&... ConstructorArgs)
Definition: BugReporter.h:498
llvm::SmallSet< const ExplodedNode *, 4 > TrackedConditions
Conditions we're already tracking.
Definition: BugReporter.h:351
PathDiagnosticLocation getUniqueingLocation() const override
Get the location on which the report should be uniqued.
Definition: BugReporter.h:412
VisitorList Callbacks
A set of custom visitors which generate "event" diagnostics at interesting points in the path.
Definition: BugReporter.h:327
std::string getCallStackMessage(PathDiagnosticPieceRef Piece, const ExplodedNode *N) const
Produce the hint for the given node.
Definition: BugReporter.h:531
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.
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...
Definition: BugReporter.h:366
std::pair< const void *, const void * > InvalidationRecord
Used to track unique reasons why a bug report might be invalid.
Definition: BugReporter.h:341
bool shouldPrunePath() const
Indicates whether or not any path pruning should take place when generating a PathDiagnostic from thi...
Definition: BugReporter.h:406
PathDiagnosticLocation UniqueingLocation
Reports with different uniqueing locations are considered to be different for the purposes of dedupli...
Definition: BugReporter.h:355
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.
Definition: BugReporter.h:311
const Decl * getUniqueingDecl() const override
Get the declaration containing the uniqueing location.
Definition: BugReporter.h:417
llvm::SmallSet< InvalidationRecord, 4 > Invalidations
If non-empty, this bug report is likely a false positive and should not be shown to the user.
Definition: BugReporter.h:348
const ExplodedNode * getErrorNode() const
Definition: BugReporter.h:402
PathSensitiveBugReport(const BugType &bt, StringRef desc, const ExplodedNode *errorNode)
Definition: BugReporter.h:369
static bool classof(const BugReport *R)
Definition: BugReporter.h:398
const ExplodedNode * ErrorNode
The ExplodedGraph node against which the report was thrown.
Definition: BugReporter.h:298
PathSensitiveBugReport(const BugType &bt, StringRef shortDesc, StringRef desc, const ExplodedNode *errorNode)
Definition: BugReporter.h:373
bool addTrackedCondition(const ExplodedNode *Cond)
Notes that the condition of the CFGBlock associated with Cond is being tracked.
Definition: BugReporter.h:515
visitor_iterator visitor_begin()
Iterators through the custom diagnostic visitors.
Definition: BugReporter.h:508
void addCallStackHint(PathDiagnosticPieceRef Piece, std::unique_ptr< StackHintGenerator > StackHint)
Definition: BugReporter.h:519
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...
Definition: BugReporter.h:481
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
Definition: BugReporter.h:524
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.
Definition: BugReporter.h:468
std::optional< bugreporter::TrackingKind > getInterestingnessKind(SymbolRef sym) const
void markNotInteresting(SymbolRef sym)
bool DoNotPrunePath
When set, this flag disables all callstack pruning from a diagnostic path.
Definition: BugReporter.h:335
PathSensitiveBugReport(const BugType &bt, StringRef desc, const ExplodedNode *errorNode, PathDiagnosticLocation LocationToUnique, const Decl *DeclToUnique)
Create a PathSensitiveBugReport with a custom uniqueing location.
Definition: BugReporter.h:386
llvm::DenseMap< const MemRegion *, bugreporter::TrackingKind > InterestingRegions
A (stack of) set of regions that are registered with this report as being "interesting",...
Definition: BugReporter.h:319
llvm::iterator_range< visitor_iterator > visitor_range
Definition: BugReporter.h:293
bool isInteresting(SymbolRef sym) const
const SourceRange ErrorNodeRange
The range that corresponds to ErrorNode's program point.
Definition: BugReporter.h:302
VisitorList::iterator visitor_iterator
Definition: BugReporter.h:292
llvm::FoldingSet< BugReporterVisitor > CallbacksSet
Used for ensuring the visitors are only added once.
Definition: BugReporter.h:330
void disablePathPruning()
Disable all path pruning when generating a PathDiagnostic.
Definition: BugReporter.h:409
GRBugReporter is used for generating path-sensitive reports.
Definition: BugReporter.h:679
const ExplodedGraph & getGraph() const
getGraph - Get the exploded graph created by the analysis engine for the analyzed method or function.
std::unique_ptr< DiagnosticForConsumerMapTy > generatePathDiagnostics(ArrayRef< PathDiagnosticConsumer * > consumers, ArrayRef< PathSensitiveBugReport * > &bugReports)
bugReports A set of bug reports within a single equivalence class
void emitReport(std::unique_ptr< BugReport > R) override
Add the given report to the set of reports tracked by BugReporter.
ProgramStateManager & getStateManager() const
getStateManager - Return the state manager used by the analysis engine.
PathSensitiveBugReporter(BugReporterData &d, ExprEngine &eng)
Definition: BugReporter.h:692
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition: SVals.h:55
Constructs a Stack hint for the given symbol.
Definition: BugReporter.h:91
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()
Definition: BugReporter.h:112
virtual std::string getMessageForReturn(const CallExpr *CallExpr)
Definition: BugReporter.h:108
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.
Symbolic value.
Definition: SymExpr.h:30
The visitor detects NoteTags and displays the event notes they contain.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
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...
llvm::DenseMap< PathDiagnosticConsumer *, std::unique_ptr< PathDiagnostic > > DiagnosticForConsumerMapTy
A mapping from diagnostic consumers to the diagnostics they should consume.
Definition: BugReporter.h:71
std::shared_ptr< PathDiagnosticPiece > PathDiagnosticPieceRef
The JSON file list parser is used to communicate input to InstallAPI.
const FunctionProtoType * T
Definition: Format.h:5394