[clang-tools-extra] [clang-tidy] New bugprone-unsafe-format-string check (PR #168691)
Daniel Krupp via cfe-commits
cfe-commits at lists.llvm.org
Wed Nov 26 11:18:56 PST 2025
================
@@ -0,0 +1,153 @@
+//===--- UnsafeFormatStringCheck.cpp - clang-tidy -----------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "UnsafeFormatStringCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/Support/ConvertUTF.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+UnsafeFormatStringCheck::UnsafeFormatStringCheck(StringRef Name,
+ ClangTidyContext *Context)
+ : ClangTidyCheck(Name, Context) {}
+
+void UnsafeFormatStringCheck::registerMatchers(MatchFinder *Finder) {
+ // Matches sprintf and scanf family functions in std namespace in C++ and
+ // globally in C.
+ auto VulnerableFunctions =
+ hasAnyName("sprintf", "vsprintf", "scanf", "fscanf", "sscanf", "vscanf",
+ "vfscanf", "vsscanf", "wscanf", "fwscanf", "swscanf",
+ "vwscanf", "vfwscanf", "vswscanf");
----------------
dkrupp wrote:
These functions are now matched against function int std namespace and globally.
I can imagine introducing 2 config variables:
CustomPrintfFunctions
CustomScanfFunctions
These would be a list of regex definable functions like in https://clang.llvm.org/extra/clang-tidy/checks/bugprone/unsafe-functions.html#cmdoption-arg-CustomFunctions
CustomPrintFunctions: "mysprintf, 0; mylogger, 1;"
Where the first argument is a regex matching the function name and the second parameter would be indicating which parameter contains the format string (0 is the first parameter).
We need to distinguish between scanf like and printf like functions, as their format strings behave differently.
Is that what you mean?
Should this be added in this PR or as a later improvement in a follow-up PR?
https://github.com/llvm/llvm-project/pull/168691
More information about the cfe-commits
mailing list