mt_rand.c 11 KB

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