Skip to content

Commit c710118

Browse files
[clang] Implement __attribute__((format_matches)) (#116708)
This implements ``__attribute__((format_matches))``, as described in the RFC: https://discourse.llvm.org/t/rfc-format-attribute-attribute-format-like/83076 The ``format`` attribute only allows the compiler to check that a format string matches its arguments. If the format string is passed independently of its arguments, there is no way to have the compiler check it. ``format_matches(flavor, fmtidx, example)`` allows the compiler to check format strings against the ``example`` format string instead of against format arguments. See the changes to AttrDocs.td in this diff for more information. Implementation-wise, this change subclasses CheckPrintfHandler and CheckScanfHandler to allow them to collect specifiers into arrays, and implements comparing that two specifiers are equivalent. `checkFormatStringExpr` gets a new `ReferenceFormatString` argument that is piped down when calling a function with the `format_matches` attribute (and is `nullptr` otherwise); this is the string that the actual format string is compared against. Although this change does not enable -Wformat-nonliteral by default, IMO, all the pieces are now in place such that it could be.
1 parent 253e116 commit c710118

File tree

14 files changed

+1411
-180
lines changed

14 files changed

+1411
-180
lines changed

clang/docs/ReleaseNotes.rst

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,50 @@ Attribute Changes in Clang
132132
This forces the global to be considered small or large in regards to the
133133
x86-64 code model, regardless of the code model specified for the compilation.
134134

135+
- There is a new ``format_matches`` attribute to complement the existing
136+
``format`` attribute. ``format_matches`` allows the compiler to verify that
137+
a format string argument is equivalent to a reference format string: it is
138+
useful when a function accepts a format string without its accompanying
139+
arguments to format. For instance:
140+
141+
.. code-block:: c
142+
143+
static int status_code;
144+
static const char *status_string;
145+
146+
void print_status(const char *fmt) {
147+
fprintf(stderr, fmt, status_code, status_string);
148+
// ^ warning: format string is not a string literal [-Wformat-nonliteral]
149+
}
150+
151+
void stuff(void) {
152+
print_status("%s (%#08x)\n");
153+
// order of %s and %x is swapped but there is no diagnostic
154+
}
155+
156+
Before the introducion of ``format_matches``, this code cannot be verified
157+
at compile-time. ``format_matches`` plugs that hole:
158+
159+
.. code-block:: c
160+
161+
__attribute__((format_matches(printf, 1, "%x %s")))
162+
void print_status(const char *fmt) {
163+
fprintf(stderr, fmt, status_code, status_string);
164+
// ^ `fmt` verified as if it was "%x %s" here; no longer triggers
165+
// -Wformat-nonliteral, would warn if arguments did not match "%x %s"
166+
}
167+
168+
void stuff(void) {
169+
print_status("%s (%#08x)\n");
170+
// warning: format specifier 's' is incompatible with 'x'
171+
// warning: format specifier 'x' is incompatible with 's'
172+
}
173+
174+
Like with ``format``, the first argument is the format string flavor and the
175+
second argument is the index of the format string parameter.
176+
``format_matches`` accepts an example valid format string as its third
177+
argument. For more information, see the Clang attributes documentation.
178+
135179
Improvements to Clang's diagnostics
136180
-----------------------------------
137181

clang/include/clang/AST/FormatString.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ class ArgType {
292292
};
293293

294294
private:
295-
const Kind K;
295+
Kind K;
296296
QualType T;
297297
const char *Name = nullptr;
298298
bool Ptr = false;
@@ -338,6 +338,7 @@ class ArgType {
338338
}
339339

340340
MatchKind matchesType(ASTContext &C, QualType argTy) const;
341+
MatchKind matchesArgType(ASTContext &C, const ArgType &other) const;
341342

342343
QualType getRepresentativeType(ASTContext &C) const;
343344

clang/include/clang/Basic/Attr.td

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1834,6 +1834,16 @@ def Format : InheritableAttr {
18341834
let Documentation = [FormatDocs];
18351835
}
18361836

1837+
def FormatMatches : InheritableAttr {
1838+
let Spellings = [GCC<"format_matches">];
1839+
let Args = [IdentifierArgument<"Type">, IntArgument<"FormatIdx">, ExprArgument<"ExpectedFormat">];
1840+
let AdditionalMembers = [{
1841+
StringLiteral *getFormatString() const;
1842+
}];
1843+
let Subjects = SubjectList<[ObjCMethod, Block, HasFunctionProto]>;
1844+
let Documentation = [FormatMatchesDocs];
1845+
}
1846+
18371847
def FormatArg : InheritableAttr {
18381848
let Spellings = [GCC<"format_arg">];
18391849
let Args = [ParamIdxArgument<"FormatIdx">];

clang/include/clang/Basic/AttrDocs.td

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3886,6 +3886,132 @@ behavior of the program is undefined.
38863886
}];
38873887
}
38883888

