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 /* Safety gap from the heap's break address.
97 * Try to increase this first if you experience strange errors under
99 #define HEAP_OFFSET (128UL<<20)
101 void *mmalloc_get_default_md(void)
103 xbt_assert(__mmalloc_default_mdp);
104 return __mmalloc_default_mdp;
107 static void mmalloc_fork_prepare(void)
109 struct mdesc* mdp = NULL;
110 if ((mdp =__mmalloc_default_mdp)){
116 mdp = mdp->next_mdesc;
121 static void mmalloc_fork_parent(void)
123 struct mdesc* mdp = NULL;
124 if ((mdp =__mmalloc_default_mdp)){
128 mdp = mdp->next_mdesc;
133 static void mmalloc_fork_child(void)
135 struct mdesc* mdp = NULL;
136 if ((mdp =__mmalloc_default_mdp)){
139 mdp = mdp->next_mdesc;
144 /* Initialize the default malloc descriptor. */
145 void mmalloc_preinit(void)
148 if (!__mmalloc_default_mdp) {
149 unsigned long mask = ~((unsigned long)getpagesize() - 1);
150 void *addr = (void*)(((unsigned long)sbrk(0) + HEAP_OFFSET) & mask);
151 __mmalloc_default_mdp = mmalloc_attach(-1, addr);
152 /* Fixme? only the default mdp in protected against forks */
153 res = xbt_os_thread_atfork(mmalloc_fork_prepare,
154 mmalloc_fork_parent, mmalloc_fork_child);
156 THROWF(system_error,0,"xbt_os_thread_atfork() failed: return value %d",res);
158 xbt_assert(__mmalloc_default_mdp != NULL);
161 void mmalloc_postexit(void)
163 /* Do not detach the default mdp or ldl won't be able to free the memory it allocated since we're in memory */
164 // mmalloc_detach(__mmalloc_default_mdp);
165 mmalloc_pre_detach(__mmalloc_default_mdp);