Skip to content

Commit 38d9734

Browse files
[clang] Catch missing format attributes
1 parent af3295b commit 38d9734

File tree

10 files changed

+648
-4
lines changed

10 files changed

+648
-4
lines changed

clang/docs/ReleaseNotes.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -535,6 +535,8 @@ Improvements to Clang's diagnostics
535535

536536
- Improved diagnostic message for ``__builtin_bit_cast`` size mismatch (#GH115870).
537537

538+
- Clang now diagnoses missing format attributes for non-template functions and class/struct/union members. (#GH60718)
539+
538540
Improvements to Clang's time-trace
539541
----------------------------------
540542

clang/include/clang/Basic/DiagnosticGroups.td

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -530,7 +530,6 @@ def MainReturnType : DiagGroup<"main-return-type">;
530530
def MaxUnsignedZero : DiagGroup<"max-unsigned-zero">;
531531
def MissingBraces : DiagGroup<"missing-braces">;
532532
def MissingDeclarations: DiagGroup<"missing-declarations">;
533-
def : DiagGroup<"missing-format-attribute">;
534533
def MissingIncludeDirs : DiagGroup<"missing-include-dirs">;
535534
def MissingNoreturn : DiagGroup<"missing-noreturn">;
536535
def MultiChar : DiagGroup<"multichar">;

clang/include/clang/Basic/DiagnosticSemaKinds.td

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1055,6 +1055,10 @@ def err_opencl_invalid_param : Error<
10551055
"declaring function parameter of type %0 is not allowed%select{; did you forget * ?|}1">;
10561056
def err_opencl_invalid_return : Error<
10571057
"declaring function return value of type %0 is not allowed %select{; did you forget * ?|}1">;
1058+
def warn_missing_format_attribute : Warning<
1059+
"diagnostic behavior may be improved by adding the %0 format attribute to the declaration of %1">,
1060+
InGroup<DiagGroup<"missing-format-attribute">>, DefaultIgnore;
1061+
def note_format_function : Note<"%0 format function">;
10581062
def warn_pragma_options_align_reset_failed : Warning<
10591063
"#pragma options align=reset failed: %0">,
10601064
InGroup<IgnoredPragmas>;

clang/include/clang/Sema/Attr.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,13 @@ inline bool isInstanceMethod(const Decl *D) {
123123
return false;
124124
}
125125

126+
inline bool checkIfMethodHasImplicitObjectParameter(const Decl *D) {
127+
if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(D))
128+
return MethodDecl->isInstance() &&
129+
!MethodDecl->hasCXXExplicitFunctionObjectParameter();
130+
return false;
131+
}
132+
126133
/// Diagnose mutually exclusive attributes when present on a given
127134
/// declaration. Returns true if diagnosed.
128135
template <typename AttrTy>

clang/include/clang/Sema/Sema.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4586,6 +4586,11 @@ class Sema final : public SemaBase {
45864586

45874587
enum class RetainOwnershipKind { NS, CF, OS };
45884588

4589+
void DetectMissingFormatAttributes(const FunctionDecl *Callee,
4590+
ArrayRef<const Expr *> Args,
4591+
SourceLocation Loc);
4592+
void EmitMissingFormatAttributesDiagnostic(const FunctionDecl *Caller);
4593+
45894594
UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
45904595
StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
45914596

clang/lib/Sema/SemaChecking.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3410,8 +3410,10 @@ void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
34103410
}
34113411
}
34123412

3413-
if (FD)
3413+
if (FD) {
34143414
diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
3415+
DetectMissingFormatAttributes(FD, Args, Loc);
3416+
}
34153417
}
34163418

34173419
void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {

clang/lib/Sema/SemaDecl.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16105,6 +16105,8 @@ Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
1610516105
}
1610616106
}
1610716107

16108+
EmitMissingFormatAttributesDiagnostic(FD);
16109+
1610816110
// We might not have found a prototype because we didn't wish to warn on
1610916111
// the lack of a missing prototype. Try again without the checks for
1611016112
// whether we want to warn on the missing prototype.

clang/lib/Sema/SemaDeclAttr.cpp

Lines changed: 177 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3625,7 +3625,7 @@ static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
36253625

36263626
// In C++ the implicit 'this' function parameter also counts, and they are
36273627
// counted from one.
3628-
bool HasImplicitThisParam = isInstanceMethod(D);
3628+
bool HasImplicitThisParam = checkIfMethodHasImplicitObjectParameter(D);
36293629
unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
36303630

