Skip to content

Commit f720ba7

Browse files
[clang] Catch missing format attributes
1 parent d6f7f2a commit f720ba7

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
@@ -788,6 +788,8 @@ Improvements to Clang's diagnostics
788788
require(scope); // Warning! Requires mu1.
789789
}
790790

791+
- Clang now diagnoses missing format attributes for non-template functions and class/struct/union members. (#GH60718)
792+
791793
Improvements to Clang's time-trace
792794
----------------------------------
793795

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
@@ -4610,6 +4610,11 @@ class Sema final : public SemaBase {
46104610

46114611
enum class RetainOwnershipKind { NS, CF, OS };
46124612

4613+
void DetectMissingFormatAttributes(const FunctionDecl *Callee,
4614+
ArrayRef<const Expr *> Args,
4615+
SourceLocation Loc);
4616+
void EmitMissingFormatAttributesDiagnostic(const FunctionDecl *Caller);
4617+
46134618
UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
46144619
StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
46154620

clang/lib/Sema/SemaChecking.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3455,8 +3455,10 @@ void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
34553455
}
34563456
}
34573457

3458-
if (FD)
3458+
if (FD) {
34593459
diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
3460+
DetectMissingFormatAttributes(FD, Args, Loc);
3461+
}
34603462
}
34613463

34623464
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
@@ -16120,6 +16120,8 @@ Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
1612016120
}
1612116121
}
1612216122

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

36603660
// In C++ the implicit 'this' function parameter also counts, and they are
36613661
// counted from one.
3662-
bool HasImplicitThisParam = isInstanceMethod(D);
3662+
bool HasImplicitThisParam = checkIfMethodHasImplicitObjectParameter(D);
36633663
unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
36643664

36653665
IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
@@ -3772,7 +3772,7 @@ static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
37723772
return;
37733773
}
37743774

3775-
bool HasImplicitThisParam = isInstanceMethod(D);
3775+
bool HasImplicitThisParam = checkIfMethodHasImplicitObjectParameter(D);
37763776
int32_t NumArgs = getFunctionOrMethodNumParams(D);
37773777

37783778
FunctionDecl *FD = D->getAsFunction();
@@ -5578,6 +5578,181 @@ static void handlePreferredTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
55785578
D->addAttr(::new (S.Context) PreferredTypeAttr(S.Context, AL, ParmTSI));
55795579
}
55805580

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

0 commit comments

Comments
 (0)