Skip to content

Commit 91af329

Browse files
committed
Merge remote-tracking branch 'origin/pr/2214' into development
2 parents 14eca24 + 8a6917d commit 91af329

File tree

2 files changed

+27
-13
lines changed

2 files changed

+27
-13
lines changed

ChangeLog

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ Bugfix
1717
build error. Fixed by Haijun Gu #2319.
1818
* Fix signed-to-unsigned integer conversion warning
1919
in X.509 module. Fixes #2212.
20+
* Reduce stack usage of `mpi_write_hlp()` by eliminating recursion.
21+
Fixes #2190.
2022

2123
Changes
2224
* Include configuration file in all header files that use configuration,

library/bignum.c

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -527,26 +527,38 @@ int mbedtls_mpi_read_string( mbedtls_mpi *X, int radix, const char *s )
527527
}
528528

529529
/*
530-
* Helper to write the digits high-order first
530+
* Helper to write the digits high-order first.
531531
*/
532-
static int mpi_write_hlp( mbedtls_mpi *X, int radix, char **p )
532+
static int mpi_write_hlp( mbedtls_mpi *X, int radix,
533+
char **p, const size_t buflen )
533534
{
534535
int ret;
535536
mbedtls_mpi_uint r;
537+
size_t length = 0;
538+
char *p_end = *p + buflen;
536539

537-
if( radix < 2 || radix > 16 )
538-
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
540+
do
541+
{
542+
if( length >= buflen )
543+
{
544+
return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
545+
}
539546

540-
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, radix ) );
541-
MBEDTLS_MPI_CHK( mbedtls_mpi_div_int( X, NULL, X, radix ) );
547+
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, radix ) );
548+
MBEDTLS_MPI_CHK( mbedtls_mpi_div_int( X, NULL, X, radix ) );
549+
/*
550+
* Write the residue in the current position, as an ASCII character.
551+
*/
552+
if( r < 0xA )
553+
*(--p_end) = (char)( '0' + r );
554+
else
555+
*(--p_end) = (char)( 'A' + ( r - 0xA ) );
542556

543-
if( mbedtls_mpi_cmp_int( X, 0 ) != 0 )
544-
MBEDTLS_MPI_CHK( mpi_write_hlp( X, radix, p ) );
557+
length++;
558+
} while( mbedtls_mpi_cmp_int( X, 0 ) != 0 );
545559

546-
if( r < 10 )
547-
*(*p)++ = (char)( r + 0x30 );
548-
else
549-
*(*p)++ = (char)( r + 0x37 );
560+
memmove( *p, p_end, length );
561+
*p += length;
550562

551563
cleanup:
552564

@@ -619,7 +631,7 @@ int mbedtls_mpi_write_string( const mbedtls_mpi *X, int radix,
619631
if( T.s == -1 )
620632
T.s = 1;
621633

622-
MBEDTLS_MPI_CHK( mpi_write_hlp( &T, radix, &p ) );
634+
MBEDTLS_MPI_CHK( mpi_write_hlp( &T, radix, &p, buflen ) );
623635
}
624636

625637
*p++ = '\0';

0 commit comments

Comments
 (0)