/[path-sandbox]/trunk/libsandbox/memory.c
Gentoo

Contents of /trunk/libsandbox/memory.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 400 - (show annotations) (download) (as text)
Mon Nov 10 22:12:20 2008 UTC (5 years, 9 months ago) by vapier
File MIME type: text/x-csrc
File size: 1998 byte(s)
do a little memory memory checking on free() to make sure the pointer didnt get corrupt
1 /* memory.c
2 * Minimal mmap-based malloc/free implementation to be used by libsandbox
3 * internal routines, since we can't trust the current process to have a
4 * malloc/free implementation that is sane and available at all times.
5 *
6 * Copyright 1999-2008 Gentoo Foundation
7 * Licensed under the GPL-2
8 */
9
10 #include "headers.h"
11 #include "libsandbox.h"
12 #include "sbutil.h"
13
14 #define SB_MALLOC_TO_MMAP(ptr) ((void*)(((size_t*)ptr) - 1))
15 #define SB_MMAP_TO_MALLOC(ptr) ((void*)(((size_t*)ptr) + 1))
16 #define SB_MALLOC_TO_SIZE(ptr) (*((size_t*)SB_MALLOC_TO_MMAP(ptr)))
17
18 void *malloc(size_t size)
19 {
20 size_t *ret;
21 size += sizeof(size_t);
22 ret = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
23 if (ret == MAP_FAILED)
24 return NULL;
25 *ret = size;
26 return SB_MMAP_TO_MALLOC(ret);
27 }
28
29 void free(void *ptr)
30 {
31 if (ptr == NULL)
32 return;
33 if (munmap(SB_MALLOC_TO_MMAP(ptr), SB_MALLOC_TO_SIZE(ptr))) {
34 int color = ((is_env_on(ENV_NOCOLOR)) ? 0 : 1);
35 SB_EERROR(color, "sandbox memory corruption", " free(%p): %s\n",
36 ptr, strerror(errno));
37 #ifdef HAVE_BACKTRACE
38 void *funcs[10];
39 int num_funcs;
40 num_funcs = backtrace(funcs, sizeof(funcs));
41 backtrace_symbols_fd(funcs, num_funcs, STDERR_FILENO);
42 #endif
43 }
44 }
45
46 void *calloc(size_t nmemb, size_t size)
47 {
48 void *ret;
49 size_t malloc_size = nmemb * size;
50 ret = malloc(malloc_size); /* dont care about overflow */
51 if (ret == NULL)
52 return NULL;
53 memset(ret, 0x00, malloc_size);
54 return ret;
55 }
56
57 void *realloc(void *ptr, size_t size)
58 {
59 void *ret;
60 size_t old_malloc_size;
61
62 if (ptr == NULL)
63 return malloc(size);
64 if (size == 0) {
65 free(ptr);
66 return ptr;
67 }
68
69 old_malloc_size = SB_MALLOC_TO_SIZE(ptr);
70 ret = malloc(size);
71 if (ret == NULL)
72 return NULL;
73 memcpy(ret, ptr, MIN(size, old_malloc_size));
74 free(ptr);
75 return ret;
76 }
77
78 char *strdup(const char *s)
79 {
80 size_t len;
81 char *ret;
82
83 if (s == NULL)
84 return NULL;
85
86 len = strlen(s);
87 ret = malloc(len + 1);
88 if (ret == NULL)
89 return NULL;
90 return memcpy(ret, s, len + 1);
91 }

  ViewVC Help
Powered by ViewVC 1.1.20