https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108896

            Bug ID: 108896
           Summary: provide "element_count" attribute to give more context
                    to __builtin_dynamic_object_size() and
                    -fsanitize=bounds
           Product: gcc
           Version: unknown
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: kees at outflux dot net
  Target Milestone: ---

Frequently a structure containing a flexible array member will also contain a
member where the count of array elements is stored. For example:

struct foo {
    ...
    unsigned int count;
    ...
    int data[];
};

struct foo *allocate_foo(unsigned int how_many)
{
    struct foo *p;

    p = malloc(sizeof(*p) + how_many * sizeof(*byte_array));
    p->count = how_many;

    return p;
}

While __builtin_dynamic_object_size(p->data, 1) will know the size within
"allocate_foo" due to malloc's __alloc_size hinting, this information is
immediately lost on return. However, the information _is_ still available in
p->count, but the compiler has no way to know about it.

Please provide a struct member attribute "element_count" that can be used to
associate the size of a flexible array to another struct member. For example:

struct foo {
    ...
    unsigned int count;
    ...
    int data[] __attribute__((__element_count__(count)));
};

Now any later examination of the size of "data" can be calculated. For example,
this equality will hold true:

    __builtin_dynamic_object_size(p->data) == p->count * sizeof(*p->data)

and -fsanitize-bounds can examine this as well, to trap:

    p->data[index] = ...; /* traps when index < 0, or index >= p->count */

Reply via email to