1 /* Initialization for access to a mmap'd malloc managed region. */
3 /* Copyright (c) 2012-2014. The SimGrid Team.
4 * All rights reserved. */
6 /* This program is free software; you can redistribute it and/or modify it
7 * under the terms of the license (GNU LGPL) which comes with this package. */
9 /* Copyright 1992, 2000 Free Software Foundation, Inc.
11 Contributed by Fred Fish at Cygnus Support. fnf@cygnus.com
13 This file is part of the GNU C Library.
15 The GNU C Library is free software; you can redistribute it and/or
16 modify it under the terms of the GNU Library General Public License as
17 published by the Free Software Foundation; either version 2 of the
18 License, or (at your option) any later version.
20 The GNU C Library is distributed in the hope that it will be useful,
21 but WITHOUT ANY WARRANTY; without even the implied warranty of
22 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 Library General Public License for more details.
25 You should have received a copy of the GNU Library General Public
26 License along with the GNU C Library; see the file COPYING.LIB. If
27 not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
28 Boston, MA 02111-1307, USA. */
30 #include <sys/types.h>
31 #include <fcntl.h> /* After sys/types.h, at least for dpx/2. */
35 #include <unistd.h> /* Prototypes for lseek */
37 #include "mmprivate.h"
39 #include "xbt_modinter.h" /* declarations of mmalloc_preinit and friends that live here */
45 /* Initialize access to a mmalloc managed region.
47 If FD is a valid file descriptor for an open file then data for the
48 mmalloc managed region is mapped to that file, otherwise an anonymous
49 map is used if supported by the underlying OS. In case of running in
50 an OS without support of anonymous mappings then "/dev/zero" is used
51 and in both cases the data will not exist in any filesystem object.
53 If the open file corresponding to FD is from a previous use of
54 mmalloc and passes some basic sanity checks to ensure that it is
55 compatible with the current mmalloc package, then its data is
56 mapped in and is immediately accessible at the same addresses in
57 the current process as the process that created the file (ignoring
58 the BASEADDR parameter).
60 For non valid FDs or empty files ones the mapping is established
61 starting at the specified address BASEADDR in the process address
64 The provided BASEADDR should be choosed carefully in order to avoid
65 bumping into existing mapped regions or future mapped regions.
67 On success, returns a "malloc descriptor" which is used in subsequent
68 calls to other mmalloc package functions. It is explicitly "void *"
69 so that users of the package don't have to worry about the actual
70 implementation details.
72 On failure returns NULL. */
74 xbt_mheap_t xbt_mheap_new(int fd, void *baseaddr)
81 /* First check to see if FD is a valid file descriptor, and if so, see
82 if the file has any current contents (size > 0). If it does, then
83 attempt to reuse the file. If we can't reuse the file, either
84 because it isn't a valid mmalloc produced file, was produced by an
85 obsolete version, or any other reason, then we fail to attach to
89 if (fstat(fd, &sbuf) < 0)
92 else if (sbuf.st_size > 0) {
93 /* We were given an valid file descriptor on an open file, so try to remap
94 it into the current process at the same address to which it was previously
95 mapped. It naturally have to pass some sanity checks for that.
97 Note that we have to update the file descriptor number in the malloc-
98 descriptor read from the file to match the current valid one, before
99 trying to map the file in, and again after a successful mapping and
100 after we've switched over to using the mapped in malloc descriptor
101 rather than the temporary one on the stack.
103 Once we've switched over to using the mapped in malloc descriptor, we
104 have to update the pointer to the morecore function, since it almost
105 certainly will be at a different address if the process reusing the
106 mapped region is from a different executable.
108 Also note that if the heap being remapped previously used the mmcheckf()
109 routines, we need to update the hooks since their target functions
110 will have certainly moved if the executable has changed in any way.
111 We do this by calling mmcheckf() internally.
113 Returns a pointer to the malloc descriptor if successful, or NULL if
114 unsuccessful for some reason. */
117 struct mdesc *mdptr = NULL, *mdptemp = NULL;
119 if (lseek(fd, 0L, SEEK_SET) != 0)
121 if (read(fd, (char *) &newmd, sizeof(newmd)) != sizeof(newmd))
123 if (newmd.headersize != sizeof(newmd))
125 if (strcmp(newmd.magic, MMALLOC_MAGIC) != 0)
127 if (newmd.version > MMALLOC_VERSION)
131 if (__mmalloc_remap_core(&newmd) == newmd.base) {
132 mdptr = (struct mdesc *) newmd.base;
134 if(!mdptr->refcount){
135 sem_init(&mdptr->sem, 0, 1);
140 /* Add the new heap to the linked list of heaps attached by mmalloc */
141 mdptemp = __mmalloc_default_mdp;
142 while(mdptemp->next_mdesc)
143 mdptemp = mdptemp->next_mdesc;
146 mdptemp->next_mdesc = mdptr;
153 /* NULL is not a valid baseaddr as we cannot map anything there.
154 C'mon, user. Think! */
155 if (baseaddr == NULL)
158 /* We start off with the malloc descriptor allocated on the stack, until
159 we build it up enough to call _mmalloc_mmap_morecore() to allocate the
160 first page of the region and copy it there. Ensure that it is zero'd and
161 then initialize the fields that we know values for. */
164 memset((char *) mdp, 0, sizeof(mtemp));
165 strncpy(mdp->magic, MMALLOC_MAGIC, MMALLOC_MAGIC_SIZE);
166 mdp->headersize = sizeof(mtemp);
167 mdp->version = MMALLOC_VERSION;
169 mdp->base = mdp->breakval = mdp->top = baseaddr;
170 mdp->next_mdesc = NULL;
173 /* If we have not been passed a valid open file descriptor for the file
174 to map to, then we go for an anonymous map */
177 mdp->flags |= MMALLOC_ANONYMOUS;
179 sem_init(&mdp->sem, 0, 1);
181 /* If we have not been passed a valid open file descriptor for the file
182 to map to, then open /dev/zero and use that to map to. */
184 /* Now try to map in the first page, copy the malloc descriptor structure
185 there, and arrange to return a pointer to this new copy. If the mapping
186 fails, then close the file descriptor if it was opened by us, and arrange
189 if ((mbase = mmorecore(mdp, sizeof(mtemp))) != NULL) {
190 memcpy(mbase, mdp, sizeof(mtemp));
192 fprintf(stderr, "morecore failed to get some more memory!\n");
196 /* Add the new heap to the linked list of heaps attached by mmalloc */
197 if(__mmalloc_default_mdp){
198 mdp = __mmalloc_default_mdp;
199 while(mdp->next_mdesc)
200 mdp = mdp->next_mdesc;
203 mdp->next_mdesc = (struct mdesc *)mbase;
212 /** Terminate access to a mmalloc managed region, but do not free its content.
214 * This is for example useful for the base region where ldl stores its data
215 * because it leaves the place after us.
217 void xbt_mheap_destroy_no_free(xbt_mheap_t md)
219 struct mdesc *mdp = md;
221 if(--mdp->refcount == 0){
223 sem_destroy(&mdp->sem);
227 /** Terminate access to a mmalloc managed region by unmapping all memory pages
228 associated with the region, and closing the file descriptor if it is one
231 Returns NULL on success.
233 Returns the malloc descriptor on failure, which can subsequently be used
234 for further action, such as obtaining more information about the nature of
237 Note that the malloc descriptor that we are using is currently located in
238 region we are about to unmap, so we first make a local copy of it on the
239 stack and use the copy. */
241 void *xbt_mheap_destroy(xbt_mheap_t mdp)
243 struct mdesc mtemp, *mdptemp;
246 /* Remove the heap from the linked list of heaps attached by mmalloc */
247 mdptemp = __mmalloc_default_mdp;
248 while(mdptemp->next_mdesc != mdp )
249 mdptemp = mdptemp->next_mdesc;
251 mdptemp->next_mdesc = mdp->next_mdesc;
253 xbt_mheap_destroy_no_free(mdp);
256 /* Now unmap all the pages associated with this region by asking for a
257 negative increment equal to the current size of the region. */
259 if (mmorecore(&mtemp, (char *)mtemp.base - (char *)mtemp.breakval) == NULL) {
260 /* Deallocating failed. Update the original malloc descriptor
264 if (mtemp.flags & MMALLOC_DEVZERO) {
274 /* Safety gap from the heap's break address.
275 * Try to increase this first if you experience strange errors under
277 #define HEAP_OFFSET (128UL<<20)
279 xbt_mheap_t mmalloc_get_default_md(void)
281 xbt_assert(__mmalloc_default_mdp);
282 return __mmalloc_default_mdp;
285 static void mmalloc_fork_prepare(void)
287 xbt_mheap_t mdp = NULL;
288 if ((mdp =__mmalloc_default_mdp)){
294 mdp = mdp->next_mdesc;
299 static void mmalloc_fork_parent(void)
301 xbt_mheap_t mdp = NULL;
302 if ((mdp =__mmalloc_default_mdp)){
306 mdp = mdp->next_mdesc;
311 static void mmalloc_fork_child(void)
313 struct mdesc* mdp = NULL;
314 if ((mdp =__mmalloc_default_mdp)){
317 mdp = mdp->next_mdesc;
322 /* Initialize the default malloc descriptor. */
323 void *mmalloc_preinit(void)
326 if (__mmalloc_default_mdp == NULL) {
327 unsigned long mask = ~((unsigned long)xbt_pagesize - 1);
328 void *addr = (void*)(((unsigned long)sbrk(0) + HEAP_OFFSET) & mask);
329 __mmalloc_default_mdp = xbt_mheap_new(-1, addr);
330 /* Fixme? only the default mdp in protected against forks */
331 // This is mandated to protect the mmalloced areas through forks. Think of tesh.
332 // Nah, removing the mutex isn't a good idea either for tesh
333 res = xbt_os_thread_atfork(mmalloc_fork_prepare,
334 mmalloc_fork_parent, mmalloc_fork_child);
336 THROWF(system_error,0,"xbt_os_thread_atfork() failed: return value %d",res);
338 xbt_assert(__mmalloc_default_mdp != NULL);
340 #if defined(HAVE_GNU_LD) && defined(MMALLOC_WANT_OVERRIDE_LEGACY)
341 mm_gnuld_legacy_init();
344 return __mmalloc_default_mdp;
347 void mmalloc_postexit(void)
349 /* Do not destroy the default mdp or ldl won't be able to free the memory it
350 * allocated since we're in memory */
351 // xbt_mheap_destroy_no_free(__mmalloc_default_mdp);
354 size_t mmalloc_get_bytes_used(xbt_mheap_t heap){
358 while(i<=((struct mdesc *)heap)->heaplimit){
359 if(((struct mdesc *)heap)->heapinfo[i].type == 0){
360 if(((struct mdesc *)heap)->heapinfo[i].busy_block.busy_size > 0)
361 bytes += ((struct mdesc *)heap)->heapinfo[i].busy_block.busy_size;
363 }else if(((struct mdesc *)heap)->heapinfo[i].type > 0){
364 for(j=0; j < (size_t) (BLOCKSIZE >> ((struct mdesc *)heap)->heapinfo[i].type); j++){
365 if(((struct mdesc *)heap)->heapinfo[i].busy_frag.frag_size[j] > 0)
366 bytes += ((struct mdesc *)heap)->heapinfo[i].busy_frag.frag_size[j];
375 ssize_t mmalloc_get_busy_size(xbt_mheap_t heap, void *ptr){
377 ssize_t block = ((char*)ptr - (char*)(heap->heapbase)) / BLOCKSIZE + 1;
378 if(heap->heapinfo[block].type == -1)
380 else if(heap->heapinfo[block].type == 0)
381 return heap->heapinfo[block].busy_block.busy_size;
383 ssize_t frag = ((uintptr_t) (ADDR2UINT (ptr) % (BLOCKSIZE))) >> heap->heapinfo[block].type;
384 return heap->heapinfo[block].busy_frag.frag_size[frag];