-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathrandom.c
1892 lines (1701 loc) · 49.2 KB
/
random.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**********************************************************************
random.c -
$Author$
created at: Fri Dec 24 16:39:21 JST 1993
Copyright (C) 1993-2007 Yukihiro Matsumoto
**********************************************************************/
#include "ruby/internal/config.h"
#include <errno.h>
#include <limits.h>
#include <math.h>
#include <float.h>
#include <time.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#ifdef HAVE_FCNTL_H
# include <fcntl.h>
#endif
#if defined(HAVE_SYS_TIME_H)
# include <sys/time.h>
#endif
#ifdef HAVE_SYSCALL_H
# include <syscall.h>
#elif defined HAVE_SYS_SYSCALL_H
# include <sys/syscall.h>
#endif
#ifdef _WIN32
# include <winsock2.h>
# include <windows.h>
# include <wincrypt.h>
# include <bcrypt.h>
#endif
#if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
/* to define OpenBSD and FreeBSD for version check */
# include <sys/param.h>
#endif
#if defined HAVE_GETRANDOM || defined HAVE_GETENTROPY
# if defined(HAVE_SYS_RANDOM_H)
# include <sys/random.h>
# endif
#elif defined __linux__ && defined __NR_getrandom
# include <linux/random.h>
#endif
#if defined __APPLE__
# include <AvailabilityMacros.h>
#endif
#include "internal.h"
#include "internal/array.h"
#include "internal/compilers.h"
#include "internal/numeric.h"
#include "internal/random.h"
#include "internal/sanitizers.h"
#include "internal/variable.h"
#include "ruby_atomic.h"
#include "ruby/random.h"
#include "ruby/ractor.h"
STATIC_ASSERT(int_must_be_32bit_at_least, sizeof(int) * CHAR_BIT >= 32);
#include "missing/mt19937.c"
/* generates a random number on [0,1) with 53-bit resolution*/
static double int_pair_to_real_exclusive(uint32_t a, uint32_t b);
static double
genrand_real(struct MT *mt)
{
/* mt must be initialized */
unsigned int a = genrand_int32(mt), b = genrand_int32(mt);
return int_pair_to_real_exclusive(a, b);
}
static const double dbl_reduce_scale = /* 2**(-DBL_MANT_DIG) */
(1.0
/ (double)(DBL_MANT_DIG > 2*31 ? (1ul<<31) : 1.0)
/ (double)(DBL_MANT_DIG > 1*31 ? (1ul<<31) : 1.0)
/ (double)(1ul<<(DBL_MANT_DIG%31)));
static double
int_pair_to_real_exclusive(uint32_t a, uint32_t b)
{
static const int a_shift = DBL_MANT_DIG < 64 ?
(64-DBL_MANT_DIG)/2 : 0;
static const int b_shift = DBL_MANT_DIG < 64 ?
(65-DBL_MANT_DIG)/2 : 0;
a >>= a_shift;
b >>= b_shift;
return (a*(double)(1ul<<(32-b_shift))+b)*dbl_reduce_scale;
}
/* generates a random number on [0,1] with 53-bit resolution*/
static double int_pair_to_real_inclusive(uint32_t a, uint32_t b);
#if 0
static double
genrand_real2(struct MT *mt)
{
/* mt must be initialized */
uint32_t a = genrand_int32(mt), b = genrand_int32(mt);
return int_pair_to_real_inclusive(a, b);
}
#endif
/* These real versions are due to Isaku Wada, 2002/01/09 added */
#undef N
#undef M
typedef struct {
rb_random_t base;
struct MT mt;
} rb_random_mt_t;
#define DEFAULT_SEED_CNT 4
static VALUE rand_init(const rb_random_interface_t *, rb_random_t *, VALUE);
static VALUE random_seed(VALUE);
static void fill_random_seed(uint32_t *seed, size_t cnt, bool try_bytes);
static VALUE make_seed_value(uint32_t *ptr, size_t len);
#define fill_random_bytes ruby_fill_random_bytes
RB_RANDOM_INTERFACE_DECLARE(rand_mt);
static const rb_random_interface_t random_mt_if = {
DEFAULT_SEED_CNT * 32,
RB_RANDOM_INTERFACE_DEFINE(rand_mt)
};
static rb_random_mt_t *
rand_mt_start(rb_random_mt_t *r)
{
if (!genrand_initialized(&r->mt)) {
r->base.seed = rand_init(&random_mt_if, &r->base, random_seed(Qundef));
}
return r;
}
static rb_random_t *
rand_start(rb_random_mt_t *r)
{
return &rand_mt_start(r)->base;
}
static rb_ractor_local_key_t default_rand_key;
void
rb_free_default_rand_key(void)
{
xfree(default_rand_key);
}
static void
default_rand_mark(void *ptr)
{
rb_random_mt_t *rnd = (rb_random_mt_t *)ptr;
rb_gc_mark(rnd->base.seed);
}
static const struct rb_ractor_local_storage_type default_rand_key_storage_type = {
default_rand_mark,
ruby_xfree,
};
static rb_random_mt_t *
default_rand(void)
{
rb_random_mt_t *rnd;
if ((rnd = rb_ractor_local_storage_ptr(default_rand_key)) == NULL) {
rnd = ZALLOC(rb_random_mt_t);
rb_ractor_local_storage_ptr_set(default_rand_key, rnd);
}
return rnd;
}
static rb_random_mt_t *
default_mt(void)
{
return rand_mt_start(default_rand());
}
unsigned int
rb_genrand_int32(void)
{
struct MT *mt = &default_mt()->mt;
return genrand_int32(mt);
}
double
rb_genrand_real(void)
{
struct MT *mt = &default_mt()->mt;
return genrand_real(mt);
}
#define SIZEOF_INT32 (31/CHAR_BIT + 1)
static double
int_pair_to_real_inclusive(uint32_t a, uint32_t b)
{
double r;
enum {dig = DBL_MANT_DIG};
enum {dig_u = dig-32, dig_r64 = 64-dig, bmask = ~(~0u<<(dig_r64))};
#if defined HAVE_UINT128_T
const uint128_t m = ((uint128_t)1 << dig) | 1;
uint128_t x = ((uint128_t)a << 32) | b;
r = (double)(uint64_t)((x * m) >> 64);
#elif defined HAVE_UINT64_T && !MSC_VERSION_BEFORE(1300)
uint64_t x = ((uint64_t)a << dig_u) +
(((uint64_t)b + (a >> dig_u)) >> dig_r64);
r = (double)x;
#else
/* shift then add to get rid of overflow */
b = (b >> dig_r64) + (((a >> dig_u) + (b & bmask)) >> dig_r64);
r = (double)a * (1 << dig_u) + b;
#endif
return r * dbl_reduce_scale;
}
VALUE rb_cRandom;
#define id_minus '-'
#define id_plus '+'
static ID id_rand, id_bytes;
NORETURN(static void domain_error(void));
/* :nodoc: */
#define random_mark rb_random_mark
void
random_mark(void *ptr)
{
rb_gc_mark(((rb_random_t *)ptr)->seed);
}
#define random_free RUBY_TYPED_DEFAULT_FREE
static size_t
random_memsize(const void *ptr)
{
return sizeof(rb_random_t);
}
const rb_data_type_t rb_random_data_type = {
"random",
{
random_mark,
random_free,
random_memsize,
},
0, 0, RUBY_TYPED_FREE_IMMEDIATELY
};
#define random_mt_mark rb_random_mark
#define random_mt_free RUBY_TYPED_DEFAULT_FREE
static size_t
random_mt_memsize(const void *ptr)
{
return sizeof(rb_random_mt_t);
}
static const rb_data_type_t random_mt_type = {
"random/MT",
{
random_mt_mark,
random_mt_free,
random_mt_memsize,
},
&rb_random_data_type,
(void *)&random_mt_if,
RUBY_TYPED_FREE_IMMEDIATELY
};
static rb_random_t *
get_rnd(VALUE obj)
{
rb_random_t *ptr;
TypedData_Get_Struct(obj, rb_random_t, &rb_random_data_type, ptr);
if (RTYPEDDATA_TYPE(obj) == &random_mt_type)
return rand_start((rb_random_mt_t *)ptr);
return ptr;
}
static rb_random_mt_t *
get_rnd_mt(VALUE obj)
{
rb_random_mt_t *ptr;
TypedData_Get_Struct(obj, rb_random_mt_t, &random_mt_type, ptr);
return ptr;
}
static rb_random_t *
try_get_rnd(VALUE obj)
{
if (obj == rb_cRandom) {
return rand_start(default_rand());
}
if (!rb_typeddata_is_kind_of(obj, &rb_random_data_type)) return NULL;
if (RTYPEDDATA_TYPE(obj) == &random_mt_type)
return rand_start(DATA_PTR(obj));
rb_random_t *rnd = DATA_PTR(obj);
if (!rnd) {
rb_raise(rb_eArgError, "uninitialized random: %s",
RTYPEDDATA_TYPE(obj)->wrap_struct_name);
}
return rnd;
}
static const rb_random_interface_t *
try_rand_if(VALUE obj, rb_random_t *rnd)
{
if (rnd == &default_rand()->base) {
return &random_mt_if;
}
return rb_rand_if(obj);
}
/* :nodoc: */
void
rb_random_base_init(rb_random_t *rnd)
{
rnd->seed = INT2FIX(0);
}
/* :nodoc: */
static VALUE
random_alloc(VALUE klass)
{
rb_random_mt_t *rnd;
VALUE obj = TypedData_Make_Struct(klass, rb_random_mt_t, &random_mt_type, rnd);
rb_random_base_init(&rnd->base);
return obj;
}
static VALUE
rand_init_default(const rb_random_interface_t *rng, rb_random_t *rnd)
{
VALUE seed, buf0 = 0;
size_t len = roomof(rng->default_seed_bits, 32);
uint32_t *buf = ALLOCV_N(uint32_t, buf0, len+1);
fill_random_seed(buf, len, true);
rng->init(rnd, buf, len);
seed = make_seed_value(buf, len);
explicit_bzero(buf, len * sizeof(*buf));
ALLOCV_END(buf0);
return seed;
}
static VALUE
rand_init(const rb_random_interface_t *rng, rb_random_t *rnd, VALUE seed)
{
uint32_t *buf;
VALUE buf0 = 0;
size_t len;
int sign;
len = rb_absint_numwords(seed, 32, NULL);
if (len == 0) len = 1;
buf = ALLOCV_N(uint32_t, buf0, len);
sign = rb_integer_pack(seed, buf, len, sizeof(uint32_t), 0,
INTEGER_PACK_LSWORD_FIRST|INTEGER_PACK_NATIVE_BYTE_ORDER);
if (sign < 0)
sign = -sign;
if (len == 1) {
rng->init_int32(rnd, buf[0]);
}
else {
if (sign != 2 && buf[len-1] == 1) /* remove leading-zero-guard */
len--;
rng->init(rnd, buf, len);
}
explicit_bzero(buf, len * sizeof(*buf));
ALLOCV_END(buf0);
return seed;
}
/*
* call-seq:
* Random.new(seed = Random.new_seed) -> prng
*
* Creates a new PRNG using +seed+ to set the initial state. If +seed+ is
* omitted, the generator is initialized with Random.new_seed.
*
* See Random.srand for more information on the use of seed values.
*/
static VALUE
random_init(int argc, VALUE *argv, VALUE obj)
{
rb_random_t *rnd = try_get_rnd(obj);
const rb_random_interface_t *rng = rb_rand_if(obj);
if (!rng) {
rb_raise(rb_eTypeError, "undefined random interface: %s",
RTYPEDDATA_TYPE(obj)->wrap_struct_name);
}
unsigned int major = rng->version.major;
unsigned int minor = rng->version.minor;
if (major != RUBY_RANDOM_INTERFACE_VERSION_MAJOR) {
rb_raise(rb_eTypeError, "Random interface version "
STRINGIZE(RUBY_RANDOM_INTERFACE_VERSION_MAJOR) "."
STRINGIZE(RUBY_RANDOM_INTERFACE_VERSION_MINOR) " "
"expected: %d.%d", major, minor);
}
argc = rb_check_arity(argc, 0, 1);
rb_check_frozen(obj);
if (argc == 0) {
rnd->seed = rand_init_default(rng, rnd);
}
else {
rnd->seed = rand_init(rng, rnd, rb_to_int(argv[0]));
}
return obj;
}
#define DEFAULT_SEED_LEN (DEFAULT_SEED_CNT * (int)sizeof(int32_t))
#if defined(S_ISCHR) && !defined(DOSISH)
# define USE_DEV_URANDOM 1
#else
# define USE_DEV_URANDOM 0
#endif
#ifdef HAVE_GETENTROPY
# define MAX_SEED_LEN_PER_READ 256
static int
fill_random_bytes_urandom(void *seed, size_t size)
{
unsigned char *p = (unsigned char *)seed;
while (size) {
size_t len = size < MAX_SEED_LEN_PER_READ ? size : MAX_SEED_LEN_PER_READ;
if (getentropy(p, len) != 0) {
return -1;
}
p += len;
size -= len;
}
return 0;
}
#elif USE_DEV_URANDOM
static int
fill_random_bytes_urandom(void *seed, size_t size)
{
/*
O_NONBLOCK and O_NOCTTY is meaningless if /dev/urandom correctly points
to a urandom device. But it protects from several strange hazard if
/dev/urandom is not a urandom device.
*/
int fd = rb_cloexec_open("/dev/urandom",
# ifdef O_NONBLOCK
O_NONBLOCK|
# endif
# ifdef O_NOCTTY
O_NOCTTY|
# endif
O_RDONLY, 0);
struct stat statbuf;
ssize_t ret = 0;
size_t offset = 0;
if (fd < 0) return -1;
rb_update_max_fd(fd);
if (fstat(fd, &statbuf) == 0 && S_ISCHR(statbuf.st_mode)) {
do {
ret = read(fd, ((char*)seed) + offset, size - offset);
if (ret < 0) {
close(fd);
return -1;
}
offset += (size_t)ret;
} while (offset < size);
}
close(fd);
return 0;
}
#else
# define fill_random_bytes_urandom(seed, size) -1
#endif
#if ! defined HAVE_GETRANDOM && defined __linux__ && defined __NR_getrandom
# ifndef GRND_NONBLOCK
# define GRND_NONBLOCK 0x0001 /* not defined in musl libc */
# endif
# define getrandom(ptr, size, flags) \
(ssize_t)syscall(__NR_getrandom, (ptr), (size), (flags))
# define HAVE_GETRANDOM 1
#endif
#if 0
#elif defined MAC_OS_X_VERSION_10_7 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_7
# if defined(USE_COMMON_RANDOM)
# elif defined MAC_OS_X_VERSION_10_10 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10
# define USE_COMMON_RANDOM 1
# else
# define USE_COMMON_RANDOM 0
# endif
# if USE_COMMON_RANDOM
# include <CommonCrypto/CommonCryptoError.h> /* for old Xcode */
# include <CommonCrypto/CommonRandom.h>
# else
# include <Security/SecRandom.h>
# endif
static int
fill_random_bytes_syscall(void *seed, size_t size, int unused)
{
#if USE_COMMON_RANDOM
CCRNGStatus status = CCRandomGenerateBytes(seed, size);
int failed = status != kCCSuccess;
#else
int status = SecRandomCopyBytes(kSecRandomDefault, size, seed);
int failed = status != errSecSuccess;
#endif
if (failed) {
# if 0
# if USE_COMMON_RANDOM
/* How to get the error message? */
fprintf(stderr, "CCRandomGenerateBytes failed: %d\n", status);
# else
CFStringRef s = SecCopyErrorMessageString(status, NULL);
const char *m = s ? CFStringGetCStringPtr(s, kCFStringEncodingUTF8) : NULL;
fprintf(stderr, "SecRandomCopyBytes failed: %d: %s\n", status,
m ? m : "unknown");
if (s) CFRelease(s);
# endif
# endif
return -1;
}
return 0;
}
#elif defined(HAVE_ARC4RANDOM_BUF)
static int
fill_random_bytes_syscall(void *buf, size_t size, int unused)
{
#if (defined(__OpenBSD__) && OpenBSD >= 201411) || \
(defined(__NetBSD__) && __NetBSD_Version__ >= 700000000) || \
(defined(__FreeBSD__) && __FreeBSD_version >= 1200079)
arc4random_buf(buf, size);
return 0;
#else
return -1;
#endif
}
#elif defined(_WIN32)
#ifndef DWORD_MAX
# define DWORD_MAX (~(DWORD)0UL)
#endif
# if defined(CRYPT_VERIFYCONTEXT)
/* Although HCRYPTPROV is not a HANDLE, it looks like
* INVALID_HANDLE_VALUE is not a valid value */
static const HCRYPTPROV INVALID_HCRYPTPROV = (HCRYPTPROV)INVALID_HANDLE_VALUE;
static void
release_crypt(void *p)
{
HCRYPTPROV *ptr = p;
HCRYPTPROV prov = (HCRYPTPROV)ATOMIC_PTR_EXCHANGE(*ptr, INVALID_HCRYPTPROV);
if (prov && prov != INVALID_HCRYPTPROV) {
CryptReleaseContext(prov, 0);
}
}
static const rb_data_type_t crypt_prov_type = {
"HCRYPTPROV",
{0, release_crypt,},
0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_EMBEDDABLE
};
static int
fill_random_bytes_crypt(void *seed, size_t size)
{
static HCRYPTPROV perm_prov;
HCRYPTPROV prov = perm_prov, old_prov;
if (!prov) {
VALUE wrapper = TypedData_Wrap_Struct(0, &crypt_prov_type, 0);
if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
prov = INVALID_HCRYPTPROV;
}
old_prov = (HCRYPTPROV)ATOMIC_PTR_CAS(perm_prov, 0, prov);
if (LIKELY(!old_prov)) { /* no other threads acquired */
if (prov != INVALID_HCRYPTPROV) {
DATA_PTR(wrapper) = (void *)prov;
rb_vm_register_global_object(wrapper);
}
}
else { /* another thread acquired */
if (prov != INVALID_HCRYPTPROV) {
CryptReleaseContext(prov, 0);
}
prov = old_prov;
}
}
if (prov == INVALID_HCRYPTPROV) return -1;
while (size > 0) {
DWORD n = (size > (size_t)DWORD_MAX) ? DWORD_MAX : (DWORD)size;
if (!CryptGenRandom(prov, n, seed)) return -1;
seed = (char *)seed + n;
size -= n;
}
return 0;
}
# else
# define fill_random_bytes_crypt(seed, size) -1
# endif
static int
fill_random_bytes_bcrypt(void *seed, size_t size)
{
while (size > 0) {
ULONG n = (size > (size_t)ULONG_MAX) ? LONG_MAX : (ULONG)size;
if (BCryptGenRandom(NULL, seed, n, BCRYPT_USE_SYSTEM_PREFERRED_RNG))
return -1;
seed = (char *)seed + n;
size -= n;
}
return 0;
}
static int
fill_random_bytes_syscall(void *seed, size_t size, int unused)
{
if (fill_random_bytes_bcrypt(seed, size) == 0) return 0;
return fill_random_bytes_crypt(seed, size);
}
#elif defined HAVE_GETRANDOM
static int
fill_random_bytes_syscall(void *seed, size_t size, int need_secure)
{
static rb_atomic_t try_syscall = 1;
if (try_syscall) {
size_t offset = 0;
int flags = 0;
if (!need_secure)
flags = GRND_NONBLOCK;
do {
errno = 0;
ssize_t ret = getrandom(((char*)seed) + offset, size - offset, flags);
if (ret == -1) {
ATOMIC_SET(try_syscall, 0);
return -1;
}
offset += (size_t)ret;
} while (offset < size);
return 0;
}
return -1;
}
#else
# define fill_random_bytes_syscall(seed, size, need_secure) -1
#endif
int
ruby_fill_random_bytes(void *seed, size_t size, int need_secure)
{
int ret = fill_random_bytes_syscall(seed, size, need_secure);
if (ret == 0) return ret;
return fill_random_bytes_urandom(seed, size);
}
/* cnt must be 4 or more */
static void
fill_random_seed(uint32_t *seed, size_t cnt, bool try_bytes)
{
static rb_atomic_t n = 0;
#if defined HAVE_CLOCK_GETTIME
struct timespec tv;
#elif defined HAVE_GETTIMEOFDAY
struct timeval tv;
#endif
size_t len = cnt * sizeof(*seed);
if (try_bytes) {
fill_random_bytes(seed, len, FALSE);
return;
}
memset(seed, 0, len);
#if defined HAVE_CLOCK_GETTIME
clock_gettime(CLOCK_REALTIME, &tv);
seed[0] ^= tv.tv_nsec;
#elif defined HAVE_GETTIMEOFDAY
gettimeofday(&tv, 0);
seed[0] ^= tv.tv_usec;
#endif
seed[1] ^= (uint32_t)tv.tv_sec;
#if SIZEOF_TIME_T > SIZEOF_INT
seed[0] ^= (uint32_t)((time_t)tv.tv_sec >> SIZEOF_INT * CHAR_BIT);
#endif
seed[2] ^= getpid() ^ (ATOMIC_FETCH_ADD(n, 1) << 16);
seed[3] ^= (uint32_t)(VALUE)&seed;
#if SIZEOF_VOIDP > SIZEOF_INT
seed[2] ^= (uint32_t)((VALUE)&seed >> SIZEOF_INT * CHAR_BIT);
#endif
}
static VALUE
make_seed_value(uint32_t *ptr, size_t len)
{
VALUE seed;
if (ptr[len-1] <= 1) {
/* set leading-zero-guard */
ptr[len++] = 1;
}
seed = rb_integer_unpack(ptr, len, sizeof(uint32_t), 0,
INTEGER_PACK_LSWORD_FIRST|INTEGER_PACK_NATIVE_BYTE_ORDER);
return seed;
}
#define with_random_seed(size, add, try_bytes) \
for (uint32_t seedbuf[(size)+(add)], loop = (fill_random_seed(seedbuf, (size), try_bytes), 1); \
loop; explicit_bzero(seedbuf, (size)*sizeof(seedbuf[0])), loop = 0)
/*
* call-seq: Random.new_seed -> integer
*
* Returns an arbitrary seed value. This is used by Random.new
* when no seed value is specified as an argument.
*
* Random.new_seed #=> 115032730400174366788466674494640623225
*/
static VALUE
random_seed(VALUE _)
{
VALUE v;
with_random_seed(DEFAULT_SEED_CNT, 1, true) {
v = make_seed_value(seedbuf, DEFAULT_SEED_CNT);
}
return v;
}
/*
* call-seq: Random.urandom(size) -> string
*
* Returns a string, using platform providing features.
* Returned value is expected to be a cryptographically secure
* pseudo-random number in binary form.
* This method raises a RuntimeError if the feature provided by platform
* failed to prepare the result.
*
* In 2017, Linux manpage random(7) writes that "no cryptographic
* primitive available today can hope to promise more than 256 bits of
* security". So it might be questionable to pass size > 32 to this
* method.
*
* Random.urandom(8) #=> "\x78\x41\xBA\xAF\x7D\xEA\xD8\xEA"
*/
static VALUE
random_raw_seed(VALUE self, VALUE size)
{
long n = NUM2ULONG(size);
VALUE buf = rb_str_new(0, n);
if (n == 0) return buf;
if (fill_random_bytes(RSTRING_PTR(buf), n, TRUE))
rb_raise(rb_eRuntimeError, "failed to get urandom");
return buf;
}
/*
* call-seq: prng.seed -> integer
*
* Returns the seed value used to initialize the generator. This may be used to
* initialize another generator with the same state at a later time, causing it
* to produce the same sequence of numbers.
*
* prng1 = Random.new(1234)
* prng1.seed #=> 1234
* prng1.rand(100) #=> 47
*
* prng2 = Random.new(prng1.seed)
* prng2.rand(100) #=> 47
*/
static VALUE
random_get_seed(VALUE obj)
{
return get_rnd(obj)->seed;
}
/* :nodoc: */
static VALUE
rand_mt_copy(VALUE obj, VALUE orig)
{
rb_random_mt_t *rnd1, *rnd2;
struct MT *mt;
if (!OBJ_INIT_COPY(obj, orig)) return obj;
rnd1 = get_rnd_mt(obj);
rnd2 = get_rnd_mt(orig);
mt = &rnd1->mt;
*rnd1 = *rnd2;
mt->next = mt->state + numberof(mt->state) - mt->left + 1;
return obj;
}
static VALUE
mt_state(const struct MT *mt)
{
return rb_integer_unpack(mt->state, numberof(mt->state),
sizeof(*mt->state), 0,
INTEGER_PACK_LSWORD_FIRST|INTEGER_PACK_NATIVE_BYTE_ORDER);
}
/* :nodoc: */
static VALUE
rand_mt_state(VALUE obj)
{
rb_random_mt_t *rnd = get_rnd_mt(obj);
return mt_state(&rnd->mt);
}
/* :nodoc: */
static VALUE
random_s_state(VALUE klass)
{
return mt_state(&default_rand()->mt);
}
/* :nodoc: */
static VALUE
rand_mt_left(VALUE obj)
{
rb_random_mt_t *rnd = get_rnd_mt(obj);
return INT2FIX(rnd->mt.left);
}
/* :nodoc: */
static VALUE
random_s_left(VALUE klass)
{
return INT2FIX(default_rand()->mt.left);
}
/* :nodoc: */
static VALUE
rand_mt_dump(VALUE obj)
{
rb_random_mt_t *rnd = rb_check_typeddata(obj, &random_mt_type);
VALUE dump = rb_ary_new2(3);
rb_ary_push(dump, mt_state(&rnd->mt));
rb_ary_push(dump, INT2FIX(rnd->mt.left));
rb_ary_push(dump, rnd->base.seed);
return dump;
}
/* :nodoc: */
static VALUE
rand_mt_load(VALUE obj, VALUE dump)
{
rb_random_mt_t *rnd = rb_check_typeddata(obj, &random_mt_type);
struct MT *mt = &rnd->mt;
VALUE state, left = INT2FIX(1), seed = INT2FIX(0);
unsigned long x;
rb_check_copyable(obj, dump);
Check_Type(dump, T_ARRAY);
switch (RARRAY_LEN(dump)) {
case 3:
seed = RARRAY_AREF(dump, 2);
case 2:
left = RARRAY_AREF(dump, 1);
case 1:
state = RARRAY_AREF(dump, 0);
break;
default:
rb_raise(rb_eArgError, "wrong dump data");
}
rb_integer_pack(state, mt->state, numberof(mt->state),
sizeof(*mt->state), 0,
INTEGER_PACK_LSWORD_FIRST|INTEGER_PACK_NATIVE_BYTE_ORDER);
x = NUM2ULONG(left);
if (x > numberof(mt->state) || x == 0) {
rb_raise(rb_eArgError, "wrong value");
}
mt->left = (unsigned int)x;
mt->next = mt->state + numberof(mt->state) - x + 1;
rnd->base.seed = rb_to_int(seed);
return obj;
}
static void
rand_mt_init_int32(rb_random_t *rnd, uint32_t data)
{
struct MT *mt = &((rb_random_mt_t *)rnd)->mt;
init_genrand(mt, data);
}
static void
rand_mt_init(rb_random_t *rnd, const uint32_t *buf, size_t len)
{
struct MT *mt = &((rb_random_mt_t *)rnd)->mt;
init_by_array(mt, buf, (int)len);
}
static unsigned int
rand_mt_get_int32(rb_random_t *rnd)
{
struct MT *mt = &((rb_random_mt_t *)rnd)->mt;
return genrand_int32(mt);
}
static void
rand_mt_get_bytes(rb_random_t *rnd, void *ptr, size_t n)
{
rb_rand_bytes_int32(rand_mt_get_int32, rnd, ptr, n);
}
/*
* call-seq:
* srand(number = Random.new_seed) -> old_seed
*
* Seeds the system pseudo-random number generator, with +number+.
* The previous seed value is returned.
*
* If +number+ is omitted, seeds the generator using a source of entropy
* provided by the operating system, if available (/dev/urandom on Unix systems
* or the RSA cryptographic provider on Windows), which is then combined with
* the time, the process id, and a sequence number.
*
* srand may be used to ensure repeatable sequences of pseudo-random numbers
* between different runs of the program. By setting the seed to a known value,
* programs can be made deterministic during testing.
*
* srand 1234 # => 268519324636777531569100071560086917274
* [ rand, rand ] # => [0.1915194503788923, 0.6221087710398319]
* [ rand(10), rand(1000) ] # => [4, 664]
* srand 1234 # => 1234
* [ rand, rand ] # => [0.1915194503788923, 0.6221087710398319]
*/
static VALUE
rb_f_srand(int argc, VALUE *argv, VALUE obj)
{
VALUE seed, old;
rb_random_mt_t *r = rand_mt_start(default_rand());
if (rb_check_arity(argc, 0, 1) == 0) {
seed = random_seed(obj);
}
else {
seed = rb_to_int(argv[0]);
}
old = r->base.seed;
rand_init(&random_mt_if, &r->base, seed);
r->base.seed = seed;
return old;
}
static unsigned long
make_mask(unsigned long x)
{
x = x | x >> 1;
x = x | x >> 2;
x = x | x >> 4;
x = x | x >> 8;
x = x | x >> 16;
#if 4 < SIZEOF_LONG
x = x | x >> 32;
#endif
return x;
}
static unsigned long
limited_rand(const rb_random_interface_t *rng, rb_random_t *rnd, unsigned long limit)
{
/* mt must be initialized */
unsigned long val, mask;
if (!limit) return 0;
mask = make_mask(limit);
#if 4 < SIZEOF_LONG