11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Lex/PPCallbacks.h"
14#include "clang/Lex/Preprocessor.h"
24 "ReportDefaultFunctions";
26 "ReportMoreUnsafeFunctions";
29 "FunctionNamesWithAnnexKReplacement";
32 "AdditionalFunctionsNames";
36static std::optional<std::string>
38 return StringSwitch<std::string>(FunctionName)
39 .Case(
"strlen",
"strnlen_s")
40 .Case(
"wcslen",
"wcsnlen_s")
41 .Default((Twine{FunctionName} +
"_s").str());
45 bool IsAnnexKAvailable) {
46 if (IsAnnexKAvailable) {
48 StringRef AnnexKReplacementFunction =
49 StringSwitch<StringRef>(FunctionName)
50 .Cases({
"asctime",
"asctime_r"},
"asctime_s")
51 .Case(
"gets",
"gets_s")
53 if (!AnnexKReplacementFunction.empty())
54 return AnnexKReplacementFunction;
59 return StringSwitch<StringRef>(FunctionName)
60 .Cases({
"asctime",
"asctime_r"},
"strftime")
61 .Case(
"gets",
"fgets")
62 .Case(
"rewind",
"fseek")
63 .Case(
"setbuf",
"setvbuf");
67 bool IsAnnexKAvailable) {
68 if (IsAnnexKAvailable) {
70 StringRef AnnexKReplacementFunction = StringSwitch<StringRef>(FunctionName)
71 .Case(
"bcopy",
"memcpy_s")
72 .Case(
"bzero",
"memset_s")
75 if (!AnnexKReplacementFunction.empty())
76 return AnnexKReplacementFunction;
79 return StringSwitch<StringRef>(FunctionName)
80 .Case(
"bcmp",
"memcmp")
81 .Case(
"bcopy",
"memcpy")
82 .Case(
"bzero",
"memset")
83 .Case(
"getpw",
"getpwuid")
84 .Case(
"vfork",
"posix_spawn");
90 return StringSwitch<StringRef>(FunctionName)
91 .Cases({
"asctime",
"asctime_r",
"ctime"},
92 "is not bounds-checking and non-reentrant")
93 .Cases({
"bcmp",
"bcopy",
"bzero"},
"is deprecated")
94 .Cases({
"fopen",
"freopen"},
"has no exclusive access to the opened file")
95 .Case(
"gets",
"is insecure, was deprecated and removed in C11 and C++14")
96 .Case(
"getpw",
"is dangerous as it may overflow the provided buffer")
97 .Cases({
"rewind",
"setbuf"},
"has no error detection")
98 .Case(
"vfork",
"is insecure as it can lead to denial of service "
99 "situations in the parent process")
100 .Default(
"is not bounds-checking");
108 const LangOptions &LO) {
109 if (CacheVar.has_value())
114 return (CacheVar =
false).value();
116 assert(
PP &&
"No Preprocessor registered.");
118 if (!
PP->isMacroDefined(
"__STDC_LIB_EXT1__") ||
119 !
PP->isMacroDefined(
"__STDC_WANT_LIB_EXT1__"))
120 return (CacheVar =
false).value();
123 PP->getMacroInfo(
PP->getIdentifierInfo(
"__STDC_WANT_LIB_EXT1__"));
124 if (!MI || MI->tokens_empty())
125 return (CacheVar =
false).value();
127 const Token &T = MI->tokens().back();
128 if (!T.isLiteral() || !T.getLiteralData())
129 return (CacheVar =
false).value();
131 CacheVar = StringRef(T.getLiteralData(), T.getLength()) ==
"1";
132 return CacheVar.value();
135static std::vector<UnsafeFunctionsCheck::CheckedFunction>
137 const std::vector<StringRef> Functions =
139 std::vector<UnsafeFunctionsCheck::CheckedFunction> Result;
140 Result.reserve(Functions.size());
142 for (
const StringRef Function : Functions) {
143 if (Function.empty())
146 const auto [Name, Rest] = Function.split(
',');
147 const auto [Replacement, Reason] = Rest.split(
',');
149 if (Name.trim().empty()) {
151 "expected the name of an unsafe function")
159 Replacement.trim().str(), Reason.trim().str()});
166 const std::vector<UnsafeFunctionsCheck::CheckedFunction> &Functions) {
167 std::vector<std::string> Result;
168 Result.reserve(Functions.size());
170 for (
const auto &
Entry : Functions) {
171 if (
Entry.Reason.empty())
172 Result.push_back(
Entry.Name +
"," +
Entry.Replacement);
174 Result.push_back(
Entry.Name +
"," +
Entry.Replacement +
"," +
178 return llvm::join(Result,
";");
186 ReportDefaultFunctions(
188 ReportMoreUnsafeFunctions(
196 ReportMoreUnsafeFunctions);
200 if (ReportDefaultFunctions) {
201 if (getLangOpts().C11) {
203 auto FunctionNamesWithAnnexKReplacementMatcher = hasAnyName(
204 "::bsearch",
"::ctime",
"::fopen",
"::fprintf",
"::freopen",
205 "::fscanf",
"::fwprintf",
"::fwscanf",
"::getenv",
"::gmtime",
206 "::localtime",
"::mbsrtowcs",
"::mbstowcs",
"::memcpy",
"::memmove",
207 "::memset",
"::printf",
"::qsort",
"::scanf",
"::snprintf",
208 "::sprintf",
"::sscanf",
"::strcat",
"::strcpy",
"::strerror",
209 "::strlen",
"::strncat",
"::strncpy",
"::strtok",
"::swprintf",
210 "::swscanf",
"::vfprintf",
"::vfscanf",
"::vfwprintf",
"::vfwscanf",
211 "::vprintf",
"::vscanf",
"::vsnprintf",
"::vsprintf",
"::vsscanf",
212 "::vswprintf",
"::vswscanf",
"::vwprintf",
"::vwscanf",
"::wcrtomb",
213 "::wcscat",
"::wcscpy",
"::wcslen",
"::wcsncat",
"::wcsncpy",
214 "::wcsrtombs",
"::wcstok",
"::wcstombs",
"::wctomb",
"::wmemcpy",
215 "::wmemmove",
"::wprintf",
"::wscanf");
217 declRefExpr(to(functionDecl(FunctionNamesWithAnnexKReplacementMatcher)
224 auto FunctionNamesMatcher =
225 hasAnyName(
"::asctime",
"asctime_r",
"::gets",
"::rewind",
"::setbuf");
232 if (ReportMoreUnsafeFunctions) {
234 auto AdditionalFunctionNamesMatcher =
235 hasAnyName(
"::bcmp",
"::bcopy",
"::bzero",
"::getpw",
"::vfork");
237 declRefExpr(to(functionDecl(AdditionalFunctionNamesMatcher)
244 if (!CustomFunctions.empty()) {
245 std::vector<llvm::StringRef> FunctionNames;
246 FunctionNames.reserve(CustomFunctions.size());
248 for (
const auto &
Entry : CustomFunctions)
249 FunctionNames.emplace_back(
Entry.Name);
253 Finder->addMatcher(declRefExpr(to(functionDecl(CustomFunctionsMatcher)
259 Finder->addMatcher(memberExpr(member(functionDecl(CustomFunctionsMatcher)
267 const Expr *SourceExpr =
nullptr;
268 const FunctionDecl *
FuncDecl =
nullptr;
270 if (
const auto *DeclRef = Result.Nodes.getNodeAs<DeclRefExpr>(
DeclRefId)) {
271 SourceExpr = DeclRef;
272 FuncDecl = cast<FunctionDecl>(DeclRef->getDecl());
273 }
else if (
const auto *Member =
274 Result.Nodes.getNodeAs<MemberExpr>(
DeclRefId)) {
276 FuncDecl = cast<FunctionDecl>(Member->getMemberDecl());
278 llvm_unreachable(
"No valid matched node in check()");
282 assert(SourceExpr &&
FuncDecl &&
"No valid matched node in check()");
285 const auto *AnnexK = Result.Nodes.getNodeAs<FunctionDecl>(
287 const auto *Normal = Result.Nodes.getNodeAs<FunctionDecl>(
FunctionNamesId);
288 const auto *Additional =
292 assert((AnnexK || Normal || Additional || Custom) &&
293 "No valid match category.");
295 bool AnnexKIsAvailable =
297 StringRef FunctionName =
FuncDecl->getName();
300 for (
const auto &
Entry : CustomFunctions) {
303 Entry.Reason.empty() ?
"is marked as unsafe" :
Entry.Reason.c_str();
306 if (Reason.consume_front(
">")) {
307 diag(SourceExpr->getExprLoc(),
"function %0 %1")
308 <<
FuncDecl << Reason.trim() << SourceExpr->getSourceRange();
310 }
else if (
Entry.Replacement.empty()) {
311 diag(SourceExpr->getExprLoc(),
312 "function %0 %1; it should not be used")
314 << SourceExpr->getSourceRange();
317 diag(SourceExpr->getExprLoc(),
318 "function %0 %1; '%2' should be used instead")
320 << SourceExpr->getSourceRange();
327 llvm_unreachable(
"No custom function was matched.");
331 const std::optional<std::string> ReplacementFunctionName =
332 [&]() -> std::optional<std::string> {
334 if (AnnexKIsAvailable)
345 llvm_unreachable(
"Unhandled match category");
347 if (!ReplacementFunctionName)
350 diag(SourceExpr->getExprLoc(),
"function %0 %1; '%2' should be used instead")
352 << ReplacementFunctionName.value() << SourceExpr->getSourceRange();
356 const SourceManager &SM, Preprocessor *PP,
363 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 > matchesAnyListedName(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[]