ossl_bn.c: reduce alloca/malloc

* ext/openssl/ossl_bn.c (ossl_bn_initialize): no need of alloca for
  small fixed size array.
* ext/openssl/ossl_bn.c (ossl_bn_initialize): check overflow first,
  and use alloca for small size input.

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@40518 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
nobu 2013-04-28 21:58:36 +00:00
parent 312a5a8cb4
commit 6fb5140dd6
2 changed files with 18 additions and 9 deletions

View File

@ -1,3 +1,11 @@
Mon Apr 29 06:58:30 2013 Nobuyoshi Nakada <nobu@ruby-lang.org>
* ext/openssl/ossl_bn.c (ossl_bn_initialize): no need of alloca for
small fixed size array.
* ext/openssl/ossl_bn.c (ossl_bn_initialize): check overflow first,
and use alloca for small size input.
Mon Apr 29 00:40:13 2013 Benoit Daloze <eregontp@gmail.com> Mon Apr 29 00:40:13 2013 Benoit Daloze <eregontp@gmail.com>
* lib/yaml.rb: Clarify documentation about YAML being always Psych. * lib/yaml.rb: Clarify documentation about YAML being always Psych.

View File

@ -123,7 +123,7 @@ ossl_bn_initialize(int argc, VALUE *argv, VALUE self)
if (RB_TYPE_P(str, T_FIXNUM)) { if (RB_TYPE_P(str, T_FIXNUM)) {
long i; long i;
unsigned char *bin = (unsigned char*)ALLOCA_N(long, 1); unsigned char bin[sizeof(long)];
long n = FIX2LONG(str); long n = FIX2LONG(str);
unsigned long un = labs(n); unsigned long un = labs(n);
@ -133,31 +133,32 @@ ossl_bn_initialize(int argc, VALUE *argv, VALUE self)
} }
GetBN(self, bn); GetBN(self, bn);
if (!BN_bin2bn(bin, sizeof(long), bn)) { if (!BN_bin2bn(bin, sizeof(bin), bn)) {
ossl_raise(eBNError, NULL); ossl_raise(eBNError, NULL);
} }
if (n < 0) BN_set_negative(bn, 1); if (n < 0) BN_set_negative(bn, 1);
return self; return self;
} }
else if (RB_TYPE_P(str, T_BIGNUM)) { else if (RB_TYPE_P(str, T_BIGNUM)) {
long i, j; int i, j, len = RBIGNUM_LENINT(str);
BDIGIT *ds = RBIGNUM_DIGITS(str); BDIGIT *ds = RBIGNUM_DIGITS(str);
unsigned char *bin = (unsigned char*)ALLOC_N(BDIGIT, RBIGNUM_LEN(str)); VALUE buf;
unsigned char *bin = (unsigned char*)ALLOCV_N(BDIGIT, buf, len);
for (i = 0; RBIGNUM_LEN(str) > i; i++) { for (i = 0; len > i; i++) {
BDIGIT v = ds[i]; BDIGIT v = ds[i];
for (j = sizeof(BDIGIT) - 1; 0 <= j; j--) { for (j = sizeof(BDIGIT) - 1; 0 <= j; j--) {
bin[(RBIGNUM_LEN(str)-1-i)*sizeof(BDIGIT)+j] = v&0xff; bin[(len-1-i)*sizeof(BDIGIT)+j] = v&0xff;
v >>= 8; v >>= 8;
} }
} }
GetBN(self, bn); GetBN(self, bn);
if (!BN_bin2bn(bin, (int)sizeof(BDIGIT)*RBIGNUM_LENINT(str), bn)) { if (!BN_bin2bn(bin, (int)sizeof(BDIGIT)*len, bn)) {
xfree(bin); ALLOCV_END(buf);
ossl_raise(eBNError, NULL); ossl_raise(eBNError, NULL);
} }
xfree(bin); ALLOCV_END(buf);
if (!RBIGNUM_SIGN(str)) BN_set_negative(bn, 1); if (!RBIGNUM_SIGN(str)) BN_set_negative(bn, 1);
return self; return self;
} }