1//===- UnsafeBufferUsage.h - Replace pointers with modern C++ ---*- 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 an analysis that aids replacing buffer accesses through
10// raw pointers with safer C++ abstractions such as containers and views/spans.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_UNSAFEBUFFERUSAGE_H
15#define LLVM_CLANG_ANALYSIS_ANALYSES_UNSAFEBUFFERUSAGE_H
16
17#include "clang/AST/ASTTypeTraits.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/Stmt.h"
21#include "clang/Basic/SourceLocation.h"
22#include "llvm/Support/Debug.h"
23#include <set>
24
25namespace clang {
26
27using VarGrpTy = std::vector<const VarDecl *>;
28using VarGrpRef = ArrayRef<const VarDecl *>;
29
30class VariableGroupsManager {
31public:
32 VariableGroupsManager() = default;
33 virtual ~VariableGroupsManager() = default;
34 /// Returns the set of variables (including `Var`) that need to be fixed
35 /// together in one step.
36 ///
37 /// `Var` must be a variable that needs fix (so it must be in a group).
38 /// `HasParm` is an optional argument that will be set to true if the set of
39 /// variables, where `Var` is in, contains parameters.
40 virtual VarGrpRef getGroupOfVar(const VarDecl *Var,
41 bool *HasParm = nullptr) const =0;
42
43 /// Returns the non-empty group of variables that include parameters of the
44 /// analyzing function, if such a group exists. An empty group, otherwise.
45 virtual VarGrpRef getGroupOfParms() const =0;
46};
47
48// FixitStrategy is a map from variables to the way we plan to emit fixes for
49// these variables. It is figured out gradually by trying different fixes
50// for different variables depending on gadgets in which these variables
51// participate.
52class FixitStrategy {
53public:
54 enum class Kind {
55 Wontfix, // We don't plan to emit a fixit for this variable.
56 Span, // We recommend replacing the variable with std::span.
57 Iterator, // We recommend replacing the variable with std::span::iterator.
58 Array, // We recommend replacing the variable with std::array.
59 Vector // We recommend replacing the variable with std::vector.
60 };
61
62private:
63 using MapTy = llvm::DenseMap<const VarDecl *, Kind>;
64
65 MapTy Map;
66
67public:
68 FixitStrategy() = default;
69 FixitStrategy(const FixitStrategy &) = delete; // Let's avoid copies.
70 FixitStrategy &operator=(const FixitStrategy &) = delete;
71 FixitStrategy(FixitStrategy &&) = default;
72 FixitStrategy &operator=(FixitStrategy &&) = default;
73
74 void set(const VarDecl *VD, Kind K) { Map[VD] = K; }
75
76 Kind lookup(const VarDecl *VD) const {
77 auto I = Map.find(Val: VD);
78 if (I == Map.end())
79 return Kind::Wontfix;
80
81 return I->second;
82 }
83};
84
85/// The family of an unsafe libc function. Each family except `Other` has its
86/// own subgroup of -Wunsafe-buffer-usage-in-libc-call.
87enum class UnsafeLibcFunctionFamily {
88 Other,
89 NumericConversion,
90 StringManipulation,
91 StringExamination,
92 Memory,
93 IO,
94 Printf,
95 Scanf,
96};
97
98/// The interface that lets the caller handle unsafe buffer usage analysis
99/// results by overriding this class's handle... methods.
100class UnsafeBufferUsageHandler {
101#ifndef NDEBUG
102public:
103 // A self-debugging facility that you can use to notify the user when
104 // suggestions or fixits are incomplete.
105 // Uses std::function to avoid computing the message when it won't
106 // actually be displayed.
107 using DebugNote = std::pair<SourceLocation, std::string>;
108 using DebugNoteList = std::vector<DebugNote>;
109 using DebugNoteByVar = std::map<const VarDecl *, DebugNoteList>;
110 DebugNoteByVar DebugNotesByVar;
111#endif
112
113public:
114 UnsafeBufferUsageHandler() = default;
115 virtual ~UnsafeBufferUsageHandler() = default;
116
117 /// This analyses produces large fixits that are organized into lists
118 /// of primitive fixits (individual insertions/removals/replacements).
119 using FixItList = llvm::SmallVectorImpl<FixItHint>;
120
121 /// Invoked when an unsafe operation over raw pointers is found.
122 virtual void handleUnsafeOperation(const Stmt *Operation,
123 bool IsRelatedToDecl, ASTContext &Ctx) = 0;
124
125 /// Invoked when a call to an unsafe libc function is found.
126 /// \param PrintfInfo
127 /// is 0 if the callee function is not a member of the printf family;
128 /// is 1 if the callee is `sprintf`;
129 /// is 2 if arguments of the call have `__size_by` relation but are not in a
130 /// safe pattern;
131 /// is 3 if string arguments do not guarantee null-termination
132 /// is 4 if the callee takes va_list
133 /// has bit 3 (0x8) set if the callee is a function with the format attribute
134 /// \param Family the family of the callee, ignored when `PrintfInfo` has the
135 /// format attribute bit set
136 /// \param UnsafeArg one of the actual arguments that is unsafe, non-null
137 /// only when `2 <= PrintfInfo <= 3 (ignoring the "format attribute" bit)`
138 virtual void handleUnsafeLibcCall(const CallExpr *Call, unsigned PrintfInfo,
139 UnsafeLibcFunctionFamily Family,
140 ASTContext &Ctx,
141 const Expr *UnsafeArg = nullptr) = 0;
142
143 /// Invoked when an unsafe operation with a std container is found.
144 virtual void handleUnsafeOperationInContainer(const Stmt *Operation,
145 bool IsRelatedToDecl,
146 ASTContext &Ctx) = 0;
147
148 virtual void handleUnsafeOperationInStringView(const Stmt *Operation,
149 bool IsRelatedToDecl,
150 ASTContext &Ctx) = 0;
151
152 /// Invoked when a fix is suggested against a variable. This function groups
153 /// all variables that must be fixed together (i.e their types must be changed
154 /// to the same target type to prevent type mismatches) into a single fixit.
155 ///
156 /// `D` is the declaration of the callable under analysis that owns `Variable`
157 /// and all of its group mates.
158 virtual void
159 handleUnsafeVariableGroup(const VarDecl *Variable,
160 const VariableGroupsManager &VarGrpMgr,
161 FixItList &&Fixes, const Decl *D,
162 const FixitStrategy &VarTargetTypes) = 0;
163
164 // Invoked when an array subscript operator[] is used on a
165 // std::unique_ptr<T[]>.
166 virtual void handleUnsafeUniquePtrArrayAccess(const DynTypedNode &Node,
167 bool IsRelatedToDecl,
168 ASTContext &Ctx) = 0;
169
170#ifndef NDEBUG
171public:
172 bool areDebugNotesRequested() {
173 DEBUG_WITH_TYPE("SafeBuffers", return true);
174 return false;
175 }
176
177 void addDebugNoteForVar(const VarDecl *VD, SourceLocation Loc,
178 std::string Text) {
179 if (areDebugNotesRequested())
180 DebugNotesByVar[VD].push_back(std::make_pair(Loc, Text));
181 }
182
183 void clearDebugNotes() {
184 if (areDebugNotesRequested())
185 DebugNotesByVar.clear();
186 }
187#endif
188
189public:
190 /// \return true iff buffer safety is opt-out at `Loc`; false otherwise.
191 virtual bool isSafeBufferOptOut(const SourceLocation &Loc) const = 0;
192
193 /// \return true iff unsafe uses in containers should NOT be reported at
194 /// `Loc`; false otherwise.
195 virtual bool
196 ignoreUnsafeBufferInContainer(const SourceLocation &Loc) const = 0;
197
198 /// \return true iff every kind of unsafe libc call warning should NOT be
199 /// reported at `Loc`
200 virtual bool
201 ignoreUnsafeBufferInLibcCall(const SourceLocation &Loc) const = 0;
202
203 /// \return true iff unsafe calls to functions with the format attribute
204 /// should NOT be reported at `Loc`
205 virtual bool
206 ignoreUnsafeBufferInFormatAttrCall(const SourceLocation &Loc) const = 0;
207
208 /// \return true iff array subscript accesses on fixed size arrays should NOT
209 /// be reported at `Loc`
210 virtual bool
211 ignoreUnsafeBufferInStaticSizedArray(const SourceLocation &Loc) const = 0;
212
213 virtual std::string
214 getUnsafeBufferUsageAttributeTextAt(SourceLocation Loc,
215 StringRef WSSuffix = "") const = 0;
216};
217
218// This function invokes the analysis and allows the caller to react to it
219// through the handler class.
220void checkUnsafeBufferUsage(const Decl *D, UnsafeBufferUsageHandler &Handler,
221 bool EmitSuggestions);
222
223namespace internal {
224// Tests if any two `FixItHint`s in `FixIts` conflict. Two `FixItHint`s
225// conflict if they have overlapping source ranges.
226bool anyConflict(const llvm::SmallVectorImpl<FixItHint> &FixIts,
227 const SourceManager &SM);
228} // namespace internal
229
230/// \return true iff `N` is an unsafe buffer usage and populates the unsafe
231/// pointers in `UnsafePointers`
232bool matchUnsafePointers(const DynTypedNode &N, ASTContext &Ctx,
233 std::set<const Expr *> &UnsafePointers);
234} // end namespace clang
235
236#endif /* LLVM_CLANG_ANALYSIS_ANALYSES_UNSAFEBUFFERUSAGE_H */
237