libmbedtls: mbedtls_mpi_exp_mod(): optimize mempool usage
With W allocated in the mempool instead of the stack it is more important
to utilize the mempool in a stack like way.
With this patch allocation and initialization of W is moved to a point
where all following mempool allocations are free before the function
returns.
This reduces maximum memory consumption of mempool in regression case
8101 for an AArch64 TA in from 17280 to 7640 bytes. Figures for an
AArch32 TA are 12040 to 5288 bytes.
Reviewed-by: Joakim Bech <joakim.bech@linaro.org>
Signed-off-by: Jens Wiklander <jens.wiklander@linaro.org>
diff --git a/lib/libmbedtls/mbedtls/library/bignum.c b/lib/libmbedtls/mbedtls/library/bignum.c
index 4c1840a..e947a1c 100644
--- a/lib/libmbedtls/mbedtls/library/bignum.c
+++ b/lib/libmbedtls/mbedtls/library/bignum.c
@@ -1789,7 +1789,7 @@
size_t bufsize, nbits;
mbedtls_mpi_uint ei, mm, state;
mbedtls_mpi RR, T, Apos;
- mbedtls_mpi *W;
+ mbedtls_mpi *W = NULL;
const size_t array_size_W = 2 << MBEDTLS_MPI_WINDOW_SIZE;
int neg;
@@ -1804,19 +1804,12 @@
if( mbedtls_mpi_cmp_int( E, 0 ) < 0 )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
- W = mempool_alloc( mbedtls_mpi_mempool,
- sizeof( mbedtls_mpi ) * array_size_W );
- if( W == NULL )
- return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
-
/*
* Init temps and window size
*/
mbedtls_mpi_montg_init( &mm, N );
mbedtls_mpi_init_mempool( &RR ); mbedtls_mpi_init_mempool( &T );
mbedtls_mpi_init_mempool( &Apos );
- for( i = 0; i < array_size_W; i++ )
- mbedtls_mpi_init_mempool( W + i );
i = mbedtls_mpi_bitlen( E );
@@ -1828,7 +1821,7 @@
j = N->n + 1;
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, j ) );
- MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[1], j ) );
+
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &T, j * 2 ) );
/*
@@ -1857,6 +1850,16 @@
else
memcpy( &RR, _RR, sizeof( mbedtls_mpi ) );
+ W = mempool_alloc( mbedtls_mpi_mempool,
+ sizeof( mbedtls_mpi ) * array_size_W );
+ if( W == NULL ) {
+ ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
+ goto cleanup;
+ }
+ for( i = 0; i < array_size_W; i++ )
+ mbedtls_mpi_init_mempool( W + i );
+ MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[1], j ) );
+
/*
* W[1] = A * R^2 * R^-1 mod N = A * R mod N
*/
@@ -1988,8 +1991,9 @@
cleanup:
- for( i = 0; i < array_size_W; i++ )
- mbedtls_mpi_free( W + i );
+ if( W )
+ for( i = 0; i < array_size_W; i++ )
+ mbedtls_mpi_free( W + i );
mempool_free( mbedtls_mpi_mempool , W );
mbedtls_mpi_free( &T ); mbedtls_mpi_free( &Apos );