brintos

brintos / llvm-project-archived public Read only

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