1 //===-- Unittests for read and write --------------------------------------===//
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/fsync.h"
12 #include "src/unistd/read.h"
13 #include "src/unistd/write.h"
14 #include "test/ErrnoSetterMatcher.h"
15 #include "utils/UnitTest/Test.h"
16 #include "utils/testutils/FDReader.h"
17 
18 #include <errno.h>
19 
TEST(LlvmLibcUniStd,WriteAndReadBackTest)20 TEST(LlvmLibcUniStd, WriteAndReadBackTest) {
21   using __llvm_libc::testing::ErrnoSetterMatcher::Succeeds;
22   constexpr const char *TEST_FILE = "__unistd_read_write.test";
23   int write_fd = __llvm_libc::open(TEST_FILE, O_WRONLY | O_CREAT, S_IRWXU);
24   ASSERT_EQ(errno, 0);
25   ASSERT_GT(write_fd, 0);
26   constexpr const char HELLO[] = "hello";
27   constexpr int HELLO_SIZE = sizeof(HELLO);
28   ASSERT_THAT(__llvm_libc::write(write_fd, HELLO, HELLO_SIZE),
29               Succeeds(HELLO_SIZE));
30   ASSERT_THAT(__llvm_libc::fsync(write_fd), Succeeds(0));
31   ASSERT_THAT(__llvm_libc::close(write_fd), Succeeds(0));
32 
33   int read_fd = __llvm_libc::open(TEST_FILE, O_RDONLY);
34   ASSERT_EQ(errno, 0);
35   ASSERT_GT(read_fd, 0);
36   char read_buf[10];
37   ASSERT_THAT(__llvm_libc::read(read_fd, read_buf, HELLO_SIZE),
38               Succeeds(HELLO_SIZE));
39   EXPECT_STREQ(read_buf, HELLO);
40   ASSERT_THAT(__llvm_libc::close(read_fd), Succeeds(0));
41 
42   // TODO: 'remove' the test file after the test.
43 }
44 
TEST(LlvmLibcUniStd,WriteFails)45 TEST(LlvmLibcUniStd, WriteFails) {
46   using __llvm_libc::testing::ErrnoSetterMatcher::Fails;
47 
48   EXPECT_THAT(__llvm_libc::write(-1, "", 1), Fails(EBADF));
49   EXPECT_THAT(__llvm_libc::write(1, reinterpret_cast<const void *>(-1), 1),
50               Fails(EFAULT));
51 }
52 
TEST(LlvmLibcUniStd,ReadFails)53 TEST(LlvmLibcUniStd, ReadFails) {
54   using __llvm_libc::testing::ErrnoSetterMatcher::Fails;
55 
56   EXPECT_THAT(__llvm_libc::read(-1, nullptr, 1), Fails(EBADF));
57   EXPECT_THAT(__llvm_libc::read(0, reinterpret_cast<void *>(-1), 1),
58               Fails(EFAULT));
59 }
60