apps: introduce app_malloc_array()

Similar to app_malloc(), provides a wrapper for OPENSSL_malloc_array()
that bails out when a NULL pointer is returned.

Signed-off-by: Eugene Syromiatnikov <esyr@openssl.org>

Reviewed-by: Paul Dale <ppzgs1@gmail.com>
Reviewed-by: Dmitry Belyavskiy <beldmit@gmail.com>
Reviewed-by: Neil Horman <nhorman@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/28444)
This commit is contained in:
Eugene Syromiatnikov 2025-09-04 17:57:18 +02:00 committed by Neil Horman
parent 362739d771
commit 4f288b60e8
3 changed files with 44 additions and 0 deletions

View File

@ -230,7 +230,26 @@ typedef struct ca_db_st {
extern int do_updatedb(CA_DB *db, time_t *now);
void app_bail_out(char *fmt, ...);
/**
* OPENSSL_malloc() wrapper that bails out with a meaningful message on failure.
*
* @param sz Number of bytes to allocate.
* @param what Description of the object being allocated.
* @return On success, returns a pointer to the newly allocated memory.
* on failure, calls app_bail_out() to terminate the program.
*/
void *app_malloc(size_t sz, const char *what);
/**
* OPENSSL_malloc_array() wrapper that bails out with a meaningful message
* on failure.
*
* @param n Number of objects to allocate memory for.
* @param sz Size in bytes of each object to be allocated.
* @param what Description of the array being allocated.
* @return On success, returns a pointer to the newly allocated memory;
* on failure, calls app_bail_out() to terminate the program.
*/
void *app_malloc_array(size_t n, size_t sz, const char *what);
/* load_serial, save_serial, and rotate_serial are also used for CRL numbers */
BIGNUM *load_serial(const char *serialfile, int *exists, int create,

View File

@ -695,6 +695,16 @@ void *app_malloc(size_t sz, const char *what)
return vp;
}
void *app_malloc_array(size_t n, size_t sz, const char *what)
{
void *vp = OPENSSL_malloc_array(n, sz);
if (vp == NULL)
app_bail_out("%s: Could not allocate %zu*%zu bytes for %s\n",
opt_getprog(), n, sz, what);
return vp;
}
char *next_item(char *opt) /* in list separated by comma and/or space */
{
/* advance to separator (comma or whitespace), if any */

View File

@ -29,6 +29,21 @@ void *app_malloc(size_t sz, const char *what)
return vp;
}
void *app_malloc_array(size_t n, size_t sz, const char *what)
{
void *vp;
/*
* Instead of exiting with a failure, abort() is called which makes sure
* that there will be a good stack trace for debugging purposes.
*/
if (!TEST_ptr(vp = OPENSSL_malloc_array(n, sz))) {
TEST_info("Could not allocate %zu*%zu bytes for %s\n", n, sz, what);
abort();
}
return vp;
}
/* shim to prevent sucking in too much from apps */
int opt_legacy_okay(void)