1 | //===-- Unittests for fchmodat --------------------------------------------===// |
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/fcntl/open.h" |
10 | #include "src/sys/stat/fchmodat.h" |
11 | #include "src/unistd/close.h" |
12 | #include "src/unistd/write.h" |
13 | #include "test/UnitTest/ErrnoCheckingTest.h" |
14 | #include "test/UnitTest/ErrnoSetterMatcher.h" |
15 | #include "test/UnitTest/Test.h" |
16 | |
17 | #include "hdr/fcntl_macros.h" |
18 | #include <sys/stat.h> |
19 | |
20 | using namespace LIBC_NAMESPACE::testing::ErrnoSetterMatcher; |
21 | using LlvmLibcFchmodatTest = LIBC_NAMESPACE::testing::ErrnoCheckingTest; |
22 | |
23 | TEST_F(LlvmLibcFchmodatTest, ChangeAndOpen) { |
24 | // The test file is initially writable. We open it for writing and ensure |
25 | // that it indeed can be opened for writing. Next, we close the file and |
26 | // make it readonly using chmod. We test that chmod actually succeeded by |
27 | // trying to open the file for writing and failing. |
28 | constexpr const char *TEST_FILE = "testdata/fchmodat.test" ; |
29 | constexpr const char *TEST_DIR = "testdata" ; |
30 | constexpr const char *TEST_FILE_BASENAME = "fchmodat.test" ; |
31 | const char WRITE_DATA[] = "fchmodat test" ; |
32 | constexpr ssize_t WRITE_SIZE = ssize_t(sizeof(WRITE_DATA)); |
33 | |
34 | int fd = LIBC_NAMESPACE::open(TEST_FILE, O_CREAT | O_WRONLY, S_IRWXU); |
35 | ASSERT_GT(fd, 0); |
36 | ASSERT_ERRNO_SUCCESS(); |
37 | ASSERT_EQ(LIBC_NAMESPACE::write(fd, WRITE_DATA, sizeof(WRITE_DATA)), |
38 | WRITE_SIZE); |
39 | ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0)); |
40 | |
41 | int dirfd = LIBC_NAMESPACE::open(TEST_DIR, O_DIRECTORY); |
42 | ASSERT_GT(dirfd, 0); |
43 | ASSERT_ERRNO_SUCCESS(); |
44 | |
45 | EXPECT_THAT(LIBC_NAMESPACE::fchmodat(dirfd, TEST_FILE_BASENAME, S_IRUSR, 0), |
46 | Succeeds(0)); |
47 | |
48 | // Opening for writing should fail. |
49 | EXPECT_EQ(LIBC_NAMESPACE::open(TEST_FILE, O_APPEND | O_WRONLY), -1); |
50 | ASSERT_ERRNO_FAILURE(); |
51 | // But opening for reading should succeed. |
52 | fd = LIBC_NAMESPACE::open(TEST_FILE, O_APPEND | O_RDONLY); |
53 | EXPECT_GT(fd, 0); |
54 | ASSERT_ERRNO_SUCCESS(); |
55 | |
56 | EXPECT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0)); |
57 | EXPECT_THAT(LIBC_NAMESPACE::fchmodat(dirfd, TEST_FILE_BASENAME, S_IRWXU, 0), |
58 | Succeeds(0)); |
59 | |
60 | EXPECT_THAT(LIBC_NAMESPACE::close(dirfd), Succeeds(0)); |
61 | } |
62 | |
63 | TEST_F(LlvmLibcFchmodatTest, NonExistentFile) { |
64 | ASSERT_THAT( |
65 | LIBC_NAMESPACE::fchmodat(AT_FDCWD, "non-existent-file" , S_IRUSR, 0), |
66 | Fails(ENOENT)); |
67 | } |
68 | |