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 "utils/UnitTest/Test.h" 15 16 TEST(MMapTest, NoError) { 17 size_t alloc_size = 128; 18 llvmlibc_errno = 0; 19 void *addr = __llvm_libc::mmap(nullptr, alloc_size, PROT_READ, 20 MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); 21 EXPECT_EQ(0, llvmlibc_errno); 22 EXPECT_NE(addr, MAP_FAILED); 23 24 int *array = reinterpret_cast<int *>(addr); 25 // Reading from the memory should not crash the test. 26 // Since we used the MAP_ANONYMOUS flag, the contents of the newly 27 // allocated memory should be initialized to zero. 28 EXPECT_EQ(array[0], 0); 29 30 int ret_val = __llvm_libc::munmap(addr, alloc_size); 31 EXPECT_EQ(0, ret_val); 32 EXPECT_EQ(0, llvmlibc_errno); 33 } 34 35 TEST(MMapTest, Error_InvalidSize) { 36 llvmlibc_errno = 0; 37 void *addr = __llvm_libc::mmap(nullptr, 0, PROT_READ, 38 MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); 39 EXPECT_EQ(EINVAL, llvmlibc_errno); 40 EXPECT_EQ(addr, MAP_FAILED); 41 42 llvmlibc_errno = 0; 43 int ret_val = __llvm_libc::munmap(0, 0); 44 EXPECT_EQ(-1, ret_val); 45 EXPECT_EQ(EINVAL, llvmlibc_errno); 46 } 47