Line 0
Link Here
|
|
|
1 |
/* Minimal mmap-based malloc/free implementation to be used by libsandbox |
2 |
* internal routines, since we can't trust the current process to have a |
3 |
* malloc/free implementation that is sane and available at all times. |
4 |
*/ |
5 |
|
6 |
#include <stdlib.h> /* malloc()/free() prototypes */ |
7 |
#include <string.h> /* mem*(), strdup() prototype */ |
8 |
#include <sys/mman.h> /* mmap() */ |
9 |
|
10 |
#define SB_MALLOC_TO_MMAP(ptr) ((void*)(((size_t*)ptr) - 1)) |
11 |
#define SB_MMAP_TO_MALLOC(ptr) ((void*)(((size_t*)ptr) + 1)) |
12 |
#define SB_MALLOC_TO_SIZE(ptr) (*((size_t*)SB_MALLOC_TO_MMAP(ptr))) |
13 |
|
14 |
void *malloc(size_t size) |
15 |
{ |
16 |
size_t *ret; |
17 |
size += sizeof(size_t); |
18 |
ret = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); |
19 |
if (ret == MAP_FAILED) |
20 |
return NULL; |
21 |
*ret = size; |
22 |
return SB_MMAP_TO_MALLOC(ret); |
23 |
} |
24 |
|
25 |
void free(void *ptr) |
26 |
{ |
27 |
if (ptr == NULL) |
28 |
return; |
29 |
munmap(SB_MALLOC_TO_MMAP(ptr), SB_MALLOC_TO_SIZE(ptr)); |
30 |
} |
31 |
|
32 |
void *calloc(size_t nmemb, size_t size) |
33 |
{ |
34 |
void *ret; |
35 |
size_t malloc_size = nmemb * size; |
36 |
ret = malloc(malloc_size); /* dont care about overflow */ |
37 |
if (ret == NULL) |
38 |
return NULL; |
39 |
memset(ret, 0x00, malloc_size); |
40 |
return ret; |
41 |
} |
42 |
|
43 |
void *realloc(void *ptr, size_t size) |
44 |
{ |
45 |
void *ret; |
46 |
size_t old_malloc_size; |
47 |
|
48 |
if (ptr == NULL) |
49 |
return malloc(size); |
50 |
if (size == 0) { |
51 |
free(ptr); |
52 |
return ptr; |
53 |
} |
54 |
|
55 |
old_malloc_size = SB_MALLOC_TO_SIZE(ptr); |
56 |
ret = malloc(size); |
57 |
if (ret == NULL) |
58 |
return NULL; |
59 |
memcpy(ret, ptr, (size < old_malloc_size ? size : old_malloc_size)); |
60 |
free(ptr); |
61 |
return ret; |
62 |
} |
63 |
|
64 |
#ifdef strdup |
65 |
#undef strdup |
66 |
#endif |
67 |
char *strdup(const char *s) |
68 |
{ |
69 |
size_t len; |
70 |
char *ret; |
71 |
|
72 |
if (s == NULL) |
73 |
return NULL; |
74 |
len = strlen(s); |
75 |
ret = malloc(len + 1); |
76 |
if (ret == NULL) |
77 |
return NULL; |
78 |
memcpy(ret, s, len + 1); |
79 |
} |