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 */
10 #include "gras_config.h"
12 static void *__mmalloc_current_heap = NULL; /* The heap we are currently using. */
14 #include "xbt_modinter.h"
16 void *mmalloc_get_current_heap(void)
18 return __mmalloc_current_heap;
21 void mmalloc_set_current_heap(void *new_heap)
23 __mmalloc_current_heap = new_heap;
26 #ifdef MMALLOC_WANT_OVERIDE_LEGACY
27 void *malloc(size_t n)
29 void *mdp = __mmalloc_current_heap;
35 void *ret = mmalloc(mdp, n);
41 void *calloc(size_t nmemb, size_t size)
43 size_t total_size = nmemb * size;
44 void *mdp = __mmalloc_current_heap;
50 void *ret = mmalloc(mdp, total_size);
53 /* Fill the allocated memory with zeroes to mimic calloc behaviour */
54 memset(ret, '\0', total_size);
59 void *realloc(void *p, size_t s)
62 void *mdp = __mmalloc_current_heap;
70 ret = mrealloc(mdp, p, s);
72 ret = mmalloc(mdp, s);
84 void *mdp = __mmalloc_current_heap;
94 /* Make sure it works with md==NULL */
96 #define HEAP_OFFSET (128<<20) /* Safety gap from the heap's break address.
97 * Try to increase this first if you experience
98 * strange errors under valgrind. */
100 void *mmalloc_get_default_md(void)
102 xbt_assert(__mmalloc_default_mdp);
103 return __mmalloc_default_mdp;
106 static void mmalloc_fork_prepare(void)
108 struct mdesc* mdp = NULL;
109 if ((mdp =__mmalloc_default_mdp)){
115 mdp = mdp->next_mdesc;
120 static void mmalloc_fork_parent(void)
122 struct mdesc* mdp = NULL;
123 if ((mdp =__mmalloc_default_mdp)){
127 mdp = mdp->next_mdesc;
132 static void mmalloc_fork_child(void)
134 struct mdesc* mdp = NULL;
135 if ((mdp =__mmalloc_default_mdp)){
138 mdp = mdp->next_mdesc;
143 /* Initialize the default malloc descriptor. */
144 void mmalloc_preinit(void)
146 if (!__mmalloc_default_mdp) {
147 __mmalloc_default_mdp =
148 mmalloc_attach(-1, (char *) sbrk(0) + HEAP_OFFSET);
149 /* Fixme? only the default mdp in protected against forks */
150 if (xbt_os_thread_atfork(mmalloc_fork_prepare,
151 mmalloc_fork_parent, mmalloc_fork_child) != 0)
154 xbt_assert(__mmalloc_default_mdp != NULL);
157 void mmalloc_postexit(void)
159 /* Do not detach the default mdp or ldl won't be able to free the memory it allocated since we're in memory */
160 // mmalloc_detach(__mmalloc_default_mdp);
161 mmalloc_pre_detach(__mmalloc_default_mdp);