| 1 | //===-- Unittests for mmap and munmap -------------------------------------===// |
| 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/munmap.h" |
| 11 | #include "test/UnitTest/ErrnoCheckingTest.h" |
| 12 | #include "test/UnitTest/ErrnoSetterMatcher.h" |
| 13 | #include "test/UnitTest/Test.h" |
| 14 | |
| 15 | #include <sys/mman.h> |
| 16 | |
| 17 | using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails; |
| 18 | using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds; |
| 19 | using LlvmLibcMMapTest = LIBC_NAMESPACE::testing::ErrnoCheckingTest; |
| 20 | |
| 21 | TEST_F(LlvmLibcMMapTest, NoError) { |
| 22 | size_t alloc_size = 128; |
| 23 | void *addr = LIBC_NAMESPACE::mmap(nullptr, alloc_size, PROT_READ, |
| 24 | MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); |
| 25 | ASSERT_ERRNO_SUCCESS(); |
| 26 | EXPECT_NE(addr, MAP_FAILED); |
| 27 | |
| 28 | int *array = reinterpret_cast<int *>(addr); |
| 29 | // Reading from the memory should not crash the test. |
| 30 | // Since we used the MAP_ANONYMOUS flag, the contents of the newly |
| 31 | // allocated memory should be initialized to zero. |
| 32 | EXPECT_EQ(array[0], 0); |
| 33 | EXPECT_THAT(LIBC_NAMESPACE::munmap(addr, alloc_size), Succeeds()); |
| 34 | } |
| 35 | |
| 36 | TEST_F(LlvmLibcMMapTest, Error_InvalidSize) { |
| 37 | void *addr = LIBC_NAMESPACE::mmap(nullptr, 0, PROT_READ, |
| 38 | MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); |
| 39 | EXPECT_THAT(addr, Fails(EINVAL, MAP_FAILED)); |
| 40 | |
| 41 | EXPECT_THAT(LIBC_NAMESPACE::munmap(0, 0), Fails(EINVAL)); |
| 42 | } |
| 43 | |