Skip to content

Commit 1a096f6

Browse files
[clang] Catch missing format attributes
1 parent fa9cef5 commit 1a096f6

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
@@ -708,6 +708,8 @@ Improvements to Clang's diagnostics
708708
709709
- Fix -Wdangling false positives on conditional operators (#120206).
710710

711+
- Clang now diagnoses missing format attributes for non-template functions and class/struct/union members. (#GH60718)
712+
711713
Improvements to Clang's time-trace
712714
----------------------------------
713715

clang/include/clang/Basic/DiagnosticGroups.td

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -536,7 +536,6 @@ def MainReturnType : DiagGroup<"main-return-type">;
536536
def MaxUnsignedZero : DiagGroup<"max-unsigned-zero">;
537537
def MissingBraces : DiagGroup<"missing-braces">;
538538
def MissingDeclarations: DiagGroup<"missing-declarations">;
539-
def : DiagGroup<"missing-format-attribute">;
540539
def MissingIncludeDirs : DiagGroup<"missing-include-dirs">;
541540
def MissingNoreturn : DiagGroup<"missing-noreturn">;
542541
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
@@ -4603,6 +4603,11 @@ class Sema final : public SemaBase {
46034603

46044604
enum class RetainOwnershipKind { NS, CF, OS };
46054605

4606+
void DetectMissingFormatAttributes(const FunctionDecl *Callee,
4607+
ArrayRef<const Expr *> Args,
4608+
SourceLocation Loc);
4609+
void EmitMissingFormatAttributesDiagnostic(const FunctionDecl *Caller);
4610+
46064611
UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
46074612
StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
46084613

clang/lib/Sema/SemaChecking.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3452,8 +3452,10 @@ void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
34523452
}
34533453
}
34543454

3455-
if (FD)
3455+
if (FD) {
34563456
diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
3457+
DetectMissingFormatAttributes(FD, Args, Loc);
3458+
}
34573459
}
34583460

34593461
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
@@ -16139,6 +16139,8 @@ Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
1613916139
}
1614016140
}
1614116141

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

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

36353635
IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
@@ -3742,7 +3742,7 @@ static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
37423742
return;
37433743
}
37443744

3745-
bool HasImplicitThisParam = isInstanceMethod(D);
3745+
bool HasImplicitThisParam = checkIfMethodHasImplicitObjectParameter(D);
37463746
int32_t NumArgs = getFunctionOrMethodNumParams(D);
37473747

37483748
FunctionDecl *FD = D->getAsFunction();
@@ -5548,6 +5548,181 @@ static void handlePreferredTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
55485548
D->addAttr(::new (S.Context) PreferredTypeAttr(S.Context, AL, ParmTSI));
55495549
}
55505550

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

0 commit comments

Comments
 (0)