crypto/mem.c: use open-coded aligned alloc when posix_memalign fails

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 <esyr@openssl.org>

Reviewed-by: Neil Horman <nhorman@openssl.org>
Reviewed-by: Saša Nedvědický <sashan@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/28295)
This commit is contained in:
Eugene Syromiatnikov 2025-08-28 15:55:29 +02:00 committed by Neil Horman
parent 8e28f5c0b9
commit f75a6d951a
2 changed files with 6 additions and 25 deletions

View File

@ -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. */ /* Allow non-malloc() allocations as long as no malloc_impl is provided. */
if (malloc_impl == CRYPTO_malloc) { if (malloc_impl == CRYPTO_malloc) {
#if defined(_BSD_SOURCE) || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) #if defined(_BSD_SOURCE) || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
int memalign_ret;
void *ret; void *ret;
/* posix_memalign() requires alignment to be at least sizeof(void *) */ /* posix_memalign() requires alignment to be at least sizeof(void *) */
if (alignment < sizeof(void *)) if (alignment < sizeof(void *))
alignment = sizeof(void *); alignment = sizeof(void *);
if ((memalign_ret = posix_memalign(&ret, alignment, num))) { if (posix_memalign(&ret, alignment, num) == 0) {
ret = NULL;
switch (memalign_ret) {
case EINVAL:
ossl_report_alloc_err_inv(file, line);
break;
case ENOMEM:
ossl_report_alloc_err(file, line);
break;
}
}
*freeptr = ret; *freeptr = ret;
return ret; return ret;
}
#endif #endif
} }

View File

@ -176,19 +176,10 @@ static const struct array_aligned_alloc_vector {
{ SIZE_MAX / 8 + 9, 8, 64, EXP_NONNULL, EXP_INT_OF }, { SIZE_MAX / 8 + 9, 8, 64, EXP_NONNULL, EXP_INT_OF },
/* /*
* posix_memalign expected to fail with ENOMEM, while the open-coded * the open-coded implementation tries to alloc size + alignment,
* implementation tries to alloc size + alignment, which should fail * which should fail on integer overflow.
* on integer overflow.
*/ */
{ 1, SIZE_MAX / 2 + 2, SIZE_MAX / 2 + 1, { 1, SIZE_MAX - 32767, 65536, EXP_INT_OF, EXP_INT_OF },
#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
},
}; };
static int secure_memory_is_secure; static int secure_memory_is_secure;