From f75a6d951a95d6eea68b5ec6ca564fc8edaf1d14 Mon Sep 17 00:00:00 2001 From: Eugene Syromiatnikov Date: Thu, 28 Aug 2025 15:55:29 +0200 Subject: [PATCH] crypto/mem.c: use open-coded aligned alloc when posix_memalign fails MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit While posix_memalign() is generally not expected to fail, we can always use the internal aligned alloc implementation to ensure that any OPENSSL_aligned_malloc failure is indeed fatal and does not require a fallback. Signed-off-by: Eugene Syromiatnikov Reviewed-by: Neil Horman Reviewed-by: Saša Nedvědický (Merged from https://github.com/openssl/openssl/pull/28295) --- crypto/mem.c | 16 +++------------- test/mem_alloc_test.c | 15 +++------------ 2 files changed, 6 insertions(+), 25 deletions(-) diff --git a/crypto/mem.c b/crypto/mem.c index 985359a6813..681cecfadfd 100644 --- a/crypto/mem.c +++ b/crypto/mem.c @@ -242,26 +242,16 @@ void *CRYPTO_aligned_alloc(size_t num, size_t alignment, void **freeptr, /* Allow non-malloc() allocations as long as no malloc_impl is provided. */ if (malloc_impl == CRYPTO_malloc) { #if defined(_BSD_SOURCE) || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) - int memalign_ret; void *ret; /* posix_memalign() requires alignment to be at least sizeof(void *) */ if (alignment < sizeof(void *)) alignment = sizeof(void *); - if ((memalign_ret = posix_memalign(&ret, alignment, num))) { - ret = NULL; - switch (memalign_ret) { - case EINVAL: - ossl_report_alloc_err_inv(file, line); - break; - case ENOMEM: - ossl_report_alloc_err(file, line); - break; - } + if (posix_memalign(&ret, alignment, num) == 0) { + *freeptr = ret; + return ret; } - *freeptr = ret; - return ret; #endif } diff --git a/test/mem_alloc_test.c b/test/mem_alloc_test.c index 2571c4eceb7..30c479cd80a 100644 --- a/test/mem_alloc_test.c +++ b/test/mem_alloc_test.c @@ -176,19 +176,10 @@ static const struct array_aligned_alloc_vector { { SIZE_MAX / 8 + 9, 8, 64, EXP_NONNULL, EXP_INT_OF }, /* - * posix_memalign expected to fail with ENOMEM, while the open-coded - * implementation tries to alloc size + alignment, which should fail - * on integer overflow. + * the open-coded implementation tries to alloc size + alignment, + * which should fail on integer overflow. */ - { 1, SIZE_MAX / 2 + 2, SIZE_MAX / 2 + 1, -#if (defined(_BSD_SOURCE) \ - || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)) \ - && !USE_CUSTOM_ALLOC_FNS - EXP_OOM, EXP_OOM -#else - EXP_INT_OF, EXP_INT_OF -#endif - }, + { 1, SIZE_MAX - 32767, 65536, EXP_INT_OF, EXP_INT_OF }, }; static int secure_memory_is_secure; -- 2.47.3