https://github.com/Holo-xy created https://github.com/llvm/llvm-project/pull/244631
Stacked on #244630. Diagnose conflicting parameter counts in function redeclarations, including counts on the inner pointer of an out parameter. Adding or removing a count also causes a conflict: ```c void f(int n, int *__counted_by(n) p); void f(int n, int *p); // error: conflicting 'counted_by' attribute ``` The compatibility check is skipped when either declaration is in a system header. For functions declared through a function typedef or `__typeof__`, rebuild the counts to refer to the new function's own parameters. References to parameters of an enclosing function are preserved. >From 8e04ef9b5edc8dafb6e336a84cbb88dab70c733f Mon Sep 17 00:00:00 2001 From: Holo-xy <[email protected]> Date: Mon, 19 Oct 2026 20:04:36 +0300 Subject: [PATCH] [BoundsSafety] Diagnose conflicting counts in function redeclarations Counts are part of a function's interface, so a redeclaration has to repeat the counts on its parameters' pointers, also on the pointers they point to. A parameter named by a count compares by its position and type, so a redeclaration may rename it. Functions declared in system headers may be redeclared with counts. A function declared with a typedef or __typeof__ gets parameters of its own, so the counts in its type are rebuilt to name them. --- .../clang/Basic/DiagnosticSemaKinds.td | 2 + clang/lib/Sema/SemaDecl.cpp | 179 ++++++++++++++++++ .../AST/attr-counted-by-function-params.c | 17 ++ .../attr-counted-by-function-params-redecl.c | 122 ++++++++++++ 4 files changed, 320 insertions(+) create mode 100644 clang/test/Sema/attr-counted-by-function-params-redecl.c diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index f63cd14e8f9bd..57c23659f50e5 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -7214,6 +7214,8 @@ def err_count_attr_refer_to_non_param : Error< "count expression in function declaration may only reference function parameters">; def err_count_attr_on_sized_array_param : Error< "'%select{counted_by|sized_by|counted_by_or_null|sized_by_or_null}0' cannot be applied to an array parameter with an explicit size">; +def err_count_attr_conflicting_redeclaration : Error< + "conflicting '%select{counted_by|sized_by|counted_by_or_null|sized_by_or_null}0' attribute with the previous function declaration">; def err_count_attr_argument_not_integer : Error< "'%select{counted_by|sized_by|counted_by_or_null|sized_by_or_null}0' requires a non-boolean integer type argument">; def err_count_attr_only_support_simple_decl_reference : Error< diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index df93ef4e1a2ab..ad43e50b6e419 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -10,6 +10,7 @@ // //===----------------------------------------------------------------------===// +#include "TreeTransform.h" #include "TypeLocBuilder.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" @@ -72,6 +73,7 @@ #include "llvm/TargetParser/Triple.h" #include <algorithm> #include <cstring> +#include <functional> #include <optional> #include <unordered_map> @@ -3770,6 +3772,90 @@ static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, FixSemaDC(VD->getDescribedVarTemplate()); } +/// Diagnose if \p New and \p Old have conflicting counts in their parameter +/// types. Return true if they are compatible. +static bool diagnoseFunctionConflictWithDynamicBoundTypes(FunctionDecl *New, + FunctionDecl *Old, + Sema &Self) { + // Report only the first conflict. + bool Reported = false; + auto ReportCountConflict = [&](SourceLocation NewLoc, + const CountAttributedType *DCPTy) { + if (!Reported) + Self.Diag(NewLoc, diag::err_count_attr_conflicting_redeclaration) + << DCPTy->getKind(); + Reported = true; + }; + + // Only a chain of pointers is followed, so a count below anything else, such + // as an _Atomic pointer or a callback's function type, is not compared: + // void f(void (*cb)(int m, int *__counted_by(m) p)); + // void f(void (*cb)(int m, int *p)); // not diagnosed + std::function<bool(QualType, QualType, SourceLocation)> + checkCompatibleDynamicBoundTypes = + [&](QualType NewTy, QualType OldTy, SourceLocation NewLoc) -> bool { + if (!NewTy->isPointerType() || !OldTy->isPointerType()) + return true; + const auto *NewDCPTy = NewTy->getAs<CountAttributedType>(); + const auto *OldDCPTy = OldTy->getAs<CountAttributedType>(); + + if (NewDCPTy && !OldDCPTy) { + ReportCountConflict(NewLoc, NewDCPTy); + return false; + } + + if (!NewDCPTy && OldDCPTy) { + ReportCountConflict(NewLoc, OldDCPTy); + return false; + } + + if (NewDCPTy && OldDCPTy) { + // A parameter compares by its position and type, so the declarations may + // rename their parameters, but `const int n` differs from `int n`. + assert(NewDCPTy->getCountExpr() && OldDCPTy->getCountExpr()); + if (!Self.Context.hasSameExpr(NewDCPTy->getCountExpr(), + OldDCPTy->getCountExpr())) { + ReportCountConflict(NewLoc, NewDCPTy); + return false; + } + // '__sized_by' and '__counted_by' + if (NewDCPTy->isCountInBytes() != OldDCPTy->isCountInBytes()) { + // The size of an incomplete pointee is unknown. + QualType Pointee = NewDCPTy->getPointeeType(); + if (!NewDCPTy->isVoidPointerType() && + (Pointee->isIncompleteType() || + !Self.Context.getTypeSizeInChars(Pointee).isOne())) { + ReportCountConflict(NewLoc, NewDCPTy); + return false; + } + } + // '__counted_by_or_null' and '__counted_by' + if (NewDCPTy->isOrNull() != OldDCPTy->isOrNull()) { + ReportCountConflict(NewLoc, NewDCPTy); + return false; + } + } + return checkCompatibleDynamicBoundTypes(NewTy->getPointeeType(), + OldTy->getPointeeType(), NewLoc); + }; + + bool Compatible = true; + auto MinNumParams = std::min(New->getNumParams(), Old->getNumParams()); + for (unsigned i = 0; i < MinNumParams; ++i) { + auto *OldParam = Old->getParamDecl(i); + auto *NewParam = New->getParamDecl(i); + Compatible &= checkCompatibleDynamicBoundTypes( + NewParam->getType(), OldParam->getType(), NewParam->getBeginLoc()); + } + + if (!Compatible) + Self.Diag(Old->getBeginLoc(), diag::note_previous_declaration); + + // New->getNumParams() != Old->getNumParams() should be handled in the other + // logic. + return Compatible; +} + bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S, bool MergeTypeWithOld, bool NewDeclIsDefn) { // Verify the old decl was also a function. @@ -4069,6 +4155,14 @@ bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S, return true; } + // Counts are part of the function's interface, so a redeclaration has to + // repeat those on its parameters' pointers. Functions declared in system + // headers are exempt: a program may redeclare them with counts. + if (!SourceMgr.isInSystemHeader(Old->getLocation()) && + !SourceMgr.isInSystemHeader(New->getLocation()) && + !diagnoseFunctionConflictWithDynamicBoundTypes(New, Old, *this)) + return true; + QualType OldQTypeForComparison = OldQType; if (Context.hasAnyFunctionEffects()) { const auto OldFX = Old->getFunctionEffects(); @@ -10271,6 +10365,86 @@ void Sema::addImplicitCallingConvAbiTag(FunctionDecl *FD) { FD->addAttr(Existing[I]); } +/// Make the counts in the parameter types of \p FD, a function declared with a +/// typedef or `__typeof__`, name \p FD's own parameters instead of those of the +/// prototype its type was written with. +static void rebuildBoundAttributedTypes(Sema &S, FunctionDecl *FD) { + struct ReplaceParams : TreeTransform<ReplaceParams> { + using BaseTransform = TreeTransform<ReplaceParams>; + FunctionDecl *FD; + + ReplaceParams(Sema &SemaRef, FunctionDecl *FD) + : BaseTransform(SemaRef), FD(FD) {} + + bool AlwaysRebuild() { return true; } + + ExprResult TransformDeclRefExpr(DeclRefExpr *E) { + const auto *OldParam = dyn_cast<ParmVarDecl>(E->getDecl()); + if (!OldParam || isEnclosingBodyParam(OldParam)) + return BaseTransform::TransformDeclRefExpr(E); + assert(OldParam->getFunctionScopeIndex() < FD->getNumParams()); + ParmVarDecl *NewParam = + FD->getParamDecl(OldParam->getFunctionScopeIndex()); + // The synthesized parameter is unnamed; name it after the one the count + // was written with, so that the count prints and is diagnosed by name. + if (!NewParam->getDeclName()) + NewParam->setDeclName(OldParam->getDeclName()); + return SemaRef.BuildDeclRefExpr(NewParam, E->getType(), E->getValueKind(), + E->getNameInfo()); + } + + // A parameter of a function, block or method whose body encloses FD's + // declaration keeps naming that parameter. The parameters of a prototype + // written in that body, such as a typedef's, have the same context, so + // check that it is one of the body's own. + bool isEnclosingBodyParam(const ParmVarDecl *PVD) const { + const DeclContext *DC = PVD->getDeclContext(); + ArrayRef<ParmVarDecl *> Params; + if (const auto *F = dyn_cast<FunctionDecl>(DC)) + Params = F->parameters(); + else if (const auto *B = dyn_cast<BlockDecl>(DC)) + Params = B->parameters(); + else if (const auto *M = dyn_cast<ObjCMethodDecl>(DC)) + Params = M->parameters(); + return llvm::is_contained(Params, PVD) && + DC->LexicallyEncloses(FD->getLexicalDeclContext()); + } + } Transform(S, FD); + + // Only a parameter's own count and one on the pointer it points to, as for + // an out parameter, can name the parameters. + auto HasCount = [](QualType Ty) { + return Ty->isCountAttributedType() || + (Ty->isPointerType() && + Ty->getPointeeType()->isCountAttributedType()); + }; + if (llvm::none_of(FD->parameters(), [&](const ParmVarDecl *Param) { + return HasCount(Param->getType()); + })) + return; + + // As in ActOnParamDeclarator, keep the parameters in the translation unit + // while the counts are rebuilt; a reference to a parameter of another + // function would otherwise be diagnosed as a capture. + for (ParmVarDecl *Param : FD->parameters()) + Param->setDeclContext(S.Context.getTranslationUnitDecl()); + SmallVector<QualType> NewParamTys; + for (ParmVarDecl *Param : FD->parameters()) { + QualType Ty = Param->getType(); + if (HasCount(Ty)) { + Ty = Transform.TransformType(Ty); + Param->setType(Ty); + } + NewParamTys.push_back(Ty); + } + for (ParmVarDecl *Param : FD->parameters()) + Param->setDeclContext(FD); + + const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); + FD->setType(S.Context.getFunctionType(FPT->getReturnType(), NewParamTys, + FPT->getExtProtoInfo())); +} + NamedDecl* Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, @@ -10843,6 +11017,11 @@ Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, // Finally, we know we have the right number of parameters, install them. NewFD->setParams(Params); + // The parameters synthesized for a typedef or `__typeof__` are this + // function's own, so make the counts in its type name them. + if (!D.isFunctionDeclarator() && R->isFunctionProtoType()) + rebuildBoundAttributedTypes(*this, NewFD); + // If this declarator is a declaration and not a definition, its parameters // will not be pushed onto a scope chain. That means we will not issue any // reserved identifier warnings for the declaration, but we will for the diff --git a/clang/test/AST/attr-counted-by-function-params.c b/clang/test/AST/attr-counted-by-function-params.c index 7ab9967830071..306cd987f8d21 100644 --- a/clang/test/AST/attr-counted-by-function-params.c +++ b/clang/test/AST/attr-counted-by-function-params.c @@ -79,3 +79,20 @@ void both_counted(int n, int m, int *__counted_by(n) *__counted_by(m) buf); // expected-warning@+2{{a function definition without a prototype is deprecated}} // expected-warning@+1{{'counted_by' attribute ignored}} void knr(count, buf) int count; int *__counted_by(count) buf; {} + +// A function declared with a typedef gets parameters of its own, and the counts +// in its type are rebuilt to name them. +typedef void fn_type(int count, int *__counted_by(count) buf); +// CHECK: FunctionDecl {{.*}} from_typedef 'void (int, int * __counted_by(count))' +// CHECK-NEXT: ParmVarDecl {{.*}} implicit used count 'int' +// CHECK-NEXT: ParmVarDecl {{.*}} implicit 'int * __counted_by(count)':'int *' +fn_type from_typedef; + +// A count naming a parameter of the enclosing function keeps naming it. +void enclosing(int a, int b, int count) { + typedef void local_fn_type(int n, int *__counted_by(count) buf); + // CHECK: FunctionDecl {{.*}} local_from_typedef 'void (int, int * __counted_by(count))' + // CHECK-NEXT: ParmVarDecl {{.*}} implicit 'int' + // CHECK-NEXT: ParmVarDecl {{.*}} implicit 'int * __counted_by(count)':'int *' + local_fn_type local_from_typedef; +} diff --git a/clang/test/Sema/attr-counted-by-function-params-redecl.c b/clang/test/Sema/attr-counted-by-function-params-redecl.c new file mode 100644 index 0000000000000..c9e1d83ad6793 --- /dev/null +++ b/clang/test/Sema/attr-counted-by-function-params-redecl.c @@ -0,0 +1,122 @@ +// RUN: %clang_cc1 -fsyntax-only -Wno-deprecated-non-prototype -verify %s +// RUN: %clang_cc1 -fexperimental-late-parse-attributes -fsyntax-only -Wno-deprecated-non-prototype -verify %s + +// Counts are part of a function's interface, so a redeclaration has to repeat +// them, also on the pointers that a parameter points to. Each count names an +// earlier parameter, so it resolves with or without late parsing. + +#define __counted_by(f) __attribute__((counted_by(f))) +#define __counted_by_or_null(f) __attribute__((counted_by_or_null(f))) +#define __sized_by(f) __attribute__((sized_by(f))) + +// A redeclaration or definition may rename the parameters. +void same(int n, int *__counted_by(n) p); +void same(int k, int *__counted_by(k) q) { (void)q; } +void same_out(int *len, int *__counted_by(*len) *buf); +void same_out(int *size, int *__counted_by(*size) *buf); + +// Counting one-byte elements is counting bytes. +void bytes(int n, char *__counted_by(n) p); +void bytes(int n, char *__sized_by(n) p); +void void_bytes(int n, void *__counted_by(n) p); +void void_bytes(int n, void *__sized_by(n) p); + +// A function without a prototype has no parameters to compare. +void no_proto(int n, int *__counted_by(n) p); +void no_proto(); + +// expected-note@+1{{previous declaration is here}} +void add(int n, int *p); +// expected-error@+1{{conflicting 'counted_by' attribute with the previous function declaration}} +void add(int n, int *__counted_by(n) p); + +// expected-note@+1{{previous declaration is here}} +void drop(int n, int *__counted_by(n) p); +// expected-error@+1{{conflicting 'counted_by' attribute with the previous function declaration}} +void drop(int n, int *p); + +// A count compares the parameter it names by position and type, qualifiers +// included. +// expected-note@+1{{previous declaration is here}} +void qualified_count(int n, int *__counted_by(n) p); +// expected-error@+1{{conflicting 'counted_by' attribute with the previous function declaration}} +void qualified_count(const int n, int *__counted_by(n) p); + +// expected-note@+1{{previous declaration is here}} +void other_param(int n, int m, int *__counted_by(n) p); +// expected-error@+1{{conflicting 'counted_by' attribute with the previous function declaration}} +void other_param(int n, int m, int *__counted_by(m) p); + +// expected-note@+1{{previous declaration is here}} +void kind(int n, int *__counted_by(n) p); +// expected-error@+1{{conflicting 'sized_by' attribute with the previous function declaration}} +void kind(int n, int *__sized_by(n) p); + +// expected-note@+1{{previous declaration is here}} +void or_null(int n, int *__counted_by(n) p); +// expected-error@+1{{conflicting 'counted_by_or_null' attribute with the previous function declaration}} +void or_null(int n, int *__counted_by_or_null(n) p); + +// The size of an incomplete element is unknown. +struct incomplete; +// expected-note@+1{{previous declaration is here}} +void incomplete_bytes(int n, struct incomplete *__counted_by(n) p); +// expected-error@+1{{conflicting 'sized_by' attribute with the previous function declaration}} +void incomplete_bytes(int n, struct incomplete *__sized_by(n) p); + +// expected-note@+1{{previous declaration is here}} +void out_drop(int n, int *__counted_by(n) *buf); +// expected-error@+1{{conflicting 'counted_by' attribute with the previous function declaration}} +void out_drop(int n, int **buf); + +// expected-note@+1{{previous declaration is here}} +void out_deref(int n, int *len, int *__counted_by(*len) *buf); +// expected-error@+1{{conflicting 'counted_by' attribute with the previous function declaration}} +void out_deref(int n, int *len, int *__counted_by(n) *buf); + +// A K&R definition ignores its counts. +// expected-note@+1{{previous declaration is here}} +void knr(int n, int *__counted_by(n) p); +// expected-error@+2{{conflicting 'counted_by' attribute with the previous function declaration}} +// expected-warning@+1{{'counted_by' attribute ignored}} +void knr(n, p) int n; int *__counted_by(n) p; {} + +// FIXME: A count naming a parameter of an enclosing function should compare as +// that parameter, not by its position. +void captured(int n, int *__counted_by(n) p); +void outer(int c) { + void captured(int n, int *__counted_by(c) p); + void captured_twice(int n, int *__counted_by(c) p); + void captured_twice(int k, int *__counted_by(c) q); +} + +// A function declared with a typedef or '__typeof__' gets parameters of its +// own, and the counts in its type are rebuilt to name them. +typedef void fn_type(int n, int *__counted_by(n) p); +fn_type from_typedef; +void from_typedef(int n, int *__counted_by(n) p); +void from_typeof_source(int n, int *__counted_by(n) p); +__typeof__(from_typeof_source) from_typeof; +void from_typeof(int n, int *__counted_by(n) p); +void typedef_in_body(int c) { + typedef void local_fn_type(int n, int *__counted_by(n) p); + local_fn_type local_from_typedef; + void local_from_typedef(int n, int *__counted_by(n) p); +} +// Also when they take a callback's type, whose parameters are written in a +// prototype at another depth. +void (*callback_var)(int n, int *__counted_by(n) p); +__typeof__(*callback_var) from_callback; +void callback_param(void (*cb)(int n, int *__counted_by(n) p)) { + __typeof__(*cb) from_callback; +} + +// Functions declared in system headers may be redeclared with counts. + +# 1 "system.h" 1 3 +void sys_add(int n, int *p); +void sys_drop(int n, int *__counted_by(n) p); +# 119 "attr-counted-by-function-params-redecl.c" 2 + +void sys_add(int n, int *__counted_by(n) p); +void sys_drop(int n, int *p); _______________________________________________ llvm-branch-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits
