From a4b36cd0d5901f6142596bda39ddad67c86a71cc Mon Sep 17 00:00:00 2001 From: Sergey Sharybin Date: Fri, 12 Apr 2024 17:22:46 +0200 Subject: [PATCH] Guarded allocator: Ensure alignment and size of MemHead Ensure that the MemHead and MemHeadAligned are such that memory allocation followed with the head offset keeps the allocation aligned to at least MEM_MIN_CPP_ALIGNMENT. Pull Request: https://projects.blender.org/blender/blender/pulls/120582 --- intern/guardedalloc/MEM_guardedalloc.h | 7 +++++++ intern/guardedalloc/intern/mallocn_guarded_impl.cc | 2 ++ intern/guardedalloc/intern/mallocn_lockfree_impl.cc | 4 ++++ 3 files changed, 13 insertions(+) diff --git a/intern/guardedalloc/MEM_guardedalloc.h b/intern/guardedalloc/MEM_guardedalloc.h index e142802e6c5..02011da11cb 100644 --- a/intern/guardedalloc/MEM_guardedalloc.h +++ b/intern/guardedalloc/MEM_guardedalloc.h @@ -258,6 +258,13 @@ void MEM_use_guarded_allocator(void); # include # include +/* Conservative value of memory alignment returned by non-aligned OS-level memory allocation + * functions. For alignments smaller than this value, using non-aligned versions of allocator API + * functions is okay, allowing use of calloc, for example. */ +# define MEM_MIN_CPP_ALIGNMENT \ + (__STDCPP_DEFAULT_NEW_ALIGNMENT__ < alignof(void *) ? __STDCPP_DEFAULT_NEW_ALIGNMENT__ : \ + alignof(void *)) + /** * Allocate new memory for and constructs an object of type #T. * #MEM_delete should be used to delete the object. Just calling #MEM_freeN is not enough when #T diff --git a/intern/guardedalloc/intern/mallocn_guarded_impl.cc b/intern/guardedalloc/intern/mallocn_guarded_impl.cc index 39c389e9e7e..3efeea6f039 100644 --- a/intern/guardedalloc/intern/mallocn_guarded_impl.cc +++ b/intern/guardedalloc/intern/mallocn_guarded_impl.cc @@ -129,6 +129,8 @@ typedef struct MemHead { #endif } MemHead; +static_assert(MEM_MIN_CPP_ALIGNMENT <= alignof(MemHead), "Bad alignment of MemHead"); +static_assert(MEM_MIN_CPP_ALIGNMENT <= sizeof(MemHead), "Bad size of MemHead"); typedef MemHead MemHeadAligned; diff --git a/intern/guardedalloc/intern/mallocn_lockfree_impl.cc b/intern/guardedalloc/intern/mallocn_lockfree_impl.cc index 82d14e990db..e154c17cf6d 100644 --- a/intern/guardedalloc/intern/mallocn_lockfree_impl.cc +++ b/intern/guardedalloc/intern/mallocn_lockfree_impl.cc @@ -32,11 +32,15 @@ typedef struct MemHead { /* Length of allocated memory block. */ size_t len; } MemHead; +static_assert(MEM_MIN_CPP_ALIGNMENT <= alignof(MemHead), "Bad alignment of MemHead"); +static_assert(MEM_MIN_CPP_ALIGNMENT <= sizeof(MemHead), "Bad size of MemHead"); typedef struct MemHeadAligned { short alignment; size_t len; } MemHeadAligned; +static_assert(MEM_MIN_CPP_ALIGNMENT <= alignof(MemHeadAligned), "Bad alignment of MemHeadAligned"); +static_assert(MEM_MIN_CPP_ALIGNMENT <= sizeof(MemHeadAligned), "Bad size of MemHeadAligned"); static bool malloc_debug_memset = false;