[clang] 2ec79af - [Sema] check InitListExpr format strings like {"foo"}
Yingchi Long via cfe-commits
cfe-commits at lists.llvm.org
Tue Nov 22 12:59:45 PST 2022
Author: Yingchi Long
Date: 2022-11-23T04:58:19+08:00
New Revision: 2ec79afd89932f0d5a9c44050e7b6dc08ff51699
URL: https://github.com/llvm/llvm-project/commit/2ec79afd89932f0d5a9c44050e7b6dc08ff51699
DIFF: https://github.com/llvm/llvm-project/commit/2ec79afd89932f0d5a9c44050e7b6dc08ff51699.diff
LOG: [Sema] check InitListExpr format strings like {"foo"}
Adds InitListExpr case in format string checks.
e.g.
int sprintf(char *__restrict, const char * __restrict, ...);
int foo()
{
char data[100];
constexpr const char* fmt2{"%d"}; // no-warning
sprintf(data, fmt2, 123);
}
Fixes: https://github.com/llvm/llvm-project/issues/58900
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D137839
Added:
Modified:
clang/lib/Sema/SemaChecking.cpp
clang/test/SemaCXX/format-strings.cpp
Removed:
################################################################################
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 75bd0ef57bcc0..7b6279baf8eed 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -8585,6 +8585,15 @@ checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
return SLCT_UncheckedLiteral;
switch (E->getStmtClass()) {
+ case Stmt::InitListExprClass:
+ // Handle expressions like {"foobar"}.
+ if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
+ return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg,
+ Type, CallType, /*InFunctionCall*/ false,
+ CheckedVarArgs, UncoveredArg, Offset,
+ IgnoreStringsWithoutSpecifiers);
+ }
+ return SLCT_NotALiteral;
case Stmt::BinaryConditionalOperatorClass:
case Stmt::ConditionalOperatorClass: {
// The expression is a literal if both sub-expressions were, and it was
diff --git a/clang/test/SemaCXX/format-strings.cpp b/clang/test/SemaCXX/format-strings.cpp
index 2378eea9b3c07..2def986bdf9f6 100644
--- a/clang/test/SemaCXX/format-strings.cpp
+++ b/clang/test/SemaCXX/format-strings.cpp
@@ -203,6 +203,12 @@ void f() {
printf(string_linebreak(), 1, 2, 3, 4); // expected-warning {{format specifies type 'char *' but the argument has type 'int'}}
printf(not_literal(), 1, 2, 3, 4); // expected-warning {{format string is not a string literal}}
printf(wrap_constexpr(), 1, 2); // expected-warning {{format specifies type 'char *' but the argument has type 'int'}}
+
+ constexpr const char *fmt {"%d%d"};
+ printf(fmt, 1, 1); // no-warning
+
+ constexpr const char *fmt2 {"%d"}; // expected-note{{format string is defined here}}
+ printf(fmt2, "oops"); // expected-warning{{format specifies type 'int' but the argument has type}}
}
More information about the cfe-commits
mailing list