1 //===-- Unittests for getrlimit and setrlimit -----------------------------===//
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/string_view.h"
10 #include "src/errno/libc_errno.h"
11 #include "src/fcntl/open.h"
12 #include "src/sys/resource/getrlimit.h"
13 #include "src/sys/resource/setrlimit.h"
14 #include "src/unistd/close.h"
15 #include "src/unistd/unlink.h"
16 #include "test/UnitTest/ErrnoSetterMatcher.h"
17 #include "test/UnitTest/Test.h"
19 #include <sys/resource.h>
21 TEST(LlvmLibcResourceLimitsTest
, SetNoFileLimit
) {
22 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails
;
23 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds
;
25 // The test strategy is to first create initialize two file descriptors
26 // successfully. Next, close the files and set the file descriptor limit
27 // to 4. This will allow us to open one of those file but not the other.
29 constexpr const char *TEST_FILE1
= "testdata/resource_limits1.test";
30 constexpr const char *TEST_FILE2
= "testdata/resource_limits2.test";
33 int fd1
= LIBC_NAMESPACE::open(TEST_FILE1
, O_CREAT
| O_WRONLY
, S_IRWXU
);
35 ASSERT_EQ(libc_errno
, 0);
36 int fd2
= LIBC_NAMESPACE::open(TEST_FILE2
, O_CREAT
| O_WRONLY
, S_IRWXU
);
38 ASSERT_EQ(libc_errno
, 0);
40 ASSERT_THAT(LIBC_NAMESPACE::close(fd1
), Succeeds(0));
41 ASSERT_THAT(LIBC_NAMESPACE::close(fd2
), Succeeds(0));
43 struct rlimit limits
{
46 ASSERT_THAT(LIBC_NAMESPACE::setrlimit(RLIMIT_NOFILE
, &limits
), Succeeds(0));
48 // One can now only open one of the files successfully.
49 fd1
= LIBC_NAMESPACE::open(TEST_FILE1
, O_RDONLY
);
51 ASSERT_EQ(libc_errno
, 0);
52 fd2
= LIBC_NAMESPACE::open(TEST_FILE2
, O_RDONLY
);
54 ASSERT_NE(libc_errno
, 0);
57 ASSERT_THAT(LIBC_NAMESPACE::close(fd1
), Succeeds(0));
59 fd2
= LIBC_NAMESPACE::open(TEST_FILE2
, O_RDONLY
);
61 ASSERT_EQ(libc_errno
, 0);
62 fd1
= LIBC_NAMESPACE::open(TEST_FILE1
, O_RDONLY
);
64 ASSERT_NE(libc_errno
, 0);
67 ASSERT_THAT(LIBC_NAMESPACE::close(fd2
), Succeeds(0));
69 ASSERT_THAT(LIBC_NAMESPACE::unlink(TEST_FILE1
), Succeeds(0));
70 ASSERT_THAT(LIBC_NAMESPACE::unlink(TEST_FILE2
), Succeeds(0));
72 struct rlimit current_limits
;
73 ASSERT_THAT(LIBC_NAMESPACE::getrlimit(RLIMIT_NOFILE
, ¤t_limits
),
75 ASSERT_EQ(current_limits
.rlim_cur
, rlim_t(4));
76 ASSERT_EQ(current_limits
.rlim_max
, rlim_t(4));