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<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)
257 const FunctionDecl *
FuncDecl, StringRef Replacement,
259 if (Reason.consume_front(
">")) {
260 Check.diag(SourceExpr->getExprLoc(),
"function %0 %1")
261 <<
FuncDecl << Reason.trim() << SourceExpr->getSourceRange();
264 if (Replacement.empty()) {
265 Check.diag(SourceExpr->getExprLoc(),
266 "function %0 %1; it should not be used")
267 <<
FuncDecl << Reason << SourceExpr->getSourceRange();
270 Check.diag(SourceExpr->getExprLoc(),
271 "function %0 %1; '%2' should be used instead")
272 <<
FuncDecl << Reason << Replacement << SourceExpr->getSourceRange();
276 const Expr *SourceExpr =
nullptr;
277 const FunctionDecl *
FuncDecl =
nullptr;
279 if (
const auto *DeclRef = Result.Nodes.getNodeAs<DeclRefExpr>(
DeclRefId)) {
280 SourceExpr = DeclRef;
281 FuncDecl = cast<FunctionDecl>(DeclRef->getDecl());
282 }
else if (
const auto *Member =
283 Result.Nodes.getNodeAs<MemberExpr>(
DeclRefId)) {
285 FuncDecl = cast<FunctionDecl>(Member->getMemberDecl());
287 llvm_unreachable(
"No valid matched node in check()");
291 assert(SourceExpr &&
FuncDecl &&
"No valid matched node in check()");
294 const auto *AnnexK = Result.Nodes.getNodeAs<FunctionDecl>(
296 const auto *Normal = Result.Nodes.getNodeAs<FunctionDecl>(
FunctionNamesId);
297 const auto *Additional =
301 assert((AnnexK || Normal || Additional || Custom) &&
302 "No valid match category.");
304 bool AnnexKIsAvailable =
306 StringRef FunctionName =
FuncDecl->getName();
308 std::string Replacement;
313 for (
const auto &
Entry : CustomFunctions) {
315 MatchedEntry = &
Entry;
320 llvm_unreachable(
"No custom function was matched.");
324 Reason = MatchedEntry->
Reason.empty() ?
"is marked as unsafe"
327 const std::optional<std::string> ReplacementFunctionName =
328 [&]() -> std::optional<std::string> {
330 if (AnnexKIsAvailable)
342 llvm_unreachable(
"Unhandled match category");
344 if (!ReplacementFunctionName)
347 Replacement = *ReplacementFunctionName;
355 const SourceManager &SM, Preprocessor *PP,
362 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 void emitDiag(ClangTidyCheck &Check, const Expr *SourceExpr, const FunctionDecl *FuncDecl, StringRef Replacement, StringRef Reason)
A Reason prefixed with > produces a fully-custom message and / suppresses the Replacement suffix; an ...
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[]