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 "include/errno.h" 10 #include "include/sys/mman.h" 11 #include "src/errno/llvmlibc_errno.h" 12 #include "src/sys/mman/mmap.h" 13 #include "src/sys/mman/munmap.h" 14 #include "test/ErrnoSetterMatcher.h" 15 #include "utils/UnitTest/Test.h" 16 17 using __llvm_libc::testing::ErrnoSetterMatcher::Fails; 18 using __llvm_libc::testing::ErrnoSetterMatcher::Succeeds; 19 20 TEST(LlvmLibcMMapTest, NoError) { 21 size_t alloc_size = 128; 22 llvmlibc_errno = 0; 23 void *addr = __llvm_libc::mmap(nullptr, alloc_size, PROT_READ, 24 MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); 25 EXPECT_EQ(0, llvmlibc_errno); 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(__llvm_libc::munmap(addr, alloc_size), Succeeds()); 34 } 35 36 TEST(LlvmLibcMMapTest, Error_InvalidSize) { 37 llvmlibc_errno = 0; 38 void *addr = __llvm_libc::mmap(nullptr, 0, PROT_READ, 39 MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); 40 EXPECT_THAT(addr, Fails(EINVAL, MAP_FAILED)); 41 42 EXPECT_THAT(__llvm_libc::munmap(0, 0), Fails(EINVAL)); 43 } 44