3889+
def FormatMatchesDocs : Documentation {
3890+
let Category = DocCatFunction;
3891+
let Content = [{
3892+
3893+
The ``format`` attribute is the basis for the enforcement of diagnostics in the
3894+
``-Wformat`` family, but it only handles the case where the format string is
3895+
passed along with the arguments it is going to format. It cannot handle the case
3896+
where the format string and the format arguments are passed separately from each
3897+
other. For instance:
3898+
3899+
.. code-block:: c
3900+
3901+
static const char *first_name;
3902+
static double todays_temperature;
3903+
static int wind_speed;
3904+
3905+
void say_hi(const char *fmt) {
3906+
printf(fmt, first_name, todays_temperature);
3907+
// ^ warning: format string is not a string literal
3908+
printf(fmt, first_name, wind_speed);
3909+
// ^ warning: format string is not a string literal
3910+
}
3911+
3912+
int main() {
3913+
say_hi("hello %s, it is %g degrees outside");
3914+
say_hi("hello %s, it is %d degrees outside!");
3915+
// ^ no diagnostic, but %d cannot format doubles
3916+
}
3917+
3918+
In this example, ``fmt`` is expected to format a ``const char *`` and a
3919+
``double``, but these values are not passed to ``say_hi``. Without the
3920+
``format`` attribute (which cannot apply in this case), the -Wformat-nonliteral
3921+
diagnostic unnecessarily triggers in the body of ``say_hi``, and incorrect
3922+
``say_hi`` call sites do not trigger a diagnostic.
3923+
3924+
To complement the ``format`` attribute, Clang also defines the
3925+
``format_matches`` attribute. Its syntax is similar to the ``format``
3926+
attribute's, but instead of taking the index of the first formatted value
3927+
argument, it takes a C string literal with the expected specifiers:
3928+
3929+
.. code-block:: c
3930+
3931+
static const char *first_name;
3932+
static double todays_temperature;
3933+
static int wind_speed;
3934+
3935+
__attribute__((__format_matches__(printf, 1, "%s %g")))
3936+
void say_hi(const char *fmt) {
3937+
printf(fmt, first_name, todays_temperature); // no dignostic
3938+
printf(fmt, first_name, wind_speed); // warning: format specifies type 'int' but the argument has type 'double'
3939+
}
3940+
3941+
int main() {
3942+
say_hi("hello %s, it is %g degrees outside");
3943+
say_hi("it is %g degrees outside, have a good day %s!");
3944+
// warning: format specifies 'double' where 'const char *' is required
3945+
// warning: format specifies 'const char *' where 'double' is required
3946+
}
3947+
3948+
The third argument to ``format_matches`` is expected to evaluate to a **C string
3949+
literal** even when the format string would normally be a different type for the
3950+
given flavor, like a ``CFStringRef`` or a ``NSString *``.
3951+
3952+
The only requirement on the format string literal is that it has specifiers
3953+
that are compatible with the arguments that will be used. It can contain
3954+
arbitrary non-format characters. For instance, for the purposes of compile-time
3955+
validation, ``"%s scored %g%% on her test"`` and ``"%s%g"`` are interchangeable
3956+
as the format string argument. As a means of self-documentation, users may
3957+
prefer the former when it provides a useful example of an expected format
3958+
string.
3959+
3960+
In the implementation of a function with the ``format_matches`` attribute,
3961+
format verification works as if the format string was identical to the one
3962+
specified in the attribute.
3963+
3964+
.. code-block:: c
3965+
3966+
__attribute__((__format_matches__(printf, 1, "%s %g")))
3967+
void say_hi(const char *fmt) {
3968+
printf(fmt, "person", 546);
3969+
// ^ warning: format specifies type 'double' but the
3970+
// argument has type 'int'
3971+
// note: format string is defined here:
3972+
// __attribute__((__format_matches__(printf, 1, "%s %g")))
3973+
// ^~
3974+
}
3975+
3976+
3977+
At the call sites of functions with the ``format_matches`` attribute, format
3978+
verification instead compares the two format strings to evaluate their
3979+
equivalence. Each format flavor defines equivalence between format specifiers.
3980+
Generally speaking, two specifiers are equivalent if they format the same type.
3981+
For instance, in the ``printf`` flavor, ``%2i`` and ``%-0.5d`` are compatible.
3982+
When ``-Wformat-signedness`` is disabled, ``%d`` and ``%u`` are compatible. For
3983+
a negative example, ``%ld`` is incompatible with ``%d``.
3984+
3985+
Do note the following un-obvious cases:
3986+
3987+
* Passing ``NULL`` as the format string does not trigger format diagnostics.
3988+
* When the format string is not NULL, it cannot _miss_ specifiers, even in
3989+
trailing positions. For instance, ``%d`` is not accepted when the required
3990+
format is ``%d %d %d``.
3991+
* While checks for the ``format`` attribute tolerate sone size mismatches
3992+
that standard argument promotion renders immaterial (such as formatting an
3993+
``int`` with ``%hhd``, which specifies a ``char``-sized integer), checks for
3994+
``format_matches`` require specified argument sizes to match exactly.
3995+
* Format strings expecting a variable modifier (such as ``%*s``) are
3996+
incompatible with format strings that would itemize the variable modifiers
3997+
(such as ``%i %s``), even if the two specify ABI-compatible argument lists.
3998+
* All pointer specifiers, modifiers aside, are mutually incompatible. For
3999+
instance, ``%s`` is not compatible with ``%p``, and ``%p`` is not compatible
4000+
with ``%n``, and ``%hhn`` is incompatible with ``%s``, even if the pointers
4001+
are ABI-compatible or identical on the selected platform. However, ``%0.5s``
4002+
is compatible with ``%s``, since the difference only exists in modifier flags.
4003+
This is not overridable with ``-Wformat-pedantic`` or its inverse, which
4004+
control similar behavior in ``-Wformat``.
4005+
4006+
At this time, clang implements ``format_matches`` only for format types in the
4007+
``printf`` family. This includes variants such as Apple's NSString format and
4008+
the FreeBSD ``kprintf``, but excludes ``scanf``. Using a known but unsupported
4009+
format silently fails in order to be compatible with other implementations that
4010+
would support these formats.
4011+
4012+
}];
4013+
}
4014+
38894015
def FlagEnumDocs : Documentation {
38904016
let Category = DocCatDecl;
38914017
let Content = [{

clang/include/clang/Basic/DiagnosticSemaKinds.td

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7764,6 +7764,7 @@ def warn_format_nonliteral_noargs : Warning<
77647764
def warn_format_nonliteral : Warning<
77657765
"format string is not a string literal">,
77667766
InGroup<FormatNonLiteral>, DefaultIgnore;
7767+
def err_format_nonliteral : Error<"format string is not a string literal">;
77677768

77687769
def err_unexpected_interface : Error<
77697770
"unexpected interface name %0: expected expression">;
@@ -10066,6 +10067,8 @@ def note_previous_declaration_as : Note<
1006610067

1006710068
def warn_printf_insufficient_data_args : Warning<
1006810069
"more '%%' conversions than data arguments">, InGroup<FormatInsufficientArgs>;
10070+
def warn_format_cmp_specifier_arity : Warning<
10071+
"%select{fewer|more}0 specifiers in format string than expected">, InGroup<FormatInsufficientArgs>;
1006910072
def warn_printf_data_arg_not_used : Warning<
1007010073
"data argument not used by format string">, InGroup<FormatExtraArgs>;
1007110074
def warn_format_invalid_conversion : Warning<
@@ -10183,6 +10186,27 @@ def note_format_fix_specifier : Note<"did you mean to use '%0'?">;
1018310186
def note_printf_c_str: Note<"did you mean to call the %0 method?">;
1018410187
def note_format_security_fixit: Note<
1018510188
"treat the string as an argument to avoid this">;
10189+
def warn_format_string_type_incompatible : Warning<
10190+
"passing '%0' format string where '%1' format string is expected">,
10191+
InGroup<Format>;
10192+
def warn_format_cmp_role_mismatch : Warning<
10193+
"format argument is %select{a value|an indirect field width|an indirect "
10194+
"precision|an auxiliary value}0, but it should be %select{a value|an indirect "
10195+
"field width|an indirect precision|an auxiliary value}1">, InGroup<Format>;
10196+
def warn_format_cmp_modifierfor_mismatch : Warning<
10197+
"format argument modifies specifier at position %0, but it should modify "
10198+
"specifier at position %1">, InGroup<Format>;
10199+
def warn_format_cmp_sensitivity_mismatch : Warning<
10200+
"argument sensitivity is %select{unspecified|private|public|sensitive}0, but "
10201+
"it should be %select{unspecified|private|public|sensitive}1">, InGroup<Format>;
10202+
def warn_format_cmp_specifier_mismatch : Warning<
10203+
"format specifier '%0' is incompatible with '%1'">, InGroup<Format>;
10204+
def warn_format_cmp_specifier_sign_mismatch : Warning<
10205+
"signedness of format specifier '%0' is incompatible with '%1'">, InGroup<Format>;
10206+
def warn_format_cmp_specifier_mismatch_pedantic : Extension<
10207+
warn_format_cmp_specifier_sign_mismatch.Summary>, InGroup<FormatPedantic>;
10208+
def note_format_cmp_with : Note<
10209+
"comparing with this %select{specifier|format string}0">;
1018610210

1018710211
def warn_null_arg : Warning<
1018810212
"null passed to a callee that requires a non-null argument">,

clang/include/clang/Sema/Sema.h

Lines changed: 47 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2177,6 +2177,7 @@ class Sema final : public SemaBase {
21772177
FAPK_Fixed, // values to format are fixed (no C-style variadic arguments)
21782178
FAPK_Variadic, // values to format are passed as variadic arguments
21792179
FAPK_VAList, // values to format are passed in a va_list
2180+
FAPK_Elsewhere, // values to format are not passed to this function
21802181
};
21812182

21822183
// Used to grab the relevant information from a FormatAttr and a
@@ -2187,12 +2188,15 @@ class Sema final : public SemaBase {
21872188
FormatArgumentPassingKind ArgPassingKind;
21882189
};
21892190

2190-
/// Given a FunctionDecl's FormatAttr, attempts to populate the
2191-
/// FomatStringInfo parameter with the FormatAttr's correct format_idx and
2192-
/// firstDataArg. Returns true when the format fits the function and the
2193-
/// FormatStringInfo has been populated.
2194-
static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2195-
bool IsVariadic, FormatStringInfo *FSI);
2191+
/// Given a function and its FormatAttr or FormatMatchesAttr info, attempts to
2192+
/// populate the FomatStringInfo parameter with the attribute's correct
2193+
/// format_idx and firstDataArg. Returns true when the format fits the
2194+
/// function and the FormatStringInfo has been populated.
2195+
static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx,
2196+
unsigned FirstArg, FormatStringInfo *FSI);
2197+
static bool getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
2198+
bool IsCXXMember, bool IsVariadic,
2199+
FormatStringInfo *FSI);
21962200

