Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / libc / test / src / unistd / dup3_test.cpp
blob279cfbfea1b144be6a3b1e0bcd3f8b28d2cc8f02
1 //===-- Unittests for dup3 ------------------------------------------------===//
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 //===----------------------------------------------------------------------===//
9 #include "src/errno/libc_errno.h"
10 #include "src/fcntl/open.h"
11 #include "src/unistd/close.h"
12 #include "src/unistd/dup3.h"
13 #include "src/unistd/read.h"
14 #include "src/unistd/unlink.h"
15 #include "src/unistd/write.h"
16 #include "test/UnitTest/ErrnoSetterMatcher.h"
17 #include "test/UnitTest/Test.h"
19 // The tests here are exactly the same as those of dup2. We only test the
20 // plumbing of the dup3 syscall and not the dup3 functionality itself as it is
21 // a simple syscall wrapper. Testing dup3 functionality is beyond the scope of
22 // this test.
24 TEST(LlvmLibcdupTest, ReadAndWriteViaDup) {
25 constexpr int DUPFD = 0xD0;
26 libc_errno = 0;
27 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
28 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
29 constexpr const char *TEST_FILE = "testdata/dup3.test";
30 int fd = LIBC_NAMESPACE::open(TEST_FILE, O_WRONLY | O_CREAT, S_IRWXU);
31 ASSERT_EQ(libc_errno, 0);
32 ASSERT_GT(fd, 0);
33 int dupfd = LIBC_NAMESPACE::dup3(fd, DUPFD, 0);
34 ASSERT_EQ(libc_errno, 0);
35 ASSERT_EQ(dupfd, DUPFD);
37 // Write something via the dup
38 constexpr char WRITE_DATA[] = "Hello, dup!";
39 constexpr size_t WRITE_SIZE = sizeof(WRITE_DATA);
40 ASSERT_EQ(ssize_t(WRITE_SIZE),
41 LIBC_NAMESPACE::write(dupfd, WRITE_DATA, WRITE_SIZE));
42 ASSERT_THAT(LIBC_NAMESPACE::close(dupfd), Succeeds(0));
44 // Reopen the file for reading and create a dup.
45 fd = LIBC_NAMESPACE::open(TEST_FILE, O_RDONLY);
46 ASSERT_EQ(libc_errno, 0);
47 ASSERT_GT(fd, 0);
48 dupfd = LIBC_NAMESPACE::dup3(fd, DUPFD, 0);
49 ASSERT_EQ(libc_errno, 0);
50 ASSERT_EQ(dupfd, DUPFD);
52 // Read the file content via the dup.
53 char buf[WRITE_SIZE];
54 ASSERT_THAT(LIBC_NAMESPACE::read(dupfd, buf, WRITE_SIZE),
55 Succeeds(WRITE_SIZE));
56 ASSERT_STREQ(buf, WRITE_DATA);
58 // Verify that, unlike dup2, duping to the same fd value with dup3 fails.
59 ASSERT_THAT(LIBC_NAMESPACE::dup3(dupfd, dupfd, 0), Fails(EINVAL));
61 ASSERT_THAT(LIBC_NAMESPACE::close(dupfd), Succeeds(0));
62 ASSERT_THAT(LIBC_NAMESPACE::unlink(TEST_FILE), Succeeds(0));
65 TEST(LlvmLibcdupTest, DupBadFD) {
66 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
67 ASSERT_THAT(LIBC_NAMESPACE::dup3(-1, 123, 0), Fails(EBADF));