xref: /illumos-gate/usr/src/test/libc-tests/tests/random/getrandom.c (revision 45ede40b2394db7967e59f19288fae9b62efd4aa)
1 /*
2  * This file and its contents are supplied under the terms of the
3  * Common Development and Distribution License ("CDDL"), version 1.0.
4  * You may only use this file in accordance with the terms of version
5  * 1.0 of the CDDL.
6  *
7  * A full copy of the text of the CDDL should have accompanied this
8  * source.  A copy of the CDDL is also available via the Internet at
9  * http://www.illumos.org/license/CDDL.
10  */
11 
12 /*
13  * Copyright (c) 2015, Joyent, Inc.
14  */
15 
16 /*
17  * Test getrandom(2)
18  */
19 
20 #include <sys/random.h>
21 #include <sys/mman.h>
22 #include <assert.h>
23 #include <errno.h>
24 
25 int
26 main(void)
27 {
28 	int ret;
29 	void *addr;
30 	uint8_t buf[32];
31 	uint8_t bigbuf[4096];
32 
33 	/* Go through flags values, start with invalid */
34 	ret = getrandom(buf, sizeof (buf), 42);
35 	assert(ret == -1);
36 	assert(errno == EINVAL);
37 
38 	ret = getrandom(buf, sizeof (buf), 0);
39 	assert(ret >= 0);
40 
41 	ret = getrandom(buf, sizeof (buf), GRND_NONBLOCK);
42 	assert(ret >= 0);
43 
44 	ret = getrandom(buf, sizeof (buf), GRND_RANDOM);
45 	assert(ret >= 0);
46 
47 	ret = getrandom(buf, sizeof (buf), GRND_RANDOM | GRND_NONBLOCK);
48 	assert(ret >= 0);
49 
50 	ret = getrandom(buf, sizeof (buf), (GRND_RANDOM | GRND_NONBLOCK) << 1);
51 	assert(ret == -1);
52 	assert(errno == EINVAL);
53 
54 	/* Bad buffer addresses, eg. EFAULT */
55 	ret = getrandom(NULL, sizeof (buf), 0);
56 	assert(ret == -1);
57 	assert(errno == EFAULT);
58 
59 	ret = getrandom(NULL, sizeof (buf), GRND_RANDOM);
60 	assert(ret == -1);
61 	assert(errno == EFAULT);
62 
63 	/* Jump through a hoop to know we'll always have a bad address */
64 	addr = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE | MAP_ANON, -1, 0);
65 	assert(addr != MAP_FAILED);
66 	ret = munmap(addr, 4096);
67 	assert(ret == 0);
68 	ret = getrandom(addr, sizeof (buf), 0);
69 	assert(ret == -1);
70 	assert(errno == EFAULT);
71 	ret = getrandom(addr, sizeof (buf), GRND_RANDOM);
72 	assert(ret == -1);
73 	assert(errno == EFAULT);
74 
75 	/* Verify that we get rounded down on a getrandom of /dev/random */
76 	ret = getrandom(bigbuf, sizeof (buf), GRND_RANDOM);
77 	assert(ret >= 0 && ret < sizeof (bigbuf));
78 
79 	/* Do a few simple sets where we know we should get data */
80 	ret = getrandom(buf, sizeof (buf), 0);
81 	assert(ret == sizeof (buf));
82 	ret = getrandom(buf, sizeof (buf), GRND_RANDOM);
83 	assert(ret == sizeof (buf));
84 
85 	return (0);
86 }
87