ssl: refactoring CyaSSL_BN_rand to reduce stack usage:

--- variable decoded moved to the heap (1024 bytes saved)
--- variable tmpRNG moved to the heap (sizeof(RNG) saved)
This commit is contained in:
Moisés Guimarães 2014-09-15 16:57:34 -03:00
parent 68063874dc
commit 7cafb11791

View File

@ -10215,46 +10215,61 @@ int CyaSSL_mask_bits(CYASSL_BIGNUM* bn, int n)
/* SSL_SUCCESS on ok */ /* SSL_SUCCESS on ok */
int CyaSSL_BN_rand(CYASSL_BIGNUM* bn, int bits, int top, int bottom) int CyaSSL_BN_rand(CYASSL_BIGNUM* bn, int bits, int top, int bottom)
{ {
int ret = 0;
int len = bits / 8;
RNG* rng = NULL;
#ifdef CYASSL_SMALL_STACK
RNG* tmpRNG = NULL;
byte* buff = NULL;
#else
RNG tmpRNG[1];
byte buff[1024]; byte buff[1024];
RNG tmpRNG; #endif
RNG* rng = &tmpRNG;
int len = bits/8;
(void)top; (void)top;
(void)bottom; (void)bottom;
CYASSL_MSG("CyaSSL_BN_rand"); CYASSL_MSG("CyaSSL_BN_rand");
if (bn == NULL || bn->internal == NULL) {
CYASSL_MSG("Bad function arguments");
return 0;
}
if (bits % 8) if (bits % 8)
len++; len++;
if ( (InitRng(&tmpRNG)) != 0) { #ifdef CYASSL_SMALL_STACK
CYASSL_MSG("Bad RNG Init, trying global"); buff = (byte*)XMALLOC(1024, NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (initGlobalRNG == 0) { tmpRNG = (RNG*) XMALLOC(sizeof(RNG), NULL, DYNAMIC_TYPE_TMP_BUFFER);
CYASSL_MSG("Global RNG no Init"); if (buff == NULL || tmpRNG == NULL) {
return 0; XFREE(buff, NULL, DYNAMIC_TYPE_TMP_BUFFER);
} XFREE(tmpRNG, NULL, DYNAMIC_TYPE_TMP_BUFFER);
return ret;
}
#endif
if (bn == NULL || bn->internal == NULL)
CYASSL_MSG("Bad function arguments");
else if (InitRng(tmpRNG) == 0)
rng = tmpRNG;
else if (initGlobalRNG)
rng = &globalRNG; rng = &globalRNG;
}
if (RNG_GenerateBlock(rng, buff, len) != 0) { if (rng) {
CYASSL_MSG("Bad RNG_GenerateBlock"); if (RNG_GenerateBlock(rng, buff, len) != 0)
return 0; CYASSL_MSG("Bad RNG_GenerateBlock");
} else {
buff[0] |= 0x80 | 0x40;
buff[len-1] |= 0x01;
buff[0] |= 0x80 | 0x40; if (mp_read_unsigned_bin((mp_int*)bn->internal,buff,len) != MP_OKAY)
buff[len-1] |= 0x01; CYASSL_MSG("mp read bin failed");
else
ret = SSL_SUCCESS;
}
}
if (mp_read_unsigned_bin((mp_int*)bn->internal,buff,len) != MP_OKAY) { #ifdef CYASSL_SMALL_STACK
CYASSL_MSG("mp read bin failed"); XFREE(buff, NULL, DYNAMIC_TYPE_TMP_BUFFER);
return 0; XFREE(tmpRNG, NULL, DYNAMIC_TYPE_TMP_BUFFER);
} #endif
return SSL_SUCCESS; return ret;
} }
@ -10285,7 +10300,7 @@ int CyaSSL_BN_hex2bn(CYASSL_BIGNUM** bn, const char* str)
#ifdef CYASSL_SMALL_STACK #ifdef CYASSL_SMALL_STACK
decoded = (byte*)XMALLOC(decSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); decoded = (byte*)XMALLOC(decSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (decoded == NULL) if (decoded == NULL)
return 0; return ret;
#endif #endif
if (str == NULL) if (str == NULL)