8322 nl: misleading-indentation
[unleashed/tickless.git] / usr / src / test / libc-tests / tests / random / getrandom.c
blobb7ba90362cf60f9c75424adfe6aed54cb8009805
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.
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.
13 * Copyright (c) 2015, Joyent, Inc.
17 * Test getrandom(2)
20 #include <sys/random.h>
21 #include <sys/mman.h>
22 #include <assert.h>
23 #include <errno.h>
25 int
26 main(void)
28 int ret;
29 void *addr;
30 uint8_t buf[32];
31 uint8_t bigbuf[4096];
33 /* Go through flags values, start with invalid */
34 ret = getrandom(buf, sizeof (buf), 42);
35 assert(ret == -1);
36 assert(errno == EINVAL);
38 ret = getrandom(buf, sizeof (buf), 0);
39 assert(ret >= 0);
41 ret = getrandom(buf, sizeof (buf), GRND_NONBLOCK);
42 assert(ret >= 0);
44 ret = getrandom(buf, sizeof (buf), GRND_RANDOM);
45 assert(ret >= 0);
47 ret = getrandom(buf, sizeof (buf), GRND_RANDOM | GRND_NONBLOCK);
48 assert(ret >= 0);
50 ret = getrandom(buf, sizeof (buf), (GRND_RANDOM | GRND_NONBLOCK) << 1);
51 assert(ret == -1);
52 assert(errno == EINVAL);
54 /* Bad buffer addresses, eg. EFAULT */
55 ret = getrandom(NULL, sizeof (buf), 0);
56 assert(ret == -1);
57 assert(errno == EFAULT);
59 ret = getrandom(NULL, sizeof (buf), GRND_RANDOM);
60 assert(ret == -1);
61 assert(errno == EFAULT);
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);
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));
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));
85 return (0);