mt_rand.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. /*
  2. +----------------------------------------------------------------------+
  3. | Copyright (c) The PHP Group |
  4. +----------------------------------------------------------------------+
  5. | This source file is subject to version 3.01 of the PHP license, |
  6. | that is bundled with this package in the file LICENSE, and is |
  7. | available through the world-wide-web at the following url: |
  8. | https://www.php.net/license/3_01.txt |
  9. | If you did not receive a copy of the PHP license and are unable to |
  10. | obtain it through the world-wide-web, please send a note to |
  11. | license@php.net so we can mail you a copy immediately. |
  12. +----------------------------------------------------------------------+
  13. | Authors: Rasmus Lerdorf <rasmus@php.net> |
  14. | Zeev Suraski <zeev@php.net> |
  15. | Pedro Melo <melo@ip.pt> |
  16. | Sterling Hughes <sterling@php.net> |
  17. | |
  18. | Based on code from: Richard J. Wagner <rjwagner@writeme.com> |
  19. | Makoto Matsumoto <matumoto@math.keio.ac.jp> |
  20. | Takuji Nishimura |
  21. | Shawn Cokus <Cokus@math.washington.edu> |
  22. +----------------------------------------------------------------------+
  23. */
  24. #include "php.h"
  25. #include "php_rand.h"
  26. #include "php_random.h"
  27. #include "php_mt_rand.h"
  28. /* MT RAND FUNCTIONS */
  29. /*
  30. The following php_mt_...() functions are based on a C++ class MTRand by
  31. Richard J. Wagner. For more information see the web page at
  32. http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/C-LANG/MersenneTwister.h
  33. Mersenne Twister random number generator -- a C++ class MTRand
  34. Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus
  35. Richard J. Wagner v1.0 15 May 2003 rjwagner@writeme.com
  36. The Mersenne Twister is an algorithm for generating random numbers. It
  37. was designed with consideration of the flaws in various other generators.
  38. The period, 2^19937-1, and the order of equidistribution, 623 dimensions,
  39. are far greater. The generator is also fast; it avoids multiplication and
  40. division, and it benefits from caches and pipelines. For more information
  41. see the inventors' web page at http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
  42. Reference
  43. M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-Dimensionally
  44. Equidistributed Uniform Pseudo-Random Number Generator", ACM Transactions on
  45. Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3-30.
  46. Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
  47. Copyright (C) 2000 - 2003, Richard J. Wagner
  48. All rights reserved.
  49. Redistribution and use in source and binary forms, with or without
  50. modification, are permitted provided that the following conditions
  51. are met:
  52. 1. Redistributions of source code must retain the above copyright
  53. notice, this list of conditions and the following disclaimer.
  54. 2. Redistributions in binary form must reproduce the above copyright
  55. notice, this list of conditions and the following disclaimer in the
  56. documentation and/or other materials provided with the distribution.
  57. 3. The names of its contributors may not be used to endorse or promote
  58. products derived from this software without specific prior written
  59. permission.
  60. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  61. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  62. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  63. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  64. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  65. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  66. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  67. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  68. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  69. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  70. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  71. */
  72. #define N MT_N /* length of state vector */
  73. #define M (397) /* a period parameter */
  74. #define hiBit(u) ((u) & 0x80000000U) /* mask all but highest bit of u */
  75. #define loBit(u) ((u) & 0x00000001U) /* mask all but lowest bit of u */
  76. #define loBits(u) ((u) & 0x7FFFFFFFU) /* mask the highest bit of u */
  77. #define mixBits(u, v) (hiBit(u)|loBits(v)) /* move hi bit of u to hi bit of v */
  78. #define twist(m,u,v) (m ^ (mixBits(u,v)>>1) ^ ((uint32_t)(-(int32_t)(loBit(v))) & 0x9908b0dfU))
  79. #define twist_php(m,u,v) (m ^ (mixBits(u,v)>>1) ^ ((uint32_t)(-(int32_t)(loBit(u))) & 0x9908b0dfU))
  80. /* {{{ php_mt_initialize */
  81. static inline void php_mt_initialize(uint32_t seed, uint32_t *state)
  82. {
  83. /* Initialize generator state with seed
  84. See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier.
  85. In previous versions, most significant bits (MSBs) of the seed affect
  86. only MSBs of the state array. Modified 9 Jan 2002 by Makoto Matsumoto. */
  87. uint32_t *s = state;
  88. uint32_t *r = state;
  89. int i = 1;
  90. *s++ = seed & 0xffffffffU;
  91. for( ; i < N; ++i ) {
  92. *s++ = ( 1812433253U * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffU;
  93. r++;
  94. }
  95. }
  96. /* }}} */
  97. /* {{{ php_mt_reload */
  98. static inline void php_mt_reload(void)
  99. {
  100. /* Generate N new values in state
  101. Made clearer and faster by Matthew Bellew (matthew.bellew@home.com) */
  102. uint32_t *state = BG(state);
  103. uint32_t *p = state;
  104. int i;
  105. if (BG(mt_rand_mode) == MT_RAND_MT19937) {
  106. for (i = N - M; i--; ++p)
  107. *p = twist(p[M], p[0], p[1]);
  108. for (i = M; --i; ++p)
  109. *p = twist(p[M-N], p[0], p[1]);
  110. *p = twist(p[M-N], p[0], state[0]);
  111. }
  112. else {
  113. for (i = N - M; i--; ++p)
  114. *p = twist_php(p[M], p[0], p[1]);
  115. for (i = M; --i; ++p)
  116. *p = twist_php(p[M-N], p[0], p[1]);
  117. *p = twist_php(p[M-N], p[0], state[0]);
  118. }
  119. BG(left) = N;
  120. BG(next) = state;
  121. }
  122. /* }}} */
  123. /* {{{ php_mt_srand */
  124. PHPAPI void php_mt_srand(uint32_t seed)
  125. {
  126. /* Seed the generator with a simple uint32 */
  127. php_mt_initialize(seed, BG(state));
  128. php_mt_reload();
  129. /* Seed only once */
  130. BG(mt_rand_is_seeded) = 1;
  131. }
  132. /* }}} */
  133. /* {{{ php_mt_rand */
  134. PHPAPI uint32_t php_mt_rand(void)
  135. {
  136. /* Pull a 32-bit integer from the generator state
  137. Every other access function simply transforms the numbers extracted here */
  138. uint32_t s1;
  139. if (UNEXPECTED(!BG(mt_rand_is_seeded))) {
  140. zend_long bytes;
  141. if (php_random_bytes_silent(&bytes, sizeof(zend_long)) == FAILURE) {
  142. bytes = GENERATE_SEED();
  143. }
  144. php_mt_srand(bytes);
  145. }
  146. if (BG(left) == 0) {
  147. php_mt_reload();
  148. }
  149. --BG(left);
  150. s1 = *BG(next)++;
  151. s1 ^= (s1 >> 11);
  152. s1 ^= (s1 << 7) & 0x9d2c5680U;
  153. s1 ^= (s1 << 15) & 0xefc60000U;
  154. return ( s1 ^ (s1 >> 18) );
  155. }
  156. /* }}} */
  157. /* {{{ Seeds Mersenne Twister random number generator */
  158. PHP_FUNCTION(mt_srand)
  159. {
  160. zend_long seed = 0;
  161. zend_long mode = MT_RAND_MT19937;
  162. ZEND_PARSE_PARAMETERS_START(0, 2)
  163. Z_PARAM_OPTIONAL
  164. Z_PARAM_LONG(seed)
  165. Z_PARAM_LONG(mode)
  166. ZEND_PARSE_PARAMETERS_END();
  167. if (ZEND_NUM_ARGS() == 0) {
  168. if (php_random_bytes_silent(&seed, sizeof(zend_long)) == FAILURE) {
  169. seed = GENERATE_SEED();
  170. }
  171. }
  172. switch (mode) {
  173. case MT_RAND_PHP:
  174. BG(mt_rand_mode) = MT_RAND_PHP;
  175. break;
  176. default:
  177. BG(mt_rand_mode) = MT_RAND_MT19937;
  178. }
  179. php_mt_srand(seed);
  180. }
  181. /* }}} */
  182. static uint32_t rand_range32(uint32_t umax) {
  183. uint32_t result, limit;
  184. result = php_mt_rand();
  185. /* Special case where no modulus is required */
  186. if (UNEXPECTED(umax == UINT32_MAX)) {
  187. return result;
  188. }
  189. /* Increment the max so the range is inclusive of max */
  190. umax++;
  191. /* Powers of two are not biased */
  192. if ((umax & (umax - 1)) == 0) {
  193. return result & (umax - 1);
  194. }
  195. /* Ceiling under which UINT32_MAX % max == 0 */
  196. limit = UINT32_MAX - (UINT32_MAX % umax) - 1;
  197. /* Discard numbers over the limit to avoid modulo bias */
  198. while (UNEXPECTED(result > limit)) {
  199. result = php_mt_rand();
  200. }
  201. return result % umax;
  202. }
  203. #if ZEND_ULONG_MAX > UINT32_MAX
  204. static uint64_t rand_range64(uint64_t umax) {
  205. uint64_t result, limit;
  206. result = php_mt_rand();
  207. result = (result << 32) | php_mt_rand();
  208. /* Special case where no modulus is required */
  209. if (UNEXPECTED(umax == UINT64_MAX)) {
  210. return result;
  211. }
  212. /* Increment the max so the range is inclusive of max */
  213. umax++;
  214. /* Powers of two are not biased */
  215. if ((umax & (umax - 1)) == 0) {
  216. return result & (umax - 1);
  217. }
  218. /* Ceiling under which UINT64_MAX % max == 0 */
  219. limit = UINT64_MAX - (UINT64_MAX % umax) - 1;
  220. /* Discard numbers over the limit to avoid modulo bias */
  221. while (UNEXPECTED(result > limit)) {
  222. result = php_mt_rand();
  223. result = (result << 32) | php_mt_rand();
  224. }
  225. return result % umax;
  226. }
  227. #endif
  228. /* {{{ php_mt_rand_range */
  229. PHPAPI zend_long php_mt_rand_range(zend_long min, zend_long max)
  230. {
  231. zend_ulong umax = max - min;
  232. #if ZEND_ULONG_MAX > UINT32_MAX
  233. if (umax > UINT32_MAX) {
  234. return (zend_long) (rand_range64(umax) + min);
  235. }
  236. #endif
  237. return (zend_long) (rand_range32(umax) + min);
  238. }
  239. /* }}} */
  240. /* {{{ php_mt_rand_common
  241. * rand() allows min > max, mt_rand does not */
  242. PHPAPI zend_long php_mt_rand_common(zend_long min, zend_long max)
  243. {
  244. int64_t n;
  245. if (BG(mt_rand_mode) == MT_RAND_MT19937) {
  246. return php_mt_rand_range(min, max);
  247. }
  248. /* Legacy mode deliberately not inside php_mt_rand_range()
  249. * to prevent other functions being affected */
  250. n = (int64_t)php_mt_rand() >> 1;
  251. RAND_RANGE_BADSCALING(n, min, max, PHP_MT_RAND_MAX);
  252. return n;
  253. }
  254. /* }}} */
  255. /* {{{ Returns a random number from Mersenne Twister */
  256. PHP_FUNCTION(mt_rand)
  257. {
  258. zend_long min;
  259. zend_long max;
  260. int argc = ZEND_NUM_ARGS();
  261. if (argc == 0) {
  262. // genrand_int31 in mt19937ar.c performs a right shift
  263. RETURN_LONG(php_mt_rand() >> 1);
  264. }
  265. ZEND_PARSE_PARAMETERS_START(2, 2)
  266. Z_PARAM_LONG(min)
  267. Z_PARAM_LONG(max)
  268. ZEND_PARSE_PARAMETERS_END();
  269. if (UNEXPECTED(max < min)) {
  270. zend_argument_value_error(2, "must be greater than or equal to argument #1 ($min)");
  271. RETURN_THROWS();
  272. }
  273. RETURN_LONG(php_mt_rand_common(min, max));
  274. }
  275. /* }}} */
  276. /* {{{ Returns the maximum value a random number from Mersenne Twister can have */
  277. PHP_FUNCTION(mt_getrandmax)
  278. {
  279. ZEND_PARSE_PARAMETERS_NONE();
  280. /*
  281. * Melo: it could be 2^^32 but we only use 2^^31 to maintain
  282. * compatibility with the previous php_rand
  283. */
  284. RETURN_LONG(PHP_MT_RAND_MAX); /* 2^^31 */
  285. }
  286. /* }}} */
  287. PHP_MINIT_FUNCTION(mt_rand)
  288. {
  289. REGISTER_LONG_CONSTANT("MT_RAND_MT19937", MT_RAND_MT19937, CONST_CS | CONST_PERSISTENT);
  290. REGISTER_LONG_CONSTANT("MT_RAND_PHP", MT_RAND_PHP, CONST_CS | CONST_PERSISTENT);
  291. return SUCCESS;
  292. }