1 //===-- Unittests for pread and pwrite ------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "src/errno/libc_errno.h"
10 #include "src/fcntl/open.h"
11 #include "src/unistd/close.h"
12 #include "src/unistd/fsync.h"
13 #include "src/unistd/pread.h"
14 #include "src/unistd/pwrite.h"
15 #include "src/unistd/unlink.h"
16 #include "src/unistd/write.h"
17 #include "test/UnitTest/ErrnoSetterMatcher.h"
18 #include "test/UnitTest/Test.h"
22 TEST(LlvmLibcUniStd
, PWriteAndPReadBackTest
) {
23 // The strategy here is that we first create a file and write to it. Next,
24 // we open that file again and write at an offset. Finally, we open the
25 // file again and pread at an offset and make sure that only expected data
26 // is being read back. This also confirms that pwrite happened successfully.
27 constexpr const char HELLO
[] = "hello";
28 constexpr int HELLO_SIZE
= sizeof(HELLO
);
29 constexpr off_t OFFSET
= 3;
30 constexpr const char OFFSET_TEXT
[] = "helhello";
31 constexpr int OFFSET_TEXT_SIZE
= sizeof(OFFSET_TEXT
);
33 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds
;
35 constexpr const char *FILENAME
= "pread_pwrite.test";
36 auto TEST_FILE
= libc_make_test_file_path(FILENAME
);
37 int fd
= LIBC_NAMESPACE::open(TEST_FILE
, O_WRONLY
| O_CREAT
, S_IRWXU
);
38 ASSERT_ERRNO_SUCCESS();
40 ASSERT_THAT(LIBC_NAMESPACE::write(fd
, HELLO
, HELLO_SIZE
),
41 Succeeds(HELLO_SIZE
));
42 ASSERT_THAT(LIBC_NAMESPACE::fsync(fd
), Succeeds(0));
43 ASSERT_THAT(LIBC_NAMESPACE::close(fd
), Succeeds(0));
45 fd
= LIBC_NAMESPACE::open(TEST_FILE
, O_WRONLY
);
46 ASSERT_ERRNO_SUCCESS();
48 ASSERT_THAT(LIBC_NAMESPACE::pwrite(fd
, HELLO
, HELLO_SIZE
, OFFSET
),
49 Succeeds(HELLO_SIZE
));
50 ASSERT_THAT(LIBC_NAMESPACE::fsync(fd
), Succeeds(0));
51 ASSERT_THAT(LIBC_NAMESPACE::close(fd
), Succeeds(0));
53 fd
= LIBC_NAMESPACE::open(TEST_FILE
, O_RDONLY
);
54 ASSERT_ERRNO_SUCCESS();
56 char read_buf
[OFFSET_TEXT_SIZE
];
57 ASSERT_THAT(LIBC_NAMESPACE::pread(fd
, read_buf
, HELLO_SIZE
, OFFSET
),
58 Succeeds(HELLO_SIZE
));
59 EXPECT_STREQ(read_buf
, HELLO
);
60 ASSERT_THAT(LIBC_NAMESPACE::pread(fd
, read_buf
, OFFSET_TEXT_SIZE
, 0),
61 Succeeds(OFFSET_TEXT_SIZE
));
62 EXPECT_STREQ(read_buf
, OFFSET_TEXT
);
63 ASSERT_THAT(LIBC_NAMESPACE::close(fd
), Succeeds(0));
65 ASSERT_THAT(LIBC_NAMESPACE::unlink(TEST_FILE
), Succeeds(0));
68 TEST(LlvmLibcUniStd
, PWriteFails
) {
69 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails
;
70 EXPECT_THAT(LIBC_NAMESPACE::pwrite(-1, "", 1, 0), Fails(EBADF
));
73 TEST(LlvmLibcUniStd
, PReadFails
) {
74 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails
;
75 EXPECT_THAT(LIBC_NAMESPACE::pread(-1, nullptr, 1, 0), Fails(EBADF
));