1/* ===-- enable_execute_stack.c - Implement __enable_execute_stack ---------===
2 *
3 *                     The LLVM Compiler Infrastructure
4 *
5 * This file is dual licensed under the MIT and the University of Illinois Open
6 * Source Licenses. See LICENSE.TXT for details.
7 *
8 * ===----------------------------------------------------------------------===
9 */
10
11#include "int_lib.h"
12
13#include <sys/mman.h>
14
15/* #include "config.h"
16 * FIXME: CMake - include when cmake system is ready.
17 * Remove #define HAVE_SYSCONF 1 line.
18 */
19#define HAVE_SYSCONF 1
20
21#ifndef __APPLE__
22#include <unistd.h>
23#endif /* __APPLE__ */
24
25#if __LP64__
26	#define TRAMPOLINE_SIZE 48
27#else
28	#define TRAMPOLINE_SIZE 40
29#endif
30
31/*
32 * The compiler generates calls to __enable_execute_stack() when creating
33 * trampoline functions on the stack for use with nested functions.
34 * It is expected to mark the page(s) containing the address
35 * and the next 48 bytes as executable.  Since the stack is normally rw-
36 * that means changing the protection on those page(s) to rwx.
37 */
38
39COMPILER_RT_ABI void
40__enable_execute_stack(void* addr)
41{
42
43#if __APPLE__
44	/* On Darwin, pagesize is always 4096 bytes */
45	const uintptr_t pageSize = 4096;
46#elif !defined(HAVE_SYSCONF)
47#error "HAVE_SYSCONF not defined! See enable_execute_stack.c"
48#else
49        const uintptr_t pageSize = sysconf(_SC_PAGESIZE);
50#endif /* __APPLE__ */
51
52	const uintptr_t pageAlignMask = ~(pageSize-1);
53	uintptr_t p = (uintptr_t)addr;
54	unsigned char* startPage = (unsigned char*)(p & pageAlignMask);
55	unsigned char* endPage = (unsigned char*)((p+TRAMPOLINE_SIZE+pageSize) & pageAlignMask);
56	size_t length = endPage - startPage;
57	(void) mprotect((void *)startPage, length, PROT_READ | PROT_WRITE | PROT_EXEC);
58}
59