Skip to content

Commit cb720b8

Browse files
committed
Throw MemoryError in GMP string rendering and gmp_export()
1 parent 9770294 commit cb720b8

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

ext/gmp/gmp.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -672,6 +672,11 @@ static void gmp_strval(zval *result, mpz_t gmpnum, int base) /* {{{ */
672672
num_len++;
673673
}
674674

675+
if (UNEXPECTED(zend_string_alloc_size_exceeds_memory(num_len, 1, 0))) {
676+
ZVAL_EMPTY_STRING(result);
677+
return;
678+
}
679+
675680
str = zend_string_alloc(num_len, 0);
676681
mpz_get_str(ZSTR_VAL(str), base, gmpnum);
677682

@@ -841,6 +846,10 @@ ZEND_FUNCTION(gmp_export)
841846
size_t bits_per_word = (size_t) size * 8;
842847
size_t count = (size_in_base_2 + bits_per_word - 1) / bits_per_word;
843848

849+
if (UNEXPECTED(zend_string_alloc_size_exceeds_memory(count, size, 0))) {
850+
RETURN_THROWS();
851+
}
852+
844853
zend_string *out_string = zend_string_safe_alloc(count, size, 0, 0);
845854
mpz_export(ZSTR_VAL(out_string), NULL, order, size, endian, 0, gmpnumber);
846855
ZSTR_VAL(out_string)[ZSTR_LEN(out_string)] = '\0';
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
--TEST--
2+
GMP string rendering throws a catchable MemoryError when the result cannot fit in the memory limit
3+
--EXTENSIONS--
4+
gmp
5+
--INI--
6+
memory_limit=64M
7+
opcache.enable_cli=0
8+
--FILE--
9+
<?php
10+
11+
$huge = gmp_pow(2, 2000000000);
12+
13+
try {
14+
gmp_strval($huge);
15+
} catch (MemoryError $e) {
16+
echo 'gmp_strval: ' . $e::class . ': ' . $e->getMessage() . "\n";
17+
}
18+
19+
try {
20+
(string) $huge;
21+
} catch (MemoryError $e) {
22+
echo 'cast: ' . $e::class . ': ' . $e->getMessage() . "\n";
23+
}
24+
25+
try {
26+
gmp_export($huge);
27+
} catch (MemoryError $e) {
28+
echo 'gmp_export: ' . $e::class . ': ' . $e->getMessage() . "\n";
29+
}
30+
31+
var_dump(gmp_strval(gmp_init(255)));
32+
33+
?>
34+
--EXPECT--
35+
gmp_strval: MemoryError: The resulting string is too large to fit in the configured memory limit
36+
cast: MemoryError: The resulting string is too large to fit in the configured memory limit
37+
gmp_export: MemoryError: The resulting string is too large to fit in the configured memory limit
38+
string(3) "255"

0 commit comments

Comments
 (0)