xref: /xnu-11215/tests/prng.c (revision a5e72196)
1 #include <dispatch/dispatch.h>
2 #include <darwintest.h>
3 #include <darwintest_utils.h>
4 #include <sys/random.h>
5 
6 T_GLOBAL_META(T_META_RUN_CONCURRENTLY(true));
7 
8 #define BUF_SIZE ((size_t)(1 << 25))
9 #define BLOCK_SIZE ((size_t)16)
10 
11 static int
cmp(const void * a,const void * b)12 cmp(const void *a, const void *b)
13 {
14 	return memcmp(a, b, 16);
15 }
16 
17 static void
prng_sanitycheck(uint8_t * buf,size_t buf_size)18 prng_sanitycheck(uint8_t *buf, size_t buf_size)
19 {
20 	size_t nblocks = buf_size / BLOCK_SIZE;
21 	qsort(buf, nblocks, BLOCK_SIZE, cmp);
22 
23 	for (size_t i = 0; i < nblocks - 1; i += 1) {
24 		T_QUIET;
25 		T_ASSERT_NE(memcmp(buf, buf + BLOCK_SIZE, BLOCK_SIZE), 0, "duplicate block");
26 		buf += BLOCK_SIZE;
27 	}
28 }
29 
30 static void
prng_getentropy(void * ctx,size_t i)31 prng_getentropy(void *ctx, size_t i)
32 {
33 	uint8_t *buf = ((uint8_t *)ctx) + (BUF_SIZE * i);
34 
35 	for (size_t j = 0; j < BUF_SIZE; j += 256) {
36 		T_QUIET;
37 		T_ASSERT_POSIX_SUCCESS(getentropy(&buf[j], 256), "getentropy");
38 	}
39 
40 	prng_sanitycheck(buf, BUF_SIZE);
41 }
42 
43 static void
prng_devrandom(void * ctx,size_t i)44 prng_devrandom(void *ctx, size_t i)
45 {
46 	uint8_t *buf = ((uint8_t *)ctx) + (BUF_SIZE * i);
47 
48 	int fd = open("/dev/random", O_RDONLY);
49 	T_QUIET;
50 	T_ASSERT_POSIX_SUCCESS(fd, "open");
51 
52 	size_t n = BUF_SIZE;
53 	while (n > 0) {
54 		ssize_t m = read(fd, buf, n);
55 		T_QUIET;
56 		T_ASSERT_POSIX_SUCCESS(m, "read");
57 
58 		n -= (size_t)m;
59 		buf += m;
60 	}
61 
62 	buf = ((uint8_t *)ctx) + (BUF_SIZE * i);
63 	prng_sanitycheck(buf, BUF_SIZE);
64 }
65 
66 T_DECL(prng, "prng test")
67 {
68 	size_t ncpu = (size_t)dt_ncpu();
69 
70 	uint8_t *buf = malloc(BUF_SIZE * ncpu);
71 	T_QUIET;
72 	T_ASSERT_NOTNULL(buf, "malloc");
73 
74 	dispatch_apply_f(ncpu, DISPATCH_APPLY_AUTO, buf, prng_getentropy);
75 
76 	dispatch_apply_f(ncpu, DISPATCH_APPLY_AUTO, buf, prng_devrandom);
77 
78 	prng_sanitycheck(buf, BUF_SIZE * ncpu);
79 
80 	free(buf);
81 }
82