Hi, This is the 2nd version of the patch, per our discussion based on the review comments for the 1st version, the major changes in this version are:
1. change the name "element_count" to "counted_by"; 2. change the parameter for the attribute from a STRING to an Identifier; 3. Add logic and testing cases to handle anonymous structure/unions; 4. Clarify documentation to permit the situation when the allocation size is larger than what's specified by "counted_by", at the same time, it's user's error if allocation size is smaller than what's specified by "counted_by"; 5. Add a complete testing case for using counted_by attribute in __builtin_dynamic_object_size when there is mismatch between the allocation size and the value of "counted_by", the expecting behavior for each case and the explanation on why in the comments. As discussed, I plan to add two more separate patch sets after this initial patch set is approved and committed. set 1. A new warning option and a new sanitizer option for the user error when the allocation size is smaller than the value of "counted_by". set 2. An improvement to __builtin_dynamic_object_size for the following case: struct A { size_t foo; int array[] __attribute__((counted_by (foo))); }; extern struct fix * alloc_buf (); int main () { struct fix *p = alloc_buf (); __builtin_object_size(p->array, 0) == sizeof(struct A) + p->foo * sizeof(int); /* with the current algorithm, it’s UNKNOWN */ __builtin_object_size(p->array, 2) == sizeof(struct A) + p->foo * sizeof(int); /* with the current algorithm, it’s UNKNOWN */ } Bootstrapped and regression tested on both aarch64 and X86, no issue. Please see more details on the description of this work on: https://gcc.gnu.org/pipermail/gcc-patches/2023-May/619708.html Okay for committing? thanks. Qing Qing Zhao (3): Provide counted_by attribute to flexible array member field (PR108896) Use the counted_by atribute info in builtin object size [PR108896] Use the counted_by attribute information in bound sanitizer[PR108896] gcc/c-family/c-attribs.cc | 54 ++++- gcc/c-family/c-common.cc | 13 ++ gcc/c-family/c-common.h | 1 + gcc/c-family/c-ubsan.cc | 16 ++ gcc/c/c-decl.cc | 79 +++++-- gcc/doc/extend.texi | 73 +++++++ .../gcc.dg/flex-array-counted-by-2.c | 74 +++++++ .../gcc.dg/flex-array-counted-by-3.c | 197 ++++++++++++++++++ gcc/testsuite/gcc.dg/flex-array-counted-by.c | 40 ++++ .../ubsan/flex-array-counted-by-bounds-2.c | 27 +++ .../ubsan/flex-array-counted-by-bounds.c | 46 ++++ gcc/tree-object-size.cc | 37 +++- gcc/tree.cc | 133 ++++++++++++ gcc/tree.h | 15 ++ 14 files changed, 780 insertions(+), 25 deletions(-) create mode 100644 gcc/testsuite/gcc.dg/flex-array-counted-by-2.c create mode 100644 gcc/testsuite/gcc.dg/flex-array-counted-by-3.c create mode 100644 gcc/testsuite/gcc.dg/flex-array-counted-by.c create mode 100644 gcc/testsuite/gcc.dg/ubsan/flex-array-counted-by-bounds-2.c create mode 100644 gcc/testsuite/gcc.dg/ubsan/flex-array-counted-by-bounds.c -- 2.31.1