* malloc/mcheck.c (reallochook): If size==0, free the block.
[glibc.git] / malloc / arena.c
blob9e3ff47347dbe5cd3106cbcefa6f206ce97709d1
1 /* Malloc implementation for multiple threads without lock contention.
2 Copyright (C) 2001,2002,2003,2004,2005,2006,2007
3 Free Software Foundation, Inc.
4 This file is part of the GNU C Library.
5 Contributed by Wolfram Gloger <wg@malloc.de>, 2001.
7 The GNU C Library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public License as
9 published by the Free Software Foundation; either version 2.1 of the
10 License, or (at your option) any later version.
12 The GNU C Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public
18 License along with the GNU C Library; see the file COPYING.LIB. If not,
19 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 #include <stdbool.h>
24 /* Compile-time constants. */
26 #define HEAP_MIN_SIZE (32*1024)
27 #ifndef HEAP_MAX_SIZE
28 # ifdef DEFAULT_MMAP_THRESHOLD_MAX
29 # define HEAP_MAX_SIZE (2 * DEFAULT_MMAP_THRESHOLD_MAX)
30 # else
31 # define HEAP_MAX_SIZE (1024*1024) /* must be a power of two */
32 # endif
33 #endif
35 /* HEAP_MIN_SIZE and HEAP_MAX_SIZE limit the size of mmap()ed heaps
36 that are dynamically created for multi-threaded programs. The
37 maximum size must be a power of two, for fast determination of
38 which heap belongs to a chunk. It should be much larger than the
39 mmap threshold, so that requests with a size just below that
40 threshold can be fulfilled without creating too many heaps. */
43 #ifndef THREAD_STATS
44 #define THREAD_STATS 0
45 #endif
47 /* If THREAD_STATS is non-zero, some statistics on mutex locking are
48 computed. */
50 /***************************************************************************/
52 #define top(ar_ptr) ((ar_ptr)->top)
54 /* A heap is a single contiguous memory region holding (coalesceable)
55 malloc_chunks. It is allocated with mmap() and always starts at an
56 address aligned to HEAP_MAX_SIZE. Not used unless compiling with
57 USE_ARENAS. */
59 typedef struct _heap_info {
60 mstate ar_ptr; /* Arena for this heap. */
61 struct _heap_info *prev; /* Previous heap. */
62 size_t size; /* Current size in bytes. */
63 size_t mprotect_size; /* Size in bytes that has been mprotected
64 PROT_READ|PROT_WRITE. */
65 /* Make sure the following data is properly aligned, particularly
66 that sizeof (heap_info) + 2 * SIZE_SZ is a multiple of
67 MALLOC_ALIGNMENT. */
68 char pad[-6 * SIZE_SZ & MALLOC_ALIGN_MASK];
69 } heap_info;
71 /* Get a compile-time error if the heap_info padding is not correct
72 to make alignment work as expected in sYSMALLOc. */
73 extern int sanity_check_heap_info_alignment[(sizeof (heap_info)
74 + 2 * SIZE_SZ) % MALLOC_ALIGNMENT
75 ? -1 : 1];
77 /* Thread specific data */
79 static tsd_key_t arena_key;
80 static mutex_t list_lock;
82 #if THREAD_STATS
83 static int stat_n_heaps;
84 #define THREAD_STAT(x) x
85 #else
86 #define THREAD_STAT(x) do ; while(0)
87 #endif
89 /* Mapped memory in non-main arenas (reliable only for NO_THREADS). */
90 static unsigned long arena_mem;
92 /* Already initialized? */
93 int __malloc_initialized = -1;
95 /**************************************************************************/
97 #if USE_ARENAS
99 /* arena_get() acquires an arena and locks the corresponding mutex.
100 First, try the one last locked successfully by this thread. (This
101 is the common case and handled with a macro for speed.) Then, loop
102 once over the circularly linked list of arenas. If no arena is
103 readily available, create a new one. In this latter case, `size'
104 is just a hint as to how much memory will be required immediately
105 in the new arena. */
107 #define arena_get(ptr, size) do { \
108 Void_t *vptr = NULL; \
109 ptr = (mstate)tsd_getspecific(arena_key, vptr); \
110 if(ptr && !mutex_trylock(&ptr->mutex)) { \
111 THREAD_STAT(++(ptr->stat_lock_direct)); \
112 } else \
113 ptr = arena_get2(ptr, (size)); \
114 } while(0)
116 /* find the heap and corresponding arena for a given ptr */
118 #define heap_for_ptr(ptr) \
119 ((heap_info *)((unsigned long)(ptr) & ~(HEAP_MAX_SIZE-1)))
120 #define arena_for_chunk(ptr) \
121 (chunk_non_main_arena(ptr) ? heap_for_ptr(ptr)->ar_ptr : &main_arena)
123 #else /* !USE_ARENAS */
125 /* There is only one arena, main_arena. */
127 #if THREAD_STATS
128 #define arena_get(ar_ptr, sz) do { \
129 ar_ptr = &main_arena; \
130 if(!mutex_trylock(&ar_ptr->mutex)) \
131 ++(ar_ptr->stat_lock_direct); \
132 else { \
133 (void)mutex_lock(&ar_ptr->mutex); \
134 ++(ar_ptr->stat_lock_wait); \
136 } while(0)
137 #else
138 #define arena_get(ar_ptr, sz) do { \
139 ar_ptr = &main_arena; \
140 (void)mutex_lock(&ar_ptr->mutex); \
141 } while(0)
142 #endif
143 #define arena_for_chunk(ptr) (&main_arena)
145 #endif /* USE_ARENAS */
147 /**************************************************************************/
149 #ifndef NO_THREADS
151 /* atfork support. */
153 static __malloc_ptr_t (*save_malloc_hook) (size_t __size,
154 __const __malloc_ptr_t);
155 # if !defined _LIBC || (defined SHARED && !USE___THREAD)
156 static __malloc_ptr_t (*save_memalign_hook) (size_t __align, size_t __size,
157 __const __malloc_ptr_t);
158 # endif
159 static void (*save_free_hook) (__malloc_ptr_t __ptr,
160 __const __malloc_ptr_t);
161 static Void_t* save_arena;
163 /* Magic value for the thread-specific arena pointer when
164 malloc_atfork() is in use. */
166 #define ATFORK_ARENA_PTR ((Void_t*)-1)
168 /* The following hooks are used while the `atfork' handling mechanism
169 is active. */
171 static Void_t*
172 malloc_atfork(size_t sz, const Void_t *caller)
174 Void_t *vptr = NULL;
175 Void_t *victim;
177 tsd_getspecific(arena_key, vptr);
178 if(vptr == ATFORK_ARENA_PTR) {
179 /* We are the only thread that may allocate at all. */
180 if(save_malloc_hook != malloc_check) {
181 return _int_malloc(&main_arena, sz);
182 } else {
183 if(top_check()<0)
184 return 0;
185 victim = _int_malloc(&main_arena, sz+1);
186 return mem2mem_check(victim, sz);
188 } else {
189 /* Suspend the thread until the `atfork' handlers have completed.
190 By that time, the hooks will have been reset as well, so that
191 mALLOc() can be used again. */
192 (void)mutex_lock(&list_lock);
193 (void)mutex_unlock(&list_lock);
194 return public_mALLOc(sz);
198 static void
199 free_atfork(Void_t* mem, const Void_t *caller)
201 Void_t *vptr = NULL;
202 mstate ar_ptr;
203 mchunkptr p; /* chunk corresponding to mem */
205 if (mem == 0) /* free(0) has no effect */
206 return;
208 p = mem2chunk(mem); /* do not bother to replicate free_check here */
210 #if HAVE_MMAP
211 if (chunk_is_mmapped(p)) /* release mmapped memory. */
213 munmap_chunk(p);
214 return;
216 #endif
218 ar_ptr = arena_for_chunk(p);
219 tsd_getspecific(arena_key, vptr);
220 if(vptr != ATFORK_ARENA_PTR)
221 (void)mutex_lock(&ar_ptr->mutex);
222 _int_free(ar_ptr, mem);
223 if(vptr != ATFORK_ARENA_PTR)
224 (void)mutex_unlock(&ar_ptr->mutex);
228 /* Counter for number of times the list is locked by the same thread. */
229 static unsigned int atfork_recursive_cntr;
231 /* The following two functions are registered via thread_atfork() to
232 make sure that the mutexes remain in a consistent state in the
233 fork()ed version of a thread. Also adapt the malloc and free hooks
234 temporarily, because the `atfork' handler mechanism may use
235 malloc/free internally (e.g. in LinuxThreads). */
237 static void
238 ptmalloc_lock_all (void)
240 mstate ar_ptr;
242 if(__malloc_initialized < 1)
243 return;
244 if (mutex_trylock(&list_lock))
246 Void_t *my_arena;
247 tsd_getspecific(arena_key, my_arena);
248 if (my_arena == ATFORK_ARENA_PTR)
249 /* This is the same thread which already locks the global list.
250 Just bump the counter. */
251 goto out;
253 /* This thread has to wait its turn. */
254 (void)mutex_lock(&list_lock);
256 for(ar_ptr = &main_arena;;) {
257 (void)mutex_lock(&ar_ptr->mutex);
258 ar_ptr = ar_ptr->next;
259 if(ar_ptr == &main_arena) break;
261 save_malloc_hook = __malloc_hook;
262 save_free_hook = __free_hook;
263 __malloc_hook = malloc_atfork;
264 __free_hook = free_atfork;
265 /* Only the current thread may perform malloc/free calls now. */
266 tsd_getspecific(arena_key, save_arena);
267 tsd_setspecific(arena_key, ATFORK_ARENA_PTR);
268 out:
269 ++atfork_recursive_cntr;
272 static void
273 ptmalloc_unlock_all (void)
275 mstate ar_ptr;
277 if(__malloc_initialized < 1)
278 return;
279 if (--atfork_recursive_cntr != 0)
280 return;
281 tsd_setspecific(arena_key, save_arena);
282 __malloc_hook = save_malloc_hook;
283 __free_hook = save_free_hook;
284 for(ar_ptr = &main_arena;;) {
285 (void)mutex_unlock(&ar_ptr->mutex);
286 ar_ptr = ar_ptr->next;
287 if(ar_ptr == &main_arena) break;
289 (void)mutex_unlock(&list_lock);
292 #ifdef __linux__
294 /* In NPTL, unlocking a mutex in the child process after a
295 fork() is currently unsafe, whereas re-initializing it is safe and
296 does not leak resources. Therefore, a special atfork handler is
297 installed for the child. */
299 static void
300 ptmalloc_unlock_all2 (void)
302 mstate ar_ptr;
304 if(__malloc_initialized < 1)
305 return;
306 #if defined _LIBC || defined MALLOC_HOOKS
307 tsd_setspecific(arena_key, save_arena);
308 __malloc_hook = save_malloc_hook;
309 __free_hook = save_free_hook;
310 #endif
311 for(ar_ptr = &main_arena;;) {
312 mutex_init(&ar_ptr->mutex);
313 ar_ptr = ar_ptr->next;
314 if(ar_ptr == &main_arena) break;
316 mutex_init(&list_lock);
317 atfork_recursive_cntr = 0;
320 #else
322 #define ptmalloc_unlock_all2 ptmalloc_unlock_all
324 #endif
326 #endif /* !defined NO_THREADS */
328 /* Initialization routine. */
329 #ifdef _LIBC
330 #include <string.h>
331 extern char **_environ;
333 static char *
334 internal_function
335 next_env_entry (char ***position)
337 char **current = *position;
338 char *result = NULL;
340 while (*current != NULL)
342 if (__builtin_expect ((*current)[0] == 'M', 0)
343 && (*current)[1] == 'A'
344 && (*current)[2] == 'L'
345 && (*current)[3] == 'L'
346 && (*current)[4] == 'O'
347 && (*current)[5] == 'C'
348 && (*current)[6] == '_')
350 result = &(*current)[7];
352 /* Save current position for next visit. */
353 *position = ++current;
355 break;
358 ++current;
361 return result;
363 #endif /* _LIBC */
365 /* Set up basic state so that _int_malloc et al can work. */
366 static void
367 ptmalloc_init_minimal (void)
369 #if DEFAULT_TOP_PAD != 0
370 mp_.top_pad = DEFAULT_TOP_PAD;
371 #endif
372 mp_.n_mmaps_max = DEFAULT_MMAP_MAX;
373 #if MALLOC_DEBUG
374 mp_.n_mmaps_cmax = DEFAULT_MMAP_MAX;
375 #endif
376 mp_.mmap_threshold = DEFAULT_MMAP_THRESHOLD;
377 mp_.trim_threshold = DEFAULT_TRIM_THRESHOLD;
378 mp_.pagesize = malloc_getpagesize;
382 #ifdef _LIBC
383 # ifdef SHARED
384 static void *
385 __failing_morecore (ptrdiff_t d)
387 return (void *) MORECORE_FAILURE;
390 extern struct dl_open_hook *_dl_open_hook;
391 libc_hidden_proto (_dl_open_hook);
392 # endif
394 # if defined SHARED && !USE___THREAD
395 /* This is called by __pthread_initialize_minimal when it needs to use
396 malloc to set up the TLS state. We cannot do the full work of
397 ptmalloc_init (below) until __pthread_initialize_minimal has finished,
398 so it has to switch to using the special startup-time hooks while doing
399 those allocations. */
400 void
401 __libc_malloc_pthread_startup (bool first_time)
403 if (first_time)
405 ptmalloc_init_minimal ();
406 save_malloc_hook = __malloc_hook;
407 save_memalign_hook = __memalign_hook;
408 save_free_hook = __free_hook;
409 __malloc_hook = malloc_starter;
410 __memalign_hook = memalign_starter;
411 __free_hook = free_starter;
413 else
415 __malloc_hook = save_malloc_hook;
416 __memalign_hook = save_memalign_hook;
417 __free_hook = save_free_hook;
420 # endif
421 #endif
423 static void
424 ptmalloc_init (void)
426 #if __STD_C
427 const char* s;
428 #else
429 char* s;
430 #endif
431 int secure = 0;
433 if(__malloc_initialized >= 0) return;
434 __malloc_initialized = 0;
436 #ifdef _LIBC
437 # if defined SHARED && !USE___THREAD
438 /* ptmalloc_init_minimal may already have been called via
439 __libc_malloc_pthread_startup, above. */
440 if (mp_.pagesize == 0)
441 # endif
442 #endif
443 ptmalloc_init_minimal();
445 #ifndef NO_THREADS
446 # if defined _LIBC
447 /* We know __pthread_initialize_minimal has already been called,
448 and that is enough. */
449 # define NO_STARTER
450 # endif
451 # ifndef NO_STARTER
452 /* With some threads implementations, creating thread-specific data
453 or initializing a mutex may call malloc() itself. Provide a
454 simple starter version (realloc() won't work). */
455 save_malloc_hook = __malloc_hook;
456 save_memalign_hook = __memalign_hook;
457 save_free_hook = __free_hook;
458 __malloc_hook = malloc_starter;
459 __memalign_hook = memalign_starter;
460 __free_hook = free_starter;
461 # ifdef _LIBC
462 /* Initialize the pthreads interface. */
463 if (__pthread_initialize != NULL)
464 __pthread_initialize();
465 # endif /* !defined _LIBC */
466 # endif /* !defined NO_STARTER */
467 #endif /* !defined NO_THREADS */
468 mutex_init(&main_arena.mutex);
469 main_arena.next = &main_arena;
471 #if defined _LIBC && defined SHARED
472 /* In case this libc copy is in a non-default namespace, never use brk.
473 Likewise if dlopened from statically linked program. */
474 Dl_info di;
475 struct link_map *l;
477 if (_dl_open_hook != NULL
478 || (_dl_addr (ptmalloc_init, &di, &l, NULL) != 0
479 && l->l_ns != LM_ID_BASE))
480 __morecore = __failing_morecore;
481 #endif
483 mutex_init(&list_lock);
484 tsd_key_create(&arena_key, NULL);
485 tsd_setspecific(arena_key, (Void_t *)&main_arena);
486 thread_atfork(ptmalloc_lock_all, ptmalloc_unlock_all, ptmalloc_unlock_all2);
487 #ifndef NO_THREADS
488 # ifndef NO_STARTER
489 __malloc_hook = save_malloc_hook;
490 __memalign_hook = save_memalign_hook;
491 __free_hook = save_free_hook;
492 # else
493 # undef NO_STARTER
494 # endif
495 #endif
496 #ifdef _LIBC
497 secure = __libc_enable_secure;
498 s = NULL;
499 if (__builtin_expect (_environ != NULL, 1))
501 char **runp = _environ;
502 char *envline;
504 while (__builtin_expect ((envline = next_env_entry (&runp)) != NULL,
507 size_t len = strcspn (envline, "=");
509 if (envline[len] != '=')
510 /* This is a "MALLOC_" variable at the end of the string
511 without a '=' character. Ignore it since otherwise we
512 will access invalid memory below. */
513 continue;
515 switch (len)
517 case 6:
518 if (memcmp (envline, "CHECK_", 6) == 0)
519 s = &envline[7];
520 break;
521 case 8:
522 if (! secure)
524 if (memcmp (envline, "TOP_PAD_", 8) == 0)
525 mALLOPt(M_TOP_PAD, atoi(&envline[9]));
526 else if (memcmp (envline, "PERTURB_", 8) == 0)
527 mALLOPt(M_PERTURB, atoi(&envline[9]));
529 break;
530 case 9:
531 if (! secure && memcmp (envline, "MMAP_MAX_", 9) == 0)
532 mALLOPt(M_MMAP_MAX, atoi(&envline[10]));
533 break;
534 case 15:
535 if (! secure)
537 if (memcmp (envline, "TRIM_THRESHOLD_", 15) == 0)
538 mALLOPt(M_TRIM_THRESHOLD, atoi(&envline[16]));
539 else if (memcmp (envline, "MMAP_THRESHOLD_", 15) == 0)
540 mALLOPt(M_MMAP_THRESHOLD, atoi(&envline[16]));
542 break;
543 default:
544 break;
548 #else
549 if (! secure)
551 if((s = getenv("MALLOC_TRIM_THRESHOLD_")))
552 mALLOPt(M_TRIM_THRESHOLD, atoi(s));
553 if((s = getenv("MALLOC_TOP_PAD_")))
554 mALLOPt(M_TOP_PAD, atoi(s));
555 if((s = getenv("MALLOC_PERTURB_")))
556 mALLOPt(M_PERTURB, atoi(s));
557 if((s = getenv("MALLOC_MMAP_THRESHOLD_")))
558 mALLOPt(M_MMAP_THRESHOLD, atoi(s));
559 if((s = getenv("MALLOC_MMAP_MAX_")))
560 mALLOPt(M_MMAP_MAX, atoi(s));
562 s = getenv("MALLOC_CHECK_");
563 #endif
564 if(s && s[0]) {
565 mALLOPt(M_CHECK_ACTION, (int)(s[0] - '0'));
566 if (check_action != 0)
567 __malloc_check_init();
569 if(__malloc_initialize_hook != NULL)
570 (*__malloc_initialize_hook)();
571 __malloc_initialized = 1;
574 /* There are platforms (e.g. Hurd) with a link-time hook mechanism. */
575 #ifdef thread_atfork_static
576 thread_atfork_static(ptmalloc_lock_all, ptmalloc_unlock_all, \
577 ptmalloc_unlock_all2)
578 #endif
582 /* Managing heaps and arenas (for concurrent threads) */
584 #if USE_ARENAS
586 #if MALLOC_DEBUG > 1
588 /* Print the complete contents of a single heap to stderr. */
590 static void
591 #if __STD_C
592 dump_heap(heap_info *heap)
593 #else
594 dump_heap(heap) heap_info *heap;
595 #endif
597 char *ptr;
598 mchunkptr p;
600 fprintf(stderr, "Heap %p, size %10lx:\n", heap, (long)heap->size);
601 ptr = (heap->ar_ptr != (mstate)(heap+1)) ?
602 (char*)(heap + 1) : (char*)(heap + 1) + sizeof(struct malloc_state);
603 p = (mchunkptr)(((unsigned long)ptr + MALLOC_ALIGN_MASK) &
604 ~MALLOC_ALIGN_MASK);
605 for(;;) {
606 fprintf(stderr, "chunk %p size %10lx", p, (long)p->size);
607 if(p == top(heap->ar_ptr)) {
608 fprintf(stderr, " (top)\n");
609 break;
610 } else if(p->size == (0|PREV_INUSE)) {
611 fprintf(stderr, " (fence)\n");
612 break;
614 fprintf(stderr, "\n");
615 p = next_chunk(p);
619 #endif /* MALLOC_DEBUG > 1 */
621 /* If consecutive mmap (0, HEAP_MAX_SIZE << 1, ...) calls return decreasing
622 addresses as opposed to increasing, new_heap would badly fragment the
623 address space. In that case remember the second HEAP_MAX_SIZE part
624 aligned to HEAP_MAX_SIZE from last mmap (0, HEAP_MAX_SIZE << 1, ...)
625 call (if it is already aligned) and try to reuse it next time. We need
626 no locking for it, as kernel ensures the atomicity for us - worst case
627 we'll call mmap (addr, HEAP_MAX_SIZE, ...) for some value of addr in
628 multiple threads, but only one will succeed. */
629 static char *aligned_heap_area;
631 /* Create a new heap. size is automatically rounded up to a multiple
632 of the page size. */
634 static heap_info *
635 internal_function
636 #if __STD_C
637 new_heap(size_t size, size_t top_pad)
638 #else
639 new_heap(size, top_pad) size_t size, top_pad;
640 #endif
642 size_t page_mask = malloc_getpagesize - 1;
643 char *p1, *p2;
644 unsigned long ul;
645 heap_info *h;
647 if(size+top_pad < HEAP_MIN_SIZE)
648 size = HEAP_MIN_SIZE;
649 else if(size+top_pad <= HEAP_MAX_SIZE)
650 size += top_pad;
651 else if(size > HEAP_MAX_SIZE)
652 return 0;
653 else
654 size = HEAP_MAX_SIZE;
655 size = (size + page_mask) & ~page_mask;
657 /* A memory region aligned to a multiple of HEAP_MAX_SIZE is needed.
658 No swap space needs to be reserved for the following large
659 mapping (on Linux, this is the case for all non-writable mappings
660 anyway). */
661 p2 = MAP_FAILED;
662 if(aligned_heap_area) {
663 p2 = (char *)MMAP(aligned_heap_area, HEAP_MAX_SIZE, PROT_NONE,
664 MAP_PRIVATE|MAP_NORESERVE);
665 aligned_heap_area = NULL;
666 if (p2 != MAP_FAILED && ((unsigned long)p2 & (HEAP_MAX_SIZE-1))) {
667 munmap(p2, HEAP_MAX_SIZE);
668 p2 = MAP_FAILED;
671 if(p2 == MAP_FAILED) {
672 p1 = (char *)MMAP(0, HEAP_MAX_SIZE<<1, PROT_NONE,
673 MAP_PRIVATE|MAP_NORESERVE);
674 if(p1 != MAP_FAILED) {
675 p2 = (char *)(((unsigned long)p1 + (HEAP_MAX_SIZE-1))
676 & ~(HEAP_MAX_SIZE-1));
677 ul = p2 - p1;
678 if (ul)
679 munmap(p1, ul);
680 else
681 aligned_heap_area = p2 + HEAP_MAX_SIZE;
682 munmap(p2 + HEAP_MAX_SIZE, HEAP_MAX_SIZE - ul);
683 } else {
684 /* Try to take the chance that an allocation of only HEAP_MAX_SIZE
685 is already aligned. */
686 p2 = (char *)MMAP(0, HEAP_MAX_SIZE, PROT_NONE, MAP_PRIVATE|MAP_NORESERVE);
687 if(p2 == MAP_FAILED)
688 return 0;
689 if((unsigned long)p2 & (HEAP_MAX_SIZE-1)) {
690 munmap(p2, HEAP_MAX_SIZE);
691 return 0;
695 if(mprotect(p2, size, PROT_READ|PROT_WRITE) != 0) {
696 munmap(p2, HEAP_MAX_SIZE);
697 return 0;
699 h = (heap_info *)p2;
700 h->size = size;
701 h->mprotect_size = size;
702 THREAD_STAT(stat_n_heaps++);
703 return h;
706 /* Grow or shrink a heap. size is automatically rounded up to a
707 multiple of the page size if it is positive. */
709 static int
710 #if __STD_C
711 grow_heap(heap_info *h, long diff)
712 #else
713 grow_heap(h, diff) heap_info *h; long diff;
714 #endif
716 size_t page_mask = malloc_getpagesize - 1;
717 long new_size;
719 if(diff >= 0) {
720 diff = (diff + page_mask) & ~page_mask;
721 new_size = (long)h->size + diff;
722 if((unsigned long) new_size > (unsigned long) HEAP_MAX_SIZE)
723 return -1;
724 if((unsigned long) new_size > h->mprotect_size) {
725 if (mprotect((char *)h + h->mprotect_size,
726 (unsigned long) new_size - h->mprotect_size,
727 PROT_READ|PROT_WRITE) != 0)
728 return -2;
729 h->mprotect_size = new_size;
731 } else {
732 new_size = (long)h->size + diff;
733 if(new_size < (long)sizeof(*h))
734 return -1;
735 /* Try to re-map the extra heap space freshly to save memory, and
736 make it inaccessible. */
737 #ifdef _LIBC
738 if (__builtin_expect (__libc_enable_secure, 0))
739 #else
740 if (1)
741 #endif
743 if((char *)MMAP((char *)h + new_size, -diff, PROT_NONE,
744 MAP_PRIVATE|MAP_FIXED) == (char *) MAP_FAILED)
745 return -2;
746 h->mprotect_size = new_size;
748 #ifdef _LIBC
749 else
750 madvise ((char *)h + new_size, -diff, MADV_DONTNEED);
751 #endif
752 /*fprintf(stderr, "shrink %p %08lx\n", h, new_size);*/
754 h->size = new_size;
755 return 0;
758 /* Delete a heap. */
760 #define delete_heap(heap) \
761 do { \
762 if ((char *)(heap) + HEAP_MAX_SIZE == aligned_heap_area) \
763 aligned_heap_area = NULL; \
764 munmap((char*)(heap), HEAP_MAX_SIZE); \
765 } while (0)
767 static int
768 internal_function
769 #if __STD_C
770 heap_trim(heap_info *heap, size_t pad)
771 #else
772 heap_trim(heap, pad) heap_info *heap; size_t pad;
773 #endif
775 mstate ar_ptr = heap->ar_ptr;
776 unsigned long pagesz = mp_.pagesize;
777 mchunkptr top_chunk = top(ar_ptr), p, bck, fwd;
778 heap_info *prev_heap;
779 long new_size, top_size, extra;
781 /* Can this heap go away completely? */
782 while(top_chunk == chunk_at_offset(heap, sizeof(*heap))) {
783 prev_heap = heap->prev;
784 p = chunk_at_offset(prev_heap, prev_heap->size - (MINSIZE-2*SIZE_SZ));
785 assert(p->size == (0|PREV_INUSE)); /* must be fencepost */
786 p = prev_chunk(p);
787 new_size = chunksize(p) + (MINSIZE-2*SIZE_SZ);
788 assert(new_size>0 && new_size<(long)(2*MINSIZE));
789 if(!prev_inuse(p))
790 new_size += p->prev_size;
791 assert(new_size>0 && new_size<HEAP_MAX_SIZE);
792 if(new_size + (HEAP_MAX_SIZE - prev_heap->size) < pad + MINSIZE + pagesz)
793 break;
794 ar_ptr->system_mem -= heap->size;
795 arena_mem -= heap->size;
796 delete_heap(heap);
797 heap = prev_heap;
798 if(!prev_inuse(p)) { /* consolidate backward */
799 p = prev_chunk(p);
800 unlink(p, bck, fwd);
802 assert(((unsigned long)((char*)p + new_size) & (pagesz-1)) == 0);
803 assert( ((char*)p + new_size) == ((char*)heap + heap->size) );
804 top(ar_ptr) = top_chunk = p;
805 set_head(top_chunk, new_size | PREV_INUSE);
806 /*check_chunk(ar_ptr, top_chunk);*/
808 top_size = chunksize(top_chunk);
809 extra = ((top_size - pad - MINSIZE + (pagesz-1))/pagesz - 1) * pagesz;
810 if(extra < (long)pagesz)
811 return 0;
812 /* Try to shrink. */
813 if(grow_heap(heap, -extra) != 0)
814 return 0;
815 ar_ptr->system_mem -= extra;
816 arena_mem -= extra;
818 /* Success. Adjust top accordingly. */
819 set_head(top_chunk, (top_size - extra) | PREV_INUSE);
820 /*check_chunk(ar_ptr, top_chunk);*/
821 return 1;
824 /* Create a new arena with initial size "size". */
826 static mstate
827 _int_new_arena(size_t size)
829 mstate a;
830 heap_info *h;
831 char *ptr;
832 unsigned long misalign;
834 h = new_heap(size + (sizeof(*h) + sizeof(*a) + MALLOC_ALIGNMENT),
835 mp_.top_pad);
836 if(!h) {
837 /* Maybe size is too large to fit in a single heap. So, just try
838 to create a minimally-sized arena and let _int_malloc() attempt
839 to deal with the large request via mmap_chunk(). */
840 h = new_heap(sizeof(*h) + sizeof(*a) + MALLOC_ALIGNMENT, mp_.top_pad);
841 if(!h)
842 return 0;
844 a = h->ar_ptr = (mstate)(h+1);
845 malloc_init_state(a);
846 /*a->next = NULL;*/
847 a->system_mem = a->max_system_mem = h->size;
848 arena_mem += h->size;
849 #ifdef NO_THREADS
850 if((unsigned long)(mp_.mmapped_mem + arena_mem + main_arena.system_mem) >
851 mp_.max_total_mem)
852 mp_.max_total_mem = mp_.mmapped_mem + arena_mem + main_arena.system_mem;
853 #endif
855 /* Set up the top chunk, with proper alignment. */
856 ptr = (char *)(a + 1);
857 misalign = (unsigned long)chunk2mem(ptr) & MALLOC_ALIGN_MASK;
858 if (misalign > 0)
859 ptr += MALLOC_ALIGNMENT - misalign;
860 top(a) = (mchunkptr)ptr;
861 set_head(top(a), (((char*)h + h->size) - ptr) | PREV_INUSE);
863 return a;
866 static mstate
867 internal_function
868 #if __STD_C
869 arena_get2(mstate a_tsd, size_t size)
870 #else
871 arena_get2(a_tsd, size) mstate a_tsd; size_t size;
872 #endif
874 mstate a;
876 if(!a_tsd)
877 a = a_tsd = &main_arena;
878 else {
879 a = a_tsd->next;
880 if(!a) {
881 /* This can only happen while initializing the new arena. */
882 (void)mutex_lock(&main_arena.mutex);
883 THREAD_STAT(++(main_arena.stat_lock_wait));
884 return &main_arena;
888 /* Check the global, circularly linked list for available arenas. */
889 bool retried = false;
890 repeat:
891 do {
892 if(!mutex_trylock(&a->mutex)) {
893 if (retried)
894 (void)mutex_unlock(&list_lock);
895 THREAD_STAT(++(a->stat_lock_loop));
896 tsd_setspecific(arena_key, (Void_t *)a);
897 return a;
899 a = a->next;
900 } while(a != a_tsd);
902 /* If not even the list_lock can be obtained, try again. This can
903 happen during `atfork', or for example on systems where thread
904 creation makes it temporarily impossible to obtain _any_
905 locks. */
906 if(!retried && mutex_trylock(&list_lock)) {
907 /* We will block to not run in a busy loop. */
908 (void)mutex_lock(&list_lock);
910 /* Since we blocked there might be an arena available now. */
911 retried = true;
912 a = a_tsd;
913 goto repeat;
916 /* Nothing immediately available, so generate a new arena. */
917 a = _int_new_arena(size);
918 if(a)
920 tsd_setspecific(arena_key, (Void_t *)a);
921 mutex_init(&a->mutex);
922 mutex_lock(&a->mutex); /* remember result */
924 /* Add the new arena to the global list. */
925 a->next = main_arena.next;
926 atomic_write_barrier ();
927 main_arena.next = a;
929 THREAD_STAT(++(a->stat_lock_loop));
931 (void)mutex_unlock(&list_lock);
933 return a;
936 #endif /* USE_ARENAS */
939 * Local variables:
940 * c-basic-offset: 2
941 * End: