[clang] [Clang][Sema] Support 'counted_by' attribute on FAM/pointers in anonymous unions (PR #171996)
Kees Cook via cfe-commits
cfe-commits at lists.llvm.org
Wed Jan 14 11:22:20 PST 2026
kees wrote:
> For __counted_by to work on a union, one of the following must be true:
>
> Homogeneous Sizes: All members of the union must have the exact same sizeof(). Byte-Size Semantics: The attribute would need to be __sized_by.
>
> Plus, I'm assuming if you have a union field that has `counted_by` or `sized_by`, all of the fields need the same annotation following the above rule.
>
> Requesting changes to add these restrictions.
This makes sense to me for FAMs, but not for pointer members. e.g.:
```C
struct foo {
int count;
union {
u16 a[] __counted_by(count);
s16 b[] __counted_by(count):
};
} *p;
```
With this, `__builtin_dynamic_object_size(p, 1)` will be unambiguous. If `b` were an `int`, the compiler cannot know which member (`a` or `b`) to use to figure out the object size.
For pointer members, though, it shouldn't matter. They can be anything:
```C
struct foo {
int count1, count2;
union {
int z;
char *buf __counted_by(count1);
short *weird __counted_by(count2);
};
} *p;
```
Both `p->buf` and `p->weird` have unambiguous sizes. Is the concern about aliasing due to `buf` and `weird` having the same memory location?
https://github.com/llvm/llvm-project/pull/171996
More information about the cfe-commits
mailing list