1 //===---------- Linux implementation of the POSIX mmap function -----------===// 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 11 #include "config/linux/syscall.h" // For internal syscall function. 12 #include "include/sys/syscall.h" // For syscall numbers. 13 #include "src/__support/common.h" 14 #include "src/errno/llvmlibc_errno.h" 15 16 #include <linux/param.h> // For EXEC_PAGESIZE. 17 18 namespace __llvm_libc { 19 20 // This function is currently linux only. It has to be refactored suitably if 21 // mmap is to be supported on non-linux operating systems also. 22 void *LLVM_LIBC_ENTRYPOINT(mmap)(void *addr, size_t size, int prot, int flags, 23 int fd, off_t offset) { 24 // A lot of POSIX standard prescribed validation of the parameters is not 25 // done in this function as modern linux versions do it in the syscall. 26 // TODO: Perform argument validation not done by the linux syscall. 27 28 // EXEC_PAGESIZE is used for the page size. While this is OK for x86_64, it 29 // might not be correct in general. 30 // TODO: Use pagesize read from the ELF aux vector instead of EXEC_PAGESIZE. 31 32 #ifdef SYS_mmap2 33 offset /= EXEC_PAGESIZE; 34 long syscall_number = SYS_mmap2; 35 #elif SYS_mmap 36 long syscall_number = SYS_mmap; 37 #else 38 #error "Target platform does not have SYS_mmap or SYS_mmap2 defined" 39 #endif 40 41 long ret_val = 42 __llvm_libc::syscall(syscall_number, reinterpret_cast<long>(addr), size, 43 prot, flags, fd, offset); 44 45 // The mmap/mmap2 syscalls return negative values on error. These negative 46 // values are actually the negative values of the error codes. So, fix them 47 // up in case an error code is detected. 48 // 49 // A point to keep in mind for the fix up is that a negative return value 50 // from the syscall can also be an error-free value returned by the syscall. 51 // However, since a valid return address cannot be within the last page, a 52 // return value corresponding to a location in the last page is an error 53 // value. 54 if (ret_val < 0 && ret_val > -EXEC_PAGESIZE) { 55 llvmlibc_errno = -ret_val; 56 return MAP_FAILED; 57 } 58 59 return reinterpret_cast<void *>(ret_val); 60 } 61 62 } // namespace __llvm_libc 63