[clang] [BoundsSafety] Allow 'counted_by' attribute on pointers in structs in C (PR #90786)

Dan Liew via cfe-commits cfe-commits at lists.llvm.org
Fri May 10 16:13:00 PDT 2024


delcypher wrote:

> @rapidsna @delcypher @apple-fcloutier @kees:
> 
> Okay, I think I see what the complication is. Are you trying to prevent the use case of someone writing something like:
> 
> ```c
> struct bar;
> 
> struct foo {
>   size_t count;
>   struct bar *ptr __counted_by(count);
> };
> ```
> 
> where `ptr` is a pointer to one large space that the user splits up into `count` number of `struct bar` objects?
> 
> ```c
> struct foo *alloc_foo(size_t count) {
>   struct foo *p = malloc(sizeof(struct foo));
> 
>   p->count;
>   p->ptr = malloc(sizeof(struct bar) * count); // struct bar can't be incomplete here
>   return p;
> }
> ```

With the PR in its current form we **are** preventing this code but **only** because `struct bar` is an incomplete type at the point the attribute is applied. If `struct bar` was defined at the point `struct foo` was defined then this would be allowed. So this restriction has nothing to do with how the user wants to allocate their memory. It's all about the pointee type having a defined size when the `__counted_by` attribute is applied.

As @apple-fcloutier @rapidsna noted this is how `-fbounds-safety` is currently implemented (because its much simpler) but it is a restriction that could be lifted in future by only requiring `struct bar` to be defined at the point that `foo::bar` is used rather than when the `__counted_by` attribute is applied. Given that this PR is allowing `__counted_by` in a new place (pointers in structs) I think its reasonable for us to place restrictions on that until we've proved its actually necessary to have the more complicated implementation.

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


More information about the cfe-commits mailing list