blob: 15ab03fd73bfdf8f53221985026215b1da42d26d [file] [log] [blame]
Daniel Dunbarfd089992009-06-26 16:47:03 +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
10#include <stdint.h>
11#include <sys/mman.h>
Daniel Dunbarc6cd62b2009-07-01 06:06:42 +000012#ifndef __APPLE__
13#include <unistd.h>
14#endif
Daniel Dunbarfd089992009-06-26 16:47:03 +000015
16
17//
18// The compiler generates calls to __enable_execute_stack() when creating
19// trampoline functions on the stack for use with nested functions.
20// It is expected to mark the page(s) containing the address
21// and the next 48 bytes as executable. Since the stack is normally rw-
22// that means changing the protection on those page(s) to rwx.
23//
24void __enable_execute_stack(void* addr)
25{
26#if __APPLE__
27 // On Darwin, pagesize is always 4096 bytes
28 const uintptr_t pageSize = 4096;
29#else
Daniel Dunbarf1184022009-07-01 06:02:53 +000030 // FIXME: We should have a configure check for this.
Daniel Dunbarc6cd62b2009-07-01 06:06:42 +000031 const uintptr_t pageSize = getpagesize();
Daniel Dunbarfd089992009-06-26 16:47:03 +000032#endif
33 const uintptr_t pageAlignMask = ~(pageSize-1);
34 uintptr_t p = (uintptr_t)addr;
35 unsigned char* startPage = (unsigned char*)(p & pageAlignMask);
36 unsigned char* endPage = (unsigned char*)((p+48+pageSize) & pageAlignMask);
37 mprotect(startPage, endPage-startPage, PROT_READ | PROT_WRITE | PROT_EXEC);
38}
39
40