[clang] [Clang] Fix __builtin_dynamic_object_size off by 4 (PR #111015)

Jan Hendrik Farr via cfe-commits cfe-commits at lists.llvm.org
Wed Oct 9 16:09:14 PDT 2024


Cydox wrote:

Changing the `struct_size` macro in the kernel [1] would likely be an unreasonable amount of work. To quote Kees from the kernel mailing list [2]:

> [...] if we want to change struct_size(), then we must (via
allmodconfig builds) determine all the places in the kernel
where the calculated size changes, and audit those for safety.

Additionally I think the kernel's code is not unreasonable as this is a common way to allocate structs with flexible array members. It's even how the example in the C11 standard does it. So it's likely that other projects are also expecting the same behavior.

I think it would be way easier to get clang to follow what the kernel currently expects. While I think clang's current behavior is not quite correct and the maximum size should be calculated differently [3], that doesn't solve the compatibility with the linux kernel for all cases. So ideally we should introduce the behavior that this PR calls for:
```
sizeof(struct s) + p->count * sizeof(*p->array))
```
via an option.

I see a few ways this could be accomplished:
1. a global `-f` flag
2. adding the flag as the third bit of the `type` parameter to `__bdos`
3. add a separate builtin

I prefer option 2. Should this be coordinated with gcc? Currently they don't implement `counted_by` for this case at all, but I don't know if they have plans to do so.

I'm happy to adjust this PR to hide it behind an option.

[1] https://github.com/torvalds/linux/blob/b983b271662bd6104d429b0fd97af3333ba760bf/include/linux/overflow.h#L354-L373
[2] https://lore.kernel.org/linux-bcachefs/202410040958.C19D3B9E48@keescook/
[3] https://lore.kernel.org/linux-bcachefs/ZwNb-_UPL9BPSg9N@archlinux/#t

https://github.com/llvm/llvm-project/pull/111015


More information about the cfe-commits mailing list