https://github.com/Holo-xy created https://github.com/llvm/llvm-project/pull/244629
Stacked on #244628. Support `counted_by`, `sized_by`, and their `_or_null` variants on array parameters. When an array parameter decays to a pointer, a count written on the parameter is transferred to that pointer, even when other type attributes follow the count. A count inherited through a typedef or `__typeof__` belongs to another declaration and is not transferred to the pointer. Array parameters with an explicit size cannot also have a count. >From 4afc9c20a087e05a7543b92eb943514860036e41 Mon Sep 17 00:00:00 2001 From: Holo-xy <[email protected]> Date: Mon, 19 Oct 2026 19:40:18 +0300 Subject: [PATCH] [BoundsSafety] Support the counted_by family on array parameters An array parameter decays to a pointer, so its count moves to that pointer, also when other type attributes are written after the count. A count that comes with the array's type through a typedef or __typeof__ belongs to another declaration and does not move. An array with an explicit size cannot also have a count. --- .../clang/Basic/DiagnosticSemaKinds.td | 2 + clang/include/clang/Sema/Sema.h | 8 +++- clang/lib/Sema/SemaBoundsSafety.cpp | 35 ++++++++++++---- clang/lib/Sema/SemaDecl.cpp | 29 +++++++++++++ clang/lib/Sema/SemaDeclAttr.cpp | 12 +++--- clang/lib/Sema/SemaType.cpp | 15 ++++--- .../AST/attr-counted-by-function-params.c | 42 +++++++++++++++++++ .../Sema/attr-counted-by-function-params.c | 28 ++++++++++--- 8 files changed, 145 insertions(+), 26 deletions(-) diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index 18f12697424226..f63cd14e8f9bdd 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -7212,6 +7212,8 @@ def err_count_attr_must_be_in_structure : Error< "field %0 in '%select{counted_by|sized_by|counted_by_or_null|sized_by_or_null}1' not inside structure">; 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_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/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 9cb1bd877edf89..d95e0af922f4e2 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -2561,13 +2561,14 @@ class Sema final : public SemaBase { /// array declarator chunks enclosing the attribute, up to the nearest /// function declarator chunk. \p OnReturnType is true if a function chunk /// encloses it, i.e. the attribute is in a function's return type. + /// \p IsParameter is set for a count in a parameter's declarator. /// /// \returns false after diagnosing an attribute that must be dropped (see /// ValidateBoundsAttrTypeShape). bool ValidateBoundsAttrTypeForTypePosition( QualType Ty, AttributeCommonInfo::Kind AttrKind, SourceLocation AttrLoc, SourceRange AttrRange, unsigned PointerNestLevel, bool OnReturnType, - BoundsAttrFlags &Flags); + BoundsAttrFlags &Flags, bool IsParameter); /// Check where a counted_by-family attribute of kind \p Kind sits in its /// declarator, as described by \p PointerNestLevel and \p OnReturnType (see @@ -2643,6 +2644,11 @@ class Sema final : public SemaBase { bool CheckCountedByAttrOnParam(QualType ParamTy, Expr *E, bool CountInBytes, bool OrNull); + /// A parameter declared as an array decays to a pointer to its element type. + /// Move the valid count \p CATy on the array to that pointer. + void AdjustCountedArrayParamType(ParmVarDecl *PVD, + const CountAttributedType *CATy); + /// Perform Bounds Safety Semantic checks for assigning to a `__counted_by` or /// `__counted_by_or_null` pointer type \param LHSTy. /// diff --git a/clang/lib/Sema/SemaBoundsSafety.cpp b/clang/lib/Sema/SemaBoundsSafety.cpp index 91452c8db27158..6fcce221a26f76 100644 --- a/clang/lib/Sema/SemaBoundsSafety.cpp +++ b/clang/lib/Sema/SemaBoundsSafety.cpp @@ -256,10 +256,17 @@ bool Sema::ValidateBoundsAttrPosition(BoundsAttributedType::BoundsAttrKind Kind, bool Sema::ValidateBoundsAttrTypeForTypePosition( QualType Ty, AttributeCommonInfo::Kind AttrKind, SourceLocation AttrLoc, SourceRange AttrRange, unsigned PointerNestLevel, bool OnReturnType, - BoundsAttrFlags &Flags) { + BoundsAttrFlags &Flags, bool IsParameter) { Flags = BoundsAttrFlags::get(AttrKind); - if (!ValidateBoundsAttrTypeShape(Ty, AttrLoc, AttrRange, Flags, + // An array parameter decays to a pointer, which is what the attribute + // describes. Whether the array may have a size is checked on the parameter. + // Decaying would drop a count already on the array, so check that one as is. + QualType ShapeTy = Ty; + if (IsParameter && Ty->isArrayType() && !Ty->getAs<CountAttributedType>()) + ShapeTy = getASTContext().getArrayDecayedType(Ty); + + if (!ValidateBoundsAttrTypeShape(ShapeTy, AttrLoc, AttrRange, Flags, /*AttrSpelling=*/{}, /*AllowRedecl=*/false, /*AttrArg=*/nullptr, /*UpdateFlags=*/false)) return false; @@ -387,15 +394,15 @@ bool Sema::CheckCountedByAttrOnParam(QualType ParamTy, Expr *E, if (E->containsErrors()) return true; - // FIXME: Support array parameters. The count has to move to the pointer - // that the array decays to. - if (ParamTy->isArrayType()) { - Diag(E->getBeginLoc(), - diag::err_counted_by_attr_on_array_not_flexible_array_member); + // An array parameter decays to a pointer, which the count then describes. + // An array with an explicit size is not supported: in the -fbounds-safety + // programming model, its size becomes that pointer's count. + const unsigned Kind = getCountAttrKind(CountInBytes, OrNull); + if (ParamTy->isArrayType() && !ParamTy->isIncompleteArrayType()) { + Diag(E->getBeginLoc(), diag::err_count_attr_on_sized_array_param) << Kind; return true; } - const unsigned Kind = getCountAttrKind(CountInBytes, OrNull); ValueDecl *CountDecl = checkCountRefersToDecl(*this, E, Kind); if (!CountDecl) return true; @@ -409,6 +416,18 @@ bool Sema::CheckCountedByAttrOnParam(QualType ParamTy, Expr *E, return false; } +void Sema::AdjustCountedArrayParamType(ParmVarDecl *PVD, + const CountAttributedType *CATy) { + if (!CATy->desugar()->isArrayType()) + return; + // The parameter's type is already adjusted, with the qualifiers written + // outside the count moved to the element (C99 6.7.3p8), but the decayed + // pointer does not carry the count. Put it back on the pointer. + PVD->setType(Context.getCountAttributedType( + PVD->getType(), CATy->getCountExpr(), CATy->isCountInBytes(), + CATy->isOrNull(), CATy->getCoupledDecls())); +} + static void EmitIncompleteCountedByPointeeNotes(Sema &S, const CountAttributedType *CATy, NamedDecl *IncompleteTyDecl) { diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index 87726ba9c41d8a..df93ef4e1a2ab2 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -15935,6 +15935,27 @@ static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, LSI->ExplicitObjectParameter = P; } +/// Return the CountAttributedType at the top of \p T, looking through only +/// parentheses, type attributes, and macro qualifiers. Return null otherwise. +/// A count inside a typedef or `__typeof__` belongs to another declaration. +static const CountAttributedType *getWrittenCountAttributedType(QualType T) { + const Type *Ty = T.getTypePtr(); + while (true) { + if (const auto *CATy = dyn_cast<CountAttributedType>(Ty)) + return CATy; + if (const auto *A = dyn_cast<AttributedType>(Ty)) + Ty = A->getModifiedType().getTypePtr(); + else if (const auto *A = dyn_cast<BTFTagAttributedType>(Ty)) + Ty = A->getWrappedType().getTypePtr(); + else if (const auto *P = dyn_cast<ParenType>(Ty)) + Ty = P->getInnerType().getTypePtr(); + else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty)) + Ty = M->getUnderlyingType().getTypePtr(); + else + return nullptr; + } +} + Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc) { const DeclSpec &DS = D.getDeclSpec(); @@ -16057,6 +16078,14 @@ Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D, ProcessDeclAttributes(S, New, D); + // A count written on an array parameter, also under other type attributes + // written with it, moves to the pointer the parameter decays to; it was + // checked where it was applied. One that comes with the array's type through + // a typedef or `__typeof__` belongs to another declaration and stays behind. + if (const CountAttributedType *CATy = + getWrittenCountAttributedType(TInfo->getType())) + AdjustCountedArrayParamType(New, CATy); + if (D.getDeclSpec().isModulePrivateSpecified()) Diag(New->getLocation(), diag::err_module_private_local) << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp index 89ff88e425f08a..5e42579b39ec03 100644 --- a/clang/lib/Sema/SemaDeclAttr.cpp +++ b/clang/lib/Sema/SemaDeclAttr.cpp @@ -7128,17 +7128,17 @@ static void handleCountedByAttrField(Sema &S, Decl *D, const ParsedAttr &AL) { // the parameter list, before the function's type is built from the // parameters' types. if (auto *PVD = dyn_cast<ParmVarDecl>(D)) { - // An array or function parameter has decayed to a pointer by now; check - // it as written. - QualType Ty = PVD->getType(); - if (!PVD->getOriginalType()->isPointerType()) - Ty = PVD->getOriginalType(); + // An array parameter has decayed by now to the pointer the count + // describes, so check that pointer, and whether the array may have a size + // as written. A function parameter is checked as written. + QualType Written = PVD->getOriginalType(); + QualType Ty = Written->isFunctionType() ? Written : PVD->getType(); if (!S.ValidateBoundsAttrTypeShape(Ty, AL.getLoc(), AL.getRange(), Flags, /*AttrSpelling=*/{}, /*AllowRedecl=*/false, /*AttrArg=*/nullptr, /*UpdateFlags=*/false) || - S.CheckCountedByAttrOnParam(Ty, CountExpr, Flags.CountInBytes, + S.CheckCountedByAttrOnParam(Written, CountExpr, Flags.CountInBytes, Flags.OrNull)) return; QualType CAT = S.BuildCountAttributedArrayOrPointerType( diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp index 3f6040de8bb2ed..5215c9acab9c50 100644 --- a/clang/lib/Sema/SemaType.cpp +++ b/clang/lib/Sema/SemaType.cpp @@ -9147,11 +9147,14 @@ static void HandleCountedByAttrOnType(TypeProcessingState &State, unsigned chunkIndex = State.getCurrentChunkIndex(); + bool IsParameter = D.getContext() == DeclaratorContext::Prototype || + D.getContext() == DeclaratorContext::ObjCParameter; + Sema::BoundsAttrFlags Flags; if (!S.ValidateBoundsAttrTypeForTypePosition( CurType, Attr.getKind(), Attr.getLoc(), Attr.getRange(), getPointerNestLevel(D, chunkIndex), - isOnFunctionReturnType(D, chunkIndex), Flags)) { + isOnFunctionReturnType(D, chunkIndex), Flags, IsParameter)) { Attr.setInvalid(); return; } @@ -9171,8 +9174,7 @@ static void HandleCountedByAttrOnType(TypeProcessingState &State, // A parameter's count is checked before the type is built, and dropped if // invalid. - if ((D.getContext() == DeclaratorContext::Prototype || - D.getContext() == DeclaratorContext::ObjCParameter) && + if (IsParameter && S.CheckCountedByAttrOnParam(CurType, CountExpr, Flags.CountInBytes, Flags.OrNull)) { Attr.setInvalid(); @@ -10264,9 +10266,10 @@ QualType Sema::BuildCountAttributedArrayOrPointerType(QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull) { - // Accept any array or pointer type here. The caller has checked the field - // and its count (see CheckCountedByAttrInRecord), so the count is a - // DeclRefExpr and an array is a flexible array member. + // Accept any array or pointer type here. The caller has checked the + // declaration and its count (see CheckCountedByAttrInRecord and + // CheckCountedByAttrOnParam), so the count is a DeclRefExpr, and an array is + // a flexible array member or a parameter. assert(WrappedTy->isArrayType() || WrappedTy->isPointerType()); assert(isa<DeclRefExpr>(CountExpr) && "count must be checked by the caller"); diff --git a/clang/test/AST/attr-counted-by-function-params.c b/clang/test/AST/attr-counted-by-function-params.c index c53afd81b396da..67a6decbc94ff6 100644 --- a/clang/test/AST/attr-counted-by-function-params.c +++ b/clang/test/AST/attr-counted-by-function-params.c @@ -2,6 +2,7 @@ // RUN: %clang_cc1 -fexperimental-late-parse-attributes -verify %s -ast-dump | FileCheck %s #define __counted_by(f) __attribute__((counted_by(f))) +#define __sized_by_or_null(f) __attribute__((sized_by_or_null(f))) int global_count; @@ -17,6 +18,47 @@ void back_ref(int count, int *__counted_by(count) buf); // CHECK-NEXT: ParmVarDecl {{.*}} buf 'int * __counted_by(count)':'int *' void trailing(int count, int *buf __counted_by(count)); +// An array parameter's count moves to the pointer it decays to. +// CHECK: FunctionDecl {{.*}} array 'void (int, int * __sized_by_or_null(count))' +// CHECK-NEXT: ParmVarDecl {{.*}} count 'int' +// CHECK-NEXT: ParmVarDecl {{.*}} arr 'int * __sized_by_or_null(count)':'int *' +void array(int count, int arr[] __sized_by_or_null(count)); + +// The array's qualifiers apply to its element (C99 6.7.3p8), also when they are +// outside the count, as when it is written in the declaration specifiers. +typedef int int_array[]; +// CHECK: FunctionDecl {{.*}} array_qualified 'void (int, const int * __counted_by(count))' +// CHECK-NEXT: ParmVarDecl {{.*}} count 'int' +// CHECK-NEXT: ParmVarDecl {{.*}} arr 'const int * __counted_by(count)':'const int *' +void array_qualified(int count, const int_array __counted_by(count) arr); + +// Parentheses around the name do not hide a count written in the declaration +// specifiers. +// CHECK: FunctionDecl {{.*}} array_paren 'void (int, int * __counted_by(count))' +// CHECK-NEXT: ParmVarDecl {{.*}} count 'int' +// CHECK-NEXT: ParmVarDecl {{.*}} arr 'int * __counted_by(count)':'int *' +void array_paren(int count, int_array __counted_by(count) (arr)); + +// A type attribute written after the count does not hide it. +// CHECK: FunctionDecl {{.*}} array_attr_after 'void (int, int * __counted_by(count))' +void array_attr_after(int count, + int arr[] __counted_by(count) __attribute__((btf_type_tag("t")))); +// Nor does one that comes from a macro. +#define __noderef __attribute__((noderef)) +// CHECK: FunctionDecl {{.*}} array_macro_attr_after 'void (int, int * __counted_by(count))' +void array_macro_attr_after(int count, int arr[] __counted_by(count) __noderef); + +// A count that comes with the array's type through '__typeof__' names a field, +// so it does not move to the pointer the parameter decays to. +struct fam { int n; int arr[] __counted_by(n); }; +// CHECK: FunctionDecl {{.*}} typeof_fam 'void (int *)' +void typeof_fam(__typeof__(((struct fam *)0)->arr) arr); + +// A second count is rejected, so the first stays on the pointer. +// CHECK: FunctionDecl {{.*}} repeated_array 'void (int, int, int * __counted_by(n))' +// expected-error@+1{{'counted_by' attribute cannot be applied to a pointer that already has a 'counted_by' attribute}} +void repeated_array(int n, int m, int arr[] __counted_by(n) __counted_by(m)); + // A rejected count is not applied, and the function stays valid. // CHECK: FunctionDecl {{.*}} not_a_param 'void (int *)' // expected-error@+1{{count expression in function declaration may only reference function parameters}} diff --git a/clang/test/Sema/attr-counted-by-function-params.c b/clang/test/Sema/attr-counted-by-function-params.c index ba7bdeaaa87781..ff1abe099da7fe 100644 --- a/clang/test/Sema/attr-counted-by-function-params.c +++ b/clang/test/Sema/attr-counted-by-function-params.c @@ -142,18 +142,36 @@ void not_a_reference_sized(int count, void *__sized_by(count + 1) buf); void not_a_reference_sized_or_null(int count, void *__sized_by_or_null(count + 1) buf); //============================================================================== -// Not supported yet +// Array parameters //============================================================================== -// expected-error@+1{{'counted_by' on arrays only applies to C99 flexible array members}} +// An array without a size decays to a pointer that carries the count, so each +// kind is allowed, although a flexible array member takes only counted_by. void array(int count, int arr[] __counted_by(count)); -// expected-error@+1{{'counted_by_or_null' only applies to pointers; did you mean to use 'counted_by'?}} void array_or_null(int count, int arr[] __counted_by_or_null(count)); -// expected-error@+1{{'sized_by' only applies to pointers; did you mean to use 'counted_by'?}} void array_sized(int count, int arr[] __sized_by(count)); -// expected-error@+1{{'sized_by_or_null' only applies to pointers; did you mean to use 'counted_by'?}} void array_sized_or_null(int count, int arr[] __sized_by_or_null(count)); +// expected-error@+1{{'counted_by' cannot be applied to an array parameter with an explicit size}} +void array_with_size(int count, int arr[10] __counted_by(count)); +// expected-error@+1{{'counted_by_or_null' cannot be applied to an array parameter with an explicit size}} +void array_with_size_or_null(int count, int arr[10] __counted_by_or_null(count)); +// expected-error@+1{{'sized_by' cannot be applied to an array parameter with an explicit size}} +void array_with_size_sized(int count, int arr[10] __sized_by(count)); +// expected-error@+1{{'sized_by_or_null' cannot be applied to an array parameter with an explicit size}} +void array_with_size_sized_or_null(int count, int arr[10] __sized_by_or_null(count)); + +// A type attribute written after the count does not hide it, so the count +// still moves to the pointer. +void array_attr_after(int count, + int arr[] [[clang::counted_by(count), + clang::annotate_type("x")]]); +void array_attr_after(int count, int *__counted_by(count) arr); + +//============================================================================== +// Not supported yet +//============================================================================== + // expected-error@+1{{'counted_by' attribute on nested pointer type is not allowed}} void out(int count, int *__counted_by(count) *buf); // expected-error@+1{{'counted_by_or_null' attribute on nested pointer type is not allowed}} _______________________________________________ llvm-branch-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits
