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)
47 case 0: r
= rand() & rand();
54 case 1: r
= rand() % rand();
61 case 2: r
= rand() | rand();
83 * Pick 8 random bytes, and concatenate them into a long.
85 static unsigned long rand8x8(void)
87 unsigned long r
= 0UL;
90 for (i
= (rand() % 7) + 1; i
> 0; --i
)
91 r
= (r
<< 8) | rand() % 256;
97 * Pick 1 random byte, and repeat it through a long.
99 static unsigned long rept8(unsigned int num
)
101 unsigned long r
= 0UL;
106 for (i
= rand() % (num
- 1) ; i
> 0; --i
)
113 * "selector" function for 32bit random.
114 * only called from rand32()
116 static unsigned int __rand32(void)
120 switch (rand() % 7) {
121 case 0: r
= rand_single_bit(32);
123 case 1: r
= randbits(32);
127 case 3: r
= taviso();
129 case 4: r
= rand8x8();
131 case 5: r
= rept8(4);
133 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
++) {
157 switch (rand_bool()) {
158 case 0: r
|= __rand32();
160 case 1: r
^= __rand32();
168 /* Sometimes deduct it from INT_MAX */
172 /* Sometimes flip sign */
176 /* we might get lucky if something is counting ints/longs etc. */
177 if (rand() % 100 < 25) {
178 int _div
= 1 << ((rand() % 4) + 1); /* 2,4,8 or 16 */
183 switch (rand() % 4) {
188 case 2: r
&= 0xffffff;
198 * Generate and munge a 64bit number.
209 /* 33:64-bit ranges. */
210 switch (rand() % 7) {
211 case 0: r
= rand_single_bit(64);
213 case 1: r
= randbits(64);
215 case 2: r
= rand32() | rand32() << 31;
217 case 3: r
= taviso();
219 case 4: r
= rand8x8();
221 case 5: r
= rept8(8);
223 /* Sometimes pick a not-so-random number. */
224 case 6: return get_interesting_value();
230 switch (rand() % 4) {
231 case 0: r
&= 0x000000ffffffffffULL
;
233 case 1: r
&= 0x0000ffffffffffffULL
;
235 case 2: r
&= 0x00ffffffffffffffULL
;
242 /* Sometimes invert the generated number. */
246 /* increase distribution in MSB */
252 for (i
= 0; i
< rounds
; i
++)
253 r
|= (1L << ((__WORDSIZE
- 1) - (rand() % 8)));
256 /* randomly flip sign bit. */
258 r
|= (1L << (__WORDSIZE
- 1));