1
0
mirror of https://github.com/php/php-src.git synced 2026-03-24 00:02:20 +01:00

Fix undefined behavior of MT_RAND_PHP if range exceeds ZEND_LONG_MAX (#9197)

RAND_RANGE_BADSCALING() invokes undefined behavior when (max - min) >
ZEND_LONG_MAX, because the intermediate `double` might not fit into
`zend_long`.

Fix this by inlining a fixed version of the macro into Mt19937's range()
function. Fixing the macro itself cannot be done in the general case, because
the types of the inputs are not known. Instead of replacing one possibly broken
version with another possibly broken version, the macro is simply left as is
and should be removed in a future version.

The fix itself is simple: Instead of storing the "offset" in a `zend_long`, we
use a `zend_ulong` which is capable of storing the resulting double by
construction. With this fix the implementation of this broken scaling is
effectively identical to the implementation of php_random_range from a data
type perspective, making it easy to verify the correctness.

It was further empirically verified that the broken macro and the fix return
the same results for all possible values of `r` for several distinct pairs of
(min, max).

Fixes GH-9190
Fixes GH-9191
This commit is contained in:
Tim Düsterhus
2022-08-03 18:46:36 +02:00
committed by GitHub
parent 3331832b04
commit 60ace13f9c
2 changed files with 11 additions and 3 deletions

2
NEWS
View File

@@ -5,6 +5,8 @@ PHP NEWS
- Random:
. Fixed bug GH-9235 (non-existant $sequence parameter in stub for
PcgOneseq128XslRr64::__construct()). (timwolla)
. Fixed bug GH-9190, GH-9191 (undefined behavior for MT_RAND_PHP when
handling large ranges). (timwolla)
. Removed redundant RuntimeExceptions from Randomizer methods. The
exceptions thrown by the engines will be exposed directly. (timwolla)
. Added extension specific Exceptions/Errors (RandomException, RandomError,

View File

@@ -168,11 +168,17 @@ static zend_long range(php_random_status *status, zend_long min, zend_long max)
return php_random_range(&php_random_algo_mt19937, status, min, max);
}
uint64_t r = php_random_algo_mt19937.generate(status) >> 1;
/* Legacy mode deliberately not inside php_mt_rand_range()
* to prevent other functions being affected */
RAND_RANGE_BADSCALING(r, min, max, PHP_MT_RAND_MAX);
return (zend_long) r;
uint64_t r = php_random_algo_mt19937.generate(status) >> 1;
/* This is an inlined version of the RAND_RANGE_BADSCALING macro that does not invoke UB when encountering
* (max - min) > ZEND_LONG_MAX.
*/
zend_ulong offset = (double) ( (double) max - min + 1.0) * (r / (PHP_MT_RAND_MAX + 1.0));
return (zend_long) (offset + min);
}
static bool serialize(php_random_status *status, HashTable *data)