On Tue, Oct 21, 2025 at 11:54:47AM +0200, Peter Zijlstra wrote:
> On Mon, Oct 20, 2025 at 03:01:15PM -0700, Kees Cook wrote:
> > Introduce __counted_by_ptr(), which works like __counted_by(), but for
> > pointer struct members:
> > 
> > struct foo {
> >     int a, b, c;
> >     char *buffer __counted_by_ptr(bytes);
> >     short nr_bars;
> >     struct bar *bars __counted_by_ptr(nr_bars);
> >     size_t bytes;
> > };
> > 
> > Since "counted_by" can only be applied to pointer members in very recent
> > compiler versions, its application ends up needing to be distinct from
> > flexible array "counted_by" annotations, hence a separate macro.
> > 
> > Unfortunately, this annotation cannot be used for "void *" members
> > (since such a member is considered a pointer to an incomplete type,
> > and neither Clang nor GCC developers could be convinced otherwise[1],
> > even in the face of the GNU extension that "void *" has size "1 byte"
> > for pointer arithmetic). For "void *" members, we must use the coming
> > "sized_by" attribute.
> 
> So why do we need both __counted_by_ptr() and this __sized_by(), won't
> one be good enough?

I remain extraordinarily frustrated that counted_by can't be used with
"void *". I hit a brick wall on this, though, and don't know how to
convince either GCC or Clang devs to fix it. It's so obviously correct
to me: "void *" uses a 1 byte iterator for arithmetic... so asking how
big a given allocation is should be byte sized!

Let me take another stab at it...

> Also, given the existing __counted_by() is really only usable with
> >=19.1.3 and we're now at 22-ish, do we really need two of these?
> 
> That is, I'm really hating the idea we need 3 different annotations for
> what is effectively the same thing and feel we should try *really* hard
> to make it 1.

As for avoiding __counted_by_ptr(), we could just raise the minimum
Clang and GCC versions to require this, but that means dropping existing
coverage (e.g GCC 15 supports only flexible array counted_by).

Maybe we could do a global __counted_by_ptr -> __counted_by replacement
once GCC 16 is released?

-- 
Kees Cook

Reply via email to