]> git.ipfire.org Git - thirdparty/linux.git/commit
compiler_types: Introduce __flex_counter() and family
authorKees Cook <kees@kernel.org>
Wed, 3 Dec 2025 23:30:33 +0000 (15:30 -0800)
committerKees Cook <kees@kernel.org>
Wed, 14 Jan 2026 22:43:01 +0000 (14:43 -0800)
commit81cee9166a9073b4da28e970e75d7f89c98ed966
tree8354986a0fa6c2f2d1d016394d2b5a8f25041ade
parent070580b0b1740a4b930f367d21fdb5b253a8b3fb
compiler_types: Introduce __flex_counter() and family

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".)

overflows_flex_counter_type(typeof(*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().)

Link: https://patch.msgid.link/20251203233036.3212363-3-kees@kernel.org
Signed-off-by: Kees Cook <kees@kernel.org>
include/linux/compiler_types.h
include/linux/overflow.h