1/*
2 * Copyright (C) 2015 Cedric Hnyda ced.hnyda@gmail.com
3 *
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of version 2 of the GNU General Public License as
6 * published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it would be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11 *
12 * Further, this software is distributed without any warranty that it is
13 * free of the rightful claim of any third person regarding infringement
14 * or the like.  Any license provided herein, whether implied or
15 * otherwise, applies only to this software file.  Patent licenses, if
16 * any, provided herein do not apply to combinations of this program with
17 * other software, or any other product whatsoever.
18 *
19 */
20
21/*
22 * AUTHOR   : Cédric Hnyda
23 * DATE STARTED : 06/13/2015
24 *
25 *  Calls getrandom(2), checks that the buffer is filled with random bytes
26 *  and expects success.
27 *
28 */
29
30#include "lapi/getrandom.h"
31#include "lapi/syscalls.h"
32#include "tst_test.h"
33
34static int modes[] = { 0, GRND_RANDOM, GRND_NONBLOCK,
35		       GRND_RANDOM | GRND_NONBLOCK };
36
37static int check_content(unsigned char *buf, int nb)
38{
39	int table[256];
40	int i, index, max;
41
42	memset(table, 0, sizeof(table));
43
44	max = 6 + nb * 0.2;
45
46	for (i = 0; i < nb; i++) {
47		index = buf[i];
48		table[index]++;
49	}
50
51	for (i = 0; i < nb; i++) {
52		if (max > 0 && table[i] > max)
53			return 0;
54	}
55	return 1;
56}
57
58static void verify_getrandom(unsigned int n)
59{
60	unsigned char buf[256];
61
62	memset(buf, 0, sizeof(buf));
63
64	do {
65		TEST(tst_syscall(__NR_getrandom, buf, sizeof(buf), modes[n]));
66	} while ((modes[n] & GRND_NONBLOCK) && TEST_RETURN == -1
67		  && TEST_ERRNO == EAGAIN);
68
69	if (!check_content(buf, TEST_RETURN))
70		tst_res(TFAIL | TTERRNO, "getrandom failed");
71	else
72		tst_res(TPASS, "getrandom returned %ld", TEST_RETURN);
73}
74
75static struct tst_test test = {
76	.tcnt = ARRAY_SIZE(modes),
77	.test = verify_getrandom,
78};
79