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/errno/libc_errno.h" |
10 | #include "src/sys/mman/mmap.h" |
11 | #include "src/sys/mman/munmap.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 | |
20 | TEST(LlvmLibcMMapTest, NoError) { |
21 | size_t alloc_size = 128; |
22 | LIBC_NAMESPACE::libc_errno = 0; |
23 | void *addr = LIBC_NAMESPACE::mmap(addr: nullptr, size: alloc_size, PROT_READ, |
24 | MAP_ANONYMOUS | MAP_PRIVATE, fd: -1, offset: 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(LlvmLibcMMapTest, Error_InvalidSize) { |
37 | LIBC_NAMESPACE::libc_errno = 0; |
38 | void *addr = LIBC_NAMESPACE::mmap(addr: nullptr, size: 0, PROT_READ, |
39 | MAP_ANONYMOUS | MAP_PRIVATE, fd: -1, offset: 0); |
40 | EXPECT_THAT(addr, Fails(EINVAL, MAP_FAILED)); |
41 | |
42 | EXPECT_THAT(LIBC_NAMESPACE::munmap(0, 0), Fails(EINVAL)); |
43 | } |
44 | |