docs: Update the documentation for G_GNUC_MALLOC to reflect recent GCC

Thanks to some great investigation by Benjamin Moody, it’s clear that
our documentation and usage of G_GNUC_MALLOC has fallen behind GCC’s
interpretation of the malloc attribute, meaning that recent versions of
GCC could miscompile code which uses G_GNUC_MALLOC incorrectly.

Update the documentation of G_GNUC_MALLOC to match the current GCC
documentation (for GCC 8.2). Following commits will drop our use of
G_GNUC_MALLOC from inappropriate functions.

Specifically, the change in GCC’s interpretation of the malloc attribute
which could cause miscompilation is that returned storage areas are now
assumed to not contain valid pointers — so realloc() cannot have the
malloc attribute, and neither can a function which returns a newly
allocated structure with fields initialised to other pointers.

Signed-off-by: Philip Withnall <withnall@endlessm.com>

https://gitlab.gnome.org/GNOME/glib/issues/1465
This commit is contained in:
Philip Withnall 2018-08-22 11:05:30 +01:00
parent b2029fa9c7
commit c879f50f8a

View File

@ -2096,15 +2096,29 @@
/**
* G_GNUC_MALLOC:
*
* Expands to the GNU C malloc function attribute if the compiler is gcc.
* Declaring a function as malloc enables better optimization of the function.
* A function can have the malloc attribute if it returns a pointer which is
* guaranteed to not alias with any other pointer when the function returns
* (in practice, this means newly allocated memory).
* Expands to the
* [GNU C `malloc` function attribute](https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-functions-that-behave-like-malloc)
* if the compiler is gcc.
* Declaring a function as `malloc` enables better optimization of the function,
* but must only be done if the allocation behaviour of the function is fully
* understood, otherwise miscompilation can result.
*
* A function can have the `malloc` attribute if it returns a pointer which is
* guaranteed to not alias with any other pointer valid when the function
* returns, and moreover no pointers to valid objects occur in any storage
* addressed by the returned pointer.
*
* In practice, this means that `G_GNUC_MALLOC` can be used with any function
* which returns unallocated or zeroed-out memory, but not with functions which
* return initialised structures containing other pointers, or with functions
* that reallocate memory. This definition changed in GLib 2.58 to match the
* stricter definition introduced around GCC 5.
*
* Place the attribute after the declaration, just before the semicolon.
*
* See the GNU C documentation for more details.
* See the
* [GNU C documentation](https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-functions-that-behave-like-malloc)
* for more details.
*
* Since: 2.6
*/