Skip to content

Fix undefined behavior of MT_RAND_PHP if range exceeds ZEND_LONG_MAX #9197

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions NEWS
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
12 changes: 9 additions & 3 deletions ext/random/engine_mt19937.c
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down