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 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
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, StringRef desc, PathDiagnosticLocation l)
257 : BugReport(Kind::Basic, bt, desc), Location(l) {}
258
259 BasicBugReport(const BugType &BT, StringRef ShortDesc, StringRef Desc,
261 : BugReport(Kind::Basic, BT, ShortDesc, Desc), Location(L) {}
262
263 static bool classof(const BugReport *R) {
264 return R->getKind() == Kind::Basic;
265 }
266
268 assert(Location.isValid());
269 return Location;
270 }
271
272 const Decl *getDeclWithIssue() const override {
273 return DeclWithIssue;
274 }
275
277 return getLocation();
278 }
279
280 const Decl *getUniqueingDecl() const override {
281 return getDeclWithIssue();
282 }
283
284 /// Specifically set the Decl where an issue occurred. This isn't necessary
285 /// for BugReports that cover a path as it will be automatically inferred.
286 void setDeclWithIssue(const Decl *declWithIssue) {
287 DeclWithIssue = declWithIssue;
288 }
289
290 void Profile(llvm::FoldingSetNodeID& hash) const override;
291};
292
294public:
296 using visitor_iterator = VisitorList::iterator;
297 using visitor_range = llvm::iterator_range<visitor_iterator>;
298
299protected:
300 /// The ExplodedGraph node against which the report was thrown. It corresponds
301 /// to the end of the execution path that demonstrates the bug.
302 const ExplodedNode *ErrorNode = nullptr;
303
304 /// The range that corresponds to ErrorNode's program point. It is usually
305 /// highlighted in the report.
307
308 /// Profile to identify equivalent bug reports for error report coalescing.
309
310 /// A (stack of) a set of symbols that are registered with this
311 /// report as being "interesting", and thus used to help decide which
312 /// diagnostics to include when constructing the final path diagnostic.
313 /// The stack is largely used by BugReporter when generating PathDiagnostics
314 /// for multiple PathDiagnosticConsumers.
315 llvm::DenseMap<SymbolRef, bugreporter::TrackingKind> InterestingSymbols;
316
317 /// A (stack of) set of regions that are registered with this report as being
318 /// "interesting", and thus used to help decide which diagnostics
319 /// to include when constructing the final path diagnostic.
320 /// The stack is largely used by BugReporter when generating PathDiagnostics
321 /// for multiple PathDiagnosticConsumers.
322 llvm::DenseMap<const MemRegion *, bugreporter::TrackingKind>
324
325 /// A set of location contexts that correspoind to call sites which should be
326 /// considered "interesting".
328
329 /// A set of custom visitors which generate "event" diagnostics at
330 /// interesting points in the path.
332
333 /// Used for ensuring the visitors are only added once.
334 llvm::FoldingSet<BugReporterVisitor> CallbacksSet;
335
336 /// When set, this flag disables all callstack pruning from a diagnostic
337 /// path. This is useful for some reports that want maximum fidelty
338 /// when reporting an issue.
339 bool DoNotPrunePath = false;
340
341 /// Used to track unique reasons why a bug report might be invalid.
342 ///
343 /// \sa markInvalid
344 /// \sa removeInvalidation
345 using InvalidationRecord = std::pair<const void *, const void *>;
346
347 /// If non-empty, this bug report is likely a false positive and should not be
348 /// shown to the user.
349 ///
350 /// \sa markInvalid
351 /// \sa removeInvalidation
352 llvm::SmallSet<InvalidationRecord, 4> Invalidations;
353
354 /// Conditions we're already tracking.
356
357 /// Reports with different uniqueing locations are considered to be different
358 /// for the purposes of deduplication.
361
362 const Stmt *getStmt() const;
363
364 /// If an event occurs in a different frame than the final diagnostic,
365 /// supply a message that will be used to construct an extra hint on the
366 /// returns from all the calls on the stack from this event to the final
367 /// diagnostic.
368 // FIXME: Allow shared_ptr keys in DenseMap?
369 std::map<PathDiagnosticPieceRef, std::unique_ptr<StackHintGenerator>>
371
372public:
373 PathSensitiveBugReport(const BugType &bt, StringRef desc,
374 const ExplodedNode *errorNode)
375 : PathSensitiveBugReport(bt, desc, desc, errorNode) {}
376
377 PathSensitiveBugReport(const BugType &bt, StringRef shortDesc, StringRef desc,
378 const ExplodedNode *errorNode)
379 : PathSensitiveBugReport(bt, shortDesc, desc, errorNode,
380 /*LocationToUnique*/ {},
381 /*DeclToUnique*/ nullptr) {}
382
383 /// Create a PathSensitiveBugReport with a custom uniqueing location.
384 ///
385 /// The reports that have the same report location, description, bug type, and
386 /// ranges are uniqued - only one of the equivalent reports will be presented
387 /// to the user. This method allows to rest the location which should be used
388 /// for uniquing reports. For example, memory leaks checker, could set this to
389 /// the allocation site, rather then the location where the bug is reported.
390 PathSensitiveBugReport(const BugType &bt, StringRef desc,
391 const ExplodedNode *errorNode,
392 PathDiagnosticLocation LocationToUnique,
393 const Decl *DeclToUnique)
394 : PathSensitiveBugReport(bt, desc, desc, errorNode, LocationToUnique,
395 DeclToUnique) {}
396
397 PathSensitiveBugReport(const BugType &bt, StringRef shortDesc, StringRef desc,
398 const ExplodedNode *errorNode,
399 PathDiagnosticLocation LocationToUnique,
400 const Decl *DeclToUnique);
401
402 static bool classof(const BugReport *R) {
403 return R->getKind() == Kind::PathSensitive;
404 }
405
406 const ExplodedNode *getErrorNode() const { return ErrorNode; }
407
408 /// Indicates whether or not any path pruning should take place
409 /// when generating a PathDiagnostic from this BugReport.
410 bool shouldPrunePath() const { return !DoNotPrunePath; }
411
412 /// Disable all path pruning when generating a PathDiagnostic.
414
415 /// Get the location on which the report should be uniqued.
419
420 /// Get the declaration containing the uniqueing location.
421 const Decl *getUniqueingDecl() const override {
422 return UniqueingDecl;
423 }
424
425 const Decl *getDeclWithIssue() const override;
426
427 ArrayRef<SourceRange> getRanges() const override;
428
429 PathDiagnosticLocation getLocation() const override;
430
431 /// Marks a symbol as interesting. Different kinds of interestingness will
432 /// be processed differently by visitors (e.g. if the tracking kind is
433 /// condition, will append "will be used as a condition" to the message).
436
438
439 /// Marks a region as interesting. Different kinds of interestingness will
440 /// be processed differently by visitors (e.g. if the tracking kind is
441 /// condition, will append "will be used as a condition" to the message).
442 void markInteresting(
443 const MemRegion *R,
445
446 void markNotInteresting(const MemRegion *R);
447
448 /// Marks a symbolic value as interesting. Different kinds of interestingness
449 /// will be processed differently by visitors (e.g. if the tracking kind is
450 /// condition, will append "will be used as a condition" to the message).
453 void markInteresting(const LocationContext *LC);
454
455 bool isInteresting(SymbolRef sym) const;
456 bool isInteresting(const MemRegion *R) const;
457 bool isInteresting(SVal V) const;
458 bool isInteresting(const LocationContext *LC) const;
459
460 std::optional<bugreporter::TrackingKind>
462
463 std::optional<bugreporter::TrackingKind>
464 getInterestingnessKind(const MemRegion *R) const;
465
466 std::optional<bugreporter::TrackingKind> getInterestingnessKind(SVal V) const;
467
468 /// Returns whether or not this report should be considered valid.
469 ///
470 /// Invalid reports are those that have been classified as likely false
471 /// positives after the fact.
472 bool isValid() const {
473 return Invalidations.empty();
474 }
475
476 /// Marks the current report as invalid, meaning that it is probably a false
477 /// positive and should not be reported to the user.
478 ///
479 /// The \p Tag and \p Data arguments are intended to be opaque identifiers for
480 /// this particular invalidation, where \p Tag represents the visitor
481 /// responsible for invalidation, and \p Data represents the reason this
482 /// visitor decided to invalidate the bug report.
483 ///
484 /// \sa removeInvalidation
485 void markInvalid(const void *Tag, const void *Data) {
486 Invalidations.insert(std::make_pair(Tag, Data));
487 }
488
489 /// Profile to identify equivalent bug reports for error report coalescing.
490 /// Reports are uniqued to ensure that we do not emit multiple diagnostics
491 /// for each bug.
492 void Profile(llvm::FoldingSetNodeID &hash) const override;
493
494 /// Add custom or predefined bug report visitors to this report.
495 ///
496 /// The visitors should be used when the default trace is not sufficient.
497 /// For example, they allow constructing a more elaborate trace.
498 /// @{
499 void addVisitor(std::unique_ptr<BugReporterVisitor> visitor);
500
501 template <class VisitorType, class... Args>
502 void addVisitor(Args &&... ConstructorArgs) {
504 std::make_unique<VisitorType>(std::forward<Args>(ConstructorArgs)...));
505 }
506 /// @}
507
508 /// Remove all visitors attached to this bug report.
509 void clearVisitors();
510
511 /// Iterators through the custom diagnostic visitors.
515
516 /// Notes that the condition of the CFGBlock associated with \p Cond is
517 /// being tracked.
518 /// \returns false if the condition is already being tracked.
520 return TrackedConditions.insert(Cond).second;
521 }
522
524 std::unique_ptr<StackHintGenerator> StackHint) {
525 StackHints[Piece] = std::move(StackHint);
526 }
527
529 return StackHints.count(Piece) > 0;
530 }
531
532 /// Produce the hint for the given node. The node contains
533 /// information about the call for which the diagnostic can be generated.
534 std::string
536 const ExplodedNode *N) const {
537 auto I = StackHints.find(Piece);
538 if (I != StackHints.end())
539 return I->second->getMessage(N);
540 return "";
541 }
542};
543
544//===----------------------------------------------------------------------===//
545// BugTypes (collections of related reports).
546//===----------------------------------------------------------------------===//
547
548class BugReportEquivClass : public llvm::FoldingSetNode {
549 friend class BugReporter;
550
551 /// List of *owned* BugReport objects.
553
554 void AddReport(std::unique_ptr<BugReport> &&R) {
555 Reports.push_back(std::move(R));
556 }
557
558public:
559 BugReportEquivClass(std::unique_ptr<BugReport> R) { AddReport(std::move(R)); }
560
562
563 void Profile(llvm::FoldingSetNodeID& ID) const {
564 assert(!Reports.empty());
565 Reports.front()->Profile(ID);
566 }
567};
568
569//===----------------------------------------------------------------------===//
570// BugReporter and friends.
571//===----------------------------------------------------------------------===//
572
584
585/// BugReporter is a utility class for generating PathDiagnostics for analysis.
586/// It collects the BugReports and BugTypes and knows how to generate
587/// and flush the corresponding diagnostics.
588///
589/// The base class is used for generating path-insensitive
591private:
593
594 /// The top-level entry point for the issue to be reported.
595 const Decl *AnalysisEntryPoint = nullptr;
596
597 /// Generate and flush the diagnostics for the given bug report.
598 void FlushReport(BugReportEquivClass& EQ);
599
600 /// The set of bug reports tracked by the BugReporter.
601 llvm::FoldingSet<BugReportEquivClass> EQClasses;
602
603 /// A vector of BugReports for tracking the allocated pointers and cleanup.
604 std::vector<BugReportEquivClass *> EQClassesVector;
605
606 /// User-provided in-code suppressions.
607 BugSuppression UserSuppressions;
608
609public:
611 virtual ~BugReporter();
612
613 /// Generate and flush diagnostics for all bug reports.
614 void FlushReports();
615
618 return D.getPathDiagnosticConsumers();
619 }
620
621 /// Iterator over the set of BugReports tracked by the BugReporter.
622 using EQClasses_iterator = llvm::FoldingSet<BugReportEquivClass>::iterator;
623 llvm::iterator_range<EQClasses_iterator> equivalenceClasses() {
624 return EQClasses;
625 }
626
627 ASTContext &getContext() { return D.getASTContext(); }
628
629 const SourceManager &getSourceManager() { return D.getSourceManager(); }
630 const SourceManager &getSourceManager() const { return D.getSourceManager(); }
631
632 const AnalyzerOptions &getAnalyzerOptions() { return D.getAnalyzerOptions(); }
633
634 Preprocessor &getPreprocessor() { return D.getPreprocessor(); }
635 const Preprocessor &getPreprocessor() const { return D.getPreprocessor(); }
636
637 /// Get the top-level entry point for the issue to be reported.
638 const Decl *getAnalysisEntryPoint() const { return AnalysisEntryPoint; }
639
640 void setAnalysisEntryPoint(const Decl *EntryPoint) {
641 assert(EntryPoint);
642 AnalysisEntryPoint = EntryPoint;
643 }
644
645 /// Add the given report to the set of reports tracked by BugReporter.
646 ///
647 /// The reports are usually generated by the checkers. Further, they are
648 /// folded based on the profile value, which is done to coalesce similar
649 /// reports.
650 virtual void emitReport(std::unique_ptr<BugReport> R);
651
652 void EmitBasicReport(const Decl *DeclWithIssue,
653 const CheckerFrontend *Checker, StringRef BugName,
654 StringRef BugCategory, StringRef BugStr,
656 ArrayRef<SourceRange> Ranges = {},
657 ArrayRef<FixItHint> Fixits = {});
658
659 void EmitBasicReport(const Decl *DeclWithIssue, CheckerNameRef CheckerName,
660 StringRef BugName, StringRef BugCategory,
661 StringRef BugStr, PathDiagnosticLocation Loc,
662 ArrayRef<SourceRange> Ranges = {},
663 ArrayRef<FixItHint> Fixits = {});
664
665private:
666 llvm::StringMap<std::unique_ptr<BugType>> StrBugTypes;
667
668 /// Returns a BugType that is associated with the given name and
669 /// category.
670 BugType *getBugTypeForName(CheckerNameRef CheckerName, StringRef name,
671 StringRef category);
672
673 virtual BugReport *
674 findReportInEquivalenceClass(BugReportEquivClass &eqClass,
675 SmallVectorImpl<BugReport *> &bugReports) {
676 return eqClass.getReports()[0].get();
677 }
678
679protected:
680 /// Generate the diagnostics for the given bug report.
681 virtual std::unique_ptr<DiagnosticForConsumerMapTy>
683 BugReport *exampleReport,
684 ArrayRef<std::unique_ptr<PathDiagnosticConsumer>> consumers,
685 ArrayRef<BugReport *> bugReports);
686};
687
688/// GRBugReporter is used for generating path-sensitive reports.
690 ExprEngine& Eng;
691
692 BugReport *findReportInEquivalenceClass(
693 BugReportEquivClass &eqClass,
694 SmallVectorImpl<BugReport *> &bugReports) override;
695
696 /// Generate the diagnostics for the given bug report.
697 std::unique_ptr<DiagnosticForConsumerMapTy> generateDiagnosticForConsumerMap(
698 BugReport *exampleReport,
699 ArrayRef<std::unique_ptr<PathDiagnosticConsumer>> consumers,
700 ArrayRef<BugReport *> bugReports) override;
701
702public:
705
706 /// getGraph - Get the exploded graph created by the analysis engine
707 /// for the analyzed method or function.
708 const ExplodedGraph &getGraph() const;
709
710 /// getStateManager - Return the state manager used by the analysis
711 /// engine.
713
714 /// \p bugReports A set of bug reports within a *single* equivalence class
715 ///
716 /// \return A mapping from consumers to the corresponding diagnostics.
717 /// Iterates through the bug reports within a single equivalence class,
718 /// stops at a first non-invalidated report.
719 std::unique_ptr<DiagnosticForConsumerMapTy> generatePathDiagnostics(
720 ArrayRef<std::unique_ptr<PathDiagnosticConsumer>> consumers,
722
723 void emitReport(std::unique_ptr<BugReport> R) override;
724};
725
726
729
730 virtual void anchor();
731
732public:
734
735 virtual ~BugReporterContext() = default;
736
738 const PathSensitiveBugReporter &getBugReporter() const { return BR; }
739
741 return BR.getStateManager();
742 }
743
745 return BR.getContext();
746 }
747
749 return BR.getSourceManager();
750 }
751
753 return BR.getAnalyzerOptions();
754 }
755};
756
757/// The tag that carries some information with it.
758///
759/// It can be valuable to produce tags with some bits of information and later
760/// reuse them for a better diagnostic.
761///
762/// Please make sure that derived class' constructor is private and that the
763/// user can only create objects using DataTag::Factory. This also means that
764/// DataTag::Factory should be friend for every derived class.
765class DataTag : public ProgramPointTag {
766public:
767 StringRef getDebugTag() const override { return "Data Tag"; }
768
769 // Manage memory for DataTag objects.
770 class Factory {
771 std::vector<std::unique_ptr<DataTag>> Tags;
772
773 public:
774 template <class DataTagType, class... Args>
775 const DataTagType *make(Args &&... ConstructorArgs) {
776 // We cannot use std::make_unique because we cannot access the private
777 // constructor from inside it.
778 Tags.emplace_back(
779 new DataTagType(std::forward<Args>(ConstructorArgs)...));
780 return static_cast<DataTagType *>(Tags.back().get());
781 }
782 };
783
784protected:
785 DataTag(void *TagKind) : ProgramPointTag(TagKind) {}
786};
787
788/// The tag upon which the TagVisitor reacts. Add these in order to display
789/// additional PathDiagnosticEventPieces along the path.
790class NoteTag : public DataTag {
791public:
794
795private:
796 static int Kind;
797
798 const Callback Cb;
799 const bool IsPrunable;
800
801 NoteTag(Callback &&Cb, bool IsPrunable)
802 : DataTag(&Kind), Cb(std::move(Cb)), IsPrunable(IsPrunable) {}
803
804public:
805 static bool classof(const ProgramPointTag *T) {
806 return T->getTagKind() == &Kind;
807 }
808
809 std::optional<std::string> generateMessage(BugReporterContext &BRC,
810 PathSensitiveBugReport &R) const {
811 std::string Msg = Cb(BRC, R);
812 if (Msg.empty())
813 return std::nullopt;
814
815 return std::move(Msg);
816 }
817
818 StringRef getDebugTag() const override {
819 // TODO: Remember a few examples of generated messages
820 // and display them in the ExplodedGraph dump by
821 // returning them from this function.
822 return "Note Tag";
823 }
824
825 bool isPrunable() const { return IsPrunable; }
826
827 friend class Factory;
828 friend class TagVisitor;
829};
830
831} // namespace ento
832
833} // namespace clang
834
835#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:226
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:79
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.
ProgramPointTag(void *tagKind=nullptr)
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
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:541
A CheckerFrontend instance is what the user recognizes as "one checker": it has a public canonical na...
Definition Checker.h:514
Simple checker classes that implement one frontend (i.e.
Definition Checker.h:553
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:98
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)
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.
llvm::SmallPtrSet< const LocationContext *, 2 > InterestingLocationContexts
A set of location contexts that correspoind to call sites which should be considered "interesting".
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: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