1//===-- Unittests for mremap ----------------------------------------------===//
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/sys/mman/mmap.h"
10#include "src/sys/mman/mremap.h"
11#include "src/sys/mman/munmap.h"
12#include "test/UnitTest/ErrnoCheckingTest.h"
13#include "test/UnitTest/ErrnoSetterMatcher.h"
14#include "test/UnitTest/Test.h"
15
16#include <sys/mman.h>
17
18using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
19using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
20using LlvmLibcMremapTest = LIBC_NAMESPACE::testing::ErrnoCheckingTest;
21
22TEST_F(LlvmLibcMremapTest, NoError) {
23 size_t initial_size = 128;
24 size_t new_size = 256;
25
26 // Allocate memory using mmap.
27 void *addr =
28 LIBC_NAMESPACE::mmap(nullptr, initial_size, PROT_READ | PROT_WRITE,
29 MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
30 ASSERT_ERRNO_SUCCESS();
31 EXPECT_NE(addr, MAP_FAILED);
32
33 int *array = reinterpret_cast<int *>(addr);
34 // Writing to the memory should not crash the test.
35 array[0] = 123;
36 EXPECT_EQ(array[0], 123);
37
38 // Re-map the memory using mremap with an increased size.
39 void *new_addr =
40 LIBC_NAMESPACE::mremap(addr, initial_size, new_size, MREMAP_MAYMOVE);
41 ASSERT_ERRNO_SUCCESS();
42 EXPECT_NE(new_addr, MAP_FAILED);
43 EXPECT_EQ(reinterpret_cast<int *>(new_addr)[0],
44 123); // Verify data is preserved.
45
46 // Clean up memory by unmapping it.
47 EXPECT_THAT(LIBC_NAMESPACE::munmap(new_addr, new_size), Succeeds());
48}
49
50TEST_F(LlvmLibcMremapTest, Error_InvalidSize) {
51 size_t initial_size = 128;
52
53 // Allocate memory using mmap.
54 void *addr =
55 LIBC_NAMESPACE::mmap(nullptr, initial_size, PROT_READ | PROT_WRITE,
56 MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
57 ASSERT_ERRNO_SUCCESS();
58 EXPECT_NE(addr, MAP_FAILED);
59
60 // Attempt to re-map the memory with an invalid new size (0).
61 void *new_addr =
62 LIBC_NAMESPACE::mremap(addr, initial_size, 0, MREMAP_MAYMOVE);
63 EXPECT_THAT(new_addr, Fails(EINVAL, MAP_FAILED));
64
65 // Clean up the original mapping.
66 EXPECT_THAT(LIBC_NAMESPACE::munmap(addr, initial_size), Succeeds());
67}
68

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