]>
git.saurik.com Git - apple/xnu.git/blob - tests/prng.c
1 #include <dispatch/dispatch.h>
2 #include <darwintest.h>
3 #include <darwintest_utils.h>
4 #include <sys/random.h>
6 T_GLOBAL_META(T_META_RUN_CONCURRENTLY(true));
8 #define BUF_SIZE ((size_t)(1 << 25))
9 #define BLOCK_SIZE ((size_t)16)
12 cmp(const void *a
, const void *b
)
14 return memcmp(a
, b
, 16);
18 prng_sanitycheck(uint8_t *buf
, size_t buf_size
)
20 size_t nblocks
= buf_size
/ BLOCK_SIZE
;
21 qsort(buf
, nblocks
, BLOCK_SIZE
, cmp
);
23 for (size_t i
= 0; i
< nblocks
- 1; i
+= 1) {
25 T_ASSERT_NE(memcmp(buf
, buf
+ BLOCK_SIZE
, BLOCK_SIZE
), 0, "duplicate block");
31 prng_getentropy(void *ctx
, size_t i
)
33 uint8_t *buf
= ((uint8_t *)ctx
) + (BUF_SIZE
* i
);
35 for (size_t j
= 0; j
< BUF_SIZE
; j
+= 256) {
37 T_ASSERT_POSIX_SUCCESS(getentropy(&buf
[j
], 256), "getentropy");
40 prng_sanitycheck(buf
, BUF_SIZE
);
44 prng_devrandom(void *ctx
, size_t i
)
46 uint8_t *buf
= ((uint8_t *)ctx
) + (BUF_SIZE
* i
);
48 int fd
= open("/dev/random", O_RDONLY
);
50 T_ASSERT_POSIX_SUCCESS(fd
, "open");
54 ssize_t m
= read(fd
, buf
, n
);
56 T_ASSERT_POSIX_SUCCESS(m
, "read");
62 buf
= ((uint8_t *)ctx
) + (BUF_SIZE
* i
);
63 prng_sanitycheck(buf
, BUF_SIZE
);
66 T_DECL(prng
, "prng test")
68 size_t ncpu
= (size_t)dt_ncpu();
70 uint8_t *buf
= malloc(BUF_SIZE
* ncpu
);
72 T_ASSERT_NOTNULL(buf
, "malloc");
74 dispatch_apply_f(ncpu
, DISPATCH_APPLY_AUTO
, buf
, prng_getentropy
);
76 dispatch_apply_f(ncpu
, DISPATCH_APPLY_AUTO
, buf
, prng_devrandom
);
78 prng_sanitycheck(buf
, BUF_SIZE
* ncpu
);