[clang] Handle __declspec() attributes in using
[llvm-project.git] / compiler-rt / lib / builtins / enable_execute_stack.c
blobe18de4eaebf2a764554683fc87150e754f6c8e77
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 //===----------------------------------------------------------------------===//
9 #include "int_lib.h"
11 #ifndef _WIN32
12 #include <sys/mman.h>
13 #endif
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
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
29 #if __LP64__
30 #define TRAMPOLINE_SIZE 48
31 #else
32 #define TRAMPOLINE_SIZE 40
33 #endif
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) {
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__
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);
66 #endif