36313631
IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
@@ -3738,7 +3738,7 @@ static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
37383738
return;
37393739
}
37403740

3741-
bool HasImplicitThisParam = isInstanceMethod(D);
3741+
bool HasImplicitThisParam = checkIfMethodHasImplicitObjectParameter(D);
37423742
int32_t NumArgs = getFunctionOrMethodNumParams(D);
37433743

37443744
FunctionDecl *FD = D->getAsFunction();
@@ -5544,6 +5544,181 @@ static void handlePreferredTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
55445544
D->addAttr(::new (S.Context) PreferredTypeAttr(S.Context, AL, ParmTSI));
55455545
}
55465546

5547+
// Diagnosing missing format attributes is implemented in two steps:
5548+
// 1. Detect missing format attributes while checking function calls.
5549+
// 2. Emit diagnostic in part that processes function body.
5550+
// For this purpose it is created vector that stores information about format
5551+
// attributes. There are no two format attributes with same arguments in a
5552+
// vector. Vector could contains attributes that only store information about
5553+
// format type (format string and first to check argument are set to -1).
5554+
namespace {
5555+
std::vector<FormatAttr *> MissingAttributes;
5556+
} // end anonymous namespace
5557+
5558+
// This function is called only if function call is not inside template body.
5559+
// TODO: Add call for function calls inside template body.
5560+
// Detects and stores missing format attributes in a vector.
5561+
void Sema::DetectMissingFormatAttributes(const FunctionDecl *Callee,
5562+
ArrayRef<const Expr *> Args,
5563+
SourceLocation Loc) {
5564+
assert(Callee);
5565+
5566+
// If there is no caller, exit.
5567+
const FunctionDecl *Caller = getCurFunctionDecl();
5568+
if (!getCurFunctionDecl())
5569+
return;
5570+
5571+
// Check if callee function is a format function.
5572+
// If it is, check if caller function misses format attributes.
5573+
5574+
if (!Callee->hasAttr<FormatAttr>())
5575+
return;
5576+
5577+
// va_list is not intended to be passed to variadic function.
5578+
if (Callee->isVariadic())
5579+
return;
5580+
5581+
// Check if va_list is passed to callee function.
5582+
// If va_list is not passed, return.
5583+
bool hasVaList = false;
5584+
for (const auto *Param : Callee->parameters()) {
5585+
if (Param->getOriginalType().getCanonicalType() ==
5586+
getASTContext().getBuiltinVaListType().getCanonicalType()) {
5587+
hasVaList = true;
5588+
break;
5589+
}
5590+
}
5591+
if (!hasVaList)
5592+
return;
5593+
5594+
unsigned int FormatArgumentIndexOffset =
5595+
checkIfMethodHasImplicitObjectParameter(Callee) ? 2 : 1;
5596+
5597+
// If callee function is format function and format arguments are not
5598+
// relevant to emit diagnostic, save only information about format type
5599+
// (format index and first-to-check argument index are set to -1).
5600+
// Information about format type is later used to determine if there are
5601+
// more than one format type found.
5602+
5603+
unsigned int NumArgs = Args.size();
5604+
// Check if function has format attribute with forwarded format string.
5605+
IdentifierInfo *AttrType;
5606+
const ParmVarDecl *FormatStringArg;
5607+
if (!llvm::any_of(
5608+
Callee->specific_attrs<FormatAttr>(), [&](const FormatAttr *Attr) {
5609+
AttrType = Attr->getType();
5610+
5611+
int OffsetFormatIndex =
5612+
Attr->getFormatIdx() - FormatArgumentIndexOffset;
5613+
if (OffsetFormatIndex < 0 || (unsigned)OffsetFormatIndex >= NumArgs)
5614+
return false;
5615+
5616+
if (const auto *FormatArgExpr = dyn_cast<DeclRefExpr>(
5617+
Args[OffsetFormatIndex]->IgnoreParenCasts()))
5618+
if (FormatStringArg = dyn_cast_or_null<ParmVarDecl>(
5619+
FormatArgExpr->getReferencedDeclOfCallee()))
5620+
return true;
5621+
return false;
5622+
})) {
5623+
MissingAttributes.push_back(
5624+
FormatAttr::CreateImplicit(getASTContext(), AttrType, -1, -1));
5625+
return;
5626+
}
5627+
5628+
unsigned ArgumentIndexOffset =
5629+
checkIfMethodHasImplicitObjectParameter(Caller) ? 2 : 1;
5630+
5631+
unsigned NumOfCallerFunctionParams = Caller->getNumParams();
5632+
5633+
// Compare caller and callee function format attribute arguments (archetype
5634+
// and format string). If they don't match, caller misses format attribute.
5635+
if (llvm::any_of(
5636+
Caller->specific_attrs<FormatAttr>(), [&](const FormatAttr *Attr) {
5637+
if (Attr->getType() != AttrType)
5638+
return false;
5639+
int OffsetFormatIndex = Attr->getFormatIdx() - ArgumentIndexOffset;
5640+
5641+
if (OffsetFormatIndex < 0 ||
5642+
(unsigned)OffsetFormatIndex >= NumOfCallerFunctionParams)
5643+
return false;
5644+
5645+
if (Caller->parameters()[OffsetFormatIndex] != FormatStringArg)
5646+
return false;
5647+
5648+
return true;
5649+
})) {
5650+
MissingAttributes.push_back(
5651+
FormatAttr::CreateImplicit(getASTContext(), AttrType, -1, -1));
5652+
return;
5653+
}
5654+
5655+
// Get format string index
5656+
int FormatStringIndex =
5657+
FormatStringArg->getFunctionScopeIndex() + ArgumentIndexOffset;
5658+
5659+
// Get first argument index
5660+
int FirstToCheck = Caller->isVariadic()
5661+
? (NumOfCallerFunctionParams + ArgumentIndexOffset)
5662+
: 0;
5663+
5664+
// Do not add duplicate in a vector of missing format attributes.
5665+
if (!llvm::any_of(MissingAttributes, [&](const FormatAttr *Attr) {
5666+
return Attr->getType() == AttrType &&
5667+
Attr->getFormatIdx() == FormatStringIndex &&
5668+
Attr->getFirstArg() == FirstToCheck;
5669+
}))
5670+
MissingAttributes.push_back(FormatAttr::CreateImplicit(
5671+
getASTContext(), AttrType, FormatStringIndex, FirstToCheck, Loc));
5672+
}
5673+
5674+
// This function is called only if caller function is not template.
5675+
// TODO: Add call for template functions.
5676+
// Emits missing format attribute diagnostics.
5677+
void Sema::EmitMissingFormatAttributesDiagnostic(const FunctionDecl *Caller) {
5678+
const clang::IdentifierInfo *AttrType = MissingAttributes[0]->getType();
5679+
for (unsigned i = 1; i < MissingAttributes.size(); ++i) {
5680+
if (AttrType != MissingAttributes[i]->getType()) {
5681+
// Clear vector of missing attributes because it could be used in
5682+
// diagnosing missing format attributes in another caller.
5683+
MissingAttributes.clear();
5684+
return;
5685+
}
5686+
}
5687+
5688+
for (const FormatAttr *FA : MissingAttributes) {
5689+
// If format index and first-to-check argument index are negative, it means
5690+
// that this attribute is only saved for multiple format types checking.
5691+
if (FA->getFormatIdx() < 0 || FA->getFirstArg() < 0)
5692+
continue;
5693+
5694+
// If caller function has format attributes and callee format attribute type
5695+
// mismatches caller attribute type, do not emit diagnostic.
5696+
if (Caller->hasAttr<FormatAttr>() &&
5697+
!llvm::any_of(Caller->specific_attrs<FormatAttr>(),
5698+
[FA](const FormatAttr *FunctionAttr) {
5699+
return FA->getType() == FunctionAttr->getType();
5700+
}))
5701+
continue;
5702+
5703+
// Emit diagnostic
5704+
SourceLocation Loc = Caller->getFirstDecl()->getLocation();
5705+
Diag(Loc, diag::warn_missing_format_attribute)
5706+
<< FA->getType() << Caller
5707+
<< FixItHint::CreateInsertion(Loc,
5708+
(llvm::Twine("__attribute__((format(") +
5709+
FA->getType()->getName() + ", " +
5710+
llvm::Twine(FA->getFormatIdx()) + ", " +
5711+
llvm::Twine(FA->getFirstArg()) + ")))")
5712+
.str());
5713+
Diag(FA->getLocation(), diag::note_format_function) << FA->getType();
5714+
}
5715+
5716+
// Clear vector of missing attributes after emitting diagnostics for caller
5717+
// function because it could be used in diagnosing missing format attributes
5718+
// in another caller.
5719+
MissingAttributes.clear();
5720+
}
5721+
55475722
//===----------------------------------------------------------------------===//
55485723
// Microsoft specific attribute handlers.
55495724
//===----------------------------------------------------------------------===//

0 commit comments

Comments
 (0)