main
mem.c
1/*
2 Copyright 2013 Michael Pavone
3 This file is part of BlastEm.
4 BlastEm is free software distributed under the terms of the GNU General Public License version 3 or greater. See COPYING for full license text.
5*/
6#include <sys/mman.h>
7#include <stddef.h>
8#include <stdint.h>
9#include <stdlib.h>
10#include <unistd.h>
11#include <errno.h>
12#include <stdio.h>
13
14#include "mem.h"
15#include "arena.h"
16#ifndef MAP_ANONYMOUS
17#define MAP_ANONYMOUS MAP_ANON
18#endif
19
20#ifndef MAP_32BIT
21#define MAP_32BIT 0
22#endif
23
24void * alloc_code(size_t *size)
25{
26 //start at the 1GB mark to allow plenty of room for sbrk based malloc implementations
27 //while still keeping well within 32-bit displacement range for calling code compiled into the executable
28 static uint8_t *next = (uint8_t *)0x40000000;
29 uint8_t *ret = try_alloc_arena();
30 if (ret) {
31 return ret;
32 }
33 if (*size & (PAGE_SIZE -1)) {
34 *size += PAGE_SIZE - (*size & (PAGE_SIZE - 1));
35 }
36 ret = mmap(next, *size, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_32BIT, -1, 0);
37 if (ret == MAP_FAILED) {
38 perror("alloc_code");
39 return NULL;
40 }
41 track_block(ret);
42 next = ret + *size;
43 return ret;
44}
45