1 /* Copyright (c) 2010. The SimGrid Team.
2 * All rights reserved. */
4 /* This program is free software; you can redistribute it and/or modify it
5 * under the terms of the license (GNU LGPL) which comes with this package. */
7 /* Redefine the classical malloc/free/realloc functions so that they fit well in the mmalloc framework */
11 static void *__mmalloc_current_heap = NULL; /* The heap we are currently using. */
13 #include "xbt_modinter.h"
15 void *mmalloc_get_current_heap(void)
17 return __mmalloc_current_heap;
20 void mmalloc_set_current_heap(void *new_heap)
22 __mmalloc_current_heap = new_heap;
25 #ifdef MMALLOC_WANT_OVERIDE_LEGACY
26 void *malloc(size_t n)
28 void *mdp = __mmalloc_current_heap;
34 void *ret = mmalloc(mdp, n);
40 void *calloc(size_t nmemb, size_t size)
42 size_t total_size = nmemb * size;
43 void *mdp = __mmalloc_current_heap;
49 void *ret = mmalloc(mdp, total_size);
52 /* Fill the allocated memory with zeroes to mimic calloc behaviour */
53 memset(ret, '\0', total_size);
58 void *realloc(void *p, size_t s)
61 void *mdp = __mmalloc_current_heap;
69 ret = mrealloc(mdp, p, s);
71 ret = mmalloc(mdp, s);
83 void *mdp = __mmalloc_current_heap;
90 /* Make sure it works with md==NULL */
92 #define HEAP_OFFSET (128<<20) /* Safety gap from the heap's break address.
93 * Try to increase this first if you experience
94 * strange errors under valgrind. */
96 void *mmalloc_get_default_md(void)
98 xbt_assert(__mmalloc_default_mdp);
99 return __mmalloc_default_mdp;
102 static void mmalloc_fork_prepare(void)
104 struct mdesc* mdp = NULL;
105 if ((mdp =__mmalloc_default_mdp)){
111 mdp = mdp->next_mdesc;
116 static void mmalloc_fork_parent(void)
118 struct mdesc* mdp = NULL;
119 if ((mdp =__mmalloc_default_mdp)){
123 mdp = mdp->next_mdesc;
128 static void mmalloc_fork_child(void)
130 struct mdesc* mdp = NULL;
131 if ((mdp =__mmalloc_default_mdp)){
134 mdp = mdp->next_mdesc;
139 /* Initialize the default malloc descriptor. */
140 void mmalloc_preinit(void)
142 if (!__mmalloc_default_mdp) {
143 __mmalloc_default_mdp =
144 mmalloc_attach(-1, (char *) sbrk(0) + HEAP_OFFSET);
145 /* Fixme? only the default mdp in protected against forks */
146 if (xbt_os_thread_atfork(mmalloc_fork_prepare,
147 mmalloc_fork_parent, mmalloc_fork_child) != 0)
150 xbt_assert(__mmalloc_default_mdp != NULL);
153 void mmalloc_postexit(void)
155 /* Do not detach the default mdp or ldl won't be able to free the memory it allocated since we're in memory */
156 // mmalloc_detach(__mmalloc_default_mdp);
157 mmalloc_pre_detach(__mmalloc_default_mdp);