Skip to content

Commit 34f0afe

Browse files
committed
changes from feedback
1 parent 972f582 commit 34f0afe

File tree

2 files changed

+35
-23
lines changed

2 files changed

+35
-23
lines changed

ext/gmp/gmp.c

+25-11
Original file line numberDiff line numberDiff line change
@@ -1278,23 +1278,37 @@ ZEND_FUNCTION(gmp_pow)
12781278

12791279
if (Z_TYPE_P(base_arg) == IS_LONG && Z_LVAL_P(base_arg) >= 0) {
12801280
INIT_GMP_RETVAL(gmpnum_result);
1281-
if ((log10(Z_LVAL_P(base_arg)) * exp) > (double)ULONG_MAX) {
1282-
zend_value_error("base and exponent overflow");
1283-
RETURN_THROWS();
1281+
if (exp > UINT_MAX) {
1282+
mpz_t base_num, exp_num, mod;
1283+
mpz_init(base_num);
1284+
mpz_init(exp_num);
1285+
mpz_init(mod);
1286+
mpz_set_si(base_num, Z_LVAL_P(base_arg));
1287+
mpz_set_si(exp_num, exp);
1288+
mpz_set_si(mod, UINT_MAX);
1289+
mpz_powm(gmpnum_result, base_num, exp_num, mod);
1290+
mpz_clear(mod);
1291+
mpz_clear(exp_num);
1292+
mpz_clear(base_num);
1293+
} else {
1294+
mpz_ui_pow_ui(gmpnum_result, Z_LVAL_P(base_arg), exp);
12841295
}
1285-
mpz_ui_pow_ui(gmpnum_result, Z_LVAL_P(base_arg), exp);
12861296
} else {
12871297
mpz_ptr gmpnum_base;
1288-
unsigned long gmpnum;
12891298
FETCH_GMP_ZVAL(gmpnum_base, base_arg, temp_base, 1);
12901299
INIT_GMP_RETVAL(gmpnum_result);
1291-
gmpnum = mpz_get_ui(gmpnum_base);
1292-
if ((log10(gmpnum) * exp) > (double)ULONG_MAX) {
1293-
FREE_GMP_TEMP(temp_base);
1294-
zend_value_error("base and exponent overflow");
1295-
RETURN_THROWS();
1300+
if (exp > UINT_MAX) {
1301+
mpz_t exp_num, mod;
1302+
mpz_init(exp_num);
1303+
mpz_init(mod);
1304+
mpz_set_si(exp_num, exp);
1305+
mpz_set_si(mod, UINT_MAX);
1306+
mpz_powm(gmpnum_result, gmpnum_base, exp_num, mod);
1307+
mpz_clear(mod);
1308+
mpz_clear(exp_num);
1309+
} else {
1310+
mpz_pow_ui(gmpnum_result, gmpnum_base, exp);
12961311
}
1297-
mpz_pow_ui(gmpnum_result, gmpnum_base, exp);
12981312
FREE_GMP_TEMP(temp_base);
12991313
}
13001314
}

ext/gmp/tests/gmp_pow_fpe.phpt

+10-12
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,15 @@ gmp
66
<?php
77
$g = gmp_init(256);
88

9-
try {
10-
gmp_pow($g, PHP_INT_MAX);
11-
} catch (\ValueError $e) {
12-
echo $e->getMessage() . PHP_EOL;
9+
var_dump(gmp_pow($g, PHP_INT_MAX));
10+
var_dump(gmp_pow(256, PHP_INT_MAX));
11+
?>
12+
--EXPECTF--
13+
object(GMP)#2 (1) {
14+
["num"]=>
15+
string(%d) "%s"
1316
}
14-
try {
15-
gmp_pow(256, PHP_INT_MAX);
16-
} catch (\ValueError $e) {
17-
echo $e->getMessage();
17+
object(GMP)#2 (1) {
18+
["num"]=>
19+
string(%d) "%s"
1820
}
19-
?>
20-
--EXPECT--
21-
base and exponent overflow
22-
base and exponent overflow

0 commit comments

Comments
 (0)