1//===-- Unittests for linkat ----------------------------------------------===//
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/unistd/close.h"
12#include "src/unistd/linkat.h"
13#include "src/unistd/unlink.h"
14#include "test/UnitTest/ErrnoSetterMatcher.h"
15#include "test/UnitTest/Test.h"
16
17#include <sys/stat.h>
18
19TEST(LlvmLibcLinkatTest, CreateAndUnlink) {
20 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
21 constexpr const char *FILENAME = "testdata";
22 auto TEST_DIR = libc_make_test_file_path(FILENAME);
23 constexpr const char *FILENAME2 = "linkat.test";
24 auto TEST_FILE = libc_make_test_file_path(FILENAME2);
25 constexpr const char *FILENAME3 = "testdata/linkat.test";
26 auto TEST_FILE_PATH = libc_make_test_file_path(FILENAME3);
27 constexpr const char *FILENAME4 = "linkat.test.link";
28 auto TEST_FILE_LINK = libc_make_test_file_path(FILENAME4);
29 constexpr const char *FILENAME5 = "testdata/linkat.test.link";
30 auto TEST_FILE_LINK_PATH = libc_make_test_file_path(FILENAME5);
31
32 // The test strategy is as follows:
33 // 1. Create a normal file
34 // 2. Create a link to that file.
35 // 3. Open the link to check that the link was created.
36 // 4. Cleanup the file and its link.
37 LIBC_NAMESPACE::libc_errno = 0;
38 int write_fd =
39 LIBC_NAMESPACE::open(path: TEST_FILE_PATH, O_WRONLY | O_CREAT, S_IRWXU);
40 ASSERT_ERRNO_SUCCESS();
41 ASSERT_GT(write_fd, 0);
42 ASSERT_THAT(LIBC_NAMESPACE::close(write_fd), Succeeds(0));
43
44 int dir_fd = LIBC_NAMESPACE::open(path: TEST_DIR, O_DIRECTORY);
45 ASSERT_THAT(
46 LIBC_NAMESPACE::linkat(dir_fd, TEST_FILE, dir_fd, TEST_FILE_LINK, 0),
47 Succeeds(0));
48
49 int link_fd = LIBC_NAMESPACE::open(path: TEST_FILE_LINK_PATH, O_PATH);
50 ASSERT_GT(link_fd, 0);
51 ASSERT_ERRNO_SUCCESS();
52 ASSERT_THAT(LIBC_NAMESPACE::close(link_fd), Succeeds(0));
53
54 ASSERT_THAT(LIBC_NAMESPACE::unlink(TEST_FILE_PATH), Succeeds(0));
55 ASSERT_THAT(LIBC_NAMESPACE::unlink(TEST_FILE_LINK_PATH), Succeeds(0));
56 ASSERT_THAT(LIBC_NAMESPACE::close(dir_fd), Succeeds(0));
57}
58
59TEST(LlvmLibcLinkatTest, LinkToNonExistentFile) {
60 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
61 ASSERT_THAT(LIBC_NAMESPACE::linkat(AT_FDCWD, "testdata/non-existent-file",
62 AT_FDCWD, "testdata/bad-link", 0),
63 Fails(ENOENT));
64}
65

source code of libc/test/src/unistd/linkat_test.cpp