Ruby  2.4.2p198(2017-09-14revision59899)
random.c
Go to the documentation of this file.
1 /**********************************************************************
2 
3  random.c -
4 
5  $Author: nagachika $
6  created at: Fri Dec 24 16:39:21 JST 1993
7 
8  Copyright (C) 1993-2007 Yukihiro Matsumoto
9 
10 **********************************************************************/
11 
12 /*
13 This is based on trimmed version of MT19937. To get the original version,
14 contact <http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html>.
15 
16 The original copyright notice follows.
17 
18  A C-program for MT19937, with initialization improved 2002/2/10.
19  Coded by Takuji Nishimura and Makoto Matsumoto.
20  This is a faster version by taking Shawn Cokus's optimization,
21  Matthe Bellew's simplification, Isaku Wada's real version.
22 
23  Before using, initialize the state by using init_genrand(mt, seed)
24  or init_by_array(mt, init_key, key_length).
25 
26  Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
27  All rights reserved.
28 
29  Redistribution and use in source and binary forms, with or without
30  modification, are permitted provided that the following conditions
31  are met:
32 
33  1. Redistributions of source code must retain the above copyright
34  notice, this list of conditions and the following disclaimer.
35 
36  2. Redistributions in binary form must reproduce the above copyright
37  notice, this list of conditions and the following disclaimer in the
38  documentation and/or other materials provided with the distribution.
39 
40  3. The names of its contributors may not be used to endorse or promote
41  products derived from this software without specific prior written
42  permission.
43 
44  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
45  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
46  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
47  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
48  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
49  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
50  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
51  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
52  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
53  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
54  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
55 
56 
57  Any feedback is very welcome.
58  http://www.math.keio.ac.jp/matumoto/emt.html
59  email: matumoto@math.keio.ac.jp
60 */
61 
62 #include "internal.h"
63 
64 #include <limits.h>
65 #ifdef HAVE_UNISTD_H
66 #include <unistd.h>
67 #endif
68 #include <time.h>
69 #include <sys/types.h>
70 #include <sys/stat.h>
71 #ifdef HAVE_FCNTL_H
72 #include <fcntl.h>
73 #endif
74 #include <math.h>
75 #include <errno.h>
76 #if defined(HAVE_SYS_TIME_H)
77 #include <sys/time.h>
78 #endif
79 
80 #ifdef HAVE_SYSCALL_H
81 #include <syscall.h>
82 #elif defined HAVE_SYS_SYSCALL_H
83 #include <sys/syscall.h>
84 #endif
85 
86 #ifdef _WIN32
87 #include <windows.h>
88 #include <wincrypt.h>
89 #endif
90 #include "ruby_atomic.h"
91 
92 typedef int int_must_be_32bit_at_least[sizeof(int) * CHAR_BIT < 32 ? -1 : 1];
93 
94 /* Period parameters */
95 #define N 624
96 #define M 397
97 #define MATRIX_A 0x9908b0dfU /* constant vector a */
98 #define UMASK 0x80000000U /* most significant w-r bits */
99 #define LMASK 0x7fffffffU /* least significant r bits */
100 #define MIXBITS(u,v) ( ((u) & UMASK) | ((v) & LMASK) )
101 #define TWIST(u,v) ((MIXBITS((u),(v)) >> 1) ^ ((v)&1U ? MATRIX_A : 0U))
102 
103 enum {MT_MAX_STATE = N};
104 
105 struct MT {
106  /* assume int is enough to store 32bits */
107  uint32_t state[N]; /* the array for the state vector */
109  int left;
110 };
111 
112 #define genrand_initialized(mt) ((mt)->next != 0)
113 #define uninit_genrand(mt) ((mt)->next = 0)
114 
115 /* initializes state[N] with a seed */
116 static void
117 init_genrand(struct MT *mt, unsigned int s)
118 {
119  int j;
120  mt->state[0] = s & 0xffffffffU;
121  for (j=1; j<N; j++) {
122  mt->state[j] = (1812433253U * (mt->state[j-1] ^ (mt->state[j-1] >> 30)) + j);
123  /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
124  /* In the previous versions, MSBs of the seed affect */
125  /* only MSBs of the array state[]. */
126  /* 2002/01/09 modified by Makoto Matsumoto */
127  mt->state[j] &= 0xffffffff; /* for >32 bit machines */
128  }
129  mt->left = 1;
130  mt->next = mt->state + N;
131 }
132 
133 /* initialize by an array with array-length */
134 /* init_key is the array for initializing keys */
135 /* key_length is its length */
136 /* slight change for C++, 2004/2/26 */
137 static void
138 init_by_array(struct MT *mt, const uint32_t init_key[], int key_length)
139 {
140  int i, j, k;
141  init_genrand(mt, 19650218U);
142  i=1; j=0;
143  k = (N>key_length ? N : key_length);
144  for (; k; k--) {
145  mt->state[i] = (mt->state[i] ^ ((mt->state[i-1] ^ (mt->state[i-1] >> 30)) * 1664525U))
146  + init_key[j] + j; /* non linear */
147  mt->state[i] &= 0xffffffffU; /* for WORDSIZE > 32 machines */
148  i++; j++;
149  if (i>=N) { mt->state[0] = mt->state[N-1]; i=1; }
150  if (j>=key_length) j=0;
151  }
152  for (k=N-1; k; k--) {
153  mt->state[i] = (mt->state[i] ^ ((mt->state[i-1] ^ (mt->state[i-1] >> 30)) * 1566083941U))
154  - i; /* non linear */
155  mt->state[i] &= 0xffffffffU; /* for WORDSIZE > 32 machines */
156  i++;
157  if (i>=N) { mt->state[0] = mt->state[N-1]; i=1; }
158  }
159 
160  mt->state[0] = 0x80000000U; /* MSB is 1; assuring non-zero initial array */
161 }
162 
163 static void
164 next_state(struct MT *mt)
165 {
166  uint32_t *p = mt->state;
167  int j;
168 
169  mt->left = N;
170  mt->next = mt->state;
171 
172  for (j=N-M+1; --j; p++)
173  *p = p[M] ^ TWIST(p[0], p[1]);
174 
175  for (j=M; --j; p++)
176  *p = p[M-N] ^ TWIST(p[0], p[1]);
177 
178  *p = p[M-N] ^ TWIST(p[0], mt->state[0]);
179 }
180 
181 /* generates a random number on [0,0xffffffff]-interval */
182 static unsigned int
183 genrand_int32(struct MT *mt)
184 {
185  /* mt must be initialized */
186  unsigned int y;
187 
188  if (--mt->left <= 0) next_state(mt);
189  y = *mt->next++;
190 
191  /* Tempering */
192  y ^= (y >> 11);
193  y ^= (y << 7) & 0x9d2c5680;
194  y ^= (y << 15) & 0xefc60000;
195  y ^= (y >> 18);
196 
197  return y;
198 }
199 
200 /* generates a random number on [0,1) with 53-bit resolution*/
201 static double int_pair_to_real_exclusive(uint32_t a, uint32_t b);
202 static double
203 genrand_real(struct MT *mt)
204 {
205  /* mt must be initialized */
206  unsigned int a = genrand_int32(mt), b = genrand_int32(mt);
207  return int_pair_to_real_exclusive(a, b);
208 }
209 
210 static double
212 {
213  a >>= 5;
214  b >>= 6;
215  return(a*67108864.0+b)*(1.0/9007199254740992.0);
216 }
217 
218 /* generates a random number on [0,1] with 53-bit resolution*/
219 static double int_pair_to_real_inclusive(uint32_t a, uint32_t b);
220 #if 0
221 static double
222 genrand_real2(struct MT *mt)
223 {
224  /* mt must be initialized */
225  uint32_t a = genrand_int32(mt), b = genrand_int32(mt);
226  return int_pair_to_real_inclusive(a, b);
227 }
228 #endif
229 
230 /* These real versions are due to Isaku Wada, 2002/01/09 added */
231 
232 #undef N
233 #undef M
234 
235 typedef struct {
237  struct MT mt;
238 } rb_random_t;
239 
240 #define DEFAULT_SEED_CNT 4
241 
243 
244 static VALUE rand_init(struct MT *mt, VALUE vseed);
245 static VALUE random_seed(void);
246 
247 static rb_random_t *
249 {
250  struct MT *mt = &r->mt;
251  if (!genrand_initialized(mt)) {
252  r->seed = rand_init(mt, random_seed());
253  }
254  return r;
255 }
256 
257 static struct MT *
259 {
260  return &rand_start(&default_rand)->mt;
261 }
262 
263 unsigned int
265 {
266  struct MT *mt = default_mt();
267  return genrand_int32(mt);
268 }
269 
270 double
272 {
273  struct MT *mt = default_mt();
274  return genrand_real(mt);
275 }
276 
277 #define SIZEOF_INT32 (31/CHAR_BIT + 1)
278 
279 static double
281 {
282  double r;
283  enum {dig = 53};
284  enum {dig_u = dig-32, dig_r64 = 64-dig, bmask = ~(~0u<<(dig_r64))};
285 #if defined HAVE_UINT128_T
286  const uint128_t m = ((uint128_t)1 << dig) | 1;
287  uint128_t x = ((uint128_t)a << 32) | b;
288  r = (double)(uint64_t)((x * m) >> 64);
289 #elif defined HAVE_UINT64_T && !(defined _MSC_VER && _MSC_VER <= 1200)
290  uint64_t x = ((uint64_t)a << dig_u) +
291  (((uint64_t)b + (a >> dig_u)) >> dig_r64);
292  r = (double)x;
293 #else
294  /* shift then add to get rid of overflow */
295  b = (b >> dig_r64) + (((a >> dig_u) + (b & bmask)) >> dig_r64);
296  r = (double)a * (1 << dig_u) + b;
297 #endif
298  return ldexp(r, -dig);
299 }
300 
302 #define id_minus '-'
303 #define id_plus '+'
305 
306 /* :nodoc: */
307 static void
308 random_mark(void *ptr)
309 {
310  rb_gc_mark(((rb_random_t *)ptr)->seed);
311 }
312 
313 static void
314 random_free(void *ptr)
315 {
316  if (ptr != &default_rand)
317  xfree(ptr);
318 }
319 
320 static size_t
321 random_memsize(const void *ptr)
322 {
323  return sizeof(rb_random_t);
324 }
325 
327  "random",
328  {
329  random_mark,
330  random_free,
332  },
334 };
335 
336 static rb_random_t *
338 {
339  rb_random_t *ptr;
340  TypedData_Get_Struct(obj, rb_random_t, &random_data_type, ptr);
341  return rand_start(ptr);
342 }
343 
344 static rb_random_t *
346 {
347  if (obj == rb_cRandom) {
348  return rand_start(&default_rand);
349  }
350  if (!rb_typeddata_is_kind_of(obj, &random_data_type)) return NULL;
351  return rand_start(DATA_PTR(obj));
352 }
353 
354 /* :nodoc: */
355 static VALUE
357 {
358  rb_random_t *rnd;
359  VALUE obj = TypedData_Make_Struct(klass, rb_random_t, &random_data_type, rnd);
360  rnd->seed = INT2FIX(0);
361  return obj;
362 }
363 
364 static VALUE
365 rand_init(struct MT *mt, VALUE seed)
366 {
367  uint32_t buf0[SIZEOF_LONG / SIZEOF_INT32 * 4], *buf = buf0;
368  size_t len;
369  int sign;
370 
371  len = rb_absint_numwords(seed, 32, NULL);
372  if (len > numberof(buf0))
373  buf = ALLOC_N(uint32_t, len);
374  sign = rb_integer_pack(seed, buf, len, sizeof(uint32_t), 0,
376  if (sign < 0)
377  sign = -sign;
378  if (len == 0) {
379  buf[0] = 0;
380  len = 1;
381  }
382  if (len <= 1) {
383  init_genrand(mt, buf[0]);
384  }
385  else {
386  if (sign != 2 && buf[len-1] == 1) /* remove leading-zero-guard */
387  len--;
388  init_by_array(mt, buf, (int)len);
389  }
390  explicit_bzero(buf, len * sizeof(*buf));
391  if (buf != buf0) xfree(buf);
392  return seed;
393 }
394 
395 /*
396  * call-seq:
397  * Random.new(seed = Random.new_seed) -> prng
398  *
399  * Creates a new PRNG using +seed+ to set the initial state. If +seed+ is
400  * omitted, the generator is initialized with Random.new_seed.
401  *
402  * See Random.srand for more information on the use of seed values.
403  */
404 static VALUE
406 {
407  VALUE vseed;
408  rb_random_t *rnd = get_rnd(obj);
409 
410  if (rb_check_arity(argc, 0, 1) == 0) {
411  rb_check_frozen(obj);
412  vseed = random_seed();
413  }
414  else {
415  vseed = argv[0];
416  rb_check_copyable(obj, vseed);
417  vseed = rb_to_int(vseed);
418  }
419  rnd->seed = rand_init(&rnd->mt, vseed);
420  return obj;
421 }
422 
423 #define DEFAULT_SEED_LEN (DEFAULT_SEED_CNT * (int)sizeof(int32_t))
424 
425 #if defined(S_ISCHR) && !defined(DOSISH)
426 # define USE_DEV_URANDOM 1
427 #else
428 # define USE_DEV_URANDOM 0
429 #endif
430 
431 #if USE_DEV_URANDOM
432 static int
433 fill_random_bytes_urandom(void *seed, size_t size)
434 {
435  /*
436  O_NONBLOCK and O_NOCTTY is meaningless if /dev/urandom correctly points
437  to a urandom device. But it protects from several strange hazard if
438  /dev/urandom is not a urandom device.
439  */
440  int fd = rb_cloexec_open("/dev/urandom",
441 # ifdef O_NONBLOCK
442  O_NONBLOCK|
443 # endif
444 # ifdef O_NOCTTY
445  O_NOCTTY|
446 # endif
447  O_RDONLY, 0);
448  struct stat statbuf;
449  ssize_t ret = 0;
450 
451  if (fd < 0) return -1;
452  rb_update_max_fd(fd);
453  if (fstat(fd, &statbuf) == 0 && S_ISCHR(statbuf.st_mode)) {
454  ret = read(fd, seed, size);
455  }
456  close(fd);
457  if (ret < 0 || (size_t)ret < size) return -1;
458  return 0;
459 }
460 #else
461 # define fill_random_bytes_urandom(seed, size) -1
462 #endif
463 
464 #if 0
465 #elif defined(HAVE_ARC4RANDOM_BUF)
466 static int
467 fill_random_bytes_syscall(void *buf, size_t size, int unused)
468 {
469  arc4random_buf(buf, size);
470  return 0;
471 }
472 #elif defined(_WIN32)
473 static void
474 release_crypt(void *p)
475 {
476  HCRYPTPROV prov = (HCRYPTPROV)ATOMIC_PTR_EXCHANGE(*(HCRYPTPROV *)p, INVALID_HANDLE_VALUE);
477  if (prov && prov != (HCRYPTPROV)INVALID_HANDLE_VALUE) {
478  CryptReleaseContext(prov, 0);
479  }
480 }
481 
482 static int
483 fill_random_bytes_syscall(void *seed, size_t size, int unused)
484 {
485  static HCRYPTPROV perm_prov;
486  HCRYPTPROV prov = perm_prov, old_prov;
487  if (!prov) {
488  if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
489  prov = (HCRYPTPROV)INVALID_HANDLE_VALUE;
490  }
491  old_prov = (HCRYPTPROV)ATOMIC_PTR_CAS(perm_prov, 0, prov);
492  if (LIKELY(!old_prov)) { /* no other threads acquried */
493  if (prov != (HCRYPTPROV)INVALID_HANDLE_VALUE) {
494  rb_gc_register_mark_object(Data_Wrap_Struct(0, 0, release_crypt, &perm_prov));
495  }
496  }
497  else { /* another thread acquried */
498  if (prov != (HCRYPTPROV)INVALID_HANDLE_VALUE) {
499  CryptReleaseContext(prov, 0);
500  }
501  prov = old_prov;
502  }
503  }
504  if (prov == (HCRYPTPROV)INVALID_HANDLE_VALUE) return -1;
505  CryptGenRandom(prov, size, seed);
506  return 0;
507 }
508 #elif defined __linux__ && defined SYS_getrandom
509 #include <linux/random.h>
510 
511 # ifndef GRND_NONBLOCK
512 # define GRND_NONBLOCK 0x0001 /* not defined in musl libc */
513 # endif
514 
515 static int
516 fill_random_bytes_syscall(void *seed, size_t size, int need_secure)
517 {
518  static rb_atomic_t try_syscall = 1;
519  if (try_syscall) {
520  long ret;
521  int flags = 0;
522  if (!need_secure)
523  flags = GRND_NONBLOCK;
524  errno = 0;
525  ret = syscall(SYS_getrandom, seed, size, flags);
526  if (errno == ENOSYS) {
527  ATOMIC_SET(try_syscall, 0);
528  return -1;
529  }
530  if ((size_t)ret == size) return 0;
531  }
532  return -1;
533 }
534 #else
535 # define fill_random_bytes_syscall(seed, size, need_secure) -1
536 #endif
537 
538 static int
539 fill_random_bytes(void *seed, size_t size, int need_secure)
540 {
541  int ret = fill_random_bytes_syscall(seed, size, need_secure);
542  if (ret == 0) return ret;
543  return fill_random_bytes_urandom(seed, size);
544 }
545 
546 static void
548 {
549  static int n = 0;
550  struct timeval tv;
551  size_t len = cnt * sizeof(*seed);
552 
553  memset(seed, 0, len);
554 
555  fill_random_bytes(seed, len, TRUE);
556 
557  gettimeofday(&tv, 0);
558  seed[0] ^= tv.tv_usec;
559  seed[1] ^= (uint32_t)tv.tv_sec;
560 #if SIZEOF_TIME_T > SIZEOF_INT
561  seed[0] ^= (uint32_t)((time_t)tv.tv_sec >> SIZEOF_INT * CHAR_BIT);
562 #endif
563  seed[2] ^= getpid() ^ (n++ << 16);
564  seed[3] ^= (uint32_t)(VALUE)&seed;
565 #if SIZEOF_VOIDP > SIZEOF_INT
566  seed[2] ^= (uint32_t)((VALUE)&seed >> SIZEOF_INT * CHAR_BIT);
567 #endif
568 }
569 
570 static VALUE
572 {
573  VALUE seed;
574 
575  if (ptr[len-1] <= 1) {
576  /* set leading-zero-guard */
577  ptr[len++] = 1;
578  }
579 
580  seed = rb_integer_unpack(ptr, len, sizeof(uint32_t), 0,
582 
583  return seed;
584 }
585 
586 /*
587  * call-seq: Random.new_seed -> integer
588  *
589  * Returns an arbitrary seed value. This is used by Random.new
590  * when no seed value is specified as an argument.
591  *
592  * Random.new_seed #=> 115032730400174366788466674494640623225
593  */
594 static VALUE
596 {
597  VALUE v;
602  return v;
603 }
604 
605 /*
606  * call-seq: Random.raw_seed(size) -> string
607  *
608  * Returns a raw seed string, using platform providing features.
609  *
610  * Random.raw_seed(8) #=> "\x78\x41\xBA\xAF\x7D\xEA\xD8\xEA"
611  */
612 static VALUE
614 {
615  long n = NUM2ULONG(size);
616  VALUE buf = rb_str_new(0, n);
617  if (n == 0) return buf;
618  if (fill_random_bytes(RSTRING_PTR(buf), n, FALSE)) return Qnil;
619  return buf;
620 }
621 
622 /*
623  * call-seq: prng.seed -> integer
624  *
625  * Returns the seed value used to initialize the generator. This may be used to
626  * initialize another generator with the same state at a later time, causing it
627  * to produce the same sequence of numbers.
628  *
629  * prng1 = Random.new(1234)
630  * prng1.seed #=> 1234
631  * prng1.rand(100) #=> 47
632  *
633  * prng2 = Random.new(prng1.seed)
634  * prng2.rand(100) #=> 47
635  */
636 static VALUE
638 {
639  return get_rnd(obj)->seed;
640 }
641 
642 /* :nodoc: */
643 static VALUE
645 {
646  rb_random_t *rnd1, *rnd2;
647  struct MT *mt;
648 
649  if (!OBJ_INIT_COPY(obj, orig)) return obj;
650 
651  rnd1 = get_rnd(obj);
652  rnd2 = get_rnd(orig);
653  mt = &rnd1->mt;
654 
655  *rnd1 = *rnd2;
656  mt->next = mt->state + numberof(mt->state) - mt->left + 1;
657  return obj;
658 }
659 
660 static VALUE
661 mt_state(const struct MT *mt)
662 {
663  return rb_integer_unpack(mt->state, numberof(mt->state),
664  sizeof(*mt->state), 0,
666 }
667 
668 /* :nodoc: */
669 static VALUE
671 {
672  rb_random_t *rnd = get_rnd(obj);
673  return mt_state(&rnd->mt);
674 }
675 
676 /* :nodoc: */
677 static VALUE
679 {
680  return mt_state(&default_rand.mt);
681 }
682 
683 /* :nodoc: */
684 static VALUE
686 {
687  rb_random_t *rnd = get_rnd(obj);
688  return INT2FIX(rnd->mt.left);
689 }
690 
691 /* :nodoc: */
692 static VALUE
694 {
695  return INT2FIX(default_rand.mt.left);
696 }
697 
698 /* :nodoc: */
699 static VALUE
701 {
702  rb_random_t *rnd = get_rnd(obj);
703  VALUE dump = rb_ary_new2(3);
704 
705  rb_ary_push(dump, mt_state(&rnd->mt));
706  rb_ary_push(dump, INT2FIX(rnd->mt.left));
707  rb_ary_push(dump, rnd->seed);
708 
709  return dump;
710 }
711 
712 /* :nodoc: */
713 static VALUE
715 {
716  rb_random_t *rnd = get_rnd(obj);
717  struct MT *mt = &rnd->mt;
718  VALUE state, left = INT2FIX(1), seed = INT2FIX(0);
719  const VALUE *ary;
720  unsigned long x;
721 
722  rb_check_copyable(obj, dump);
723  Check_Type(dump, T_ARRAY);
724  ary = RARRAY_CONST_PTR(dump);
725  switch (RARRAY_LEN(dump)) {
726  case 3:
727  seed = ary[2];
728  case 2:
729  left = ary[1];
730  case 1:
731  state = ary[0];
732  break;
733  default:
734  rb_raise(rb_eArgError, "wrong dump data");
735  }
736  rb_integer_pack(state, mt->state, numberof(mt->state),
737  sizeof(*mt->state), 0,
739  x = NUM2ULONG(left);
740  if (x > numberof(mt->state)) {
741  rb_raise(rb_eArgError, "wrong value");
742  }
743  mt->left = (unsigned int)x;
744  mt->next = mt->state + numberof(mt->state) - x + 1;
745  rnd->seed = rb_to_int(seed);
746 
747  return obj;
748 }
749 
750 /*
751  * call-seq:
752  * srand(number = Random.new_seed) -> old_seed
753  *
754  * Seeds the system pseudo-random number generator, Random::DEFAULT, with
755  * +number+. The previous seed value is returned.
756  *
757  * If +number+ is omitted, seeds the generator using a source of entropy
758  * provided by the operating system, if available (/dev/urandom on Unix systems
759  * or the RSA cryptographic provider on Windows), which is then combined with
760  * the time, the process id, and a sequence number.
761  *
762  * srand may be used to ensure repeatable sequences of pseudo-random numbers
763  * between different runs of the program. By setting the seed to a known value,
764  * programs can be made deterministic during testing.
765  *
766  * srand 1234 # => 268519324636777531569100071560086917274
767  * [ rand, rand ] # => [0.1915194503788923, 0.6221087710398319]
768  * [ rand(10), rand(1000) ] # => [4, 664]
769  * srand 1234 # => 1234
770  * [ rand, rand ] # => [0.1915194503788923, 0.6221087710398319]
771  */
772 
773 static VALUE
775 {
776  VALUE seed, old;
778 
779  if (rb_check_arity(argc, 0, 1) == 0) {
780  seed = random_seed();
781  }
782  else {
783  seed = rb_to_int(argv[0]);
784  }
785  old = r->seed;
786  r->seed = rand_init(&r->mt, seed);
787 
788  return old;
789 }
790 
791 static unsigned long
792 make_mask(unsigned long x)
793 {
794  x = x | x >> 1;
795  x = x | x >> 2;
796  x = x | x >> 4;
797  x = x | x >> 8;
798  x = x | x >> 16;
799 #if 4 < SIZEOF_LONG
800  x = x | x >> 32;
801 #endif
802  return x;
803 }
804 
805 static unsigned long
806 limited_rand(struct MT *mt, unsigned long limit)
807 {
808  /* mt must be initialized */
809  unsigned long val, mask;
810 
811  if (!limit) return 0;
812  mask = make_mask(limit);
813 
814 #if 4 < SIZEOF_LONG
815  if (0xffffffff < limit) {
816  int i;
817  retry:
818  val = 0;
819  for (i = SIZEOF_LONG/SIZEOF_INT32-1; 0 <= i; i--) {
820  if ((mask >> (i * 32)) & 0xffffffff) {
821  val |= (unsigned long)genrand_int32(mt) << (i * 32);
822  val &= mask;
823  if (limit < val)
824  goto retry;
825  }
826  }
827  return val;
828  }
829 #endif
830 
831  do {
832  val = genrand_int32(mt) & mask;
833  } while (limit < val);
834  return val;
835 }
836 
837 static VALUE
838 limited_big_rand(struct MT *mt, VALUE limit)
839 {
840  /* mt must be initialized */
841 
842  uint32_t mask;
843  long i;
844  int boundary;
845 
846  size_t len;
847  uint32_t *tmp, *lim_array, *rnd_array;
848  VALUE vtmp;
849  VALUE val;
850 
851  len = rb_absint_numwords(limit, 32, NULL);
852  tmp = ALLOCV_N(uint32_t, vtmp, len*2);
853  lim_array = tmp;
854  rnd_array = tmp + len;
855  rb_integer_pack(limit, lim_array, len, sizeof(uint32_t), 0,
857 
858  retry:
859  mask = 0;
860  boundary = 1;
861  for (i = len-1; 0 <= i; i--) {
862  uint32_t rnd;
863  uint32_t lim = lim_array[i];
864  mask = mask ? 0xffffffff : (uint32_t)make_mask(lim);
865  if (mask) {
866  rnd = genrand_int32(mt) & mask;
867  if (boundary) {
868  if (lim < rnd)
869  goto retry;
870  if (rnd < lim)
871  boundary = 0;
872  }
873  }
874  else {
875  rnd = 0;
876  }
877  rnd_array[i] = rnd;
878  }
879  val = rb_integer_unpack(rnd_array, len, sizeof(uint32_t), 0,
881  ALLOCV_END(vtmp);
882 
883  return val;
884 }
885 
886 /*
887  * Returns random unsigned long value in [0, +limit+].
888  *
889  * Note that +limit+ is included, and the range of the argument and the
890  * return value depends on environments.
891  */
892 unsigned long
893 rb_genrand_ulong_limited(unsigned long limit)
894 {
895  return limited_rand(default_mt(), limit);
896 }
897 
898 static VALUE
899 obj_random_bytes(VALUE obj, void *p, long n)
900 {
901  VALUE len = LONG2NUM(n);
902  VALUE v = rb_funcallv_public(obj, id_bytes, 1, &len);
903  long l;
904  Check_Type(v, T_STRING);
905  l = RSTRING_LEN(v);
906  if (l < n)
907  rb_raise(rb_eRangeError, "random data too short %ld", l);
908  else if (l > n)
909  rb_raise(rb_eRangeError, "random data too long %ld", l);
910  if (p) memcpy(p, RSTRING_PTR(v), n);
911  return v;
912 }
913 
914 static unsigned int
916 {
917  return genrand_int32(&rnd->mt);
918 }
919 
920 unsigned int
922 {
923  rb_random_t *rnd = try_get_rnd(obj);
924  if (!rnd) {
925  uint32_t x;
926  obj_random_bytes(obj, &x, sizeof(x));
927  return (unsigned int)x;
928  }
929  return random_int32(rnd);
930 }
931 
932 static double
933 random_real(VALUE obj, rb_random_t *rnd, int excl)
934 {
935  uint32_t a, b;
936 
937  if (!rnd) {
938  uint32_t x[2] = {0, 0};
939  obj_random_bytes(obj, x, sizeof(x));
940  a = x[0];
941  b = x[1];
942  }
943  else {
944  a = random_int32(rnd);
945  b = random_int32(rnd);
946  }
947  if (excl) {
948  return int_pair_to_real_exclusive(a, b);
949  }
950  else {
951  return int_pair_to_real_inclusive(a, b);
952  }
953 }
954 
955 double
957 {
958  rb_random_t *rnd = try_get_rnd(obj);
959  if (!rnd) {
960  VALUE v = rb_funcallv(obj, id_rand, 0, 0);
961  double d = NUM2DBL(v);
962  if (d < 0.0) {
963  rb_raise(rb_eRangeError, "random number too small %g", d);
964  }
965  else if (d >= 1.0) {
966  rb_raise(rb_eRangeError, "random number too big %g", d);
967  }
968  return d;
969  }
970  return genrand_real(&rnd->mt);
971 }
972 
973 static inline VALUE
974 ulong_to_num_plus_1(unsigned long n)
975 {
976 #if HAVE_LONG_LONG
977  return ULL2NUM((LONG_LONG)n+1);
978 #else
979  if (n >= ULONG_MAX) {
980  return rb_big_plus(ULONG2NUM(n), INT2FIX(1));
981  }
982  return ULONG2NUM(n+1);
983 #endif
984 }
985 
986 static unsigned long
987 random_ulong_limited(VALUE obj, rb_random_t *rnd, unsigned long limit)
988 {
989  if (!limit) return 0;
990  if (!rnd) {
991  const int w = sizeof(limit) * CHAR_BIT - nlz_long(limit);
992  const int n = w > 32 ? sizeof(unsigned long) : sizeof(uint32_t);
993  const unsigned long mask = ~(~0UL << w);
994  const unsigned long full =
995  (size_t)n >= sizeof(unsigned long) ? ~0UL :
996  ~(~0UL << n * CHAR_BIT);
997  unsigned long val, bits = 0, rest = 0;
998  do {
999  if (mask & ~rest) {
1000  union {uint32_t u32; unsigned long ul;} buf;
1001  obj_random_bytes(obj, &buf, n);
1002  rest = full;
1003  bits = (n == sizeof(uint32_t)) ? buf.u32 : buf.ul;
1004  }
1005  val = bits;
1006  bits >>= w;
1007  rest >>= w;
1008  val &= mask;
1009  } while (limit < val);
1010  return val;
1011  }
1012  return limited_rand(&rnd->mt, limit);
1013 }
1014 
1015 unsigned long
1016 rb_random_ulong_limited(VALUE obj, unsigned long limit)
1017 {
1018  rb_random_t *rnd = try_get_rnd(obj);
1019  if (!rnd) {
1020  VALUE lim = ulong_to_num_plus_1(limit);
1021  VALUE v = rb_to_int(rb_funcallv_public(obj, id_rand, 1, &lim));
1022  unsigned long r = NUM2ULONG(v);
1023  if (rb_num_negative_p(v)) {
1024  rb_raise(rb_eRangeError, "random number too small %ld", r);
1025  }
1026  if (r > limit) {
1027  rb_raise(rb_eRangeError, "random number too big %ld", r);
1028  }
1029  return r;
1030  }
1031  return limited_rand(&rnd->mt, limit);
1032 }
1033 
1034 static VALUE
1036 {
1037  if (!rnd) {
1038  VALUE v, vtmp;
1039  size_t i, nlz, len = rb_absint_numwords(vmax, 32, &nlz);
1040  uint32_t *tmp = ALLOCV_N(uint32_t, vtmp, len * 2);
1041  uint32_t mask = (uint32_t)~0 >> nlz;
1042  uint32_t *lim_array = tmp;
1043  uint32_t *rnd_array = tmp + len;
1045  rb_integer_pack(vmax, lim_array, len, sizeof(uint32_t), 0, flag);
1046 
1047  retry:
1048  obj_random_bytes(obj, rnd_array, len * sizeof(uint32_t));
1049  rnd_array[0] &= mask;
1050  for (i = 0; i < len; ++i) {
1051  if (lim_array[i] < rnd_array[i])
1052  goto retry;
1053  if (rnd_array[i] < lim_array[i])
1054  break;
1055  }
1056  v = rb_integer_unpack(rnd_array, len, sizeof(uint32_t), 0, flag);
1057  ALLOCV_END(vtmp);
1058  return v;
1059  }
1060  return limited_big_rand(&rnd->mt, vmax);
1061 }
1062 
1063 static VALUE genrand_bytes(rb_random_t *rnd, long n);
1064 
1065 /*
1066  * call-seq: prng.bytes(size) -> a_string
1067  *
1068  * Returns a random binary string containing +size+ bytes.
1069  *
1070  * random_string = Random.new.bytes(10) # => "\xD7:R\xAB?\x83\xCE\xFAkO"
1071  * random_string.size # => 10
1072  */
1073 static VALUE
1075 {
1076  return genrand_bytes(get_rnd(obj), NUM2LONG(rb_to_int(len)));
1077 }
1078 
1079 static VALUE
1081 {
1082  VALUE bytes;
1083  char *ptr;
1084  unsigned int r, i;
1085 
1086  bytes = rb_str_new(0, n);
1087  ptr = RSTRING_PTR(bytes);
1088  for (; n >= SIZEOF_INT32; n -= SIZEOF_INT32) {
1089  r = genrand_int32(&rnd->mt);
1090  i = SIZEOF_INT32;
1091  do {
1092  *ptr++ = (char)r;
1093  r >>= CHAR_BIT;
1094  } while (--i);
1095  }
1096  if (n > 0) {
1097  r = genrand_int32(&rnd->mt);
1098  do {
1099  *ptr++ = (char)r;
1100  r >>= CHAR_BIT;
1101  } while (--n);
1102  }
1103  return bytes;
1104 }
1105 
1106 VALUE
1108 {
1109  rb_random_t *rnd = try_get_rnd(obj);
1110  if (!rnd) {
1111  return obj_random_bytes(obj, NULL, n);
1112  }
1113  return genrand_bytes(rnd, n);
1114 }
1115 
1116 static VALUE
1117 range_values(VALUE vmax, VALUE *begp, VALUE *endp, int *exclp)
1118 {
1119  VALUE end, r;
1120 
1121  if (!rb_range_values(vmax, begp, &end, exclp)) return Qfalse;
1122  if (endp) *endp = end;
1123  if (!rb_respond_to(end, id_minus)) return Qfalse;
1124  r = rb_funcallv(end, id_minus, 1, begp);
1125  if (NIL_P(r)) return Qfalse;
1126  return r;
1127 }
1128 
1129 static VALUE
1130 rand_int(VALUE obj, rb_random_t *rnd, VALUE vmax, int restrictive)
1131 {
1132  /* mt must be initialized */
1133  unsigned long r;
1134 
1135  if (FIXNUM_P(vmax)) {
1136  long max = FIX2LONG(vmax);
1137  if (!max) return Qnil;
1138  if (max < 0) {
1139  if (restrictive) return Qnil;
1140  max = -max;
1141  }
1142  r = random_ulong_limited(obj, rnd, (unsigned long)max - 1);
1143  return ULONG2NUM(r);
1144  }
1145  else {
1146  VALUE ret;
1147  if (rb_bigzero_p(vmax)) return Qnil;
1148  if (!BIGNUM_SIGN(vmax)) {
1149  if (restrictive) return Qnil;
1150  vmax = rb_big_uminus(vmax);
1151  }
1152  vmax = rb_big_minus(vmax, INT2FIX(1));
1153  if (FIXNUM_P(vmax)) {
1154  long max = FIX2LONG(vmax);
1155  if (max == -1) return Qnil;
1156  r = random_ulong_limited(obj, rnd, max);
1157  return LONG2NUM(r);
1158  }
1159  ret = random_ulong_limited_big(obj, rnd, vmax);
1160  RB_GC_GUARD(vmax);
1161  return ret;
1162  }
1163 }
1164 
1165 NORETURN(static void domain_error(void));
1166 static void
1168 {
1169  VALUE error = INT2FIX(EDOM);
1171 }
1172 
1173 NORETURN(static void invalid_argument(VALUE));
1174 static void
1176 {
1177  rb_raise(rb_eArgError, "invalid argument - %"PRIsVALUE, arg0);
1178 }
1179 
1180 static VALUE
1182 {
1183  switch (v) {
1184  case Qfalse:
1185  (void)NUM2LONG(argv[0]);
1186  break;
1187  case Qnil:
1188  invalid_argument(argv[0]);
1189  }
1190  return v;
1191 }
1192 
1193 static inline double
1195 {
1196  double x = RFLOAT_VALUE(v);
1197  if (isinf(x) || isnan(x)) {
1198  domain_error();
1199  }
1200  return x;
1201 }
1202 
1203 static inline VALUE
1205 {
1206  VALUE beg = Qundef, end = Qundef, vmax, v;
1207  int excl = 0;
1208 
1209  if ((v = vmax = range_values(range, &beg, &end, &excl)) == Qfalse)
1210  return Qfalse;
1211  if (!RB_TYPE_P(vmax, T_FLOAT) && (v = rb_check_to_int(vmax), !NIL_P(v))) {
1212  long max;
1213  vmax = v;
1214  v = Qnil;
1215  if (FIXNUM_P(vmax)) {
1216  fixnum:
1217  if ((max = FIX2LONG(vmax) - excl) >= 0) {
1218  unsigned long r = random_ulong_limited(obj, rnd, (unsigned long)max);
1219  v = ULONG2NUM(r);
1220  }
1221  }
1222  else if (BUILTIN_TYPE(vmax) == T_BIGNUM && BIGNUM_SIGN(vmax) && !rb_bigzero_p(vmax)) {
1223  vmax = excl ? rb_big_minus(vmax, INT2FIX(1)) : rb_big_norm(vmax);
1224  if (FIXNUM_P(vmax)) {
1225  excl = 0;
1226  goto fixnum;
1227  }
1228  v = random_ulong_limited_big(obj, rnd, vmax);
1229  }
1230  }
1231  else if (v = rb_check_to_float(vmax), !NIL_P(v)) {
1232  int scale = 1;
1233  double max = RFLOAT_VALUE(v), mid = 0.5, r;
1234  if (isinf(max)) {
1235  double min = float_value(rb_to_float(beg)) / 2.0;
1236  max = float_value(rb_to_float(end)) / 2.0;
1237  scale = 2;
1238  mid = max + min;
1239  max -= min;
1240  }
1241  else if (isnan(max)) {
1242  domain_error();
1243  }
1244  v = Qnil;
1245  if (max > 0.0) {
1246  r = random_real(obj, rnd, excl);
1247  if (scale > 1) {
1248  return rb_float_new(+(+(+(r - 0.5) * max) * scale) + mid);
1249  }
1250  v = rb_float_new(r * max);
1251  }
1252  else if (max == 0.0 && !excl) {
1253  v = rb_float_new(0.0);
1254  }
1255  }
1256 
1257  if (FIXNUM_P(beg) && FIXNUM_P(v)) {
1258  long x = FIX2LONG(beg) + FIX2LONG(v);
1259  return LONG2NUM(x);
1260  }
1261  switch (TYPE(v)) {
1262  case T_NIL:
1263  break;
1264  case T_BIGNUM:
1265  return rb_big_plus(v, beg);
1266  case T_FLOAT: {
1267  VALUE f = rb_check_to_float(beg);
1268  if (!NIL_P(f)) {
1269  return DBL2NUM(RFLOAT_VALUE(v) + RFLOAT_VALUE(f));
1270  }
1271  }
1272  default:
1273  return rb_funcallv(beg, id_plus, 1, &v);
1274  }
1275 
1276  return v;
1277 }
1278 
1279 static VALUE rand_random(int argc, VALUE *argv, VALUE obj, rb_random_t *rnd);
1280 
1281 /*
1282  * call-seq:
1283  * prng.rand -> float
1284  * prng.rand(max) -> number
1285  *
1286  * When +max+ is an Integer, +rand+ returns a random integer greater than
1287  * or equal to zero and less than +max+. Unlike Kernel.rand, when +max+
1288  * is a negative integer or zero, +rand+ raises an ArgumentError.
1289  *
1290  * prng = Random.new
1291  * prng.rand(100) # => 42
1292  *
1293  * When +max+ is a Float, +rand+ returns a random floating point number
1294  * between 0.0 and +max+, including 0.0 and excluding +max+.
1295  *
1296  * prng.rand(1.5) # => 1.4600282860034115
1297  *
1298  * When +max+ is a Range, +rand+ returns a random number where
1299  * range.member?(number) == true.
1300  *
1301  * prng.rand(5..9) # => one of [5, 6, 7, 8, 9]
1302  * prng.rand(5...9) # => one of [5, 6, 7, 8]
1303  * prng.rand(5.0..9.0) # => between 5.0 and 9.0, including 9.0
1304  * prng.rand(5.0...9.0) # => between 5.0 and 9.0, excluding 9.0
1305  *
1306  * Both the beginning and ending values of the range must respond to subtract
1307  * (<tt>-</tt>) and add (<tt>+</tt>)methods, or rand will raise an
1308  * ArgumentError.
1309  */
1310 static VALUE
1312 {
1313  VALUE v = rand_random(argc, argv, obj, get_rnd(obj));
1314  check_random_number(v, argv);
1315  return v;
1316 }
1317 
1318 static VALUE
1320 {
1321  VALUE vmax, v;
1322 
1323  if (rb_check_arity(argc, 0, 1) == 0) {
1324  return rb_float_new(random_real(obj, rnd, TRUE));
1325  }
1326  vmax = argv[0];
1327  if (NIL_P(vmax)) return Qnil;
1328  if (!RB_TYPE_P(vmax, T_FLOAT)) {
1329  v = rb_check_to_int(vmax);
1330  if (!NIL_P(v)) return rand_int(obj, rnd, v, 1);
1331  }
1332  v = rb_check_to_float(vmax);
1333  if (!NIL_P(v)) {
1334  const double max = float_value(v);
1335  if (max < 0.0) {
1336  return Qnil;
1337  }
1338  else {
1339  double r = random_real(obj, rnd, TRUE);
1340  if (max > 0.0) r *= max;
1341  return rb_float_new(r);
1342  }
1343  }
1344  return rand_range(obj, rnd, vmax);
1345 }
1346 
1347 static VALUE
1349 {
1350  rb_random_t *rnd = try_get_rnd(obj);
1351  VALUE v = rand_random(argc, argv, obj, rnd);
1352  if (NIL_P(v)) v = rand_random(0, 0, obj, rnd);
1353  else if (!v) invalid_argument(argv[0]);
1354  return v;
1355 }
1356 
1357 /*
1358  * call-seq:
1359  * prng1 == prng2 -> true or false
1360  *
1361  * Returns true if the two generators have the same internal state, otherwise
1362  * false. Equivalent generators will return the same sequence of
1363  * pseudo-random numbers. Two generators will generally have the same state
1364  * only if they were initialized with the same seed
1365  *
1366  * Random.new == Random.new # => false
1367  * Random.new(1234) == Random.new(1234) # => true
1368  *
1369  * and have the same invocation history.
1370  *
1371  * prng1 = Random.new(1234)
1372  * prng2 = Random.new(1234)
1373  * prng1 == prng2 # => true
1374  *
1375  * prng1.rand # => 0.1915194503788923
1376  * prng1 == prng2 # => false
1377  *
1378  * prng2.rand # => 0.1915194503788923
1379  * prng1 == prng2 # => true
1380  */
1381 static VALUE
1383 {
1384  rb_random_t *r1, *r2;
1385  if (rb_obj_class(self) != rb_obj_class(other)) return Qfalse;
1386  r1 = get_rnd(self);
1387  r2 = get_rnd(other);
1388  if (memcmp(r1->mt.state, r2->mt.state, sizeof(r1->mt.state))) return Qfalse;
1389  if ((r1->mt.next - r1->mt.state) != (r2->mt.next - r2->mt.state)) return Qfalse;
1390  if (r1->mt.left != r2->mt.left) return Qfalse;
1391  return rb_equal(r1->seed, r2->seed);
1392 }
1393 
1394 /*
1395  * call-seq:
1396  * rand(max=0) -> number
1397  *
1398  * If called without an argument, or if <tt>max.to_i.abs == 0</tt>, rand
1399  * returns a pseudo-random floating point number between 0.0 and 1.0,
1400  * including 0.0 and excluding 1.0.
1401  *
1402  * rand #=> 0.2725926052826416
1403  *
1404  * When +max.abs+ is greater than or equal to 1, +rand+ returns a pseudo-random
1405  * integer greater than or equal to 0 and less than +max.to_i.abs+.
1406  *
1407  * rand(100) #=> 12
1408  *
1409  * When +max+ is a Range, +rand+ returns a random number where
1410  * range.member?(number) == true.
1411  *
1412  * Negative or floating point values for +max+ are allowed, but may give
1413  * surprising results.
1414  *
1415  * rand(-100) # => 87
1416  * rand(-0.5) # => 0.8130921818028143
1417  * rand(1.9) # equivalent to rand(1), which is always 0
1418  *
1419  * Kernel.srand may be used to ensure that sequences of random numbers are
1420  * reproducible between different runs of a program.
1421  *
1422  * See also Random.rand.
1423  */
1424 
1425 static VALUE
1427 {
1428  VALUE vmax;
1429  rb_random_t *rnd = rand_start(&default_rand);
1430 
1431  if (rb_check_arity(argc, 0, 1) && !NIL_P(vmax = argv[0])) {
1432  VALUE v = rand_range(Qnil, rnd, vmax);
1433  if (v != Qfalse) return v;
1434  vmax = rb_to_int(vmax);
1435  if (vmax != INT2FIX(0)) {
1436  v = rand_int(Qnil, rnd, vmax, 0);
1437  if (!NIL_P(v)) return v;
1438  }
1439  }
1440  return DBL2NUM(genrand_real(&rnd->mt));
1441 }
1442 
1443 /*
1444  * call-seq:
1445  * Random.rand -> float
1446  * Random.rand(max) -> number
1447  *
1448  * Alias of Random::DEFAULT.rand.
1449  */
1450 
1451 static VALUE
1453 {
1454  VALUE v = rand_random(argc, argv, Qnil, rand_start(&default_rand));
1455  check_random_number(v, argv);
1456  return v;
1457 }
1458 
1459 #define SIP_HASH_STREAMING 0
1460 #define sip_hash24 ruby_sip_hash24
1461 #if !defined _WIN32 && !defined BYTE_ORDER
1462 # ifdef WORDS_BIGENDIAN
1463 # define BYTE_ORDER BIG_ENDIAN
1464 # else
1465 # define BYTE_ORDER LITTLE_ENDIAN
1466 # endif
1467 # ifndef LITTLE_ENDIAN
1468 # define LITTLE_ENDIAN 1234
1469 # endif
1470 # ifndef BIG_ENDIAN
1471 # define BIG_ENDIAN 4321
1472 # endif
1473 #endif
1474 #include "siphash.c"
1475 
1476 typedef struct {
1478  uint8_t sip[16];
1479 } seed_keys_t;
1480 
1481 static union {
1484 } seed;
1485 
1486 static void
1487 init_seed(struct MT *mt)
1488 {
1489  int i;
1490 
1491  for (i = 0; i < numberof(seed.u32); ++i)
1492  seed.u32[i] = genrand_int32(mt);
1493 }
1494 
1495 st_index_t
1497 {
1498  return st_hash_start(seed.key.hash + h);
1499 }
1500 
1501 st_index_t
1502 rb_memhash(const void *ptr, long len)
1503 {
1504  sip_uint64_t h = sip_hash24(seed.key.sip, ptr, len);
1505 #ifdef HAVE_UINT64_T
1506  return (st_index_t)h;
1507 #else
1508  return (st_index_t)(h.u32[0] ^ h.u32[1]);
1509 #endif
1510 }
1511 
1512 /* Initialize Ruby internal seeds. This function is called at very early stage
1513  * of Ruby startup. Thus, you can't use Ruby's object. */
1514 void
1516 {
1517  /*
1518  Don't reuse this MT for Random::DEFAULT. Random::DEFAULT::seed shouldn't
1519  provide a hint that an attacker guess siphash's seed.
1520  */
1521  struct MT mt;
1522  uint32_t initial_seed[DEFAULT_SEED_CNT];
1523 
1524  fill_random_seed(initial_seed, DEFAULT_SEED_CNT);
1525  init_by_array(&mt, initial_seed, DEFAULT_SEED_CNT);
1526 
1527  init_seed(&mt);
1528 
1529  explicit_bzero(initial_seed, DEFAULT_SEED_LEN);
1530 }
1531 
1532 static VALUE
1533 init_randomseed(struct MT *mt)
1534 {
1535  uint32_t initial[DEFAULT_SEED_CNT+1];
1536  VALUE seed;
1537 
1539  init_by_array(mt, initial, DEFAULT_SEED_CNT);
1540  seed = make_seed_value(initial, DEFAULT_SEED_CNT);
1541  explicit_bzero(initial, DEFAULT_SEED_LEN);
1542  return seed;
1543 }
1544 
1545 /* construct Random::DEFAULT bits */
1546 static VALUE
1548 {
1549  rb_random_t *r = &default_rand;
1550  struct MT *mt = &r->mt;
1551  VALUE v = TypedData_Wrap_Struct(rb_cRandom, &random_data_type, r);
1552 
1554  r->seed = init_randomseed(mt);
1555 
1556  return v;
1557 }
1558 
1559 void
1561 {
1562  rb_random_t *r = &default_rand;
1563  uninit_genrand(&r->mt);
1564  r->seed = INT2FIX(0);
1565 }
1566 
1567 /*
1568  * Document-class: Random
1569  *
1570  * Random provides an interface to Ruby's pseudo-random number generator, or
1571  * PRNG. The PRNG produces a deterministic sequence of bits which approximate
1572  * true randomness. The sequence may be represented by integers, floats, or
1573  * binary strings.
1574  *
1575  * The generator may be initialized with either a system-generated or
1576  * user-supplied seed value by using Random.srand.
1577  *
1578  * The class method Random.rand provides the base functionality of Kernel.rand
1579  * along with better handling of floating point values. These are both
1580  * interfaces to Random::DEFAULT, the Ruby system PRNG.
1581  *
1582  * Random.new will create a new PRNG with a state independent of
1583  * Random::DEFAULT, allowing multiple generators with different seed values or
1584  * sequence positions to exist simultaneously. Random objects can be
1585  * marshaled, allowing sequences to be saved and resumed.
1586  *
1587  * PRNGs are currently implemented as a modified Mersenne Twister with a period
1588  * of 2**19937-1.
1589  */
1590 
1591 void
1593 {
1594  rb_define_global_function("srand", rb_f_srand, -1);
1595  rb_define_global_function("rand", rb_f_rand, -1);
1596 
1597  rb_cRandom = rb_define_class("Random", rb_cObject);
1599  rb_define_method(rb_cRandom, "initialize", random_init, -1);
1600  rb_define_method(rb_cRandom, "rand", random_rand, -1);
1603  rb_define_method(rb_cRandom, "initialize_copy", random_copy, 1);
1604  rb_define_private_method(rb_cRandom, "marshal_dump", random_dump, 0);
1605  rb_define_private_method(rb_cRandom, "marshal_load", random_load, 1);
1609 
1610  {
1611  /* Direct access to Ruby's Pseudorandom number generator (PRNG). */
1612  VALUE rand_default = Init_Random_default();
1613  rb_define_const(rb_cRandom, "DEFAULT", rand_default);
1614  }
1615 
1622 
1623  {
1624  VALUE m = rb_define_module_under(rb_cRandom, "Formatter");
1626  rb_define_method(m, "random_number", rand_random_number, -1);
1627  rb_define_method(m, "rand", rand_random_number, -1);
1628  }
1629 }
1630 
1631 #undef rb_intern
1632 void
1634 {
1635  id_rand = rb_intern("rand");
1636  id_bytes = rb_intern("bytes");
1637 
1638  InitVM(Random);
1639 }
void Init_Random(void)
Definition: random.c:1633
int rb_bigzero_p(VALUE x)
Definition: bignum.c:2903
static VALUE random_bytes(VALUE obj, VALUE len)
Definition: random.c:1074
static unsigned int nlz_long(unsigned long x)
Definition: internal.h:167
seed_keys_t key
Definition: random.c:1482
static rb_random_t default_rand
Definition: random.c:242
int rb_integer_pack(VALUE val, void *words, size_t numwords, size_t wordsize, size_t nails, int flags)
Definition: bignum.c:3531
#define RARRAY_LEN(a)
Definition: ruby.h:1026
int gettimeofday(struct timeval *, struct timezone *)
Definition: win32.c:4580
#define FALSE
Definition: nkf.h:174
#define RUBY_TYPED_FREE_IMMEDIATELY
Definition: ruby.h:1145
static VALUE random_s_state(VALUE klass)
Definition: random.c:678
void rb_update_max_fd(int fd)
Definition: io.c:189
static unsigned long make_mask(unsigned long x)
Definition: random.c:792
#define INTEGER_PACK_LSWORD_FIRST
Definition: intern.h:139
static double random_real(VALUE obj, rb_random_t *rnd, int excl)
Definition: random.c:933
static int max(int a, int b)
Definition: strftime.c:142
void rb_define_singleton_method(VALUE obj, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a singleton method for obj.
Definition: class.c:1716
static VALUE rand_random_number(int argc, VALUE *argv, VALUE obj)
Definition: random.c:1348
static void domain_error(void)
Definition: random.c:1167
#define type_roomof(x, y)
Definition: internal.h:839
VALUE rb_random_bytes(VALUE obj, long n)
Definition: random.c:1107
uint32_t state[N]
Definition: random.c:107
#define CLASS_OF(v)
Definition: ruby.h:453
#define r1
int rb_cloexec_open(const char *pathname, int flags, mode_t mode)
Definition: io.c:255
#define InitVM(ext)
Definition: ruby.h:2143
static VALUE rand_random(int argc, VALUE *argv, VALUE obj, rb_random_t *rnd)
Definition: random.c:1319
#define ATOMIC_PTR_CAS(var, oldval, val)
Definition: ruby_atomic.h:191
uint32_t * next
Definition: random.c:108
static VALUE random_copy(VALUE obj, VALUE orig)
Definition: random.c:644
#define TypedData_Wrap_Struct(klass, data_type, sval)
Definition: ruby.h:1169
#define OBJ_INIT_COPY(obj, orig)
Definition: intern.h:288
#define TypedData_Get_Struct(obj, type, data_type, sval)
Definition: ruby.h:1190
VALUE rb_big_plus(VALUE x, VALUE y)
Definition: bignum.c:5751
static VALUE random_raw_seed(VALUE self, VALUE size)
Definition: random.c:613
static VALUE random_rand(int argc, VALUE *argv, VALUE obj)
Definition: random.c:1311
static VALUE random_left(VALUE obj)
Definition: random.c:685
uint32_t u32[type_roomof(seed_keys_t, uint32_t)]
Definition: random.c:1483
void rb_define_private_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Definition: class.c:1527
static VALUE limited_big_rand(struct MT *mt, VALUE limit)
Definition: random.c:838
static VALUE random_seed(void)
Definition: random.c:595
#define rb_check_arity
Definition: intern.h:303
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
Definition: range.c:995
#define ULONG2NUM(x)
Definition: ruby.h:1574
VALUE rb_ary_push(VALUE ary, VALUE item)
Definition: array.c:905
static void invalid_argument(VALUE arg0)
Definition: random.c:1175
static rb_random_t * rand_start(rb_random_t *r)
Definition: random.c:248
static void random_mark(void *ptr)
Definition: random.c:308
static int fill_random_bytes(void *seed, size_t size, int need_secure)
Definition: random.c:539
#define DEFAULT_SEED_CNT
Definition: random.c:240
static VALUE random_equal(VALUE self, VALUE other)
Definition: random.c:1382
#define INTEGER_PACK_NATIVE_BYTE_ORDER
Definition: intern.h:142
VALUE rb_to_int(VALUE)
Definition: object.c:2687
st_index_t st_hash_start(st_index_t h)
Definition: st.c:1864
#define Check_Type(v, t)
Definition: ruby.h:562
void rb_raise(VALUE exc, const char *fmt,...)
Definition: error.c:2207
static unsigned int genrand_int32(struct MT *mt)
Definition: random.c:183
uint32_t u32[2]
Definition: siphash.h:13
int left
Definition: random.c:109
#define RB_GC_GUARD(v)
Definition: ruby.h:552
void rb_define_alloc_func(VALUE, rb_alloc_func_t)
#define DATA_PTR(dta)
Definition: ruby.h:1113
void rb_include_module(VALUE klass, VALUE module)
Definition: class.c:864
VALUE rb_check_to_float(VALUE)
Definition: object.c:3016
void rb_gc_mark(VALUE ptr)
Definition: gc.c:4394
static void init_by_array(struct MT *mt, const uint32_t init_key[], int key_length)
Definition: random.c:138
#define T_ARRAY
Definition: ruby.h:498
st_data_t st_index_t
Definition: st.h:50
#define ATOMIC_PTR_EXCHANGE(var, val)
Definition: ruby_atomic.h:177
void rb_define_global_function(const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a global function.
Definition: class.c:1745
time_t tv_sec
Definition: missing.h:54
static void random_free(void *ptr)
Definition: random.c:314
static void init_seed(struct MT *mt)
Definition: random.c:1487
static VALUE random_s_left(VALUE klass)
Definition: random.c:693
#define FIXNUM_P(f)
Definition: ruby.h:365
RUBY_EXTERN void explicit_bzero(void *b, size_t len)
#define NUM2DBL(x)
Definition: ruby.h:743
VALUE rb_eRangeError
Definition: error.c:766
#define rb_ary_new2
Definition: intern.h:90
unsigned char uint8_t
Definition: sha2.h:100
#define fill_random_bytes_syscall(seed, size, need_secure)
Definition: random.c:535
#define Data_Wrap_Struct(klass, mark, free, sval)
Definition: ruby.h:1149
void rb_exc_raise(VALUE mesg)
Definition: eval.c:620
#define RB_TYPE_P(obj, type)
Definition: ruby.h:527
static size_t random_memsize(const void *ptr)
Definition: random.c:321
static void next_state(struct MT *mt)
Definition: random.c:164
#define ATOMIC_SET(var, val)
Definition: ruby_atomic.h:127
#define id_minus
Definition: random.c:302
#define id_plus
Definition: random.c:303
unsigned long long uint64_t
Definition: sha2.h:102
#define ALLOC_N(type, n)
Definition: ruby.h:1587
static VALUE rand_range(VALUE obj, rb_random_t *rnd, VALUE range)
Definition: random.c:1204
#define val
long tv_usec
Definition: missing.h:55
RUBY_EXTERN VALUE rb_cObject
Definition: ruby.h:1872
#define rb_float_new(d)
Definition: internal.h:1296
static VALUE mt_state(const struct MT *mt)
Definition: random.c:661
#define T_NIL
Definition: ruby.h:490
static VALUE random_init(int argc, VALUE *argv, VALUE obj)
Definition: random.c:405
int rb_typeddata_is_kind_of(VALUE obj, const rb_data_type_t *data_type)
Definition: error.c:720
int rb_num_negative_p(VALUE)
Definition: numeric.c:342
static VALUE rand_int(VALUE obj, rb_random_t *rnd, VALUE vmax, int restrictive)
Definition: random.c:1130
st_index_t hash
Definition: random.c:1477
static VALUE rb_f_srand(int argc, VALUE *argv, VALUE obj)
Definition: random.c:774
void InitVM_Random(void)
Definition: random.c:1592
unsigned int rb_genrand_int32(void)
Definition: random.c:264
#define NIL_P(v)
Definition: ruby.h:451
unsigned int rb_random_int32(VALUE obj)
Definition: random.c:921
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition: class.c:646
void rb_define_const(VALUE, const char *, VALUE)
Definition: variable.c:2734
#define SIZEOF_INT32
Definition: random.c:277
rb_atomic_t cnt[RUBY_NSIG]
Definition: signal.c:525
#define T_FLOAT
Definition: ruby.h:495
static const rb_data_type_t random_data_type
Definition: random.c:326
#define TYPE(x)
Definition: ruby.h:521
int argc
Definition: ruby.c:183
void Init_RandomSeedCore(void)
Definition: random.c:1515
#define Qfalse
Definition: ruby.h:436
#define M
Definition: random.c:96
#define ALLOCV_N(type, v, n)
Definition: ruby.h:1657
#define S_ISCHR(m)
#define T_BIGNUM
Definition: ruby.h:501
#define range(low, item, hi)
Definition: date_strftime.c:21
void rb_gc_register_mark_object(VALUE obj)
Definition: gc.c:6154
#define genrand_initialized(mt)
Definition: random.c:112
RUBY_EXTERN int isinf(double)
Definition: isinf.c:56
#define uninit_genrand(mt)
Definition: random.c:113
#define ALLOCV_END(v)
Definition: ruby.h:1658
VALUE rb_class_new_instance(int, const VALUE *, VALUE)
Definition: object.c:1891
static ID id_bytes
Definition: random.c:304
Definition: util.c:833
#define numberof(array)
Definition: etc.c:616
VALUE rb_integer_unpack(const void *words, size_t numwords, size_t wordsize, size_t nails, int flags)
Definition: bignum.c:3617
static VALUE range_values(VALUE vmax, VALUE *begp, VALUE *endp, int *exclp)
Definition: random.c:1117
st_index_t rb_memhash(const void *ptr, long len)
Definition: random.c:1502
int int_must_be_32bit_at_least[sizeof(int) *CHAR_BIT< 32 ? -1 :1]
Definition: random.c:92
VALUE seed
Definition: random.c:236
VALUE rb_big_minus(VALUE x, VALUE y)
Definition: bignum.c:5780
#define RSTRING_LEN(str)
Definition: ruby.h:978
VALUE rb_funcallv_public(VALUE, ID, int, const VALUE *)
Calls a method.
Definition: vm_eval.c:867
#define RARRAY_CONST_PTR(a)
Definition: ruby.h:1028
static VALUE random_load(VALUE obj, VALUE dump)
Definition: random.c:714
int errno
#define TRUE
Definition: nkf.h:175
void rb_reset_random_seed(void)
Definition: random.c:1560
static void fill_random_seed(uint32_t *seed, size_t cnt)
Definition: random.c:547
VALUE rb_eSystemCallError
Definition: error.c:780
static unsigned int random_int32(rb_random_t *rnd)
Definition: random.c:915
unsigned char buf[MIME_BUF_SIZE]
Definition: nkf.c:4309
#define PRIsVALUE
Definition: ruby.h:135
unsigned long ID
Definition: ruby.h:86
#define Qnil
Definition: ruby.h:438
#define LIKELY(x)
Definition: ffi_common.h:125
#define BUILTIN_TYPE(x)
Definition: ruby.h:518
unsigned long VALUE
Definition: ruby.h:85
#define INTEGER_PACK_MSWORD_FIRST
Definition: intern.h:138
void rb_check_copyable(VALUE obj, VALUE orig)
Definition: error.c:2490
int memcmp(const void *s1, const void *s2, size_t len)
Definition: memcmp.c:7
#define isnan(x)
Definition: win32.h:346
unsigned long rb_genrand_ulong_limited(unsigned long limit)
Definition: random.c:893
static VALUE random_dump(VALUE obj)
Definition: random.c:700
#define CHAR_BIT
Definition: ruby.h:196
#define rb_funcallv
Definition: console.c:21
#define LONG2NUM(x)
Definition: ruby.h:1573
int rb_respond_to(VALUE, ID)
Definition: vm_method.c:1995
unsigned int uint32_t
Definition: sha2.h:101
register unsigned int len
Definition: zonetab.h:51
VALUE rb_define_module_under(VALUE outer, const char *name)
Definition: class.c:790
Definition: random.c:105
static double int_pair_to_real_exclusive(uint32_t a, uint32_t b)
Definition: random.c:211
static double genrand_real(struct MT *mt)
Definition: random.c:203
VALUE rb_check_to_int(VALUE)
Definition: object.c:2693
#define RSTRING_PTR(str)
Definition: ruby.h:982
static VALUE obj_random_bytes(VALUE obj, void *p, long n)
Definition: random.c:899
VALUE rb_equal(VALUE, VALUE)
Definition: object.c:86
VALUE rb_big_uminus(VALUE x)
Definition: bignum.c:5481
#define BIGNUM_SIGN(b)
Definition: internal.h:498
#define RFLOAT_VALUE(v)
Definition: ruby.h:940
int size
Definition: encoding.c:57
#define f
#define INT2FIX(i)
Definition: ruby.h:232
static double float_value(VALUE v)
Definition: random.c:1194
#define NUM2ULONG(x)
Definition: ruby.h:658
static union @153 seed
static VALUE random_alloc(VALUE klass)
Definition: random.c:356
static int nlz(BDIGIT x)
Definition: bignum.c:159
double rb_genrand_real(void)
Definition: random.c:271
static VALUE init_randomseed(struct MT *mt)
Definition: random.c:1533
#define TWIST(u, v)
Definition: random.c:101
static VALUE genrand_bytes(rb_random_t *rnd, long n)
Definition: random.c:1080
VALUE rb_big_norm(VALUE x)
Definition: bignum.c:3136
static VALUE rb_f_rand(int argc, VALUE *argv, VALUE obj)
Definition: random.c:1426
#define O_NONBLOCK
Definition: win32.h:590
#define T_STRING
Definition: ruby.h:496
static ID id_rand
Definition: random.c:304
static VALUE make_seed_value(uint32_t *ptr, size_t len)
Definition: random.c:571
#define fill_random_bytes_urandom(seed, size)
Definition: random.c:461
static VALUE rand_init(struct MT *mt, VALUE vseed)
Definition: random.c:365
static rb_random_t * get_rnd(VALUE obj)
Definition: random.c:337
static unsigned long limited_rand(struct MT *mt, unsigned long limit)
Definition: random.c:806
#define N
Definition: random.c:95
NORETURN(static void domain_error(void))
static VALUE Init_Random_default(void)
Definition: random.c:1547
static VALUE random_ulong_limited_big(VALUE obj, rb_random_t *rnd, VALUE vmax)
Definition: random.c:1035
#define TypedData_Make_Struct(klass, type, data_type, sval)
Definition: ruby.h:1182
size_t rb_absint_numwords(VALUE val, size_t word_numbits, size_t *nlz_bits_ret)
Definition: bignum.c:3366
static VALUE random_s_rand(int argc, VALUE *argv, VALUE obj)
Definition: random.c:1452
int rb_atomic_t
Definition: ruby_atomic.h:120
static void init_genrand(struct MT *mt, unsigned int s)
Definition: random.c:117
static VALUE check_random_number(VALUE v, const VALUE *argv)
Definition: random.c:1181
#define rb_check_frozen(obj)
Definition: intern.h:276
static struct MT * default_mt(void)
Definition: random.c:258
#define r2
#define memcpy(d, s, n)
Definition: ffi_common.h:55
static VALUE ulong_to_num_plus_1(unsigned long n)
Definition: random.c:974
void void xfree(void *)
#define sip_hash24
Definition: random.c:1460
static VALUE random_get_seed(VALUE obj)
Definition: random.c:637
#define rb_intern(str)
double rb_random_real(VALUE obj)
Definition: random.c:956
#define fstat(fd, st)
Definition: win32.h:184
#define stat(path, st)
Definition: win32.h:183
#define NULL
Definition: _sdbm.c:102
#define FIX2LONG(x)
Definition: ruby.h:363
#define Qundef
Definition: ruby.h:439
struct MT mt
Definition: random.c:237
static rb_random_t * try_get_rnd(VALUE obj)
Definition: random.c:345
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Definition: class.c:1515
#define DEFAULT_SEED_LEN
Definition: random.c:423
static unsigned long random_ulong_limited(VALUE obj, rb_random_t *rnd, unsigned long limit)
Definition: random.c:987
static VALUE random_state(VALUE obj)
Definition: random.c:670
VALUE rb_eArgError
Definition: error.c:763
#define NUM2LONG(x)
Definition: ruby.h:648
VALUE rb_cRandom
Definition: random.c:301
static double int_pair_to_real_inclusive(uint32_t a, uint32_t b)
Definition: random.c:280
st_index_t rb_hash_start(st_index_t h)
Definition: random.c:1496
char ** argv
Definition: ruby.c:184
#define DBL2NUM(dbl)
Definition: ruby.h:941
VALUE rb_to_float(VALUE)
Definition: object.c:3006
unsigned long rb_random_ulong_limited(VALUE obj, unsigned long limit)
Definition: random.c:1016
VALUE rb_obj_class(VALUE)
Definition: object.c:229
VALUE rb_str_new(const char *, long)
Definition: string.c:736