| 1 | //===-- Unittests for dup -------------------------------------------------===// |
| 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/unistd/close.h" |
| 11 | #include "src/unistd/dup.h" |
| 12 | #include "src/unistd/read.h" |
| 13 | #include "src/unistd/unlink.h" |
| 14 | #include "src/unistd/write.h" |
| 15 | #include "test/UnitTest/ErrnoCheckingTest.h" |
| 16 | #include "test/UnitTest/ErrnoSetterMatcher.h" |
| 17 | #include "test/UnitTest/Test.h" |
| 18 | |
| 19 | #include <sys/stat.h> |
| 20 | |
| 21 | using LlvmLibcdupTest = LIBC_NAMESPACE::testing::ErrnoCheckingTest; |
| 22 | |
| 23 | TEST_F(LlvmLibcdupTest, ReadAndWriteViaDup) { |
| 24 | using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds; |
| 25 | constexpr const char *FILENAME = "dup.test" ; |
| 26 | auto TEST_FILE = libc_make_test_file_path(FILENAME); |
| 27 | int fd = LIBC_NAMESPACE::open(TEST_FILE, O_WRONLY | O_CREAT, S_IRWXU); |
| 28 | ASSERT_ERRNO_SUCCESS(); |
| 29 | ASSERT_GT(fd, 0); |
| 30 | int dupfd = LIBC_NAMESPACE::dup(fd); |
| 31 | ASSERT_ERRNO_SUCCESS(); |
| 32 | ASSERT_GT(dupfd, 0); |
| 33 | |
| 34 | // Write something via the dup |
| 35 | constexpr char WRITE_DATA[] = "Hello, dup!" ; |
| 36 | constexpr size_t WRITE_SIZE = sizeof(WRITE_DATA); |
| 37 | ASSERT_EQ(ssize_t(WRITE_SIZE), |
| 38 | LIBC_NAMESPACE::write(dupfd, WRITE_DATA, WRITE_SIZE)); |
| 39 | ASSERT_THAT(LIBC_NAMESPACE::close(dupfd), Succeeds(0)); |
| 40 | |
| 41 | // Reopen the file for reading and create a dup. |
| 42 | fd = LIBC_NAMESPACE::open(TEST_FILE, O_RDONLY); |
| 43 | ASSERT_ERRNO_SUCCESS(); |
| 44 | ASSERT_GT(fd, 0); |
| 45 | dupfd = LIBC_NAMESPACE::dup(fd); |
| 46 | ASSERT_ERRNO_SUCCESS(); |
| 47 | ASSERT_GT(dupfd, 0); |
| 48 | |
| 49 | // Read the file content via the dup. |
| 50 | char buf[WRITE_SIZE]; |
| 51 | ASSERT_THAT(LIBC_NAMESPACE::read(dupfd, buf, WRITE_SIZE), |
| 52 | Succeeds(WRITE_SIZE)); |
| 53 | ASSERT_STREQ(buf, WRITE_DATA); |
| 54 | |
| 55 | ASSERT_THAT(LIBC_NAMESPACE::close(dupfd), Succeeds(0)); |
| 56 | ASSERT_THAT(LIBC_NAMESPACE::unlink(TEST_FILE), Succeeds(0)); |
| 57 | } |
| 58 | |
| 59 | TEST_F(LlvmLibcdupTest, DupBadFD) { |
| 60 | using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails; |
| 61 | ASSERT_THAT(LIBC_NAMESPACE::dup(-1), Fails(EBADF)); |
| 62 | } |
| 63 | |