1 //===-- enable_execute_stack.c - Implement __enable_execute_stack ---------===//
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
7 //===----------------------------------------------------------------------===//
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
21 #define WIN32_LEAN_AND_MEAN
30 #define TRAMPOLINE_SIZE 48
32 #define TRAMPOLINE_SIZE 40
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.
41 COMPILER_RT_ABI void __enable_execute_stack(void *addr) {
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,
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"
56 const uintptr_t pageSize = sysconf(_SC_PAGESIZE);
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((void *)startPage, length, PROT_READ | PROT_WRITE | PROT_EXEC);