clang-tools 23.0.0git
UnsafeFunctionsCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Analysis/AnnexKDetection.h"
14#include "clang/Lex/Preprocessor.h"
15#include <cassert>
16
17using namespace clang::ast_matchers;
18using namespace llvm;
19
20namespace clang::tidy::bugprone {
21
22static constexpr StringRef OptionNameCustomFunctions = "CustomFunctions";
23static constexpr StringRef OptionNameReportDefaultFunctions =
24 "ReportDefaultFunctions";
25static constexpr StringRef OptionNameReportMoreUnsafeFunctions =
26 "ReportMoreUnsafeFunctions";
27
28static constexpr StringRef FunctionNamesWithAnnexKReplacementId =
29 "FunctionNamesWithAnnexKReplacement";
30static constexpr StringRef FunctionNamesId = "FunctionsNames";
31static constexpr StringRef AdditionalFunctionNamesId =
32 "AdditionalFunctionsNames";
33static constexpr StringRef CustomFunctionNamesId = "CustomFunctionNames";
34static constexpr StringRef DeclRefId = "DRE";
35
36static std::optional<std::string>
37getAnnexKReplacementFor(StringRef FunctionName) {
38 return StringSwitch<std::string>(FunctionName)
39 .Case("strlen", "strnlen_s")
40 .Case("wcslen", "wcsnlen_s")
41 .Default((Twine{FunctionName} + "_s").str());
42}
43
44static StringRef getReplacementFor(StringRef FunctionName,
45 bool IsAnnexKAvailable) {
46 if (IsAnnexKAvailable) {
47 // Try to find a better replacement from Annex K first.
48 StringRef AnnexKReplacementFunction =
49 StringSwitch<StringRef>(FunctionName)
50 .Cases({"asctime", "asctime_r"}, "asctime_s")
51 .Case("gets", "gets_s")
52 .Default({});
53 if (!AnnexKReplacementFunction.empty())
54 return AnnexKReplacementFunction;
55 }
56
57 // FIXME: Some of these functions are available in C++ under "std::", and
58 // should be matched and suggested.
59 return StringSwitch<StringRef>(FunctionName)
60 .Cases({"asctime", "asctime_r"}, "strftime")
61 .Case("gets", "fgets")
62 .Case("rewind", "fseek")
63 .Case("setbuf", "setvbuf")
64 .Case("get_temporary_buffer", "operator new[]");
65}
66
67static StringRef getReplacementForAdditional(StringRef FunctionName,
68 bool IsAnnexKAvailable) {
69 if (IsAnnexKAvailable) {
70 // Try to find a better replacement from Annex K first.
71 StringRef AnnexKReplacementFunction = StringSwitch<StringRef>(FunctionName)
72 .Case("bcopy", "memcpy_s")
73 .Case("bzero", "memset_s")
74 .Default({});
75
76 if (!AnnexKReplacementFunction.empty())
77 return AnnexKReplacementFunction;
78 }
79
80 return StringSwitch<StringRef>(FunctionName)
81 .Case("bcmp", "memcmp")
82 .Case("bcopy", "memcpy")
83 .Case("bzero", "memset")
84 .Case("getpw", "getpwuid")
85 .Case("vfork", "posix_spawn");
86}
87
88/// \returns The rationale for replacing the function \p FunctionName with the
89/// safer alternative.
90static StringRef getRationaleFor(StringRef FunctionName) {
91 return StringSwitch<StringRef>(FunctionName)
92 .Cases({"asctime", "asctime_r", "ctime"},
93 "is not bounds-checking and non-reentrant")
94 .Cases({"bcmp", "bcopy", "bzero"}, "is deprecated")
95 .Cases({"fopen", "freopen"}, "has no exclusive access to the opened file")
96 .Case("gets", "is insecure, was deprecated and removed in C11 and C++14")
97 .Case("getpw", "is dangerous as it may overflow the provided buffer")
98 .Cases({"rewind", "setbuf"}, "has no error detection")
99 .Case("vfork", "is insecure as it can lead to denial of service "
100 "situations in the parent process")
101 .Case("get_temporary_buffer", "returns uninitialized memory without "
102 "performance advantages, was deprecated in "
103 "C++17 and removed in C++20")
104 .Default("is not bounds-checking");
105}
106
107/// Calculates whether Annex K is available for the current translation unit
108/// based on the macro definitions and the language options.
109///
110/// The result is cached and saved in \p CacheVar.
111static bool isAnnexKAvailable(std::optional<bool> &CacheVar, Preprocessor *PP,
112 const LangOptions &LO) {
113 if (CacheVar.has_value())
114 return *CacheVar;
115
116 CacheVar = analysis::isAnnexKAvailable(PP, LO);
117 return CacheVar.value();
118}
119
120static std::vector<UnsafeFunctionsCheck::CheckedFunction>
121parseCheckedFunctions(StringRef Option, ClangTidyContext *Context) {
122 const std::vector<StringRef> Functions =
124 std::vector<UnsafeFunctionsCheck::CheckedFunction> Result;
125 Result.reserve(Functions.size());
126
127 for (const StringRef Function : Functions) {
128 if (Function.empty())
129 continue;
130
131 const auto [Name, Rest] = Function.split(',');
132 const auto [Replacement, Reason] = Rest.split(',');
133
134 if (Name.trim().empty()) {
135 Context->configurationDiag("invalid configuration value for option '%0'; "
136 "expected the name of an unsafe function")
138 continue;
139 }
140
141 Result.push_back(
142 {Name.trim().str(),
144 Replacement.trim().str(), Reason.trim().str()});
145 }
146
147 return Result;
148}
149
150static std::string serializeCheckedFunctions(
151 const std::vector<UnsafeFunctionsCheck::CheckedFunction> &Functions) {
152 std::vector<std::string> Result;
153 Result.reserve(Functions.size());
154
155 for (const auto &Entry : Functions)
156 if (Entry.Reason.empty())
157 Result.push_back(Entry.Name + "," + Entry.Replacement);
158 else
159 Result.push_back(Entry.Name + "," + Entry.Replacement + "," +
160 Entry.Reason);
161
162 return llvm::join(Result, ";");
163}
164
166 ClangTidyContext *Context)
167 : ClangTidyCheck(Name, Context),
168 CustomFunctions(parseCheckedFunctions(
169 Options.get(OptionNameCustomFunctions, ""), Context)),
170 ReportDefaultFunctions(
171 Options.get(OptionNameReportDefaultFunctions, true)),
172 ReportMoreUnsafeFunctions(
173 Options.get(OptionNameReportMoreUnsafeFunctions, true)) {}
174
176 Options.store(Opts, OptionNameCustomFunctions,
177 serializeCheckedFunctions(CustomFunctions));
178 Options.store(Opts, OptionNameReportDefaultFunctions, ReportDefaultFunctions);
179 Options.store(Opts, OptionNameReportMoreUnsafeFunctions,
180 ReportMoreUnsafeFunctions);
181}
182
183void UnsafeFunctionsCheck::registerMatchers(MatchFinder *Finder) {
184 if (ReportDefaultFunctions) {
185 if (getLangOpts().C11) {
186 // Matching functions with safe replacements only in Annex K.
187 auto FunctionNamesWithAnnexKReplacementMatcher = hasAnyName(
188 "::bsearch", "::ctime", "::fopen", "::fprintf", "::freopen",
189 "::fscanf", "::fwprintf", "::fwscanf", "::getenv", "::gmtime",
190 "::localtime", "::mbsrtowcs", "::mbstowcs", "::memcpy", "::memmove",
191 "::memset", "::printf", "::qsort", "::scanf", "::snprintf",
192 "::sprintf", "::sscanf", "::strcat", "::strcpy", "::strerror",
193 "::strlen", "::strncat", "::strncpy", "::strtok", "::swprintf",
194 "::swscanf", "::vfprintf", "::vfscanf", "::vfwprintf", "::vfwscanf",
195 "::vprintf", "::vscanf", "::vsnprintf", "::vsprintf", "::vsscanf",
196 "::vswprintf", "::vswscanf", "::vwprintf", "::vwscanf", "::wcrtomb",
197 "::wcscat", "::wcscpy", "::wcslen", "::wcsncat", "::wcsncpy",
198 "::wcsrtombs", "::wcstok", "::wcstombs", "::wctomb", "::wmemcpy",
199 "::wmemmove", "::wprintf", "::wscanf");
200 Finder->addMatcher(
201 declRefExpr(to(functionDecl(FunctionNamesWithAnnexKReplacementMatcher)
203 .bind(DeclRefId),
204 this);
205 }
206
207 // Matching functions with replacements without Annex K.
208 auto FunctionNamesMatcher =
209 hasAnyName("::asctime", "asctime_r", "::gets", "::rewind", "::setbuf",
210 "::std::get_temporary_buffer");
211 Finder->addMatcher(
212 declRefExpr(
213 to(functionDecl(FunctionNamesMatcher).bind(FunctionNamesId)))
214 .bind(DeclRefId),
215 this);
216
217 if (ReportMoreUnsafeFunctions) {
218 // Matching functions with replacements without Annex K, at user request.
219 auto AdditionalFunctionNamesMatcher =
220 hasAnyName("::bcmp", "::bcopy", "::bzero", "::getpw", "::vfork");
221 Finder->addMatcher(
222 declRefExpr(to(functionDecl(AdditionalFunctionNamesMatcher)
224 .bind(DeclRefId),
225 this);
226 }
227 }
228
229 if (!CustomFunctions.empty()) {
230 std::vector<llvm::StringRef> FunctionNames;
231 FunctionNames.reserve(CustomFunctions.size());
232
233 for (const auto &Entry : CustomFunctions)
234 FunctionNames.emplace_back(Entry.Name);
235
236 auto CustomFunctionsMatcher =
238
239 Finder->addMatcher(declRefExpr(to(functionDecl(CustomFunctionsMatcher)
240 .bind(CustomFunctionNamesId)))
241 .bind(DeclRefId),
242 this);
243 // C++ member calls do not contain a DeclRefExpr to the function decl.
244 // Instead, they contain a MemberExpr that refers to the decl.
245 Finder->addMatcher(memberExpr(member(functionDecl(CustomFunctionsMatcher)
246 .bind(CustomFunctionNamesId)))
247 .bind(DeclRefId),
248 this);
249 }
250}
251
252void UnsafeFunctionsCheck::check(const MatchFinder::MatchResult &Result) {
253 const Expr *SourceExpr = nullptr;
254 const FunctionDecl *FuncDecl = nullptr;
255
256 if (const auto *DeclRef = Result.Nodes.getNodeAs<DeclRefExpr>(DeclRefId)) {
257 SourceExpr = DeclRef;
258 FuncDecl = cast<FunctionDecl>(DeclRef->getDecl());
259 } else if (const auto *Member =
260 Result.Nodes.getNodeAs<MemberExpr>(DeclRefId)) {
261 SourceExpr = Member;
262 FuncDecl = cast<FunctionDecl>(Member->getMemberDecl());
263 } else {
264 llvm_unreachable("No valid matched node in check()");
265 return;
266 }
267
268 assert(SourceExpr && FuncDecl && "No valid matched node in check()");
269
270 // Only one of these are matched at a time.
271 const auto *AnnexK = Result.Nodes.getNodeAs<FunctionDecl>(
273 const auto *Normal = Result.Nodes.getNodeAs<FunctionDecl>(FunctionNamesId);
274 const auto *Additional =
275 Result.Nodes.getNodeAs<FunctionDecl>(AdditionalFunctionNamesId);
276 const auto *Custom =
277 Result.Nodes.getNodeAs<FunctionDecl>(CustomFunctionNamesId);
278 assert((AnnexK || Normal || Additional || Custom) &&
279 "No valid match category.");
280
281 bool AnnexKIsAvailable =
282 isAnnexKAvailable(IsAnnexKAvailable, PP, getLangOpts());
283 StringRef FunctionName = FuncDecl->getName();
284
285 if (Custom) {
286 for (const auto &Entry : CustomFunctions) {
287 if (Entry.Pattern.match(*FuncDecl)) {
288 StringRef Reason =
289 Entry.Reason.empty() ? "is marked as unsafe" : Entry.Reason.c_str();
290
291 // Omit the replacement, when a fully-custom reason is given.
292 if (Reason.consume_front(">")) {
293 diag(SourceExpr->getExprLoc(), "function %0 %1")
294 << FuncDecl << Reason.trim() << SourceExpr->getSourceRange();
295 // Do not recommend a replacement when it is not present.
296 } else if (Entry.Replacement.empty()) {
297 diag(SourceExpr->getExprLoc(),
298 "function %0 %1; it should not be used")
299 << FuncDecl << Reason << Entry.Replacement
300 << SourceExpr->getSourceRange();
301 // Otherwise, emit the replacement.
302 } else {
303 diag(SourceExpr->getExprLoc(),
304 "function %0 %1; '%2' should be used instead")
305 << FuncDecl << Reason << Entry.Replacement
306 << SourceExpr->getSourceRange();
307 }
308
309 return;
310 }
311 }
312
313 llvm_unreachable("No custom function was matched.");
314 return;
315 }
316
317 const std::optional<std::string> ReplacementFunctionName =
318 [&]() -> std::optional<std::string> {
319 if (AnnexK) {
320 if (AnnexKIsAvailable)
321 return getAnnexKReplacementFor(FunctionName);
322 return std::nullopt;
323 }
324
325 if (Normal)
326 return getReplacementFor(FunctionName, AnnexKIsAvailable).str();
327
328 if (Additional)
329 return getReplacementForAdditional(FunctionName, AnnexKIsAvailable).str();
330
331 llvm_unreachable("Unhandled match category");
332 }();
333 if (!ReplacementFunctionName)
334 return;
335
336 diag(SourceExpr->getExprLoc(), "function %0 %1; '%2' should be used instead")
337 << FuncDecl << getRationaleFor(FunctionName)
338 << ReplacementFunctionName.value() << SourceExpr->getSourceRange();
339}
340
342 const SourceManager &SM, Preprocessor *PP,
343 Preprocessor * /*ModuleExpanderPP*/) {
344 this->PP = PP;
345}
346
348 this->PP = nullptr;
349 IsAnnexKAvailable.reset();
350}
351
352} // namespace clang::tidy::bugprone
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
DiagnosticBuilder configurationDiag(StringRef Message, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Report any errors to do with reading the configuration using this method.
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
UnsafeFunctionsCheck(StringRef Name, ClangTidyContext *Context)
void registerMatchers(ast_matchers::MatchFinder *Finder) override
static constexpr StringRef OptionNameReportMoreUnsafeFunctions
static StringRef getReplacementForAdditional(StringRef FunctionName, bool IsAnnexKAvailable)
static constexpr StringRef FunctionNamesId
static StringRef getRationaleFor(StringRef FunctionName)
static constexpr StringRef OptionNameCustomFunctions
static bool isAnnexKAvailable(std::optional< bool > &CacheVar, Preprocessor *PP, const LangOptions &LO)
Calculates whether Annex K is available for the current translation unit based on the macro definitio...
static std::optional< std::string > getAnnexKReplacementFor(StringRef FunctionName)
static StringRef getReplacementFor(StringRef FunctionName, bool IsAnnexKAvailable)
static constexpr StringRef AdditionalFunctionNamesId
static std::vector< UnsafeFunctionsCheck::CheckedFunction > parseCheckedFunctions(StringRef Option, ClangTidyContext *Context)
static constexpr StringRef CustomFunctionNamesId
static constexpr StringRef DeclRefId
static constexpr StringRef FunctionNamesWithAnnexKReplacementId
static constexpr StringRef OptionNameReportDefaultFunctions
static std::string serializeCheckedFunctions(const std::vector< UnsafeFunctionsCheck::CheckedFunction > &Functions)
inline ::clang::ast_matchers::internal::Matcher< NamedDecl > matchesAnyListedRegexName(llvm::ArrayRef< StringRef > NameList)
std::vector< StringRef > parseStringList(StringRef Option)
Parse a semicolon separated list of strings.
Some operations such as code completion produce a set of candidates.
Definition Generators.h:150
llvm::StringMap< ClangTidyValue > OptionMap
static constexpr const char FuncDecl[]