Edward O'Callaghan | 2bf6272 | 2009-08-05 04:02:56 +0000 | [diff] [blame] | 1 | /* ===-- 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 Dunbar | b3a6901 | 2009-06-26 16:47:03 +0000 | [diff] [blame] | 10 | |
| 11 | #include <stdint.h> |
| 12 | #include <sys/mman.h> |
Daniel Dunbar | f639213 | 2009-07-01 06:06:42 +0000 | [diff] [blame] | 13 | #ifndef __APPLE__ |
| 14 | #include <unistd.h> |
| 15 | #endif |
Daniel Dunbar | b3a6901 | 2009-06-26 16:47:03 +0000 | [diff] [blame] | 16 | |
| 17 | |
Edward O'Callaghan | 2bf6272 | 2009-08-05 04:02:56 +0000 | [diff] [blame] | 18 | /* |
| 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 Dunbar | b3a6901 | 2009-06-26 16:47:03 +0000 | [diff] [blame] | 26 | void __enable_execute_stack(void* addr) |
| 27 | { |
| 28 | #if __APPLE__ |
Edward O'Callaghan | 2bf6272 | 2009-08-05 04:02:56 +0000 | [diff] [blame] | 29 | /* On Darwin, pagesize is always 4096 bytes */ |
Daniel Dunbar | b3a6901 | 2009-06-26 16:47:03 +0000 | [diff] [blame] | 30 | const uintptr_t pageSize = 4096; |
| 31 | #else |
Edward O'Callaghan | 2bf6272 | 2009-08-05 04:02:56 +0000 | [diff] [blame] | 32 | /* FIXME: We should have a configure check for this. */ |
Daniel Dunbar | f639213 | 2009-07-01 06:06:42 +0000 | [diff] [blame] | 33 | const uintptr_t pageSize = getpagesize(); |
Daniel Dunbar | b3a6901 | 2009-06-26 16:47:03 +0000 | [diff] [blame] | 34 | #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 | |