GAtomicArray: Ensure metadata does not misalign the payload

We have to ensure that the memory location is sufficiently aligned to
store any object. This unbreaks the code for CHERI where using gsize
results in values that are only aligned to 8 bytes, but we need 16 byte
alignment for pointers. This is fully API/ABI compatible since amount
of padding before the actual allocation does not change for existing
architectures, only for CHERI.

Helps: https://gitlab.gnome.org/GNOME/glib/-/issues/2842
This commit is contained in:
Alex Richardson 2022-12-14 23:55:19 +00:00
parent eafd19da29
commit a03950b43c
2 changed files with 14 additions and 4 deletions

View File

@ -76,13 +76,14 @@ freelist_alloc (gsize size, gboolean reuse)
} }
} }
real_size = sizeof (gsize) + MAX (size, sizeof (FreeListNode)); real_size = sizeof (GAtomicArrayMetadata) + MAX (size, sizeof (FreeListNode));
mem = g_slice_alloc (real_size); mem = g_slice_alloc (real_size);
mem = ((char *) mem) + sizeof (gsize); mem = ((char *) mem) + sizeof (GAtomicArrayMetadata);
G_ATOMIC_ARRAY_DATA_SIZE (mem) = size; G_ATOMIC_ARRAY_DATA_SIZE (mem) = size;
#if ENABLE_VALGRIND #if ENABLE_VALGRIND
VALGRIND_MALLOCLIKE_BLOCK (mem, real_size - sizeof (gsize), FALSE, FALSE); VALGRIND_MALLOCLIKE_BLOCK (mem, real_size - sizeof (GAtomicArrayMetadata),
FALSE, FALSE);
#endif #endif
return mem; return mem;

View File

@ -27,7 +27,16 @@
G_BEGIN_DECLS G_BEGIN_DECLS
#define G_ATOMIC_ARRAY_DATA_SIZE(mem) (*((gsize *) (mem) - 1)) typedef union _GAtomicArrayMetadata
{
gsize size;
/* We have to ensure that the memory location is sufficiently aligned to
* store any object. With C11 this would be max_align_t, but in practise
* gpointer is sufficient for all known architectures. We could change
* this to `_Alignas(max_align_t) char pad` once we depend on C11. */
gpointer _alignment_padding;
} GAtomicArrayMetadata;
#define G_ATOMIC_ARRAY_DATA_SIZE(mem) (((GAtomicArrayMetadata *) (mem) - 1)->size)
typedef struct _GAtomicArray GAtomicArray; typedef struct _GAtomicArray GAtomicArray;
struct _GAtomicArray { struct _GAtomicArray {