11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Analysis/AnnexKDetection.h"
14#include "clang/Lex/PPCallbacks.h"
15#include "clang/Lex/Preprocessor.h"
25 "ReportDefaultFunctions";
27 "ReportMoreUnsafeFunctions";
30 "FunctionNamesWithAnnexKReplacement";
33 "AdditionalFunctionsNames";
37static std::optional<std::string>
39 return StringSwitch<std::string>(FunctionName)
40 .Case(
"strlen",
"strnlen_s")
41 .Case(
"wcslen",
"wcsnlen_s")
42 .Default((Twine{FunctionName} +
"_s").str());
46 bool IsAnnexKAvailable) {
47 if (IsAnnexKAvailable) {
49 StringRef AnnexKReplacementFunction =
50 StringSwitch<StringRef>(FunctionName)
51 .Cases({
"asctime",
"asctime_r"},
"asctime_s")
52 .Case(
"gets",
"gets_s")
54 if (!AnnexKReplacementFunction.empty())
55 return AnnexKReplacementFunction;
60 return StringSwitch<StringRef>(FunctionName)
61 .Cases({
"asctime",
"asctime_r"},
"strftime")
62 .Case(
"gets",
"fgets")
63 .Case(
"rewind",
"fseek")
64 .Case(
"setbuf",
"setvbuf")
65 .Case(
"get_temporary_buffer",
"operator new[]");
69 bool IsAnnexKAvailable) {
70 if (IsAnnexKAvailable) {
72 StringRef AnnexKReplacementFunction = StringSwitch<StringRef>(FunctionName)
73 .Case(
"bcopy",
"memcpy_s")
74 .Case(
"bzero",
"memset_s")
77 if (!AnnexKReplacementFunction.empty())
78 return AnnexKReplacementFunction;
81 return StringSwitch<StringRef>(FunctionName)
82 .Case(
"bcmp",
"memcmp")
83 .Case(
"bcopy",
"memcpy")
84 .Case(
"bzero",
"memset")
85 .Case(
"getpw",
"getpwuid")
86 .Case(
"vfork",
"posix_spawn");
92 return StringSwitch<StringRef>(FunctionName)
93 .Cases({
"asctime",
"asctime_r",
"ctime"},
94 "is not bounds-checking and non-reentrant")
95 .Cases({
"bcmp",
"bcopy",
"bzero"},
"is deprecated")
96 .Cases({
"fopen",
"freopen"},
"has no exclusive access to the opened file")
97 .Case(
"gets",
"is insecure, was deprecated and removed in C11 and C++14")
98 .Case(
"getpw",
"is dangerous as it may overflow the provided buffer")
99 .Cases({
"rewind",
"setbuf"},
"has no error detection")
100 .Case(
"vfork",
"is insecure as it can lead to denial of service "
101 "situations in the parent process")
102 .Case(
"get_temporary_buffer",
"returns uninitialized memory without "
103 "performance advantages, was deprecated in "
104 "C++17 and removed in C++20")
105 .Default(
"is not bounds-checking");
113 const LangOptions &LO) {
114 if (CacheVar.has_value())
117 CacheVar = analysis::isAnnexKAvailable(
PP, LO);
118 return CacheVar.value();
121static std::vector<UnsafeFunctionsCheck::CheckedFunction>
123 const std::vector<StringRef> Functions =
125 std::vector<UnsafeFunctionsCheck::CheckedFunction> Result;
126 Result.reserve(Functions.size());
128 for (
const StringRef Function : Functions) {
129 if (Function.empty())
132 const auto [Name, Rest] = Function.split(
',');
133 const auto [Replacement, Reason] = Rest.split(
',');
135 if (Name.trim().empty()) {
137 "expected the name of an unsafe function")
145 Replacement.trim().str(), Reason.trim().str()});
152 const std::vector<UnsafeFunctionsCheck::CheckedFunction> &Functions) {
153 std::vector<std::string> Result;
154 Result.reserve(Functions.size());
156 for (
const auto &
Entry : Functions)
157 if (
Entry.Reason.empty())
158 Result.push_back(
Entry.Name +
"," +
Entry.Replacement);
160 Result.push_back(
Entry.Name +
"," +
Entry.Replacement +
"," +
163 return llvm::join(Result,
";");
171 ReportDefaultFunctions(
173 ReportMoreUnsafeFunctions(
181 ReportMoreUnsafeFunctions);
185 if (ReportDefaultFunctions) {
186 if (getLangOpts().C11) {
188 auto FunctionNamesWithAnnexKReplacementMatcher = hasAnyName(
189 "::bsearch",
"::ctime",
"::fopen",
"::fprintf",
"::freopen",
190 "::fscanf",
"::fwprintf",
"::fwscanf",
"::getenv",
"::gmtime",
191 "::localtime",
"::mbsrtowcs",
"::mbstowcs",
"::memcpy",
"::memmove",
192 "::memset",
"::printf",
"::qsort",
"::scanf",
"::snprintf",
193 "::sprintf",
"::sscanf",
"::strcat",
"::strcpy",
"::strerror",
194 "::strlen",
"::strncat",
"::strncpy",
"::strtok",
"::swprintf",
195 "::swscanf",
"::vfprintf",
"::vfscanf",
"::vfwprintf",
"::vfwscanf",
196 "::vprintf",
"::vscanf",
"::vsnprintf",
"::vsprintf",
"::vsscanf",
197 "::vswprintf",
"::vswscanf",
"::vwprintf",
"::vwscanf",
"::wcrtomb",
198 "::wcscat",
"::wcscpy",
"::wcslen",
"::wcsncat",
"::wcsncpy",
199 "::wcsrtombs",
"::wcstok",
"::wcstombs",
"::wctomb",
"::wmemcpy",
200 "::wmemmove",
"::wprintf",
"::wscanf");
202 declRefExpr(to(functionDecl(FunctionNamesWithAnnexKReplacementMatcher)
209 auto FunctionNamesMatcher =
210 hasAnyName(
"::asctime",
"asctime_r",
"::gets",
"::rewind",
"::setbuf",
211 "::std::get_temporary_buffer");
218 if (ReportMoreUnsafeFunctions) {
220 auto AdditionalFunctionNamesMatcher =
221 hasAnyName(
"::bcmp",
"::bcopy",
"::bzero",
"::getpw",
"::vfork");
223 declRefExpr(to(functionDecl(AdditionalFunctionNamesMatcher)
230 if (!CustomFunctions.empty()) {
231 std::vector<llvm::StringRef> FunctionNames;
232 FunctionNames.reserve(CustomFunctions.size());
234 for (
const auto &
Entry : CustomFunctions)
235 FunctionNames.emplace_back(
Entry.Name);
237 auto CustomFunctionsMatcher =
240 Finder->addMatcher(declRefExpr(to(functionDecl(CustomFunctionsMatcher)
246 Finder->addMatcher(memberExpr(member(functionDecl(CustomFunctionsMatcher)
254 const Expr *SourceExpr =
nullptr;
255 const FunctionDecl *
FuncDecl =
nullptr;
257 if (
const auto *DeclRef = Result.Nodes.getNodeAs<DeclRefExpr>(
DeclRefId)) {
258 SourceExpr = DeclRef;
259 FuncDecl = cast<FunctionDecl>(DeclRef->getDecl());
260 }
else if (
const auto *Member =
261 Result.Nodes.getNodeAs<MemberExpr>(
DeclRefId)) {
263 FuncDecl = cast<FunctionDecl>(Member->getMemberDecl());
265 llvm_unreachable(
"No valid matched node in check()");
269 assert(SourceExpr &&
FuncDecl &&
"No valid matched node in check()");
272 const auto *AnnexK = Result.Nodes.getNodeAs<FunctionDecl>(
274 const auto *Normal = Result.Nodes.getNodeAs<FunctionDecl>(
FunctionNamesId);
275 const auto *Additional =
279 assert((AnnexK || Normal || Additional || Custom) &&
280 "No valid match category.");
282 bool AnnexKIsAvailable =
284 StringRef FunctionName =
FuncDecl->getName();
287 for (
const auto &
Entry : CustomFunctions) {
290 Entry.Reason.empty() ?
"is marked as unsafe" :
Entry.Reason.c_str();
293 if (Reason.consume_front(
">")) {
294 diag(SourceExpr->getExprLoc(),
"function %0 %1")
295 <<
FuncDecl << Reason.trim() << SourceExpr->getSourceRange();
297 }
else if (
Entry.Replacement.empty()) {
298 diag(SourceExpr->getExprLoc(),
299 "function %0 %1; it should not be used")
301 << SourceExpr->getSourceRange();
304 diag(SourceExpr->getExprLoc(),
305 "function %0 %1; '%2' should be used instead")
307 << SourceExpr->getSourceRange();
314 llvm_unreachable(
"No custom function was matched.");
318 const std::optional<std::string> ReplacementFunctionName =
319 [&]() -> std::optional<std::string> {
321 if (AnnexKIsAvailable)
332 llvm_unreachable(
"Unhandled match category");
334 if (!ReplacementFunctionName)
337 diag(SourceExpr->getExprLoc(),
"function %0 %1; '%2' should be used instead")
339 << ReplacementFunctionName.value() << SourceExpr->getSourceRange();
343 const SourceManager &SM, Preprocessor *PP,
350 IsAnnexKAvailable.reset();
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
void onEndOfTranslationUnit() 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.
llvm::StringMap< ClangTidyValue > OptionMap
static constexpr const char FuncDecl[]