Ruby  2.5.0dev(2017-10-22revision60238)
random.c
Go to the documentation of this file.
1 /**********************************************************************
2 
3  random.c -
4 
5  $Author$
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
211 int_pair_to_real_exclusive(uint32_t a, uint32_t b)
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 
242 static rb_random_t default_rand;
243 
244 static VALUE rand_init(struct MT *mt, VALUE vseed);
245 static VALUE random_seed(void);
246 
247 static rb_random_t *
248 rand_start(rb_random_t *r)
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 *
258 default_mt(void)
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
280 int_pair_to_real_inclusive(uint32_t a, uint32_t b)
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 '+'
304 static ID id_rand, id_bytes;
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 
326 static const rb_data_type_t random_data_type = {
327  "random",
328  {
329  random_mark,
330  random_free,
331  random_memsize,
332  },
334 };
335 
336 static rb_random_t *
337 get_rnd(VALUE obj)
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 *
345 try_get_rnd(VALUE obj)
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
356 random_alloc(VALUE klass)
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
405 random_init(int argc, VALUE *argv, VALUE obj)
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 __NR_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(__NR_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
547 fill_random_seed(uint32_t *seed, size_t cnt)
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
571 make_seed_value(uint32_t *ptr, size_t len)
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
595 random_seed(void)
596 {
597  VALUE v;
599  fill_random_seed(buf, DEFAULT_SEED_CNT);
600  v = make_seed_value(buf, DEFAULT_SEED_CNT);
602  return v;
603 }
604 
605 /*
606  * call-seq: Random.urandom(size) -> string
607  *
608  * Returns a string, using platform providing features.
609  * Returned value is expected to be a cryptographically secure
610  * pseudo-random number in binary form.
611  * This method raises a RuntimeError if the feature provided by platform
612  * failed to prepare the result.
613  *
614  * In 2017, Linux manpage random(7) writes that "no cryptographic
615  * primitive available today can hope to promise more than 256 bits of
616  * security". So it might be questionable to pass size > 32 to this
617  * method.
618  *
619  * Random.urandom(8) #=> "\x78\x41\xBA\xAF\x7D\xEA\xD8\xEA"
620  */
621 static VALUE
622 random_raw_seed(VALUE self, VALUE size)
623 {
624  long n = NUM2ULONG(size);
625  VALUE buf = rb_str_new(0, n);
626  if (n == 0) return buf;
627  if (fill_random_bytes(RSTRING_PTR(buf), n, FALSE))
628  rb_raise(rb_eRuntimeError, "failed to get urandom");
629  return buf;
630 }
631 
632 /*
633  * call-seq: prng.seed -> integer
634  *
635  * Returns the seed value used to initialize the generator. This may be used to
636  * initialize another generator with the same state at a later time, causing it
637  * to produce the same sequence of numbers.
638  *
639  * prng1 = Random.new(1234)
640  * prng1.seed #=> 1234
641  * prng1.rand(100) #=> 47
642  *
643  * prng2 = Random.new(prng1.seed)
644  * prng2.rand(100) #=> 47
645  */
646 static VALUE
647 random_get_seed(VALUE obj)
648 {
649  return get_rnd(obj)->seed;
650 }
651 
652 /* :nodoc: */
653 static VALUE
654 random_copy(VALUE obj, VALUE orig)
655 {
656  rb_random_t *rnd1, *rnd2;
657  struct MT *mt;
658 
659  if (!OBJ_INIT_COPY(obj, orig)) return obj;
660 
661  rnd1 = get_rnd(obj);
662  rnd2 = get_rnd(orig);
663  mt = &rnd1->mt;
664 
665  *rnd1 = *rnd2;
666  mt->next = mt->state + numberof(mt->state) - mt->left + 1;
667  return obj;
668 }
669 
670 static VALUE
671 mt_state(const struct MT *mt)
672 {
673  return rb_integer_unpack(mt->state, numberof(mt->state),
674  sizeof(*mt->state), 0,
676 }
677 
678 /* :nodoc: */
679 static VALUE
680 random_state(VALUE obj)
681 {
682  rb_random_t *rnd = get_rnd(obj);
683  return mt_state(&rnd->mt);
684 }
685 
686 /* :nodoc: */
687 static VALUE
688 random_s_state(VALUE klass)
689 {
690  return mt_state(&default_rand.mt);
691 }
692 
693 /* :nodoc: */
694 static VALUE
695 random_left(VALUE obj)
696 {
697  rb_random_t *rnd = get_rnd(obj);
698  return INT2FIX(rnd->mt.left);
699 }
700 
701 /* :nodoc: */
702 static VALUE
703 random_s_left(VALUE klass)
704 {
705  return INT2FIX(default_rand.mt.left);
706 }
707 
708 /* :nodoc: */
709 static VALUE
710 random_dump(VALUE obj)
711 {
712  rb_random_t *rnd = get_rnd(obj);
713  VALUE dump = rb_ary_new2(3);
714 
715  rb_ary_push(dump, mt_state(&rnd->mt));
716  rb_ary_push(dump, INT2FIX(rnd->mt.left));
717  rb_ary_push(dump, rnd->seed);
718 
719  return dump;
720 }
721 
722 /* :nodoc: */
723 static VALUE
724 random_load(VALUE obj, VALUE dump)
725 {
726  rb_random_t *rnd = get_rnd(obj);
727  struct MT *mt = &rnd->mt;
728  VALUE state, left = INT2FIX(1), seed = INT2FIX(0);
729  const VALUE *ary;
730  unsigned long x;
731 
732  rb_check_copyable(obj, dump);
733  Check_Type(dump, T_ARRAY);
734  ary = RARRAY_CONST_PTR(dump);
735  switch (RARRAY_LEN(dump)) {
736  case 3:
737  seed = ary[2];
738  case 2:
739  left = ary[1];
740  case 1:
741  state = ary[0];
742  break;
743  default:
744  rb_raise(rb_eArgError, "wrong dump data");
745  }
746  rb_integer_pack(state, mt->state, numberof(mt->state),
747  sizeof(*mt->state), 0,
749  x = NUM2ULONG(left);
750  if (x > numberof(mt->state)) {
751  rb_raise(rb_eArgError, "wrong value");
752  }
753  mt->left = (unsigned int)x;
754  mt->next = mt->state + numberof(mt->state) - x + 1;
755  rnd->seed = rb_to_int(seed);
756 
757  return obj;
758 }
759 
760 /*
761  * call-seq:
762  * srand(number = Random.new_seed) -> old_seed
763  *
764  * Seeds the system pseudo-random number generator, Random::DEFAULT, with
765  * +number+. The previous seed value is returned.
766  *
767  * If +number+ is omitted, seeds the generator using a source of entropy
768  * provided by the operating system, if available (/dev/urandom on Unix systems
769  * or the RSA cryptographic provider on Windows), which is then combined with
770  * the time, the process id, and a sequence number.
771  *
772  * srand may be used to ensure repeatable sequences of pseudo-random numbers
773  * between different runs of the program. By setting the seed to a known value,
774  * programs can be made deterministic during testing.
775  *
776  * srand 1234 # => 268519324636777531569100071560086917274
777  * [ rand, rand ] # => [0.1915194503788923, 0.6221087710398319]
778  * [ rand(10), rand(1000) ] # => [4, 664]
779  * srand 1234 # => 1234
780  * [ rand, rand ] # => [0.1915194503788923, 0.6221087710398319]
781  */
782 
783 static VALUE
784 rb_f_srand(int argc, VALUE *argv, VALUE obj)
785 {
786  VALUE seed, old;
787  rb_random_t *r = &default_rand;
788 
789  if (rb_check_arity(argc, 0, 1) == 0) {
790  seed = random_seed();
791  }
792  else {
793  seed = rb_to_int(argv[0]);
794  }
795  old = r->seed;
796  r->seed = rand_init(&r->mt, seed);
797 
798  return old;
799 }
800 
801 static unsigned long
802 make_mask(unsigned long x)
803 {
804  x = x | x >> 1;
805  x = x | x >> 2;
806  x = x | x >> 4;
807  x = x | x >> 8;
808  x = x | x >> 16;
809 #if 4 < SIZEOF_LONG
810  x = x | x >> 32;
811 #endif
812  return x;
813 }
814 
815 static unsigned long
816 limited_rand(struct MT *mt, unsigned long limit)
817 {
818  /* mt must be initialized */
819  unsigned long val, mask;
820 
821  if (!limit) return 0;
822  mask = make_mask(limit);
823 
824 #if 4 < SIZEOF_LONG
825  if (0xffffffff < limit) {
826  int i;
827  retry:
828  val = 0;
829  for (i = SIZEOF_LONG/SIZEOF_INT32-1; 0 <= i; i--) {
830  if ((mask >> (i * 32)) & 0xffffffff) {
831  val |= (unsigned long)genrand_int32(mt) << (i * 32);
832  val &= mask;
833  if (limit < val)
834  goto retry;
835  }
836  }
837  return val;
838  }
839 #endif
840 
841  do {
842  val = genrand_int32(mt) & mask;
843  } while (limit < val);
844  return val;
845 }
846 
847 static VALUE
848 limited_big_rand(struct MT *mt, VALUE limit)
849 {
850  /* mt must be initialized */
851 
852  uint32_t mask;
853  long i;
854  int boundary;
855 
856  size_t len;
857  uint32_t *tmp, *lim_array, *rnd_array;
858  VALUE vtmp;
859  VALUE val;
860 
861  len = rb_absint_numwords(limit, 32, NULL);
862  tmp = ALLOCV_N(uint32_t, vtmp, len*2);
863  lim_array = tmp;
864  rnd_array = tmp + len;
865  rb_integer_pack(limit, lim_array, len, sizeof(uint32_t), 0,
867 
868  retry:
869  mask = 0;
870  boundary = 1;
871  for (i = len-1; 0 <= i; i--) {
872  uint32_t rnd;
873  uint32_t lim = lim_array[i];
874  mask = mask ? 0xffffffff : (uint32_t)make_mask(lim);
875  if (mask) {
876  rnd = genrand_int32(mt) & mask;
877  if (boundary) {
878  if (lim < rnd)
879  goto retry;
880  if (rnd < lim)
881  boundary = 0;
882  }
883  }
884  else {
885  rnd = 0;
886  }
887  rnd_array[i] = rnd;
888  }
889  val = rb_integer_unpack(rnd_array, len, sizeof(uint32_t), 0,
891  ALLOCV_END(vtmp);
892 
893  return val;
894 }
895 
896 /*
897  * Returns random unsigned long value in [0, +limit+].
898  *
899  * Note that +limit+ is included, and the range of the argument and the
900  * return value depends on environments.
901  */
902 unsigned long
903 rb_genrand_ulong_limited(unsigned long limit)
904 {
905  return limited_rand(default_mt(), limit);
906 }
907 
908 static VALUE
909 obj_random_bytes(VALUE obj, void *p, long n)
910 {
911  VALUE len = LONG2NUM(n);
912  VALUE v = rb_funcallv_public(obj, id_bytes, 1, &len);
913  long l;
914  Check_Type(v, T_STRING);
915  l = RSTRING_LEN(v);
916  if (l < n)
917  rb_raise(rb_eRangeError, "random data too short %ld", l);
918  else if (l > n)
919  rb_raise(rb_eRangeError, "random data too long %ld", l);
920  if (p) memcpy(p, RSTRING_PTR(v), n);
921  return v;
922 }
923 
924 static unsigned int
925 random_int32(rb_random_t *rnd)
926 {
927  return genrand_int32(&rnd->mt);
928 }
929 
930 unsigned int
932 {
933  rb_random_t *rnd = try_get_rnd(obj);
934  if (!rnd) {
935  uint32_t x;
936  obj_random_bytes(obj, &x, sizeof(x));
937  return (unsigned int)x;
938  }
939  return random_int32(rnd);
940 }
941 
942 static double
943 random_real(VALUE obj, rb_random_t *rnd, int excl)
944 {
945  uint32_t a, b;
946 
947  if (!rnd) {
948  uint32_t x[2] = {0, 0};
949  obj_random_bytes(obj, x, sizeof(x));
950  a = x[0];
951  b = x[1];
952  }
953  else {
954  a = random_int32(rnd);
955  b = random_int32(rnd);
956  }
957  if (excl) {
958  return int_pair_to_real_exclusive(a, b);
959  }
960  else {
961  return int_pair_to_real_inclusive(a, b);
962  }
963 }
964 
965 double
967 {
968  rb_random_t *rnd = try_get_rnd(obj);
969  if (!rnd) {
970  VALUE v = rb_funcallv(obj, id_rand, 0, 0);
971  double d = NUM2DBL(v);
972  if (d < 0.0) {
973  rb_raise(rb_eRangeError, "random number too small %g", d);
974  }
975  else if (d >= 1.0) {
976  rb_raise(rb_eRangeError, "random number too big %g", d);
977  }
978  return d;
979  }
980  return genrand_real(&rnd->mt);
981 }
982 
983 static inline VALUE
984 ulong_to_num_plus_1(unsigned long n)
985 {
986 #if HAVE_LONG_LONG
987  return ULL2NUM((LONG_LONG)n+1);
988 #else
989  if (n >= ULONG_MAX) {
990  return rb_big_plus(ULONG2NUM(n), INT2FIX(1));
991  }
992  return ULONG2NUM(n+1);
993 #endif
994 }
995 
996 static unsigned long
997 random_ulong_limited(VALUE obj, rb_random_t *rnd, unsigned long limit)
998 {
999  if (!limit) return 0;
1000  if (!rnd) {
1001  const int w = sizeof(limit) * CHAR_BIT - nlz_long(limit);
1002  const int n = w > 32 ? sizeof(unsigned long) : sizeof(uint32_t);
1003  const unsigned long mask = ~(~0UL << w);
1004  const unsigned long full =
1005  (size_t)n >= sizeof(unsigned long) ? ~0UL :
1006  ~(~0UL << n * CHAR_BIT);
1007  unsigned long val, bits = 0, rest = 0;
1008  do {
1009  if (mask & ~rest) {
1010  union {uint32_t u32; unsigned long ul;} buf;
1011  obj_random_bytes(obj, &buf, n);
1012  rest = full;
1013  bits = (n == sizeof(uint32_t)) ? buf.u32 : buf.ul;
1014  }
1015  val = bits;
1016  bits >>= w;
1017  rest >>= w;
1018  val &= mask;
1019  } while (limit < val);
1020  return val;
1021  }
1022  return limited_rand(&rnd->mt, limit);
1023 }
1024 
1025 unsigned long
1026 rb_random_ulong_limited(VALUE obj, unsigned long limit)
1027 {
1028  rb_random_t *rnd = try_get_rnd(obj);
1029  if (!rnd) {
1030  VALUE lim = ulong_to_num_plus_1(limit);
1031  VALUE v = rb_to_int(rb_funcallv_public(obj, id_rand, 1, &lim));
1032  unsigned long r = NUM2ULONG(v);
1033  if (rb_num_negative_p(v)) {
1034  rb_raise(rb_eRangeError, "random number too small %ld", r);
1035  }
1036  if (r > limit) {
1037  rb_raise(rb_eRangeError, "random number too big %ld", r);
1038  }
1039  return r;
1040  }
1041  return limited_rand(&rnd->mt, limit);
1042 }
1043 
1044 static VALUE
1045 random_ulong_limited_big(VALUE obj, rb_random_t *rnd, VALUE vmax)
1046 {
1047  if (!rnd) {
1048  VALUE v, vtmp;
1049  size_t i, nlz, len = rb_absint_numwords(vmax, 32, &nlz);
1050  uint32_t *tmp = ALLOCV_N(uint32_t, vtmp, len * 2);
1051  uint32_t mask = (uint32_t)~0 >> nlz;
1052  uint32_t *lim_array = tmp;
1053  uint32_t *rnd_array = tmp + len;
1055  rb_integer_pack(vmax, lim_array, len, sizeof(uint32_t), 0, flag);
1056 
1057  retry:
1058  obj_random_bytes(obj, rnd_array, len * sizeof(uint32_t));
1059  rnd_array[0] &= mask;
1060  for (i = 0; i < len; ++i) {
1061  if (lim_array[i] < rnd_array[i])
1062  goto retry;
1063  if (rnd_array[i] < lim_array[i])
1064  break;
1065  }
1066  v = rb_integer_unpack(rnd_array, len, sizeof(uint32_t), 0, flag);
1067  ALLOCV_END(vtmp);
1068  return v;
1069  }
1070  return limited_big_rand(&rnd->mt, vmax);
1071 }
1072 
1073 static VALUE genrand_bytes(rb_random_t *rnd, long n);
1074 
1075 /*
1076  * call-seq: prng.bytes(size) -> a_string
1077  *
1078  * Returns a random binary string containing +size+ bytes.
1079  *
1080  * random_string = Random.new.bytes(10) # => "\xD7:R\xAB?\x83\xCE\xFAkO"
1081  * random_string.size # => 10
1082  */
1083 static VALUE
1084 random_bytes(VALUE obj, VALUE len)
1085 {
1086  return genrand_bytes(get_rnd(obj), NUM2LONG(rb_to_int(len)));
1087 }
1088 
1089 static VALUE
1090 genrand_bytes(rb_random_t *rnd, long n)
1091 {
1092  VALUE bytes;
1093  char *ptr;
1094  unsigned int r, i;
1095 
1096  bytes = rb_str_new(0, n);
1097  ptr = RSTRING_PTR(bytes);
1098  for (; n >= SIZEOF_INT32; n -= SIZEOF_INT32) {
1099  r = genrand_int32(&rnd->mt);
1100  i = SIZEOF_INT32;
1101  do {
1102  *ptr++ = (char)r;
1103  r >>= CHAR_BIT;
1104  } while (--i);
1105  }
1106  if (n > 0) {
1107  r = genrand_int32(&rnd->mt);
1108  do {
1109  *ptr++ = (char)r;
1110  r >>= CHAR_BIT;
1111  } while (--n);
1112  }
1113  return bytes;
1114 }
1115 
1116 VALUE
1118 {
1119  rb_random_t *rnd = try_get_rnd(obj);
1120  if (!rnd) {
1121  return obj_random_bytes(obj, NULL, n);
1122  }
1123  return genrand_bytes(rnd, n);
1124 }
1125 
1126 static VALUE
1127 range_values(VALUE vmax, VALUE *begp, VALUE *endp, int *exclp)
1128 {
1129  VALUE end, r;
1130 
1131  if (!rb_range_values(vmax, begp, &end, exclp)) return Qfalse;
1132  if (endp) *endp = end;
1133  if (!rb_respond_to(end, id_minus)) return Qfalse;
1134  r = rb_funcallv(end, id_minus, 1, begp);
1135  if (NIL_P(r)) return Qfalse;
1136  return r;
1137 }
1138 
1139 static VALUE
1140 rand_int(VALUE obj, rb_random_t *rnd, VALUE vmax, int restrictive)
1141 {
1142  /* mt must be initialized */
1143  unsigned long r;
1144 
1145  if (FIXNUM_P(vmax)) {
1146  long max = FIX2LONG(vmax);
1147  if (!max) return Qnil;
1148  if (max < 0) {
1149  if (restrictive) return Qnil;
1150  max = -max;
1151  }
1152  r = random_ulong_limited(obj, rnd, (unsigned long)max - 1);
1153  return ULONG2NUM(r);
1154  }
1155  else {
1156  VALUE ret;
1157  if (rb_bigzero_p(vmax)) return Qnil;
1158  if (!BIGNUM_SIGN(vmax)) {
1159  if (restrictive) return Qnil;
1160  vmax = rb_big_uminus(vmax);
1161  }
1162  vmax = rb_big_minus(vmax, INT2FIX(1));
1163  if (FIXNUM_P(vmax)) {
1164  long max = FIX2LONG(vmax);
1165  if (max == -1) return Qnil;
1166  r = random_ulong_limited(obj, rnd, max);
1167  return LONG2NUM(r);
1168  }
1169  ret = random_ulong_limited_big(obj, rnd, vmax);
1170  RB_GC_GUARD(vmax);
1171  return ret;
1172  }
1173 }
1174 
1175 NORETURN(static void domain_error(void));
1176 static void
1177 domain_error(void)
1178 {
1179  VALUE error = INT2FIX(EDOM);
1181 }
1182 
1183 NORETURN(static void invalid_argument(VALUE));
1184 static void
1185 invalid_argument(VALUE arg0)
1186 {
1187  rb_raise(rb_eArgError, "invalid argument - %"PRIsVALUE, arg0);
1188 }
1189 
1190 static VALUE
1191 check_random_number(VALUE v, const VALUE *argv)
1192 {
1193  switch (v) {
1194  case Qfalse:
1195  (void)NUM2LONG(argv[0]);
1196  break;
1197  case Qnil:
1198  invalid_argument(argv[0]);
1199  }
1200  return v;
1201 }
1202 
1203 static inline double
1204 float_value(VALUE v)
1205 {
1206  double x = RFLOAT_VALUE(v);
1207  if (isinf(x) || isnan(x)) {
1208  domain_error();
1209  }
1210  return x;
1211 }
1212 
1213 static inline VALUE
1214 rand_range(VALUE obj, rb_random_t* rnd, VALUE range)
1215 {
1216  VALUE beg = Qundef, end = Qundef, vmax, v;
1217  int excl = 0;
1218 
1219  if ((v = vmax = range_values(range, &beg, &end, &excl)) == Qfalse)
1220  return Qfalse;
1221  if (!RB_TYPE_P(vmax, T_FLOAT) && (v = rb_check_to_int(vmax), !NIL_P(v))) {
1222  long max;
1223  vmax = v;
1224  v = Qnil;
1225  if (FIXNUM_P(vmax)) {
1226  fixnum:
1227  if ((max = FIX2LONG(vmax) - excl) >= 0) {
1228  unsigned long r = random_ulong_limited(obj, rnd, (unsigned long)max);
1229  v = ULONG2NUM(r);
1230  }
1231  }
1232  else if (BUILTIN_TYPE(vmax) == T_BIGNUM && BIGNUM_SIGN(vmax) && !rb_bigzero_p(vmax)) {
1233  vmax = excl ? rb_big_minus(vmax, INT2FIX(1)) : rb_big_norm(vmax);
1234  if (FIXNUM_P(vmax)) {
1235  excl = 0;
1236  goto fixnum;
1237  }
1238  v = random_ulong_limited_big(obj, rnd, vmax);
1239  }
1240  }
1241  else if (v = rb_check_to_float(vmax), !NIL_P(v)) {
1242  int scale = 1;
1243  double max = RFLOAT_VALUE(v), mid = 0.5, r;
1244  if (isinf(max)) {
1245  double min = float_value(rb_to_float(beg)) / 2.0;
1246  max = float_value(rb_to_float(end)) / 2.0;
1247  scale = 2;
1248  mid = max + min;
1249  max -= min;
1250  }
1251  else if (isnan(max)) {
1252  domain_error();
1253  }
1254  v = Qnil;
1255  if (max > 0.0) {
1256  r = random_real(obj, rnd, excl);
1257  if (scale > 1) {
1258  return rb_float_new(+(+(+(r - 0.5) * max) * scale) + mid);
1259  }
1260  v = rb_float_new(r * max);
1261  }
1262  else if (max == 0.0 && !excl) {
1263  v = rb_float_new(0.0);
1264  }
1265  }
1266 
1267  if (FIXNUM_P(beg) && FIXNUM_P(v)) {
1268  long x = FIX2LONG(beg) + FIX2LONG(v);
1269  return LONG2NUM(x);
1270  }
1271  switch (TYPE(v)) {
1272  case T_NIL:
1273  break;
1274  case T_BIGNUM:
1275  return rb_big_plus(v, beg);
1276  case T_FLOAT: {
1277  VALUE f = rb_check_to_float(beg);
1278  if (!NIL_P(f)) {
1279  return DBL2NUM(RFLOAT_VALUE(v) + RFLOAT_VALUE(f));
1280  }
1281  }
1282  default:
1283  return rb_funcallv(beg, id_plus, 1, &v);
1284  }
1285 
1286  return v;
1287 }
1288 
1289 static VALUE rand_random(int argc, VALUE *argv, VALUE obj, rb_random_t *rnd);
1290 
1291 /*
1292  * call-seq:
1293  * prng.rand -> float
1294  * prng.rand(max) -> number
1295  *
1296  * When +max+ is an Integer, +rand+ returns a random integer greater than
1297  * or equal to zero and less than +max+. Unlike Kernel.rand, when +max+
1298  * is a negative integer or zero, +rand+ raises an ArgumentError.
1299  *
1300  * prng = Random.new
1301  * prng.rand(100) # => 42
1302  *
1303  * When +max+ is a Float, +rand+ returns a random floating point number
1304  * between 0.0 and +max+, including 0.0 and excluding +max+.
1305  *
1306  * prng.rand(1.5) # => 1.4600282860034115
1307  *
1308  * When +max+ is a Range, +rand+ returns a random number where
1309  * range.member?(number) == true.
1310  *
1311  * prng.rand(5..9) # => one of [5, 6, 7, 8, 9]
1312  * prng.rand(5...9) # => one of [5, 6, 7, 8]
1313  * prng.rand(5.0..9.0) # => between 5.0 and 9.0, including 9.0
1314  * prng.rand(5.0...9.0) # => between 5.0 and 9.0, excluding 9.0
1315  *
1316  * Both the beginning and ending values of the range must respond to subtract
1317  * (<tt>-</tt>) and add (<tt>+</tt>)methods, or rand will raise an
1318  * ArgumentError.
1319  */
1320 static VALUE
1321 random_rand(int argc, VALUE *argv, VALUE obj)
1322 {
1323  VALUE v = rand_random(argc, argv, obj, get_rnd(obj));
1324  check_random_number(v, argv);
1325  return v;
1326 }
1327 
1328 static VALUE
1329 rand_random(int argc, VALUE *argv, VALUE obj, rb_random_t *rnd)
1330 {
1331  VALUE vmax, v;
1332 
1333  if (rb_check_arity(argc, 0, 1) == 0) {
1334  return rb_float_new(random_real(obj, rnd, TRUE));
1335  }
1336  vmax = argv[0];
1337  if (NIL_P(vmax)) return Qnil;
1338  if (!RB_TYPE_P(vmax, T_FLOAT)) {
1339  v = rb_check_to_int(vmax);
1340  if (!NIL_P(v)) return rand_int(obj, rnd, v, 1);
1341  }
1342  v = rb_check_to_float(vmax);
1343  if (!NIL_P(v)) {
1344  const double max = float_value(v);
1345  if (max < 0.0) {
1346  return Qnil;
1347  }
1348  else {
1349  double r = random_real(obj, rnd, TRUE);
1350  if (max > 0.0) r *= max;
1351  return rb_float_new(r);
1352  }
1353  }
1354  return rand_range(obj, rnd, vmax);
1355 }
1356 
1357 static VALUE
1358 rand_random_number(int argc, VALUE *argv, VALUE obj)
1359 {
1360  rb_random_t *rnd = try_get_rnd(obj);
1361  VALUE v = rand_random(argc, argv, obj, rnd);
1362  if (NIL_P(v)) v = rand_random(0, 0, obj, rnd);
1363  else if (!v) invalid_argument(argv[0]);
1364  return v;
1365 }
1366 
1367 /*
1368  * call-seq:
1369  * prng1 == prng2 -> true or false
1370  *
1371  * Returns true if the two generators have the same internal state, otherwise
1372  * false. Equivalent generators will return the same sequence of
1373  * pseudo-random numbers. Two generators will generally have the same state
1374  * only if they were initialized with the same seed
1375  *
1376  * Random.new == Random.new # => false
1377  * Random.new(1234) == Random.new(1234) # => true
1378  *
1379  * and have the same invocation history.
1380  *
1381  * prng1 = Random.new(1234)
1382  * prng2 = Random.new(1234)
1383  * prng1 == prng2 # => true
1384  *
1385  * prng1.rand # => 0.1915194503788923
1386  * prng1 == prng2 # => false
1387  *
1388  * prng2.rand # => 0.1915194503788923
1389  * prng1 == prng2 # => true
1390  */
1391 static VALUE
1392 random_equal(VALUE self, VALUE other)
1393 {
1394  rb_random_t *r1, *r2;
1395  if (rb_obj_class(self) != rb_obj_class(other)) return Qfalse;
1396  r1 = get_rnd(self);
1397  r2 = get_rnd(other);
1398  if (memcmp(r1->mt.state, r2->mt.state, sizeof(r1->mt.state))) return Qfalse;
1399  if ((r1->mt.next - r1->mt.state) != (r2->mt.next - r2->mt.state)) return Qfalse;
1400  if (r1->mt.left != r2->mt.left) return Qfalse;
1401  return rb_equal(r1->seed, r2->seed);
1402 }
1403 
1404 /*
1405  * call-seq:
1406  * rand(max=0) -> number
1407  *
1408  * If called without an argument, or if <tt>max.to_i.abs == 0</tt>, rand
1409  * returns a pseudo-random floating point number between 0.0 and 1.0,
1410  * including 0.0 and excluding 1.0.
1411  *
1412  * rand #=> 0.2725926052826416
1413  *
1414  * When +max.abs+ is greater than or equal to 1, +rand+ returns a pseudo-random
1415  * integer greater than or equal to 0 and less than +max.to_i.abs+.
1416  *
1417  * rand(100) #=> 12
1418  *
1419  * When +max+ is a Range, +rand+ returns a random number where
1420  * range.member?(number) == true.
1421  *
1422  * Negative or floating point values for +max+ are allowed, but may give
1423  * surprising results.
1424  *
1425  * rand(-100) # => 87
1426  * rand(-0.5) # => 0.8130921818028143
1427  * rand(1.9) # equivalent to rand(1), which is always 0
1428  *
1429  * Kernel.srand may be used to ensure that sequences of random numbers are
1430  * reproducible between different runs of a program.
1431  *
1432  * See also Random.rand.
1433  */
1434 
1435 static VALUE
1436 rb_f_rand(int argc, VALUE *argv, VALUE obj)
1437 {
1438  VALUE vmax;
1439  rb_random_t *rnd = rand_start(&default_rand);
1440 
1441  if (rb_check_arity(argc, 0, 1) && !NIL_P(vmax = argv[0])) {
1442  VALUE v = rand_range(Qnil, rnd, vmax);
1443  if (v != Qfalse) return v;
1444  vmax = rb_to_int(vmax);
1445  if (vmax != INT2FIX(0)) {
1446  v = rand_int(Qnil, rnd, vmax, 0);
1447  if (!NIL_P(v)) return v;
1448  }
1449  }
1450  return DBL2NUM(genrand_real(&rnd->mt));
1451 }
1452 
1453 /*
1454  * call-seq:
1455  * Random.rand -> float
1456  * Random.rand(max) -> number
1457  *
1458  * Alias of Random::DEFAULT.rand.
1459  */
1460 
1461 static VALUE
1462 random_s_rand(int argc, VALUE *argv, VALUE obj)
1463 {
1464  VALUE v = rand_random(argc, argv, Qnil, rand_start(&default_rand));
1465  check_random_number(v, argv);
1466  return v;
1467 }
1468 
1469 #define SIP_HASH_STREAMING 0
1470 #define sip_hash13 ruby_sip_hash13
1471 #if !defined _WIN32 && !defined BYTE_ORDER
1472 # ifdef WORDS_BIGENDIAN
1473 # define BYTE_ORDER BIG_ENDIAN
1474 # else
1475 # define BYTE_ORDER LITTLE_ENDIAN
1476 # endif
1477 # ifndef LITTLE_ENDIAN
1478 # define LITTLE_ENDIAN 1234
1479 # endif
1480 # ifndef BIG_ENDIAN
1481 # define BIG_ENDIAN 4321
1482 # endif
1483 #endif
1484 #include "siphash.c"
1485 
1486 typedef struct {
1488  uint8_t sip[16];
1489 } seed_keys_t;
1490 
1491 static union {
1494 } seed;
1495 
1496 static void
1497 init_seed(struct MT *mt)
1498 {
1499  int i;
1500 
1501  for (i = 0; i < numberof(seed.u32); ++i)
1502  seed.u32[i] = genrand_int32(mt);
1503 }
1504 
1505 st_index_t
1507 {
1508  return st_hash_start(seed.key.hash + h);
1509 }
1510 
1511 st_index_t
1512 rb_memhash(const void *ptr, long len)
1513 {
1514  sip_uint64_t h = sip_hash13(seed.key.sip, ptr, len);
1515 #ifdef HAVE_UINT64_T
1516  return (st_index_t)h;
1517 #else
1518  return (st_index_t)(h.u32[0] ^ h.u32[1]);
1519 #endif
1520 }
1521 
1522 /* Initialize Ruby internal seeds. This function is called at very early stage
1523  * of Ruby startup. Thus, you can't use Ruby's object. */
1524 void
1526 {
1527  /*
1528  Don't reuse this MT for Random::DEFAULT. Random::DEFAULT::seed shouldn't
1529  provide a hint that an attacker guess siphash's seed.
1530  */
1531  struct MT mt;
1532  uint32_t initial_seed[DEFAULT_SEED_CNT];
1533 
1534  fill_random_seed(initial_seed, DEFAULT_SEED_CNT);
1535  init_by_array(&mt, initial_seed, DEFAULT_SEED_CNT);
1536 
1537  init_seed(&mt);
1538 
1539  explicit_bzero(initial_seed, DEFAULT_SEED_LEN);
1540 }
1541 
1542 static VALUE
1543 init_randomseed(struct MT *mt)
1544 {
1545  uint32_t initial[DEFAULT_SEED_CNT+1];
1546  VALUE seed;
1547 
1548  fill_random_seed(initial, DEFAULT_SEED_CNT);
1549  init_by_array(mt, initial, DEFAULT_SEED_CNT);
1550  seed = make_seed_value(initial, DEFAULT_SEED_CNT);
1551  explicit_bzero(initial, DEFAULT_SEED_LEN);
1552  return seed;
1553 }
1554 
1555 /* construct Random::DEFAULT bits */
1556 static VALUE
1557 Init_Random_default(void)
1558 {
1559  rb_random_t *r = &default_rand;
1560  struct MT *mt = &r->mt;
1561  VALUE v = TypedData_Wrap_Struct(rb_cRandom, &random_data_type, r);
1562 
1564  r->seed = init_randomseed(mt);
1565 
1566  return v;
1567 }
1568 
1569 void
1571 {
1572  rb_random_t *r = &default_rand;
1573  uninit_genrand(&r->mt);
1574  r->seed = INT2FIX(0);
1575 }
1576 
1577 /*
1578  * Document-class: Random
1579  *
1580  * Random provides an interface to Ruby's pseudo-random number generator, or
1581  * PRNG. The PRNG produces a deterministic sequence of bits which approximate
1582  * true randomness. The sequence may be represented by integers, floats, or
1583  * binary strings.
1584  *
1585  * The generator may be initialized with either a system-generated or
1586  * user-supplied seed value by using Random.srand.
1587  *
1588  * The class method Random.rand provides the base functionality of Kernel.rand
1589  * along with better handling of floating point values. These are both
1590  * interfaces to Random::DEFAULT, the Ruby system PRNG.
1591  *
1592  * Random.new will create a new PRNG with a state independent of
1593  * Random::DEFAULT, allowing multiple generators with different seed values or
1594  * sequence positions to exist simultaneously. Random objects can be
1595  * marshaled, allowing sequences to be saved and resumed.
1596  *
1597  * PRNGs are currently implemented as a modified Mersenne Twister with a period
1598  * of 2**19937-1.
1599  */
1600 
1601 void
1603 {
1604  rb_define_global_function("srand", rb_f_srand, -1);
1605  rb_define_global_function("rand", rb_f_rand, -1);
1606 
1607  rb_cRandom = rb_define_class("Random", rb_cObject);
1608  rb_define_alloc_func(rb_cRandom, random_alloc);
1609  rb_define_method(rb_cRandom, "initialize", random_init, -1);
1610  rb_define_method(rb_cRandom, "rand", random_rand, -1);
1611  rb_define_method(rb_cRandom, "bytes", random_bytes, 1);
1612  rb_define_method(rb_cRandom, "seed", random_get_seed, 0);
1613  rb_define_method(rb_cRandom, "initialize_copy", random_copy, 1);
1614  rb_define_private_method(rb_cRandom, "marshal_dump", random_dump, 0);
1615  rb_define_private_method(rb_cRandom, "marshal_load", random_load, 1);
1616  rb_define_private_method(rb_cRandom, "state", random_state, 0);
1617  rb_define_private_method(rb_cRandom, "left", random_left, 0);
1618  rb_define_method(rb_cRandom, "==", random_equal, 1);
1619 
1620  {
1621  /* Direct access to Ruby's Pseudorandom number generator (PRNG). */
1622  VALUE rand_default = Init_Random_default();
1623  rb_define_const(rb_cRandom, "DEFAULT", rand_default);
1624  }
1625 
1626  rb_define_singleton_method(rb_cRandom, "srand", rb_f_srand, -1);
1627  rb_define_singleton_method(rb_cRandom, "rand", random_s_rand, -1);
1628  rb_define_singleton_method(rb_cRandom, "new_seed", random_seed, 0);
1629  rb_define_singleton_method(rb_cRandom, "urandom", random_raw_seed, 1);
1630  rb_define_private_method(CLASS_OF(rb_cRandom), "state", random_s_state, 0);
1631  rb_define_private_method(CLASS_OF(rb_cRandom), "left", random_s_left, 0);
1632 
1633  {
1634  VALUE m = rb_define_module_under(rb_cRandom, "Formatter");
1635  rb_include_module(rb_cRandom, m);
1636  rb_define_method(m, "random_number", rand_random_number, -1);
1637  rb_define_method(m, "rand", rand_random_number, -1);
1638  }
1639 }
1640 
1641 #undef rb_intern
1642 void
1644 {
1645  id_rand = rb_intern("rand");
1646  id_bytes = rb_intern("bytes");
1647 
1648  InitVM(Random);
1649 }
void Init_Random(void)
Definition: random.c:1643
int rb_bigzero_p(VALUE x)
Definition: bignum.c:2901
VALUE rb_check_to_float(VALUE)
Tries to convert an object into Float.
Definition: object.c:3465
seed_keys_t key
Definition: random.c:1492
int rb_integer_pack(VALUE val, void *words, size_t numwords, size_t wordsize, size_t nails, int flags)
Definition: bignum.c:3529
#define RARRAY_LEN(a)
Definition: ruby.h:1019
int gettimeofday(struct timeval *, struct timezone *)
Definition: win32.c:4596
#define FALSE
Definition: nkf.h:174
#define RUBY_TYPED_FREE_IMMEDIATELY
Definition: ruby.h:1138
void rb_update_max_fd(int fd)
Definition: io.c:191
#define INTEGER_PACK_LSWORD_FIRST
Definition: intern.h:139
VALUE rb_check_to_int(VALUE)
Tries to convert val into Integer.
Definition: object.c:3099
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
#define type_roomof(x, y)
Definition: internal.h:966
VALUE rb_random_bytes(VALUE obj, long n)
Definition: random.c:1117
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:257
void rb_raise(VALUE exc, const char *fmt,...)
Definition: error.c:2284
#define InitVM(ext)
Definition: ruby.h:2164
#define ATOMIC_PTR_CAS(var, oldval, val)
Definition: ruby_atomic.h:191
uint32_t * next
Definition: random.c:108
#define TypedData_Wrap_Struct(klass, data_type, sval)
Definition: ruby.h:1162
#define OBJ_INIT_COPY(obj, orig)
Definition: intern.h:283
#define TypedData_Get_Struct(obj, type, data_type, sval)
Definition: ruby.h:1183
VALUE rb_big_plus(VALUE x, VALUE y)
Definition: bignum.c:5772
uint32_t u32[type_roomof(seed_keys_t, uint32_t)]
Definition: random.c:1493
void rb_define_private_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Definition: class.c:1527
#define rb_check_arity
Definition: intern.h:298
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
Definition: range.c:979
#define ULONG2NUM(x)
Definition: ruby.h:1574
VALUE rb_ary_push(VALUE ary, VALUE item)
Definition: array.c:924
#define DEFAULT_SEED_CNT
Definition: random.c:240
#define INTEGER_PACK_NATIVE_BYTE_ORDER
Definition: intern.h:142
st_index_t st_hash_start(st_index_t h)
Definition: st.c:1894
#define Check_Type(v, t)
Definition: ruby.h:562
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:1106
void rb_include_module(VALUE klass, VALUE module)
Definition: class.c:864
void rb_gc_mark(VALUE ptr)
Definition: gc.c:4464
#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
#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
#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
VALUE rb_eArgError
Definition: error.c:802
int rb_typeddata_is_kind_of(VALUE obj, const rb_data_type_t *data_type)
Definition: error.c:759
#define Data_Wrap_Struct(klass, mark, free, sval)
Definition: ruby.h:1142
VALUE rb_to_float(VALUE)
Converts a Numeric object into Float.
Definition: object.c:3448
VALUE rb_obj_class(VALUE)
call-seq: obj.class -> class
Definition: object.c:277
#define RB_TYPE_P(obj, type)
Definition: ruby.h:527
#define ATOMIC_SET(var, val)
Definition: ruby_atomic.h:127
#define id_minus
Definition: random.c:302
#define id_plus
Definition: random.c:303
VALUE rb_eRangeError
Definition: error.c:805
unsigned long long uint64_t
Definition: sha2.h:102
VALUE rb_equal(VALUE, VALUE)
call-seq: obj === other -> true or false
Definition: object.c:126
#define ALLOC_N(type, n)
Definition: ruby.h:1587
#define val
long tv_usec
Definition: missing.h:55
RUBY_EXTERN VALUE rb_cObject
Definition: ruby.h:1893
#define rb_float_new(d)
Definition: internal.h:1449
#define T_NIL
Definition: ruby.h:490
int rb_num_negative_p(VALUE)
Definition: numeric.c:342
st_index_t hash
Definition: random.c:1487
void InitVM_Random(void)
Definition: random.c:1602
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:931
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:2691
#define SIZEOF_INT32
Definition: random.c:277
rb_atomic_t cnt[RUBY_NSIG]
Definition: signal.c:525
#define T_FLOAT
Definition: ruby.h:495
#define TYPE(x)
Definition: ruby.h:521
int argc
Definition: ruby.c:187
void Init_RandomSeedCore(void)
Definition: random.c:1525
#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:6227
#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
Definition: util.c:841
#define numberof(array)
Definition: etc.c:618
VALUE rb_integer_unpack(const void *words, size_t numwords, size_t wordsize, size_t nails, int flags)
Definition: bignum.c:3615
st_index_t rb_memhash(const void *ptr, long len)
Definition: random.c:1512
int int_must_be_32bit_at_least[sizeof(int) *CHAR_BIT< 32 ? -1 :1]
Definition: random.c:92
VALUE seed
Definition: random.c:236
#define sip_hash13
Definition: random.c:1470
VALUE rb_big_minus(VALUE x, VALUE y)
Definition: bignum.c:5801
#define RSTRING_LEN(str)
Definition: ruby.h:971
VALUE rb_funcallv_public(VALUE, ID, int, const VALUE *)
Calls a method.
Definition: vm_eval.c:820
#define RARRAY_CONST_PTR(a)
Definition: ruby.h:1021
int errno
#define TRUE
Definition: nkf.h:175
void rb_reset_random_seed(void)
Definition: random.c:1570
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
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition: eval.c:615
#define domain_error(msg)
Definition: math.c:32
#define BUILTIN_TYPE(x)
Definition: ruby.h:518
unsigned long VALUE
Definition: ruby.h:85
VALUE rb_eSystemCallError
Definition: error.c:819
#define INTEGER_PACK_MSWORD_FIRST
Definition: intern.h:138
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:903
#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:1994
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
#define RSTRING_PTR(str)
Definition: ruby.h:975
VALUE rb_big_uminus(VALUE x)
Definition: bignum.c:5502
#define BIGNUM_SIGN(b)
Definition: internal.h:599
#define RFLOAT_VALUE(v)
Definition: ruby.h:933
int size
Definition: encoding.c:57
#define f
#define INT2FIX(i)
Definition: ruby.h:232
#define NUM2ULONG(x)
Definition: ruby.h:658
VALUE rb_eRuntimeError
Definition: error.c:800
double rb_genrand_real(void)
Definition: random.c:271
#define TWIST(u, v)
Definition: random.c:101
VALUE rb_big_norm(VALUE x)
Definition: bignum.c:3134
#define O_NONBLOCK
Definition: win32.h:590
void rb_check_copyable(VALUE obj, VALUE orig)
Definition: error.c:2627
#define T_STRING
Definition: ruby.h:496
VALUE rb_class_new_instance(int, const VALUE *, VALUE)
Allocates and initializes an instance of klass.
Definition: object.c:2170
#define fill_random_bytes_urandom(seed, size)
Definition: random.c:461
#define N
Definition: random.c:95
NORETURN(static void domain_error(void))
#define TypedData_Make_Struct(klass, type, data_type, sval)
Definition: ruby.h:1175
size_t rb_absint_numwords(VALUE val, size_t word_numbits, size_t *nlz_bits_ret)
Definition: bignum.c:3364
int rb_atomic_t
Definition: ruby_atomic.h:120
#define rb_check_frozen(obj)
Definition: intern.h:271
#define r2
void void xfree(void *)
#define rb_intern(str)
double rb_random_real(VALUE obj)
Definition: random.c:966
#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
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
#define NUM2LONG(x)
Definition: ruby.h:648
VALUE rb_cRandom
Definition: random.c:301
VALUE rb_to_int(VALUE)
Converts val into Integer.
Definition: object.c:3084
st_index_t rb_hash_start(st_index_t h)
Definition: random.c:1506
char ** argv
Definition: ruby.c:188
#define DBL2NUM(dbl)
Definition: ruby.h:934
unsigned long rb_random_ulong_limited(VALUE obj, unsigned long limit)
Definition: random.c:1026
VALUE rb_str_new(const char *, long)
Definition: string.c:737
#define LIKELY(x)
Definition: internal.h:42