Mercurial > repos > blastem
comparison mem.c @ 758:b52cd6854c28
Use mmap with a hint rather than sbrk for allocating executable memory within 32-bit displacement range of compiled code
author | Michael Pavone <pavone@retrodev.com> |
---|---|
date | Sun, 28 Jun 2015 10:12:37 -0700 |
parents | 140af5509ce7 |
children | c47e1750c264 |
comparison
equal
deleted
inserted
replaced
757:483f7e7926a6 | 758:b52cd6854c28 |
---|---|
6 #include <sys/mman.h> | 6 #include <sys/mman.h> |
7 #include <stddef.h> | 7 #include <stddef.h> |
8 #include <stdint.h> | 8 #include <stdint.h> |
9 #include <stdlib.h> | 9 #include <stdlib.h> |
10 #include <unistd.h> | 10 #include <unistd.h> |
11 | |
11 #include "mem.h" | 12 #include "mem.h" |
12 | 13 #ifndef MAP_ANONYMOUS |
13 /* | 14 #define MAP_ANONYMOUS MAP_ANON |
14 void * alloc_code(size_t *size) | 15 #endif |
15 { | |
16 *size += PAGE_SIZE - (*size & (PAGE_SIZE - 1)); | |
17 return mmap(NULL, *size, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); | |
18 } | |
19 */ | |
20 | |
21 /* | |
22 void * alloc_code(size_t *size) | |
23 { | |
24 char * ret = malloc(*size); | |
25 char * base = (char *)(((intptr_t)ret) & (~(PAGE_SIZE-1))); | |
26 mprotect(base, (ret + *size) - base, PROT_EXEC | PROT_READ | PROT_WRITE); | |
27 return ret; | |
28 } | |
29 */ | |
30 | 16 |
31 void * alloc_code(size_t *size) | 17 void * alloc_code(size_t *size) |
32 { | 18 { |
19 //start at the 1GB mark to allow plenty of room for sbrk based malloc implementations | |
20 //while still keeping well within 32-bit displacement range for calling code compiled into the executable | |
21 static uint8_t *next = (uint8_t *)0x40000000; | |
33 *size += PAGE_SIZE - (*size & (PAGE_SIZE - 1)); | 22 *size += PAGE_SIZE - (*size & (PAGE_SIZE - 1)); |
34 void * ret = sbrk(*size); | 23 uint8_t *ret = mmap(NULL, *size, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); |
35 if (ret == ((void *)-1)) { | 24 next = ret + *size; |
36 return NULL; | |
37 } | |
38 mprotect(ret, *size, PROT_EXEC | PROT_READ | PROT_WRITE); | |
39 return ret; | 25 return ret; |
40 } | 26 } |
27 |