1//===-- Unittests for getrandom -------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "src/__support/CPP/array.h"
10#include "src/errno/libc_errno.h"
11#include "src/math/fabs.h"
12#include "src/sys/random/getrandom.h"
13#include "test/UnitTest/ErrnoSetterMatcher.h"
14#include "test/UnitTest/Test.h"
15
16TEST(LlvmLibcGetRandomTest, InvalidFlag) {
17 LIBC_NAMESPACE::cpp::array<char, 10> buffer;
18 LIBC_NAMESPACE::libc_errno = 0;
19 ASSERT_THAT(LIBC_NAMESPACE::getrandom(buffer.data(), buffer.size(), -1),
20 LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails(EINVAL));
21}
22
23TEST(LlvmLibcGetRandomTest, InvalidBuffer) {
24 LIBC_NAMESPACE::libc_errno = 0;
25 ASSERT_THAT(LIBC_NAMESPACE::getrandom(nullptr, 65536, 0),
26 LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails(EFAULT));
27}
28
29TEST(LlvmLibcGetRandomTest, ReturnsSize) {
30 LIBC_NAMESPACE::cpp::array<char, 10> buffer;
31 for (size_t i = 0; i < buffer.size(); ++i) {
32 // Without GRND_RANDOM set this should never fail.
33 ASSERT_EQ(LIBC_NAMESPACE::getrandom(buffer.data(), i, 0),
34 static_cast<ssize_t>(i));
35 }
36}
37
38TEST(LlvmLibcGetRandomTest, CheckValue) {
39 // Probability of picking one particular value amongst 256 possibilities a
40 // hundred times in a row is (1/256)^100 = 1.49969681e-241.
41 LIBC_NAMESPACE::cpp::array<char, 100> buffer;
42
43 for (char &c : buffer)
44 c = 0;
45
46 LIBC_NAMESPACE::getrandom(buf: buffer.data(), buflen: buffer.size(), flags: 0);
47
48 bool all_zeros = true;
49 for (char c : buffer)
50 if (c != 0)
51 all_zeros = false;
52
53 ASSERT_FALSE(all_zeros);
54}
55

source code of libc/test/src/sys/random/linux/getrandom_test.cpp