gmacros: Add G_COUNTED_BY macro

This currently probably does nothing, but in future both gcc and clang
will support the annotation it uses, and use that to do compile-time
bounds checking on flexible arrays.

See https://people.kernel.org/kees/bounded-flexible-arrays-in-c

It’s the same implementation as used in the kernel:
805d849d7c/include/linux/compiler_attributes.h (L97-L108).

Signed-off-by: Philip Withnall <pwithnall@gnome.org>
This commit is contained in:
Philip Withnall 2024-02-29 13:40:31 +00:00
parent 8618f50d16
commit 9d23578318
2 changed files with 25 additions and 0 deletions

View File

@ -825,6 +825,25 @@ by application programmers.
`G_HAVE_GNUC_VISIBILITY`
: Defined to 1 if GCC-style visibility handling is supported.
`G_COUNTED_BY(element)`
: Indicates that the `struct` member being annotated is a flexible length
array and that the given `element` contains its length (in elements, not
bytes).
Place the attribute after the declaration of the `struct` member which is a
flexible array, just before the semicolon.
struct
{
size_t n_doubles;
double array_of_doubles[] G_COUNTED_BY(n_doubles);
};
See the [GNU C documentation](https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html#index-element-count-variable-attribute) for more details.
Since: 2.82
## Deprecation

View File

@ -405,6 +405,12 @@
#define G_GNUC_ALLOC_SIZE2(x,y)
#endif
#if g_macro__has_attribute(__counted_by__)
#define G_COUNTED_BY(x) __attribute__(__counted_by__(x))
#else
#define G_COUNTED_BY(x)
#endif
/**
* G_GNUC_PRINTF:
* @format_idx: the index of the argument corresponding to the