[clang] [Clang] Fix __builtin_dynamic_object_size off by 4 (PR #111015)
Jan Hendrik Farr via cfe-commits
cfe-commits at lists.llvm.org
Thu Oct 3 17:02:47 PDT 2024
Cydox wrote:
>From page 113 and 114 of: https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1548.pdf
"As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply. However, when a . (or ->) operator has a left operand that is (a pointer to) a structure with a flexible array member and the right operand names that member, **it behaves as if that member were replaced with the longest array (with the same element type) that would not make the structure larger than the object being accessed**; the offset of the array shall remain that of the flexible array member, even if this would differ from that of the replacement array. If this array would have no elements, it behaves as if it had one element but the behavior is undefined if any attempt is made to access that element or to generate a pointer one past it." [emphasis added]
The struct object that has an FAM behaves like if the FAM was replaced with the largest array that would not the object larger than it is (if the . or -> operator is used). Clang's behavior is currently returning just the size of the object that it would be if the FAM was replaced with that largest possible array (and the object only behaves like that when the . or -> operator is used).
So when `__builtin_dynamic_object_size(acl, 0)` returns 36 in the reproducer that is definitely not according to the standard. 1. The standard makes clear that the size of the object `acl` points to is `>=` than the struct it behaves like. 2. There is not even a `.` or `->` operator involved here.
GCC's behavior thus makes sense. It does not use `__counted_by` attributes in the determination of `__builtin_dynamic_object_size(acl, 0)` at all. It either uses an allocation size known from the context or returns the maximum possible value to indicate that it does not know the size of the object.
Returning `sizeof(struct s) + p->count * sizeof(*p->array))` instead of the INT_MAX would be a compromise as we definitely know that the object is at most that large.
https://github.com/llvm/llvm-project/pull/111015
More information about the cfe-commits
mailing list