Skip to content

Commit

Permalink
libmbedtls: mbedtls_mpi_exp_mod(): reduce stack usage
Browse files Browse the repository at this point in the history
The W variable is 3072 bytes on AArch64 with MBEDTLS_MPI_WINDOW_SIZE set
to 6 for maximum performance. Instead of allocating such a large
variable on the stack use mempool_alloc().

Reviewed-by: Etienne Carriere <etienne.carriere@linaro.org>
Reviewed-by: Jerome Forissier <jerome.forissier@linaro.org>
Signed-off-by: Jens Wiklander <jens.wiklander@linaro.org>
[jf: rebased onto mbedtls-2.27.0]
Signed-off-by: Jerome Forissier <jerome@forissier.org>
[jw: rebased onto mbedtls-3.4.0]
Signed-off-by: Jens Wiklander <jens.wiklander@linaro.org>
  • Loading branch information
jenswi-linaro committed Oct 6, 2023
1 parent 0ba4eb8 commit 7108668
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions lib/libmbedtls/mbedtls/library/bignum.c
Original file line number Diff line number Diff line change
Expand Up @@ -1714,7 +1714,9 @@ int mbedtls_mpi_exp_mod(mbedtls_mpi *X, const mbedtls_mpi *A,
size_t bufsize, nbits;
size_t exponent_bits_in_window = 0;
mbedtls_mpi_uint ei, mm, state;
mbedtls_mpi RR, T, W[(size_t) 1 << MBEDTLS_MPI_WINDOW_SIZE], WW, Apos;
mbedtls_mpi RR, T, WW, Apos;
mbedtls_mpi *W;
const size_t array_size_W = 2 << MBEDTLS_MPI_WINDOW_SIZE;
int neg;

MPI_VALIDATE_RET(X != NULL);
Expand All @@ -1735,14 +1737,19 @@ int mbedtls_mpi_exp_mod(mbedtls_mpi *X, const mbedtls_mpi *A,
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
*/
mpi_montg_init(&mm, N);
mbedtls_mpi_init_mempool(&RR); mbedtls_mpi_init(&T);
mbedtls_mpi_init_mempool(&Apos);
mbedtls_mpi_init_mempool(&WW);
for (i = 0; i < ARRAY_SIZE(W); i++)
for( i = 0; i < array_size_W; i++ )
mbedtls_mpi_init_mempool(W + i);

i = mbedtls_mpi_bitlen(E);
Expand Down Expand Up @@ -1983,8 +1990,9 @@ int mbedtls_mpi_exp_mod(mbedtls_mpi *X, const mbedtls_mpi *A,

cleanup:

for (i = 0; i < ARRAY_SIZE(W); i++)
mbedtls_mpi_free( W + i );
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);
Expand Down

0 comments on commit 7108668

Please sign in to comment.