Skip to content

Commit 2571d6f

Browse files
[clang] Catch missing format attributes
1 parent fcb1234 commit 2571d6f

File tree

10 files changed

+649
-4
lines changed

10 files changed

+649
-4
lines changed

clang/docs/ReleaseNotes.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,9 @@ Attribute Changes in Clang
110110
Improvements to Clang's diagnostics
111111
-----------------------------------
112112

113+
- Clang now diagnoses missing format attributes for non-template functions
114+
and class/struct/union members. (#GH60718)
115+
113116
Improvements to Clang's time-trace
114117
----------------------------------
115118

clang/include/clang/Basic/DiagnosticGroups.td

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -534,7 +534,6 @@ def MainReturnType : DiagGroup<"main-return-type">;
534534
def MaxUnsignedZero : DiagGroup<"max-unsigned-zero">;
535535
def MissingBraces : DiagGroup<"missing-braces">;
536536
def MissingDeclarations: DiagGroup<"missing-declarations">;
537-
def : DiagGroup<"missing-format-attribute">;
538537
def MissingIncludeDirs : DiagGroup<"missing-include-dirs">;
539538
def MissingNoreturn : DiagGroup<"missing-noreturn">;
540539
def MultiChar : DiagGroup<"multichar">;

clang/include/clang/Basic/DiagnosticSemaKinds.td

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1061,6 +1061,10 @@ def err_opencl_invalid_param : Error<
10611061
"declaring function parameter of type %0 is not allowed%select{; did you forget * ?|}1">;
10621062
def err_opencl_invalid_return : Error<
10631063
"declaring function return value of type %0 is not allowed %select{; did you forget * ?|}1">;
1064+
def warn_missing_format_attribute : Warning<
1065+
"diagnostic behavior may be improved by adding the %0 format attribute to the declaration of %1">,
1066+
InGroup<DiagGroup<"missing-format-attribute">>, DefaultIgnore;
1067+
def note_format_function : Note<"%0 format function">;
10641068
def warn_pragma_options_align_reset_failed : Warning<
10651069
"#pragma options align=reset failed: %0">,
10661070
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
@@ -4613,6 +4613,11 @@ class Sema final : public SemaBase {
46134613

46144614
enum class RetainOwnershipKind { NS, CF, OS };
46154615

4616+
void DetectMissingFormatAttributes(const FunctionDecl *Callee,
4617+
ArrayRef<const Expr *> Args,
4618+
SourceLocation Loc);
4619+
void EmitMissingFormatAttributesDiagnostic(const FunctionDecl *Caller);
4620+
46164621
UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
46174622
StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
46184623

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
@@ -16164,6 +16164,8 @@ Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
1616416164
}
1616516165
}
1616616166

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

36773677
// In C++ the implicit 'this' function parameter also counts, and they are
36783678
// counted from one.
3679-
bool HasImplicitThisParam = isInstanceMethod(D);
3679+
bool HasImplicitThisParam = checkIfMethodHasImplicitObjectParameter(D);
36803680
unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
36813681

36823682
IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
@@ -3789,7 +3789,7 @@ static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
37893789
return;
37903790
}
37913791

3792-
bool HasImplicitThisParam = isInstanceMethod(D);
3792+
bool HasImplicitThisParam = checkIfMethodHasImplicitObjectParameter(D);
37933793
int32_t NumArgs = getFunctionOrMethodNumParams(D);
37943794

37953795
FunctionDecl *FD = D->getAsFunction();
@@ -5595,6 +5595,181 @@ static void handlePreferredTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
55955595
D->addAttr(::new (S.Context) PreferredTypeAttr(S.Context, AL, ParmTSI));
55965596
}
55975597

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

0 commit comments

Comments
 (0)