1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (C) 2015 Cedric Hnyda <ced.hnyda@gmail.com>
4 *
5 * Calls getrandom(2), checks that the buffer is filled with random bytes
6 * and expects success.
7 */
8
9 #include "lapi/getrandom.h"
10 #include "lapi/syscalls.h"
11 #include "tst_test.h"
12
13 static int modes[] = { 0, GRND_RANDOM, GRND_NONBLOCK,
14 GRND_RANDOM | GRND_NONBLOCK };
15
check_content(unsigned char * buf,int nb)16 static int check_content(unsigned char *buf, int nb)
17 {
18 int table[256];
19 int i, index, max;
20
21 memset(table, 0, sizeof(table));
22
23 max = 6 + nb * 0.2;
24
25 for (i = 0; i < nb; i++) {
26 index = buf[i];
27 table[index]++;
28 }
29
30 for (i = 0; i < nb; i++) {
31 if (max > 0 && table[i] > max)
32 return 0;
33 }
34 return 1;
35 }
36
verify_getrandom(unsigned int n)37 static void verify_getrandom(unsigned int n)
38 {
39 unsigned char buf[256];
40
41 memset(buf, 0, sizeof(buf));
42
43 do {
44 TEST(tst_syscall(__NR_getrandom, buf, sizeof(buf), modes[n]));
45 } while ((modes[n] & GRND_NONBLOCK) && TST_RET == -1
46 && TST_ERR == EAGAIN);
47
48 if (!check_content(buf, TST_RET))
49 tst_res(TFAIL | TTERRNO, "getrandom failed");
50 else
51 tst_res(TPASS, "getrandom returned %ld", TST_RET);
52 }
53
54 static struct tst_test test = {
55 .tcnt = ARRAY_SIZE(modes),
56 .test = verify_getrandom,
57 };
58