2 * Routines to get randomness.
11 #include "sanitise.h" // interesting_numbers
14 unsigned int rand_bool(void)
19 static unsigned int rand_single_bit(unsigned char size
)
21 return (1L << (rand() % size
));
25 * set N bits, where N= rand(0 - WORDSIZE/2)
27 static unsigned long randbits(int limit
)
29 unsigned int num
= rand() % limit
/ 2;
33 for (i
= 0; i
< num
; i
++)
34 r
|= (1 << (rand() % (limit
- 1)));
40 * Based on very similar routine stolen from iknowthis. Thanks Tavis.
42 static unsigned long taviso(void)
48 case 0: r
= rand() & rand();
55 case 1: temp
= rand();
62 if (temp
) r
|= rand() % temp
;
66 case 2: r
= rand() | rand();
85 * Pick 8 random bytes, and concatenate them into a long.
87 static unsigned long rand8x8(void)
89 unsigned long r
= 0UL;
92 for (i
= (rand() % 7) + 1; i
> 0; --i
)
93 r
= (r
<< 8) | rand() % 256;
99 * Pick 1 random byte, and repeat it through a long.
101 static unsigned long rept8(unsigned int num
)
103 unsigned long r
= 0UL;
108 for (i
= rand() % (num
- 1) ; i
> 0; --i
)
115 * "selector" function for 32bit random.
116 * only called from rand32()
118 static unsigned int __rand32(void)
122 switch (rand() % 7) {
123 case 0: r
= rand_single_bit(32);
125 case 1: r
= randbits(32);
129 case 3: r
= taviso();
131 case 4: r
= rand8x8();
133 case 5: r
= rept8(4);
135 case 6: return get_interesting_32bit_value();
142 * Generate, and munge a 32bit number.
144 unsigned int rand32(void)
156 for (i
= 0; i
< rounds
; i
++) {
164 /* Sometimes deduct it from INT_MAX */
168 /* Sometimes flip sign */
172 /* we might get lucky if something is counting ints/longs etc. */
173 if (rand() % 100 < 25) {
174 int _div
= 1 << ((rand() % 4) + 1); /* 2,4,8 or 16 */
179 switch (rand() % 4) {
184 case 2: r
&= 0xffffff;
192 * Generate and munge a 64bit number.
203 /* 33:64-bit ranges. */
204 switch (rand() % 7) {
205 case 0: r
= rand_single_bit(64);
207 case 1: r
= randbits(64);
209 case 2: r
= rand32() | rand32() << 31;
211 case 3: r
= taviso();
213 case 4: r
= rand8x8();
215 case 5: r
= rept8(8);
217 /* Sometimes pick a not-so-random number. */
218 case 6: return get_interesting_value();
222 switch (rand() % 4) {
223 case 0: r
&= 0x000000ffffffffffULL
;
225 case 1: r
&= 0x0000ffffffffffffULL
;
227 case 2: r
&= 0x00ffffffffffffffULL
;
232 /* Sometimes invert the generated number. */
236 /* increase distribution in MSB */
242 for (i
= 0; i
< rounds
; i
++)
243 r
|= (1L << ((__WORDSIZE
- 1) - (rand() % 8)));
246 /* randomly flip sign bit. */
248 r
|= (1L << (__WORDSIZE
- 1));