Skip to content

Commit 3ffb989

Browse files
[clang] Catch missing format attributes
1 parent acc3266 commit 3ffb989

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
@@ -561,6 +561,8 @@ Improvements to Clang's diagnostics
561561

562562
- Clang now diagnoses missing return value in functions containing ``if consteval`` (#GH116485).
563563

564+
- Clang now diagnoses missing format attributes for non-template functions and class/struct/union members. (#GH60718)
565+
564566
Improvements to Clang's time-trace
565567
----------------------------------
566568

clang/include/clang/Basic/DiagnosticGroups.td

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -532,7 +532,6 @@ def MainReturnType : DiagGroup<"main-return-type">;
532532
def MaxUnsignedZero : DiagGroup<"max-unsigned-zero">;
533533
def MissingBraces : DiagGroup<"missing-braces">;
534534
def MissingDeclarations: DiagGroup<"missing-declarations">;
535-
def : DiagGroup<"missing-format-attribute">;
536535
def MissingIncludeDirs : DiagGroup<"missing-include-dirs">;
537536
def MissingNoreturn : DiagGroup<"missing-noreturn">;
538537
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
@@ -4589,6 +4589,11 @@ class Sema final : public SemaBase {
45894589

45904590
enum class RetainOwnershipKind { NS, CF, OS };
45914591

4592+
void DetectMissingFormatAttributes(const FunctionDecl *Callee,
4593+
ArrayRef<const Expr *> Args,
4594+
SourceLocation Loc);
4595+
void EmitMissingFormatAttributesDiagnostic(const FunctionDecl *Caller);
4596+
45924597
UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
45934598
StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
45944599

clang/lib/Sema/SemaChecking.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3446,8 +3446,10 @@ void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
34463446
}
34473447
}
34483448

3449-
if (FD)
3449+
if (FD) {
34503450
diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
3451+
DetectMissingFormatAttributes(FD, Args, Loc);
3452+
}
34513453
}
34523454

34533455
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
@@ -16108,6 +16108,8 @@ Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
1610816108
}
1610916109
}
1611016110

16111+
EmitMissingFormatAttributesDiagnostic(FD);
16112+
1611116113
// We might not have found a prototype because we didn't wish to warn on
1611216114
// the lack of a missing prototype. Try again without the checks for
1611316115
// 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
@@ -3621,7 +3621,7 @@ static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
36213621

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

36273627
IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
@@ -3734,7 +3734,7 @@ static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
37343734
return;
37353735
}
37363736

3737-
bool HasImplicitThisParam = isInstanceMethod(D);
3737+
bool HasImplicitThisParam = checkIfMethodHasImplicitObjectParameter(D);
37383738
int32_t NumArgs = getFunctionOrMethodNumParams(D);
37393739

37403740
FunctionDecl *FD = D->getAsFunction();
@@ -5540,6 +5540,181 @@ static void handlePreferredTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
55405540
D->addAttr(::new (S.Context) PreferredTypeAttr(S.Context, AL, ParmTSI));
55415541
}
55425542

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

0 commit comments

Comments
 (0)