blob: b349d2f312b427fd93fb4629604fb547507fbe72 [file] [log] [blame]
Edward O'Callaghan2bf62722009-08-05 04:02:56 +00001/* ===-- enable_execute_stack.c - Implement __enable_execute_stack ---------===
2 *
3 * The LLVM Compiler Infrastructure
4 *
5 * This file is distributed under the University of Illinois Open Source
6 * License. See LICENSE.TXT for details.
7 *
8 * ===----------------------------------------------------------------------===
9 */
Daniel Dunbarb3a69012009-06-26 16:47:03 +000010
11#include <stdint.h>
12#include <sys/mman.h>
Edward O'Callaghande1c6cf2009-08-10 00:56:46 +000013
14/* #include "config.h"
15 * FIXME: CMake - include when cmake system is ready.
Edward O'Callaghanb72794d2009-08-10 01:02:16 +000016 * Remove #define HAVE_SYSCONF 1 line.
Edward O'Callaghande1c6cf2009-08-10 00:56:46 +000017 */
Edward O'Callaghanb72794d2009-08-10 01:02:16 +000018#define HAVE_SYSCONF 1
Edward O'Callaghande1c6cf2009-08-10 00:56:46 +000019
Daniel Dunbarf6392132009-07-01 06:06:42 +000020#ifndef __APPLE__
21#include <unistd.h>
Edward O'Callaghande1c6cf2009-08-10 00:56:46 +000022#endif /* __APPLE__ */
Daniel Dunbarb3a69012009-06-26 16:47:03 +000023
24
Edward O'Callaghan2bf62722009-08-05 04:02:56 +000025/*
26 * The compiler generates calls to __enable_execute_stack() when creating
27 * trampoline functions on the stack for use with nested functions.
28 * It is expected to mark the page(s) containing the address
29 * and the next 48 bytes as executable. Since the stack is normally rw-
30 * that means changing the protection on those page(s) to rwx.
31 */
32
Daniel Dunbarb3a69012009-06-26 16:47:03 +000033void __enable_execute_stack(void* addr)
34{
Edward O'Callaghande1c6cf2009-08-10 00:56:46 +000035
Daniel Dunbarb3a69012009-06-26 16:47:03 +000036#if __APPLE__
Edward O'Callaghan2bf62722009-08-05 04:02:56 +000037 /* On Darwin, pagesize is always 4096 bytes */
Daniel Dunbarb3a69012009-06-26 16:47:03 +000038 const uintptr_t pageSize = 4096;
Edward O'Callaghande1c6cf2009-08-10 00:56:46 +000039#elif !defined(HAVE_SYSCONF)
40#error "HAVE_SYSCONF not defined! See enable_execute_stack.c"
Daniel Dunbarb3a69012009-06-26 16:47:03 +000041#else
Nuno Lopes166b7832009-08-09 18:59:21 +000042 const uintptr_t pageSize = sysconf(_SC_PAGESIZE);
Edward O'Callaghande1c6cf2009-08-10 00:56:46 +000043#endif /* __APPLE__ */
44
Daniel Dunbarb3a69012009-06-26 16:47:03 +000045 const uintptr_t pageAlignMask = ~(pageSize-1);
46 uintptr_t p = (uintptr_t)addr;
47 unsigned char* startPage = (unsigned char*)(p & pageAlignMask);
48 unsigned char* endPage = (unsigned char*)((p+48+pageSize) & pageAlignMask);
Edward O'Callaghanbb119a42009-08-08 02:31:50 +000049 size_t length = endPage - startPage;
50 (void) mprotect((void *)startPage, length, PROT_READ | PROT_WRITE | PROT_EXEC);
Daniel Dunbarb3a69012009-06-26 16:47:03 +000051}
52
53