1//===-- Unittests for msync -----------------------------------------------===//
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/sys/mman/mlock.h"
11#include "src/sys/mman/mmap.h"
12#include "src/sys/mman/msync.h"
13#include "src/sys/mman/munlock.h"
14#include "src/sys/mman/munmap.h"
15#include "src/unistd/sysconf.h"
16#include "test/UnitTest/ErrnoSetterMatcher.h"
17#include "test/UnitTest/LibcTest.h"
18#include "test/UnitTest/Test.h"
19
20using namespace LIBC_NAMESPACE::testing::ErrnoSetterMatcher;
21
22struct PageHolder {
23 size_t size;
24 void *addr;
25
26 PageHolder()
27 : size(LIBC_NAMESPACE::sysconf(_SC_PAGESIZE)),
28 addr(LIBC_NAMESPACE::mmap(addr: nullptr, size, PROT_READ | PROT_WRITE,
29 MAP_ANONYMOUS | MAP_PRIVATE, fd: -1, offset: 0)) {}
30 ~PageHolder() {
31 if (addr != MAP_FAILED)
32 LIBC_NAMESPACE::munmap(addr, size);
33 }
34
35 char &operator[](size_t i) { return reinterpret_cast<char *>(addr)[i]; }
36
37 bool is_valid() { return addr != MAP_FAILED; }
38};
39
40TEST(LlvmLibcMsyncTest, UnMappedMemory) {
41 EXPECT_THAT(LIBC_NAMESPACE::msync(nullptr, 1024, MS_SYNC), Fails(ENOMEM));
42 EXPECT_THAT(LIBC_NAMESPACE::msync(nullptr, 1024, MS_ASYNC), Fails(ENOMEM));
43}
44
45TEST(LlvmLibcMsyncTest, LockedPage) {
46 PageHolder page;
47 ASSERT_TRUE(page.is_valid());
48 ASSERT_THAT(LIBC_NAMESPACE::mlock(page.addr, page.size), Succeeds());
49 EXPECT_THAT(
50 LIBC_NAMESPACE::msync(page.addr, page.size, MS_SYNC | MS_INVALIDATE),
51 Fails(EBUSY));
52 ASSERT_THAT(LIBC_NAMESPACE::munlock(page.addr, page.size), Succeeds());
53 EXPECT_THAT(LIBC_NAMESPACE::msync(page.addr, page.size, MS_SYNC), Succeeds());
54}
55
56TEST(LlvmLibcMsyncTest, UnalignedAddress) {
57 PageHolder page;
58 ASSERT_TRUE(page.is_valid());
59 EXPECT_THAT(LIBC_NAMESPACE::msync(&page[1], page.size - 1, MS_SYNC),
60 Fails(EINVAL));
61}
62
63TEST(LlvmLibcMsyncTest, InvalidFlag) {
64 PageHolder page;
65 ASSERT_TRUE(page.is_valid());
66 EXPECT_THAT(LIBC_NAMESPACE::msync(page.addr, page.size, MS_SYNC | MS_ASYNC),
67 Fails(EINVAL));
68 EXPECT_THAT(LIBC_NAMESPACE::msync(page.addr, page.size, -1), Fails(EINVAL));
69}
70

source code of libc/test/src/sys/mman/linux/msync_test.cpp