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

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