|
| 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/errno/libc_errno.h" |
| 10 | +#include "src/sys/mman/mmap.h" |
| 11 | +#include "src/sys/mman/mremap.h" |
| 12 | +#include "src/sys/mman/munmap.h" |
| 13 | +#include "test/UnitTest/ErrnoSetterMatcher.h" |
| 14 | +#include "test/UnitTest/Test.h" |
| 15 | + |
| 16 | +#include <sys/mman.h> |
| 17 | + |
| 18 | +using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails; |
| 19 | +using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds; |
| 20 | + |
| 21 | +TEST(LlvmLibcMremapTest, NoError) { |
| 22 | + size_t initial_size = 128; |
| 23 | + size_t new_size = 256; |
| 24 | + LIBC_NAMESPACE::libc_errno = 0; |
| 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 | + |
| 50 | +TEST(LlvmLibcMremapTest, Error_InvalidSize) { |
| 51 | + size_t initial_size = 128; |
| 52 | + LIBC_NAMESPACE::libc_errno = 0; |
| 53 | + |
| 54 | + // Allocate memory using mmap. |
| 55 | + void *addr = |
| 56 | + LIBC_NAMESPACE::mmap(nullptr, initial_size, PROT_READ | PROT_WRITE, |
| 57 | + MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); |
| 58 | + ASSERT_ERRNO_SUCCESS(); |
| 59 | + EXPECT_NE(addr, MAP_FAILED); |
| 60 | + |
| 61 | + // Attempt to re-map the memory with an invalid new size (0). |
| 62 | + void *new_addr = |
| 63 | + LIBC_NAMESPACE::mremap(addr, initial_size, 0, MREMAP_MAYMOVE); |
| 64 | + EXPECT_THAT(new_addr, Fails(EINVAL, MAP_FAILED)); |
| 65 | + |
| 66 | + // Clean up the original mapping. |
| 67 | + EXPECT_THAT(LIBC_NAMESPACE::munmap(addr, initial_size), Succeeds()); |
| 68 | +} |
0 commit comments