-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandutils.c
91 lines (77 loc) · 1.87 KB
/
randutils.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
/*
* General purpose random utilities
*
* Based on libuuid code.
*
* This file may be redistributed under the terms of the
* GNU Lesser General Public License.
*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#if defined(HAVE_SYS_RANDOM_H)
#include <sys/random.h>
#endif
#if defined(HAVE_SYS_TIME_H)
#include <sys/time.h>
#endif
#if defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)
#include <sys/syscall.h>
#endif
#include "randutils.h"
#ifdef HAVE_TLS
#define THREAD_LOCAL static __thread
#else
#define THREAD_LOCAL static
#endif
#if defined(__linux__) && defined(__NR_gettid) && defined(HAVE_JRAND48)
#define DO_JRAND_MIX
THREAD_LOCAL unsigned short ul_jrand_seed[3];
#endif
void random_get_bytes(void *buf, size_t nbytes)
{
#if defined(HAVE_SYS_RANDOM_H) && defined(HAVE_GETRANDOM)
size_t n = 0;
while (n != nbytes) {
ssize_t r = getrandom((char *)buf + n, nbytes - n, 0);
if (r < 0) {
if (errno == EINTR || errno == EAGAIN)
continue;
break;
}
n += r;
}
#else
size_t i, n = nbytes;
int lose_counter = 0;
unsigned char *cp = (unsigned char *)buf;
for (cp = buf, i = 0; i < nbytes; i++)
*cp++ ^= (rand() >> 7) & 0xFF;
#ifdef DO_JRAND_MIX
{
unsigned short tmp_seed[3];
memcpy(tmp_seed, ul_jrand_seed, sizeof(tmp_seed));
ul_jrand_seed[2] = ul_jrand_seed[2] ^ syscall(__NR_gettid);
for (cp = buf, i = 0; i < nbytes; i++)
*cp++ ^= (jrand48(tmp_seed) >> 7) & 0xFF;
memcpy(ul_jrand_seed, tmp_seed, sizeof(ul_jrand_seed) - sizeof(unsigned short));
}
#endif
#endif
return;
}
#ifdef TEST_PROGRAM
int main(int argc __attribute__((__unused__)), char *argv[] __attribute__((__unused__)))
{
unsigned int v, i;
/* generate and print 10 random numbers */
for (i = 0; i < 10; i++) {
random_get_bytes(&v, sizeof(v));
printf("%d\n", v);
}
return EXIT_SUCCESS;
}
#endif /* TEST_PROGRAM */