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/errno/libc_errno.h"
10#include "src/fcntl/open.h"
11#include "src/sys/stat/fchmodat.h"
12#include "src/unistd/close.h"
13#include "src/unistd/write.h"
14#include "test/UnitTest/ErrnoSetterMatcher.h"
15#include "test/UnitTest/Test.h"
16
17#include <fcntl.h>
18#include <sys/stat.h>
19
20TEST(LlvmLibcFchmodatTest, ChangeAndOpen) {
21 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
22 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
23
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 LIBC_NAMESPACE::libc_errno = 0;
34
35 int fd = LIBC_NAMESPACE::open(path: TEST_FILE, O_CREAT | O_WRONLY, S_IRWXU);
36 ASSERT_GT(fd, 0);
37 ASSERT_ERRNO_SUCCESS();
38 ASSERT_EQ(LIBC_NAMESPACE::write(fd, WRITE_DATA, sizeof(WRITE_DATA)),
39 WRITE_SIZE);
40 ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0));
41
42 int dirfd = LIBC_NAMESPACE::open(path: TEST_DIR, O_DIRECTORY);
43 ASSERT_GT(dirfd, 0);
44 ASSERT_ERRNO_SUCCESS();
45
46 EXPECT_THAT(LIBC_NAMESPACE::fchmodat(dirfd, TEST_FILE_BASENAME, S_IRUSR, 0),
47 Succeeds(0));
48
49 // Opening for writing should fail.
50 EXPECT_EQ(LIBC_NAMESPACE::open(TEST_FILE, O_APPEND | O_WRONLY), -1);
51 ASSERT_ERRNO_FAILURE();
52 LIBC_NAMESPACE::libc_errno = 0;
53 // But opening for reading should succeed.
54 fd = LIBC_NAMESPACE::open(path: TEST_FILE, O_APPEND | O_RDONLY);
55 EXPECT_GT(fd, 0);
56 ASSERT_ERRNO_SUCCESS();
57
58 EXPECT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0));
59 EXPECT_THAT(LIBC_NAMESPACE::fchmodat(dirfd, TEST_FILE_BASENAME, S_IRWXU, 0),
60 Succeeds(0));
61
62 EXPECT_THAT(LIBC_NAMESPACE::close(dirfd), Succeeds(0));
63}
64
65TEST(LlvmLibcFchmodatTest, NonExistentFile) {
66 LIBC_NAMESPACE::libc_errno = 0;
67 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
68 ASSERT_THAT(
69 LIBC_NAMESPACE::fchmodat(AT_FDCWD, "non-existent-file", S_IRUSR, 0),
70 Fails(ENOENT));
71 LIBC_NAMESPACE::libc_errno = 0;
72}
73

source code of libc/test/src/sys/stat/fchmodat_test.cpp