82
83
rc4_ready = REKEY_BYTES;
84
85
#endif /* !HAVE_ARC4RANDOM */
87
#ifndef ARC4RANDOM_BUF
89
arc4random_buf(void *_buf, size_t n)
93
char *buf = (char *)_buf;
95
for (i = 0; i < n; i++) {
103
#endif /* !HAVE_ARC4RANDOM_BUF */
105
#ifndef ARC4RANDOM_UNIFORM
107
* Calculate a uniformly distributed random number less than upper_bound
108
* avoiding "modulo bias".
110
* Uniformity is achieved by generating new random numbers until the one
111
* returned is outside the range [0, 2**32 % upper_bound). This
112
* guarantees the selected random number will be inside
113
* [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
114
* after reduction modulo upper_bound.
117
arc4random_uniform(u_int32_t upper_bound)
124
#if (ULONG_MAX > 0xffffffffUL)
125
min = 0x100000000UL % upper_bound;
127
/* Calculate (2**32 % upper_bound) avoiding 64-bit math */
128
if (upper_bound > 0x80000000)
129
min = 1 + ~upper_bound; /* 2**32 - upper_bound */
131
/* (2**32 - (x * 2)) % x == 2**32 % x when x <= 2**31 */
132
min = ((0xffffffff - (upper_bound * 2)) + 1) % upper_bound;
137
* This could theoretically loop forever but each retry has
138
* p > 0.5 (worst case, usually far better) of selecting a
139
* number inside the range we need, so it should rarely need
148
return r % upper_bound;
150
#endif /* !HAVE_ARC4RANDOM_UNIFORM */