C is particularly susceptible to security issues. The advent of sanitizers mitigates some of these issues by automatically inserting bounds checking, but they are not able to do so in all situations, especially for flexible array members whose size is only known at runtime and typically opaque to the compiler. The alloc_size attribute on malloc() may be used for bounds checking flexible array members within the same function as the allocation. However, this attribute’s information is not carried with the allocated object, making it impossible to perform bounds checking elsewhere.
To mitigate this drawback, Clang and GCC are introducing the counted_by attribute for flexible array members. When applied to the flexible array member, the counted_by attribute is used by the sanitizer (enabled by -fsanitize=array-bounds) to explicitly reference the field that stores the number of elements. This creates an implicit relationship between the flexible array member and the count field, enabling the array bounds sanitizer to verify flexible array operations. There are rules to follow when using this feature.
Fortification uses the __builtin_object_size() and __builtin_dynamic_object_size() builtins to prevent buffer overflows on memory and string operations by determining if input passed into a function is valid (i.e. “safe”). However, a call to __builtin_dynamic_object_size() is generally unable to take the size of a flexible array member into account. With the counted_by attribute, it becomes possible to calculate the size and improve safety.
The aim is to expand the use of this attribute to more flexible array members and enforce its use in the future.