Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
6d1baa6b618dc1044e3ba6e8789ef918f3e14c4d
[simgrid.git] / src / xbt / mmalloc / mm_module.c
1 /* Initialization for access to a mmap'd malloc managed region.
2    Copyright 1992, 2000 Free Software Foundation, Inc.
3
4    Contributed by Fred Fish at Cygnus Support.   fnf@cygnus.com
5
6 This file is part of the GNU C Library.
7
8 The GNU C Library is free software; you can redistribute it and/or
9 modify it under the terms of the GNU Library General Public License as
10 published by the Free Software Foundation; either version 2 of the
11 License, or (at your option) any later version.
12
13 The GNU C Library is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 Library General Public License for more details.
17
18 You should have received a copy of the GNU Library General Public
19 License along with the GNU C Library; see the file COPYING.LIB.  If
20 not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 Boston, MA 02111-1307, USA.  */
22
23 #include <sys/types.h>
24 #include <fcntl.h>              /* After sys/types.h, at least for dpx/2.  */
25 #include <sys/stat.h>
26 #include <string.h>
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>             /* Prototypes for lseek */
29 #endif
30 #include "mmprivate.h"
31 #include "xbt/ex.h"
32 #include "xbt_modinter.h" /* declarations of mmalloc_preinit and friends that live here */
33
34 #ifndef SEEK_SET
35 #define SEEK_SET 0
36 #endif
37
38
39 /* Forward declarations/prototypes for local functions */
40
41 static struct mdesc *reuse(int fd);
42
43 /* Initialize access to a mmalloc managed region.
44
45    If FD is a valid file descriptor for an open file then data for the
46    mmalloc managed region is mapped to that file, otherwise an anonymous
47    map is used if supported by the underlying OS. In case of running in
48    an OS without support of anonymous mappings then "/dev/zero" is used 
49    and in both cases the data will not exist in any filesystem object.
50
51    If the open file corresponding to FD is from a previous use of
52    mmalloc and passes some basic sanity checks to ensure that it is
53    compatible with the current mmalloc package, then its data is
54    mapped in and is immediately accessible at the same addresses in
55    the current process as the process that created the file (ignoring
56    the BASEADDR parameter).
57
58    For non valid FDs or empty files ones the mapping is established 
59    starting at the specified address BASEADDR in the process address 
60    space.
61
62    The provided BASEADDR should be choosed carefully in order to avoid
63    bumping into existing mapped regions or future mapped regions.
64
65    On success, returns a "malloc descriptor" which is used in subsequent
66    calls to other mmalloc package functions.  It is explicitly "void *"
67    so that users of the package don't have to worry about the actual
68    implementation details.
69
70    On failure returns NULL. */
71
72 xbt_mheap_t mmalloc_attach(int fd, void *baseaddr)
73 {
74   struct mdesc mtemp;
75   xbt_mheap_t mdp;
76   void *mbase;
77   struct stat sbuf;
78
79   /* First check to see if FD is a valid file descriptor, and if so, see
80      if the file has any current contents (size > 0).  If it does, then
81      attempt to reuse the file.  If we can't reuse the file, either
82      because it isn't a valid mmalloc produced file, was produced by an
83      obsolete version, or any other reason, then we fail to attach to
84      this file. */
85
86   if (fd >= 0) {
87     if (fstat(fd, &sbuf) < 0)
88       return (NULL);
89
90     else if (sbuf.st_size > 0)
91       return ((void *) reuse(fd));
92   }
93
94   /* If the user provided NULL BASEADDR then fail */
95   if (baseaddr == NULL)
96     return (NULL);
97
98   /* We start off with the malloc descriptor allocated on the stack, until
99      we build it up enough to call _mmalloc_mmap_morecore() to allocate the
100      first page of the region and copy it there.  Ensure that it is zero'd and
101      then initialize the fields that we know values for. */
102
103   mdp = &mtemp;
104   memset((char *) mdp, 0, sizeof(mtemp));
105   strncpy(mdp->magic, MMALLOC_MAGIC, MMALLOC_MAGIC_SIZE);
106   mdp->headersize = sizeof(mtemp);
107   mdp->version = MMALLOC_VERSION;
108   mdp->fd = fd;
109   mdp->base = mdp->breakval = mdp->top = baseaddr;
110   mdp->next_mdesc = NULL;
111   mdp->refcount = 1;
112   
113   /* If we have not been passed a valid open file descriptor for the file
114      to map to, then we go for an anonymous map */
115
116   if (mdp->fd < 0){
117     mdp->flags |= MMALLOC_ANONYMOUS;
118     sem_init(&mdp->sem, 0, 1);
119   }else{
120     sem_init(&mdp->sem, 1, 1);
121   }
122   
123   /* If we have not been passed a valid open file descriptor for the file
124      to map to, then open /dev/zero and use that to map to. */
125
126   /* Now try to map in the first page, copy the malloc descriptor structure
127      there, and arrange to return a pointer to this new copy.  If the mapping
128      fails, then close the file descriptor if it was opened by us, and arrange
129      to return a NULL. */
130
131   if ((mbase = mmorecore(mdp, sizeof(mtemp))) != NULL) {
132     memcpy(mbase, mdp, sizeof(mtemp));
133   } else {
134     THROWF(system_error,0,"morecore failed to get some memory!");
135   }
136
137   /* Add the new heap to the linked list of heaps attached by mmalloc */  
138   if(__mmalloc_default_mdp){
139     mdp = __mmalloc_default_mdp;
140     while(mdp->next_mdesc)
141       mdp = mdp->next_mdesc;
142
143     LOCK(mdp);
144       mdp->next_mdesc = (struct mdesc *)mbase;
145     UNLOCK(mdp);
146   }
147
148   return mbase;
149 }
150
151 /* Given an valid file descriptor on an open file, test to see if that file
152    is a valid mmalloc produced file, and if so, attempt to remap it into the
153    current process at the same address to which it was previously mapped.
154
155    Note that we have to update the file descriptor number in the malloc-
156    descriptor read from the file to match the current valid one, before
157    trying to map the file in, and again after a successful mapping and
158    after we've switched over to using the mapped in malloc descriptor 
159    rather than the temporary one on the stack.
160
161    Once we've switched over to using the mapped in malloc descriptor, we
162    have to update the pointer to the morecore function, since it almost
163    certainly will be at a different address if the process reusing the
164    mapped region is from a different executable.
165
166    Also note that if the heap being remapped previously used the mmcheckf()
167    routines, we need to update the hooks since their target functions
168    will have certainly moved if the executable has changed in any way.
169    We do this by calling mmcheckf() internally.
170
171    Returns a pointer to the malloc descriptor if successful, or NULL if
172    unsuccessful for some reason. */
173
174 static struct mdesc *reuse(int fd)
175 {
176   struct mdesc mtemp;
177   struct mdesc *mdp = NULL, *mdptemp = NULL;
178
179   if (lseek(fd, 0L, SEEK_SET) != 0)
180     return NULL;
181   if (read(fd, (char *) &mtemp, sizeof(mtemp)) != sizeof(mtemp))
182     return NULL;
183   if (mtemp.headersize != sizeof(mtemp))
184     return NULL;
185   if (strcmp(mtemp.magic, MMALLOC_MAGIC) != 0)
186     return NULL;
187   if (mtemp.version > MMALLOC_VERSION)
188     return NULL;
189
190   mtemp.fd = fd;
191   if (__mmalloc_remap_core(&mtemp) == mtemp.base) {
192     mdp = (struct mdesc *) mtemp.base;
193     mdp->fd = fd;
194     if(!mdp->refcount){
195       sem_init(&mdp->sem, 1, 1);
196       mdp->refcount++;
197     }
198   }
199   
200   /* Add the new heap to the linked list of heaps attached by mmalloc */  
201   mdptemp = __mmalloc_default_mdp;
202   while(mdptemp->next_mdesc)
203     mdptemp = mdptemp->next_mdesc;
204
205   LOCK(mdptemp);
206     mdptemp->next_mdesc = mdp;
207   UNLOCK(mdptemp);
208   
209   return (mdp);
210 }
211
212
213 /** Terminate access to a mmalloc managed region, but do not free its content.
214  *
215  * This is for example useful for the base region where ldl stores its data
216  *   because it leaves the place after us.
217  */
218 void mmalloc_detach_no_free(xbt_mheap_t md)
219 {
220   struct mdesc *mdp = md;
221
222   if(--mdp->refcount == 0){
223     LOCK(mdp) ;
224     sem_destroy(&mdp->sem);
225   }
226 }
227
228 /** Terminate access to a mmalloc managed region by unmapping all memory pages
229    associated with the region, and closing the file descriptor if it is one
230    that we opened.
231
232    Returns NULL on success.
233
234    Returns the malloc descriptor on failure, which can subsequently be used
235    for further action, such as obtaining more information about the nature of
236    the failure by examining the preserved errno value.
237
238    Note that the malloc descriptor that we are using is currently located in
239    region we are about to unmap, so we first make a local copy of it on the
240    stack and use the copy. */
241
242 void *mmalloc_detach(xbt_mheap_t mdp)
243 {
244   struct mdesc mtemp, *mdptemp;
245
246   if (mdp != NULL) {
247     /* Remove the heap from the linked list of heaps attached by mmalloc */
248     mdptemp = __mmalloc_default_mdp;
249     while(mdptemp->next_mdesc != mdp )
250       mdptemp = mdptemp->next_mdesc;
251
252     mdptemp->next_mdesc = mdp->next_mdesc;
253
254     mmalloc_detach_no_free(mdp);
255     mtemp = *mdp;
256
257     /* Now unmap all the pages associated with this region by asking for a
258        negative increment equal to the current size of the region. */
259
260     if ((mmorecore(&mtemp,
261                         (char *) mtemp.base - (char *) mtemp.breakval)) ==
262         NULL) {
263       /* Deallocating failed.  Update the original malloc descriptor
264          with any changes */
265       *mdp = mtemp;
266     } else {
267       if (mtemp.flags & MMALLOC_DEVZERO) {
268         close(mtemp.fd);
269       }
270       mdp = NULL;
271     }
272   }
273
274   return (mdp);
275 }
276
277 /* Safety gap from the heap's break address.
278  * Try to increase this first if you experience strange errors under
279  * valgrind. */
280 #define HEAP_OFFSET   (128UL<<20)
281
282 xbt_mheap_t mmalloc_get_default_md(void)
283 {
284   xbt_assert(__mmalloc_default_mdp);
285   return __mmalloc_default_mdp;
286 }
287
288 static void mmalloc_fork_prepare(void)
289 {
290   xbt_mheap_t mdp = NULL;
291   if ((mdp =__mmalloc_default_mdp)){
292     while(mdp){
293       LOCK(mdp);
294       if(mdp->fd >= 0){
295         mdp->refcount++;
296       }
297       mdp = mdp->next_mdesc;
298     }
299   }
300 }
301
302 static void mmalloc_fork_parent(void)
303 {
304   xbt_mheap_t mdp = NULL;
305   if ((mdp =__mmalloc_default_mdp)){
306     while(mdp){
307       if(mdp->fd < 0)
308         UNLOCK(mdp);
309       mdp = mdp->next_mdesc;
310     }
311   }
312 }
313
314 static void mmalloc_fork_child(void)
315 {
316   struct mdesc* mdp = NULL;
317   if ((mdp =__mmalloc_default_mdp)){
318     while(mdp){
319       UNLOCK(mdp);
320       mdp = mdp->next_mdesc;
321     }
322   }
323 }
324
325
326
327 /* Initialize the default malloc descriptor. */
328 void *mmalloc_preinit(void)
329 {
330   int res;
331   if (__mmalloc_default_mdp == NULL) {
332     unsigned long mask = ~((unsigned long)getpagesize() - 1);
333     void *addr = (void*)(((unsigned long)sbrk(0) + HEAP_OFFSET) & mask);
334     __mmalloc_default_mdp = mmalloc_attach(-1, addr);
335     /* Fixme? only the default mdp in protected against forks */
336     res = xbt_os_thread_atfork(mmalloc_fork_prepare,
337                                mmalloc_fork_parent, mmalloc_fork_child);
338     if (res != 0)
339       THROWF(system_error,0,"xbt_os_thread_atfork() failed: return value %d",res);
340   }
341   xbt_assert(__mmalloc_default_mdp != NULL);
342
343   return __mmalloc_default_mdp;
344 }
345
346 void mmalloc_postexit(void)
347 {
348   /* Do not detach the default mdp or ldl won't be able to free the memory it allocated since we're in memory */
349   //  mmalloc_detach(__mmalloc_default_mdp);
350   mmalloc_detach_no_free(__mmalloc_default_mdp);
351 }