1 //===-- Unittests for getrandom -------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
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"
16 TEST(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
));
23 TEST(LlvmLibcGetRandomTest
, InvalidBuffer
) {
24 LIBC_NAMESPACE::libc_errno
= 0;
25 ASSERT_THAT(LIBC_NAMESPACE::getrandom(nullptr, 65536, 0),
26 LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails(EFAULT
));
29 TEST(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
));
38 TEST(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
;
43 for (char &c
: buffer
)
46 LIBC_NAMESPACE::getrandom(buffer
.data(), buffer
.size(), 0);
48 bool all_zeros
= true;
53 ASSERT_FALSE(all_zeros
);