| 1 | //===-- enable_execute_stack.c - Implement __enable_execute_stack ---------===// |
| 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 "int_lib.h" |
| 10 | |
| 11 | #ifndef _WIN32 |
| 12 | #include <sys/mman.h> |
| 13 | #endif |
| 14 | |
| 15 | // #include "config.h" |
| 16 | // FIXME: CMake - include when cmake system is ready. |
| 17 | // Remove #define HAVE_SYSCONF 1 line. |
| 18 | #define HAVE_SYSCONF 1 |
| 19 | |
| 20 | #ifdef _WIN32 |
| 21 | #define WIN32_LEAN_AND_MEAN |
| 22 | #include <windows.h> |
| 23 | #else |
| 24 | #ifndef __APPLE__ |
| 25 | #include <unistd.h> |
| 26 | #endif // __APPLE__ |
| 27 | #endif // _WIN32 |
| 28 | |
| 29 | #if __LP64__ |
| 30 | #define TRAMPOLINE_SIZE 48 |
| 31 | #else |
| 32 | #define TRAMPOLINE_SIZE 40 |
| 33 | #endif |
| 34 | |
| 35 | // The compiler generates calls to __enable_execute_stack() when creating |
| 36 | // trampoline functions on the stack for use with nested functions. |
| 37 | // It is expected to mark the page(s) containing the address |
| 38 | // and the next 48 bytes as executable. Since the stack is normally rw- |
| 39 | // that means changing the protection on those page(s) to rwx. |
| 40 | |
| 41 | COMPILER_RT_ABI void __enable_execute_stack(void *addr) { |
| 42 | |
| 43 | #if _WIN32 |
| 44 | MEMORY_BASIC_INFORMATION mbi; |
| 45 | if (!VirtualQuery(addr, &mbi, sizeof(mbi))) |
| 46 | return; // We should probably assert here because there is no return value |
| 47 | VirtualProtect(mbi.BaseAddress, mbi.RegionSize, PAGE_EXECUTE_READWRITE, |
| 48 | &mbi.Protect); |
| 49 | #else |
| 50 | #if __APPLE__ |
| 51 | // On Darwin, pagesize is always 4096 bytes |
| 52 | const uintptr_t pageSize = 4096; |
| 53 | #elif !defined(HAVE_SYSCONF) |
| 54 | #error "HAVE_SYSCONF not defined! See enable_execute_stack.c" |
| 55 | #else |
| 56 | const uintptr_t pageSize = sysconf(_SC_PAGESIZE); |
| 57 | #endif // __APPLE__ |
| 58 | |
| 59 | const uintptr_t pageAlignMask = ~(pageSize - 1); |
| 60 | uintptr_t p = (uintptr_t)addr; |
| 61 | unsigned char *startPage = (unsigned char *)(p & pageAlignMask); |
| 62 | unsigned char *endPage = |
| 63 | (unsigned char *)((p + TRAMPOLINE_SIZE + pageSize) & pageAlignMask); |
| 64 | size_t length = endPage - startPage; |
| 65 | (void)mprotect(addr: (void *)startPage, len: length, PROT_READ | PROT_WRITE | PROT_EXEC); |
| 66 | #endif |
| 67 | } |
| 68 | |