Skip to content

Commit

Permalink
random: Remove RAND_RANGE_BADSCALING (php#12374)
Browse files Browse the repository at this point in the history
This macro is no longer used within php-src since
60ace13, it invokes undefined behavior
depending on the input and the corresponding MT_RAND_PHP mode was deprecated in
PHP 8.3.

Thus remove this macro. Any remaining non-php-src user should just inline it
into their code, but should ideally migrate to a non-biased scaler. In any case
the undefined behavior of the original implementation should be accounted for.
  • Loading branch information
TimWolla authored Oct 7, 2023
1 parent f075710 commit 3bc63a3
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 28 deletions.
5 changes: 5 additions & 0 deletions UPGRADING.INTERNALS
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ PHP 8.4 INTERNALS UPGRADE NOTES
instead of int.
- The macros DOM_NO_ARGS() and DOM_NOT_IMPLEMENTED() have been removed.

b. ext/random
- The macro RAND_RANGE_BADSCALING() has been removed. The implementation
should either be inlined and undefined behavior fixed or it should be
replaced by a non-biased scaler.

========================
4. OpCode changes
========================
Expand Down
28 changes: 0 additions & 28 deletions ext/random/php_random.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,34 +35,6 @@

PHPAPI double php_combined_lcg(void);

/*
* A bit of tricky math here. We want to avoid using a modulus because
* that simply tosses the high-order bits and might skew the distribution
* of random values over the range. Instead we map the range directly.
*
* We need to map the range from 0...M evenly to the range a...b
* Let n = the random number and n' = the mapped random number
*
* Then we have: n' = a + n(b-a)/M
*
* We have a problem here in that only n==M will get mapped to b which
* means the chances of getting b is much much less than getting any of
* the other values in the range. We can fix this by increasing our range
* artificially and using:
*
* n' = a + n(b-a+1)/M
*
* Now we only have a problem if n==M which would cause us to produce a
* number of b+1 which would be bad. So we bump M up by one to make sure
* this will never happen, and the final algorithm looks like this:
*
* n' = a + n(b-a+1)/(M+1)
*
* -RL
*/
# define RAND_RANGE_BADSCALING(__n, __min, __max, __tmax) \
(__n) = (__min) + (zend_long) ((double) ( (double) (__max) - (__min) + 1.0) * ((__n) / ((__tmax) + 1.0)))

# ifdef PHP_WIN32
# define GENERATE_SEED() (((zend_long) ((zend_ulong) time(NULL) * (zend_ulong) GetCurrentProcessId())) ^ ((zend_long) (1000000.0 * php_combined_lcg())))
# else
Expand Down

0 comments on commit 3bc63a3

Please sign in to comment.