Re: [PATCH v4 1/2] compiler_types: Introduce __flex_counter() and family
From: Kees Cook
Date: Mon Mar 17 2025 - 12:23:09 EST
On Mon, Mar 17, 2025 at 10:43:38AM +0100, Przemek Kitszel wrote:
> On 3/17/25 10:26, Przemek Kitszel wrote:
> > On 3/15/25 04:15, 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(), can_set_flex_counter(), 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".)
> > >
> > > can_set_flex_counter(p->array, COUNT) is the same as:
> > >
> > > COUNT <= type_max(p->counter) && COUNT >= type_min(p->counter)
> > >
> > > (If p->array was not annotated it would return true since everything
> > > fits in size_t.)
> > >
> > > set_flex_counter(p->array, COUNT) is the same as:
> > >
> > > p->counter = COUNT;
> > >
> > > (It is a no-op if p->array is not annotated with __counted_by().)
> > >
> > > Signed-off-by: Kees Cook <kees@xxxxxxxxxx>
> >
> > I agree that there is no suitable fallback handy, but I see counter
> > as integral part of the struct (in contrast to being merely annotation),
> > IOW, without set_flex_counter() doing the assignment, someone will
> > reference it later anyway, without any warning when kzalloc()'d
> >
> > So, maybe BUILD_BUG() instead of no-op?
>
> I get that so far this is only used as an internal helper (in the next
> patch), so for me it would be also fine to just add __ prefix:
> __set_flex_counter(), at least until the following is true:
> "manual initialization of the flexible array counter is still
> required (at some point) after allocation as not all compiler versions
> support the __counted_by annotation yet"
Yeah, that's fair. I will rename set_... and can_set_...
Thought FWIW I'm not sure we'll ever want a BUILD_BUG_ON() just because
there will be flex arrays with future annotations that can't have their
counter set (e.g. annotations that indicate globals, expressions, etc --
support for these cases is coming, if slowly[1]).
-Kees
[1] loooong thread https://gcc.gnu.org/pipermail/gcc-patches/2025-March/677024.html
--
Kees Cook