From 9d23578318c7b5dcee7cb891e021291c91e1b773 Mon Sep 17 00:00:00 2001 From: Philip Withnall Date: Thu, 29 Feb 2024 13:40:31 +0000 Subject: [PATCH] gmacros: Add G_COUNTED_BY macro MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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: https://github.com/torvalds/linux/blob/805d849d7c3cc1f38efefd48b2480d62b7b5dcb7/include/linux/compiler_attributes.h#L97-L108. Signed-off-by: Philip Withnall --- docs/reference/glib/macros.md | 19 +++++++++++++++++++ glib/gmacros.h | 6 ++++++ 2 files changed, 25 insertions(+) diff --git a/docs/reference/glib/macros.md b/docs/reference/glib/macros.md index 2e5dc2793..162b7aa86 100644 --- a/docs/reference/glib/macros.md +++ b/docs/reference/glib/macros.md @@ -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 diff --git a/glib/gmacros.h b/glib/gmacros.h index 2d66c2f0c..a1d69a094 100644 --- a/glib/gmacros.h +++ b/glib/gmacros.h @@ -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