diff options
author | Jessica Clarke <jrtc27@jrtc27.com> | 2022-01-23 20:33:47 +0000 |
---|---|---|
committer | Junio C Hamano <gitster@pobox.com> | 2022-01-24 10:26:40 -0800 |
commit | e38bcc66d8af1a46203abe9b6ffc8aa124865803 (patch) | |
tree | 01c0873f8af3cccd5b16e52e64bf893f6ca7f29b | |
parent | Git 2.34.1 (diff) | |
download | tgif-e38bcc66d8af1a46203abe9b6ffc8aa124865803.tar.xz |
mem-pool: don't assume uintmax_t is aligned enough for all types
mem_pool_alloc uses sizeof(uintmax_t) as a proxy for what should be
_Alignof(max_align_t) in C11. On most architectures this is sufficient
(though on m68k it is in fact overly strict, since the de-facto ABI,
which differs from the specified System V ABI, has the maximum alignment
of all types as 2 bytes), but on CHERI, and thus Arm's Morello
prototype, it is insufficient for any type that stores a pointer, which
must be aligned to 128 bits (on 64-bit architectures extended with
CHERI), whilst uintmax_t is a 64-bit integer.
Fix this by introducing our own approximation for max_align_t and a
means to compute _Alignof it without relying on C11. Currently this
union only contains uintmax_t and void *, but more types can be added as
needed.
Signed-off-by: Jessica Clarke <jrtc27@jrtc27.com>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
-rw-r--r-- | mem-pool.c | 26 |
1 files changed, 23 insertions, 3 deletions
diff --git a/mem-pool.c b/mem-pool.c index ccdcad2e3d..599d8e895f 100644 --- a/mem-pool.c +++ b/mem-pool.c @@ -8,6 +8,26 @@ #define BLOCK_GROWTH_SIZE (1024 * 1024 - sizeof(struct mp_block)) /* + * The inner union is an approximation for C11's max_align_t, and the + * struct + offsetof computes _Alignof. This can all just be replaced + * with _Alignof(max_align_t) if/when C11 is part of the baseline. + * Note that _Alignof(X) need not be the same as sizeof(X); it's only + * required to be a (possibly trivial) factor. They are the same for + * most architectures, but m68k for example has only 2-byte alignment + * for its 4-byte and 8-byte types, so using sizeof would waste space. + * + * Add more types to the union if the current set is insufficient. + */ +struct git_max_alignment { + char unalign; + union { + uintmax_t max_align_uintmax; + void *max_align_pointer; + } aligned; +}; +#define GIT_MAX_ALIGNMENT offsetof(struct git_max_alignment, aligned) + +/* * Allocate a new mp_block and insert it after the block specified in * `insert_after`. If `insert_after` is NULL, then insert block at the * head of the linked list. @@ -69,9 +89,9 @@ void *mem_pool_alloc(struct mem_pool *pool, size_t len) struct mp_block *p = NULL; void *r; - /* round up to a 'uintmax_t' alignment */ - if (len & (sizeof(uintmax_t) - 1)) - len += sizeof(uintmax_t) - (len & (sizeof(uintmax_t) - 1)); + /* round up to a 'GIT_MAX_ALIGNMENT' alignment */ + if (len & (GIT_MAX_ALIGNMENT - 1)) + len += GIT_MAX_ALIGNMENT - (len & (GIT_MAX_ALIGNMENT - 1)); if (pool->mp_block && pool->mp_block->end - pool->mp_block->next_free >= len) |