Re: [PATCH] Compiler Attributes: Add __counted_by macro

From: Nathan Chancellor
Date: Thu May 04 2023 - 17:18:36 EST


On Thu, May 04, 2023 at 11:16:40AM -0700, Kees Cook wrote:
> In an effort to annotate all flexible array members with their run-time
> size information, the "element_count" attribute is being introduced by
> Clang[1] and GCC[2] in future releases. This annotation will provide
> the CONFIG_UBSAN_BOUNDS and CONFIG_FORTIFY_SOURCE features the ability
> to perform run-time bounds checking on otherwise unknown-size flexible
> arrays.
>
> Even though the attribute is under development, we can start the
> annotation process in the kernel. This requires defining a macro for
> it, even if we have to change the name of the actual attribute later.
> Since it is likely that this attribute may change its name to "counted_by"
> in the future (to better align with a future total bytes "sized_by"
> attribute), name the wrapper macro "__counted_by", which also reads more
> clearly (and concisely) in structure definitions.
>
> [1] https://reviews.llvm.org/D148381
> [2] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108896
>
> Cc: Miguel Ojeda <ojeda@xxxxxxxxxx>
> Cc: Bill Wendling <morbo@xxxxxxxxxx>
> Cc: Qing Zhao <qing.zhao@xxxxxxxxxx>
> Cc: Gustavo A. R. Silva <gustavoars@xxxxxxxxxx>
> Cc: Nick Desaulniers <ndesaulniers@xxxxxxxxxx>
> Cc: Nathan Chancellor <nathan@xxxxxxxxxx>
> Cc: Tom Rix <trix@xxxxxxxxxx>
> Cc: llvm@xxxxxxxxxxxxxxx
> Signed-off-by: Kees Cook <keescook@xxxxxxxxxxxx>

Reviewed-by: Nathan Chancellor <nathan@xxxxxxxxxx>

I agree with Miguel's comment formatting and content suggestions. Thanks
for the links, they look good. If we have to update the name of the
attribute later, it is not the end of the world, as getting the coversion
started at this phase will make the roll out quicker.

> ---
> include/linux/compiler_attributes.h | 12 ++++++++++++
> 1 file changed, 12 insertions(+)
>
> diff --git a/include/linux/compiler_attributes.h b/include/linux/compiler_attributes.h
> index e659cb6fded3..9d63fe2024d5 100644
> --- a/include/linux/compiler_attributes.h
> +++ b/include/linux/compiler_attributes.h
> @@ -123,6 +123,18 @@
> # define __designated_init
> #endif
>
> +/*
> + * Optional: future support coming in clang 17 and gcc 14
> + *
> + * gcc: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108896
> + * clang: https://reviews.llvm.org/D148381
> + */
> +#if __has_attribute(__element_count__)
> +# define __counted_by(member) __attribute__((__element_count__(member)))
> +#else
> +# define __counted_by(member)
> +#endif
> +
> /*
> * Optional: only supported since clang >= 14.0
> *
> --
> 2.34.1
>