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