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