Re: [PATCH v6 3/5] compiler_types: Introduce __flex_counter() and family

Kees Cook
2025-12-04T20:25:59Z

On Thu, Dec 04, 2025 at 09:54:35AM +0100, Peter Zijlstra wrote:
> On Wed, Dec 03, 2025 at 03:30:33PM -0800, Kees Cook wrote:
> > Introduce __flex_counter() which wraps __builtin_counted_by_ref(),
> > as newly introduced by GCC[1] and Clang[2]. Use of __flex_counter()
> > allows access to the counter member of a struct's flexible array member
> > when it has been annotated with __counted_by().
> >
> > Introduce typeof_flex_counter(), overflows_flex_counter_type(), and
> > __set_flex_counter() to provide the needed _Generic() wrappers to get
> > sane results out of __flex_counter().
> >
> > For example, with:
> >
> > struct foo {
> > int counter;
> > short array[] __counted_by(counter);
> > } *p;
> >
> > __flex_counter(p->array) will resolve to: &p->counter
> >
> > typeof_flex_counter(p->array) will resolve to "int". (If p->array was not
> > annotated, it would resolve to "size_t".)
>
> Uhh, how will this interact with the proposed extension of
> __counted_by() to normal pointer types?

Good point -- at present __builtin_counted_by_ref() only works on flex
arrays. I will ask the compiler devs their thoughts on expanding it to
the pointer references too...

--
Kees Cook