blob: c2ebc30f893996e92a5cc4383175945e1f5fa40f [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>
Daniel Dunbarf6392132009-07-01 06:06:42 +000013#ifndef __APPLE__
14#include <unistd.h>
15#endif
Daniel Dunbarb3a69012009-06-26 16:47:03 +000016
17
Edward O'Callaghan2bf62722009-08-05 04:02:56 +000018/*
19 * The compiler generates calls to __enable_execute_stack() when creating
20 * trampoline functions on the stack for use with nested functions.
21 * It is expected to mark the page(s) containing the address
22 * and the next 48 bytes as executable. Since the stack is normally rw-
23 * that means changing the protection on those page(s) to rwx.
24 */
25
Daniel Dunbarb3a69012009-06-26 16:47:03 +000026void __enable_execute_stack(void* addr)
27{
28#if __APPLE__
Edward O'Callaghan2bf62722009-08-05 04:02:56 +000029 /* On Darwin, pagesize is always 4096 bytes */
Daniel Dunbarb3a69012009-06-26 16:47:03 +000030 const uintptr_t pageSize = 4096;
31#else
Edward O'Callaghan2bf62722009-08-05 04:02:56 +000032 /* FIXME: We should have a configure check for this. */
Daniel Dunbarf6392132009-07-01 06:06:42 +000033 const uintptr_t pageSize = getpagesize();
Daniel Dunbarb3a69012009-06-26 16:47:03 +000034#endif
35 const uintptr_t pageAlignMask = ~(pageSize-1);
36 uintptr_t p = (uintptr_t)addr;
37 unsigned char* startPage = (unsigned char*)(p & pageAlignMask);
38 unsigned char* endPage = (unsigned char*)((p+48+pageSize) & pageAlignMask);
39 mprotect(startPage, endPage-startPage, PROT_READ | PROT_WRITE | PROT_EXEC);
40}
41
42