[clang] [clang] Catch missing format attributes (PR #70024)
Aaron Ballman via cfe-commits
cfe-commits at lists.llvm.org
Thu Dec 7 07:14:07 PST 2023
================
@@ -6849,6 +6849,71 @@ static void handleSwiftAsyncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
}
+// Warn if parent function misses format attribute. Parent function misses
+// format attribute if there is an argument format string forwarded to calling
+// function with format attribute, parent function has a parameter which is
+// either char or string or pointer to char and parent function format attribute
+// type does not match with calling function format attribute type.
+void Sema::DiagnoseMissingFormatAttributes(const FunctionDecl *FDecl,
+ ArrayRef<const Expr *> Args,
+ SourceLocation Loc) {
+ assert(FDecl);
+
+ // Check if function has format attribute with forwarded format string.
+ IdentifierInfo *AttrType;
+ if (!llvm::any_of(
+ FDecl->specific_attrs<FormatAttr>(), [&](const FormatAttr *Attr) {
+ if (!Args[Attr->getFirstArg()]->getReferencedDeclOfCallee())
+ return false;
+
+ AttrType = Attr->getType();
+ return true;
+ }))
+ return;
+
+ const FunctionDecl *ParentFuncDecl = getCurFunctionDecl();
+ if (!ParentFuncDecl)
+ return;
+
+ // Check if parent function has char, string or pointer to char parameter.
+ unsigned int StringIndex = 0;
+ if (!llvm::any_of(
+ ParentFuncDecl->parameters(), [&](const ParmVarDecl *Param) {
+ StringIndex = Param->getFunctionScopeIndex() + 1;
+ QualType Ty = Param->getType();
+ if (isNSStringType(Ty, Context, true))
+ return true;
+ if (isCFStringType(Ty, Context))
+ return true;
+ if (Ty->isPointerType() &&
+ Ty->castAs<PointerType>()->getPointeeType()->isCharType())
----------------
AaronBallman wrote:
That's not particularly strong logic for why we shouldn't diagnose it. It's somewhat idiomatic in C++ to handle string literals via this deduced NTTP pattern, so I think we should support it if it's not too difficult to do so. That said, if it's a pain to support for some reason, I think it's reasonable to not handle it yet (I'm not certain how often we'll find people with interfaces mimicking format strings and using the string literal pattern).
https://github.com/llvm/llvm-project/pull/70024
More information about the cfe-commits
mailing list