11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Analysis/AnnexKDetection.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")
64 .Case(
"get_temporary_buffer",
"operator new[]");
68 bool IsAnnexKAvailable) {
69 if (IsAnnexKAvailable) {
71 StringRef AnnexKReplacementFunction = StringSwitch<StringRef>(FunctionName)
72 .Case(
"bcopy",
"memcpy_s")
73 .Case(
"bzero",
"memset_s")
76 if (!AnnexKReplacementFunction.empty())
77 return AnnexKReplacementFunction;
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");
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");
112 const LangOptions &LO) {
113 if (CacheVar.has_value())
116 CacheVar = analysis::isAnnexKAvailable(
PP, LO);
117 return CacheVar.value();
120static std::vector<UnsafeFunctionsCheck::CheckedFunction>
122 const std::vector<StringRef> Functions =
124 std::vector<UnsafeFunctionsCheck::CheckedFunction> Result;
125 Result.reserve(Functions.size());
127 for (
const StringRef Function : Functions) {
128 if (Function.empty())
131 const auto [Name, Rest] = Function.split(
',');
132 const auto [Replacement, Reason] = Rest.split(
',');
134 if (Name.trim().empty()) {
136 "expected the name of an unsafe function")
144 Replacement.trim().str(), Reason.trim().str()});
151 const std::vector<UnsafeFunctionsCheck::CheckedFunction> &Functions) {
152 std::vector<std::string> Result;
153 Result.reserve(Functions.size());
155 for (
const auto &
Entry : Functions)
156 if (
Entry.Reason.empty())
157 Result.push_back(
Entry.Name +
"," +
Entry.Replacement);
159 Result.push_back(
Entry.Name +
"," +
Entry.Replacement +
"," +
162 return llvm::join(Result,
";");
170 ReportDefaultFunctions(
172 ReportMoreUnsafeFunctions(
180 ReportMoreUnsafeFunctions);
184 if (ReportDefaultFunctions) {
185 if (getLangOpts().C11) {
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");
201 declRefExpr(to(functionDecl(FunctionNamesWithAnnexKReplacementMatcher)
208 auto FunctionNamesMatcher =
209 hasAnyName(
"::asctime",
"asctime_r",
"::gets",
"::rewind",
"::setbuf",
210 "::std::get_temporary_buffer");
217 if (ReportMoreUnsafeFunctions) {
219 auto AdditionalFunctionNamesMatcher =
220 hasAnyName(
"::bcmp",
"::bcopy",
"::bzero",
"::getpw",
"::vfork");
222 declRefExpr(to(functionDecl(AdditionalFunctionNamesMatcher)
229 if (!CustomFunctions.empty()) {
230 std::vector<llvm::StringRef> FunctionNames;
231 FunctionNames.reserve(CustomFunctions.size());
233 for (
const auto &
Entry : CustomFunctions)
234 FunctionNames.emplace_back(
Entry.Name);
236 auto CustomFunctionsMatcher =
239 Finder->addMatcher(declRefExpr(to(functionDecl(CustomFunctionsMatcher)
245 Finder->addMatcher(memberExpr(member(functionDecl(CustomFunctionsMatcher)
253 const Expr *SourceExpr =
nullptr;
254 const FunctionDecl *
FuncDecl =
nullptr;
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)) {
262 FuncDecl = cast<FunctionDecl>(Member->getMemberDecl());
264 llvm_unreachable(
"No valid matched node in check()");
268 assert(SourceExpr &&
FuncDecl &&
"No valid matched node in check()");
271 const auto *AnnexK = Result.Nodes.getNodeAs<FunctionDecl>(
273 const auto *Normal = Result.Nodes.getNodeAs<FunctionDecl>(
FunctionNamesId);
274 const auto *Additional =
278 assert((AnnexK || Normal || Additional || Custom) &&
279 "No valid match category.");
281 bool AnnexKIsAvailable =
283 StringRef FunctionName =
FuncDecl->getName();
286 for (
const auto &
Entry : CustomFunctions) {
289 Entry.Reason.empty() ?
"is marked as unsafe" :
Entry.Reason.c_str();
292 if (Reason.consume_front(
">")) {
293 diag(SourceExpr->getExprLoc(),
"function %0 %1")
294 <<
FuncDecl << Reason.trim() << SourceExpr->getSourceRange();
296 }
else if (
Entry.Replacement.empty()) {
297 diag(SourceExpr->getExprLoc(),
298 "function %0 %1; it should not be used")
300 << SourceExpr->getSourceRange();
303 diag(SourceExpr->getExprLoc(),
304 "function %0 %1; '%2' should be used instead")
306 << SourceExpr->getSourceRange();
313 llvm_unreachable(
"No custom function was matched.");
317 const std::optional<std::string> ReplacementFunctionName =
318 [&]() -> std::optional<std::string> {
320 if (AnnexKIsAvailable)
331 llvm_unreachable(
"Unhandled match category");
333 if (!ReplacementFunctionName)
336 diag(SourceExpr->getExprLoc(),
"function %0 %1; '%2' should be used instead")
338 << ReplacementFunctionName.value() << SourceExpr->getSourceRange();
342 const SourceManager &SM, Preprocessor *PP,
349 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[]