21972201
// Used by C++ template instantiation.
21982202
ExprResult BuiltinShuffleVector(CallExpr *TheCall);
@@ -2215,7 +2219,10 @@ class Sema final : public SemaBase {
22152219
FST_Syslog,
22162220
FST_Unknown
22172221
};
2222+
static StringRef GetFormatStringTypeName(FormatStringType FST);
2223+
static FormatStringType GetFormatStringType(StringRef FormatFlavor);
22182224
static FormatStringType GetFormatStringType(const FormatAttr *Format);
2225+
static FormatStringType GetFormatStringType(const FormatMatchesAttr *Format);
22192226

22202227
bool FormatStringHasSArg(const StringLiteral *FExpr);
22212228

@@ -2362,6 +2369,25 @@ class Sema final : public SemaBase {
23622369
bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
23632370
VariadicCallType CallType);
23642371

2372+
/// Verify that two format strings (as understood by attribute(format) and
2373+
/// attribute(format_matches) are compatible. If they are incompatible,
2374+
/// diagnostics are emitted with the assumption that \c
2375+
/// AuthoritativeFormatString is correct and
2376+
/// \c TestedFormatString is wrong. If \c FunctionCallArg is provided,
2377+
/// diagnostics will point to it and a note will refer to \c
2378+
/// TestedFormatString or \c AuthoritativeFormatString as appropriate.
2379+
bool
2380+
CheckFormatStringsCompatible(FormatStringType FST,
2381+
const StringLiteral *AuthoritativeFormatString,
2382+
const StringLiteral *TestedFormatString,
2383+
const Expr *FunctionCallArg = nullptr);
2384+
2385+
/// Verify that one format string (as understood by attribute(format)) is
2386+
/// self-consistent; for instance, that it doesn't have multiple positional
2387+
/// arguments referring to the same argument in incompatible ways. Diagnose
2388+
/// if it isn't.
2389+
bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str);
2390+
23652391
/// \brief Enforce the bounds of a TCB
23662392
/// CheckTCBEnforcement - Enforces that every function in a named TCB only
23672393
/// directly calls other functions in the same TCB as marked by the
@@ -2577,11 +2603,17 @@ class Sema final : public SemaBase {
25772603
VariadicCallType CallType, SourceLocation Loc,
25782604
SourceRange Range,
25792605
llvm::SmallBitVector &CheckedVarArgs);
2606+
bool CheckFormatString(const FormatMatchesAttr *Format,
2607+
ArrayRef<const Expr *> Args, bool IsCXXMember,
2608+
VariadicCallType CallType, SourceLocation Loc,
2609+
SourceRange Range,
2610+
llvm::SmallBitVector &CheckedVarArgs);
25802611
bool CheckFormatArguments(ArrayRef<const Expr *> Args,
2581-
FormatArgumentPassingKind FAPK, unsigned format_idx,
2582-
unsigned firstDataArg, FormatStringType Type,
2583-
VariadicCallType CallType, SourceLocation Loc,
2584-
SourceRange range,
2612+
FormatArgumentPassingKind FAPK,
2613+
const StringLiteral *ReferenceFormatString,
2614+
unsigned format_idx, unsigned firstDataArg,
2615+
FormatStringType Type, VariadicCallType CallType,
2616+
SourceLocation Loc, SourceRange range,
25852617
llvm::SmallBitVector &CheckedVarArgs);
25862618

25872619
void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
@@ -4576,6 +4608,11 @@ class Sema final : public SemaBase {
45764608
FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
45774609
IdentifierInfo *Format, int FormatIdx,
45784610
int FirstArg);
4611+
FormatMatchesAttr *mergeFormatMatchesAttr(Decl *D,
4612+
const AttributeCommonInfo &CI,
4613+
IdentifierInfo *Format,
4614+
int FormatIdx,
4615+
StringLiteral *FormatStr);
45794616

45804617
/// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
45814618
void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,

clang/lib/AST/AttrImpl.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,4 +270,8 @@ unsigned AlignedAttr::getAlignment(ASTContext &Ctx) const {
270270
return Ctx.getTargetDefaultAlignForAttributeAligned();
271271
}
272272

273+
StringLiteral *FormatMatchesAttr::getFormatString() const {
274+
return cast<StringLiteral>(getExpectedFormat());
275+
}
276+
273277
#include "clang/AST/AttrImpl.inc"

0 commit comments

Comments
 (0)