Update.
[glibc.git] / malloc / malloc.c
blob4bdc2585cb45232d22526d2b1105e60f820559a1
1 /* Malloc implementation for multiple threads without lock contention.
2 Copyright (C) 1996, 1997, 1998, 1999 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Wolfram Gloger <wmglo@dent.med.uni-muenchen.de>
5 and Doug Lea <dl@cs.oswego.edu>, 1996.
7 The GNU C Library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Library General Public License as
9 published by the Free Software Foundation; either version 2 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 Library General Public License for more details.
17 You should have received a copy of the GNU Library 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 /* V2.6.4-pt3 Thu Feb 20 1997
24 This work is mainly derived from malloc-2.6.4 by Doug Lea
25 <dl@cs.oswego.edu>, which is available from:
27 ftp://g.oswego.edu/pub/misc/malloc.c
29 Most of the original comments are reproduced in the code below.
31 * Why use this malloc?
33 This is not the fastest, most space-conserving, most portable, or
34 most tunable malloc ever written. However it is among the fastest
35 while also being among the most space-conserving, portable and tunable.
36 Consistent balance across these factors results in a good general-purpose
37 allocator. For a high-level description, see
38 http://g.oswego.edu/dl/html/malloc.html
40 On many systems, the standard malloc implementation is by itself not
41 thread-safe, and therefore wrapped with a single global lock around
42 all malloc-related functions. In some applications, especially with
43 multiple available processors, this can lead to contention problems
44 and bad performance. This malloc version was designed with the goal
45 to avoid waiting for locks as much as possible. Statistics indicate
46 that this goal is achieved in many cases.
48 * Synopsis of public routines
50 (Much fuller descriptions are contained in the program documentation below.)
52 ptmalloc_init();
53 Initialize global configuration. When compiled for multiple threads,
54 this function must be called once before any other function in the
55 package. It is not required otherwise. It is called automatically
56 in the Linux/GNU C libray or when compiling with MALLOC_HOOKS.
57 malloc(size_t n);
58 Return a pointer to a newly allocated chunk of at least n bytes, or null
59 if no space is available.
60 free(Void_t* p);
61 Release the chunk of memory pointed to by p, or no effect if p is null.
62 realloc(Void_t* p, size_t n);
63 Return a pointer to a chunk of size n that contains the same data
64 as does chunk p up to the minimum of (n, p's size) bytes, or null
65 if no space is available. The returned pointer may or may not be
66 the same as p. If p is null, equivalent to malloc. Unless the
67 #define REALLOC_ZERO_BYTES_FREES below is set, realloc with a
68 size argument of zero (re)allocates a minimum-sized chunk.
69 memalign(size_t alignment, size_t n);
70 Return a pointer to a newly allocated chunk of n bytes, aligned
71 in accord with the alignment argument, which must be a power of
72 two.
73 valloc(size_t n);
74 Equivalent to memalign(pagesize, n), where pagesize is the page
75 size of the system (or as near to this as can be figured out from
76 all the includes/defines below.)
77 pvalloc(size_t n);
78 Equivalent to valloc(minimum-page-that-holds(n)), that is,
79 round up n to nearest pagesize.
80 calloc(size_t unit, size_t quantity);
81 Returns a pointer to quantity * unit bytes, with all locations
82 set to zero.
83 cfree(Void_t* p);
84 Equivalent to free(p).
85 malloc_trim(size_t pad);
86 Release all but pad bytes of freed top-most memory back
87 to the system. Return 1 if successful, else 0.
88 malloc_usable_size(Void_t* p);
89 Report the number usable allocated bytes associated with allocated
90 chunk p. This may or may not report more bytes than were requested,
91 due to alignment and minimum size constraints.
92 malloc_stats();
93 Prints brief summary statistics on stderr.
94 mallinfo()
95 Returns (by copy) a struct containing various summary statistics.
96 mallopt(int parameter_number, int parameter_value)
97 Changes one of the tunable parameters described below. Returns
98 1 if successful in changing the parameter, else 0.
100 * Vital statistics:
102 Alignment: 8-byte
103 8 byte alignment is currently hardwired into the design. This
104 seems to suffice for all current machines and C compilers.
106 Assumed pointer representation: 4 or 8 bytes
107 Code for 8-byte pointers is untested by me but has worked
108 reliably by Wolfram Gloger, who contributed most of the
109 changes supporting this.
111 Assumed size_t representation: 4 or 8 bytes
112 Note that size_t is allowed to be 4 bytes even if pointers are 8.
114 Minimum overhead per allocated chunk: 4 or 8 bytes
115 Each malloced chunk has a hidden overhead of 4 bytes holding size
116 and status information.
118 Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead)
119 8-byte ptrs: 24/32 bytes (including, 4/8 overhead)
121 When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte
122 ptrs but 4 byte size) or 24 (for 8/8) additional bytes are
123 needed; 4 (8) for a trailing size field
124 and 8 (16) bytes for free list pointers. Thus, the minimum
125 allocatable size is 16/24/32 bytes.
127 Even a request for zero bytes (i.e., malloc(0)) returns a
128 pointer to something of the minimum allocatable size.
130 Maximum allocated size: 4-byte size_t: 2^31 - 8 bytes
131 8-byte size_t: 2^63 - 16 bytes
133 It is assumed that (possibly signed) size_t bit values suffice to
134 represent chunk sizes. `Possibly signed' is due to the fact
135 that `size_t' may be defined on a system as either a signed or
136 an unsigned type. To be conservative, values that would appear
137 as negative numbers are avoided.
138 Requests for sizes with a negative sign bit will return a
139 minimum-sized chunk.
141 Maximum overhead wastage per allocated chunk: normally 15 bytes
143 Alignment demands, plus the minimum allocatable size restriction
144 make the normal worst-case wastage 15 bytes (i.e., up to 15
145 more bytes will be allocated than were requested in malloc), with
146 two exceptions:
147 1. Because requests for zero bytes allocate non-zero space,
148 the worst case wastage for a request of zero bytes is 24 bytes.
149 2. For requests >= mmap_threshold that are serviced via
150 mmap(), the worst case wastage is 8 bytes plus the remainder
151 from a system page (the minimal mmap unit); typically 4096 bytes.
153 * Limitations
155 Here are some features that are NOT currently supported
157 * No automated mechanism for fully checking that all accesses
158 to malloced memory stay within their bounds.
159 * No support for compaction.
161 * Synopsis of compile-time options:
163 People have reported using previous versions of this malloc on all
164 versions of Unix, sometimes by tweaking some of the defines
165 below. It has been tested most extensively on Solaris and
166 Linux. People have also reported adapting this malloc for use in
167 stand-alone embedded systems.
169 The implementation is in straight, hand-tuned ANSI C. Among other
170 consequences, it uses a lot of macros. Because of this, to be at
171 all usable, this code should be compiled using an optimizing compiler
172 (for example gcc -O2) that can simplify expressions and control
173 paths.
175 __STD_C (default: derived from C compiler defines)
176 Nonzero if using ANSI-standard C compiler, a C++ compiler, or
177 a C compiler sufficiently close to ANSI to get away with it.
178 MALLOC_DEBUG (default: NOT defined)
179 Define to enable debugging. Adds fairly extensive assertion-based
180 checking to help track down memory errors, but noticeably slows down
181 execution.
182 MALLOC_HOOKS (default: NOT defined)
183 Define to enable support run-time replacement of the allocation
184 functions through user-defined `hooks'.
185 REALLOC_ZERO_BYTES_FREES (default: NOT defined)
186 Define this if you think that realloc(p, 0) should be equivalent
187 to free(p). Otherwise, since malloc returns a unique pointer for
188 malloc(0), so does realloc(p, 0).
189 HAVE_MEMCPY (default: defined)
190 Define if you are not otherwise using ANSI STD C, but still
191 have memcpy and memset in your C library and want to use them.
192 Otherwise, simple internal versions are supplied.
193 USE_MEMCPY (default: 1 if HAVE_MEMCPY is defined, 0 otherwise)
194 Define as 1 if you want the C library versions of memset and
195 memcpy called in realloc and calloc (otherwise macro versions are used).
196 At least on some platforms, the simple macro versions usually
197 outperform libc versions.
198 HAVE_MMAP (default: defined as 1)
199 Define to non-zero to optionally make malloc() use mmap() to
200 allocate very large blocks.
201 HAVE_MREMAP (default: defined as 0 unless Linux libc set)
202 Define to non-zero to optionally make realloc() use mremap() to
203 reallocate very large blocks.
204 malloc_getpagesize (default: derived from system #includes)
205 Either a constant or routine call returning the system page size.
206 HAVE_USR_INCLUDE_MALLOC_H (default: NOT defined)
207 Optionally define if you are on a system with a /usr/include/malloc.h
208 that declares struct mallinfo. It is not at all necessary to
209 define this even if you do, but will ensure consistency.
210 INTERNAL_SIZE_T (default: size_t)
211 Define to a 32-bit type (probably `unsigned int') if you are on a
212 64-bit machine, yet do not want or need to allow malloc requests of
213 greater than 2^31 to be handled. This saves space, especially for
214 very small chunks.
215 _LIBC (default: NOT defined)
216 Defined only when compiled as part of the Linux libc/glibc.
217 Also note that there is some odd internal name-mangling via defines
218 (for example, internally, `malloc' is named `mALLOc') needed
219 when compiling in this case. These look funny but don't otherwise
220 affect anything.
221 LACKS_UNISTD_H (default: undefined)
222 Define this if your system does not have a <unistd.h>.
223 MORECORE (default: sbrk)
224 The name of the routine to call to obtain more memory from the system.
225 MORECORE_FAILURE (default: -1)
226 The value returned upon failure of MORECORE.
227 MORECORE_CLEARS (default 1)
228 True (1) if the routine mapped to MORECORE zeroes out memory (which
229 holds for sbrk).
230 DEFAULT_TRIM_THRESHOLD
231 DEFAULT_TOP_PAD
232 DEFAULT_MMAP_THRESHOLD
233 DEFAULT_MMAP_MAX
234 Default values of tunable parameters (described in detail below)
235 controlling interaction with host system routines (sbrk, mmap, etc).
236 These values may also be changed dynamically via mallopt(). The
237 preset defaults are those that give best performance for typical
238 programs/systems.
239 DEFAULT_CHECK_ACTION
240 When the standard debugging hooks are in place, and a pointer is
241 detected as corrupt, do nothing (0), print an error message (1),
242 or call abort() (2).
249 * Compile-time options for multiple threads:
251 USE_PTHREADS, USE_THR, USE_SPROC
252 Define one of these as 1 to select the thread interface:
253 POSIX threads, Solaris threads or SGI sproc's, respectively.
254 If none of these is defined as non-zero, you get a `normal'
255 malloc implementation which is not thread-safe. Support for
256 multiple threads requires HAVE_MMAP=1. As an exception, when
257 compiling for GNU libc, i.e. when _LIBC is defined, then none of
258 the USE_... symbols have to be defined.
260 HEAP_MIN_SIZE
261 HEAP_MAX_SIZE
262 When thread support is enabled, additional `heap's are created
263 with mmap calls. These are limited in size; HEAP_MIN_SIZE should
264 be a multiple of the page size, while HEAP_MAX_SIZE must be a power
265 of two for alignment reasons. HEAP_MAX_SIZE should be at least
266 twice as large as the mmap threshold.
267 THREAD_STATS
268 When this is defined as non-zero, some statistics on mutex locking
269 are computed.
276 /* Preliminaries */
278 #ifndef __STD_C
279 #if defined (__STDC__)
280 #define __STD_C 1
281 #else
282 #if __cplusplus
283 #define __STD_C 1
284 #else
285 #define __STD_C 0
286 #endif /*__cplusplus*/
287 #endif /*__STDC__*/
288 #endif /*__STD_C*/
290 #ifndef Void_t
291 #if __STD_C
292 #define Void_t void
293 #else
294 #define Void_t char
295 #endif
296 #endif /*Void_t*/
298 #if __STD_C
299 # include <stddef.h> /* for size_t */
300 # if defined _LIBC || defined MALLOC_HOOKS
301 # include <stdlib.h> /* for getenv(), abort() */
302 # endif
303 #else
304 # include <sys/types.h>
305 #endif
307 /* Macros for handling mutexes and thread-specific data. This is
308 included early, because some thread-related header files (such as
309 pthread.h) should be included before any others. */
310 #include "thread-m.h"
312 #ifdef __cplusplus
313 extern "C" {
314 #endif
316 #include <stdio.h> /* needed for malloc_stats */
320 Compile-time options
325 Debugging:
327 Because freed chunks may be overwritten with link fields, this
328 malloc will often die when freed memory is overwritten by user
329 programs. This can be very effective (albeit in an annoying way)
330 in helping track down dangling pointers.
332 If you compile with -DMALLOC_DEBUG, a number of assertion checks are
333 enabled that will catch more memory errors. You probably won't be
334 able to make much sense of the actual assertion errors, but they
335 should help you locate incorrectly overwritten memory. The
336 checking is fairly extensive, and will slow down execution
337 noticeably. Calling malloc_stats or mallinfo with MALLOC_DEBUG set will
338 attempt to check every non-mmapped allocated and free chunk in the
339 course of computing the summaries. (By nature, mmapped regions
340 cannot be checked very much automatically.)
342 Setting MALLOC_DEBUG may also be helpful if you are trying to modify
343 this code. The assertions in the check routines spell out in more
344 detail the assumptions and invariants underlying the algorithms.
348 #if MALLOC_DEBUG
349 #include <assert.h>
350 #else
351 #define assert(x) ((void)0)
352 #endif
356 INTERNAL_SIZE_T is the word-size used for internal bookkeeping
357 of chunk sizes. On a 64-bit machine, you can reduce malloc
358 overhead by defining INTERNAL_SIZE_T to be a 32 bit `unsigned int'
359 at the expense of not being able to handle requests greater than
360 2^31. This limitation is hardly ever a concern; you are encouraged
361 to set this. However, the default version is the same as size_t.
364 #ifndef INTERNAL_SIZE_T
365 #define INTERNAL_SIZE_T size_t
366 #endif
369 REALLOC_ZERO_BYTES_FREES should be set if a call to
370 realloc with zero bytes should be the same as a call to free.
371 Some people think it should. Otherwise, since this malloc
372 returns a unique pointer for malloc(0), so does realloc(p, 0).
376 #define REALLOC_ZERO_BYTES_FREES
380 HAVE_MEMCPY should be defined if you are not otherwise using
381 ANSI STD C, but still have memcpy and memset in your C library
382 and want to use them in calloc and realloc. Otherwise simple
383 macro versions are defined here.
385 USE_MEMCPY should be defined as 1 if you actually want to
386 have memset and memcpy called. People report that the macro
387 versions are often enough faster than libc versions on many
388 systems that it is better to use them.
392 #define HAVE_MEMCPY 1
394 #ifndef USE_MEMCPY
395 #ifdef HAVE_MEMCPY
396 #define USE_MEMCPY 1
397 #else
398 #define USE_MEMCPY 0
399 #endif
400 #endif
402 #if (__STD_C || defined(HAVE_MEMCPY))
404 #if __STD_C
405 void* memset(void*, int, size_t);
406 void* memcpy(void*, const void*, size_t);
407 #else
408 Void_t* memset();
409 Void_t* memcpy();
410 #endif
411 #endif
413 #if USE_MEMCPY
415 /* The following macros are only invoked with (2n+1)-multiples of
416 INTERNAL_SIZE_T units, with a positive integer n. This is exploited
417 for fast inline execution when n is small. */
419 #define MALLOC_ZERO(charp, nbytes) \
420 do { \
421 INTERNAL_SIZE_T mzsz = (nbytes); \
422 if(mzsz <= 9*sizeof(mzsz)) { \
423 INTERNAL_SIZE_T* mz = (INTERNAL_SIZE_T*) (charp); \
424 if(mzsz >= 5*sizeof(mzsz)) { *mz++ = 0; \
425 *mz++ = 0; \
426 if(mzsz >= 7*sizeof(mzsz)) { *mz++ = 0; \
427 *mz++ = 0; \
428 if(mzsz >= 9*sizeof(mzsz)) { *mz++ = 0; \
429 *mz++ = 0; }}} \
430 *mz++ = 0; \
431 *mz++ = 0; \
432 *mz = 0; \
433 } else memset((charp), 0, mzsz); \
434 } while(0)
436 #define MALLOC_COPY(dest,src,nbytes) \
437 do { \
438 INTERNAL_SIZE_T mcsz = (nbytes); \
439 if(mcsz <= 9*sizeof(mcsz)) { \
440 INTERNAL_SIZE_T* mcsrc = (INTERNAL_SIZE_T*) (src); \
441 INTERNAL_SIZE_T* mcdst = (INTERNAL_SIZE_T*) (dest); \
442 if(mcsz >= 5*sizeof(mcsz)) { *mcdst++ = *mcsrc++; \
443 *mcdst++ = *mcsrc++; \
444 if(mcsz >= 7*sizeof(mcsz)) { *mcdst++ = *mcsrc++; \
445 *mcdst++ = *mcsrc++; \
446 if(mcsz >= 9*sizeof(mcsz)) { *mcdst++ = *mcsrc++; \
447 *mcdst++ = *mcsrc++; }}} \
448 *mcdst++ = *mcsrc++; \
449 *mcdst++ = *mcsrc++; \
450 *mcdst = *mcsrc ; \
451 } else memcpy(dest, src, mcsz); \
452 } while(0)
454 #else /* !USE_MEMCPY */
456 /* Use Duff's device for good zeroing/copying performance. */
458 #define MALLOC_ZERO(charp, nbytes) \
459 do { \
460 INTERNAL_SIZE_T* mzp = (INTERNAL_SIZE_T*)(charp); \
461 long mctmp = (nbytes)/sizeof(INTERNAL_SIZE_T), mcn; \
462 if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp %= 8; } \
463 switch (mctmp) { \
464 case 0: for(;;) { *mzp++ = 0; \
465 case 7: *mzp++ = 0; \
466 case 6: *mzp++ = 0; \
467 case 5: *mzp++ = 0; \
468 case 4: *mzp++ = 0; \
469 case 3: *mzp++ = 0; \
470 case 2: *mzp++ = 0; \
471 case 1: *mzp++ = 0; if(mcn <= 0) break; mcn--; } \
473 } while(0)
475 #define MALLOC_COPY(dest,src,nbytes) \
476 do { \
477 INTERNAL_SIZE_T* mcsrc = (INTERNAL_SIZE_T*) src; \
478 INTERNAL_SIZE_T* mcdst = (INTERNAL_SIZE_T*) dest; \
479 long mctmp = (nbytes)/sizeof(INTERNAL_SIZE_T), mcn; \
480 if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp %= 8; } \
481 switch (mctmp) { \
482 case 0: for(;;) { *mcdst++ = *mcsrc++; \
483 case 7: *mcdst++ = *mcsrc++; \
484 case 6: *mcdst++ = *mcsrc++; \
485 case 5: *mcdst++ = *mcsrc++; \
486 case 4: *mcdst++ = *mcsrc++; \
487 case 3: *mcdst++ = *mcsrc++; \
488 case 2: *mcdst++ = *mcsrc++; \
489 case 1: *mcdst++ = *mcsrc++; if(mcn <= 0) break; mcn--; } \
491 } while(0)
493 #endif
496 #ifndef LACKS_UNISTD_H
497 # include <unistd.h>
498 #endif
501 Define HAVE_MMAP to optionally make malloc() use mmap() to
502 allocate very large blocks. These will be returned to the
503 operating system immediately after a free().
506 #ifndef HAVE_MMAP
507 # ifdef _POSIX_MAPPED_FILES
508 # define HAVE_MMAP 1
509 # endif
510 #endif
513 Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
514 large blocks. This is currently only possible on Linux with
515 kernel versions newer than 1.3.77.
518 #ifndef HAVE_MREMAP
519 #define HAVE_MREMAP defined(__linux__) && !defined(__arm__)
520 #endif
522 #if HAVE_MMAP
524 #include <unistd.h>
525 #include <fcntl.h>
526 #include <sys/mman.h>
528 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
529 #define MAP_ANONYMOUS MAP_ANON
530 #endif
532 #ifndef MAP_NORESERVE
533 # ifdef MAP_AUTORESRV
534 # define MAP_NORESERVE MAP_AUTORESRV
535 # else
536 # define MAP_NORESERVE 0
537 # endif
538 #endif
540 #endif /* HAVE_MMAP */
543 Access to system page size. To the extent possible, this malloc
544 manages memory from the system in page-size units.
546 The following mechanics for getpagesize were adapted from
547 bsd/gnu getpagesize.h
550 #ifndef malloc_getpagesize
551 # ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */
552 # ifndef _SC_PAGE_SIZE
553 # define _SC_PAGE_SIZE _SC_PAGESIZE
554 # endif
555 # endif
556 # ifdef _SC_PAGE_SIZE
557 # define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
558 # else
559 # if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
560 extern size_t getpagesize();
561 # define malloc_getpagesize getpagesize()
562 # else
563 # include <sys/param.h>
564 # ifdef EXEC_PAGESIZE
565 # define malloc_getpagesize EXEC_PAGESIZE
566 # else
567 # ifdef NBPG
568 # ifndef CLSIZE
569 # define malloc_getpagesize NBPG
570 # else
571 # define malloc_getpagesize (NBPG * CLSIZE)
572 # endif
573 # else
574 # ifdef NBPC
575 # define malloc_getpagesize NBPC
576 # else
577 # ifdef PAGESIZE
578 # define malloc_getpagesize PAGESIZE
579 # else
580 # define malloc_getpagesize (4096) /* just guess */
581 # endif
582 # endif
583 # endif
584 # endif
585 # endif
586 # endif
587 #endif
593 This version of malloc supports the standard SVID/XPG mallinfo
594 routine that returns a struct containing the same kind of
595 information you can get from malloc_stats. It should work on
596 any SVID/XPG compliant system that has a /usr/include/malloc.h
597 defining struct mallinfo. (If you'd like to install such a thing
598 yourself, cut out the preliminary declarations as described above
599 and below and save them in a malloc.h file. But there's no
600 compelling reason to bother to do this.)
602 The main declaration needed is the mallinfo struct that is returned
603 (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
604 bunch of fields, most of which are not even meaningful in this
605 version of malloc. Some of these fields are are instead filled by
606 mallinfo() with other numbers that might possibly be of interest.
608 HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
609 /usr/include/malloc.h file that includes a declaration of struct
610 mallinfo. If so, it is included; else an SVID2/XPG2 compliant
611 version is declared below. These must be precisely the same for
612 mallinfo() to work.
616 /* #define HAVE_USR_INCLUDE_MALLOC_H */
618 #if HAVE_USR_INCLUDE_MALLOC_H
619 # include "/usr/include/malloc.h"
620 #else
621 # ifdef _LIBC
622 # include "malloc.h"
623 # else
624 # include "ptmalloc.h"
625 # endif
626 #endif
630 #ifndef DEFAULT_TRIM_THRESHOLD
631 #define DEFAULT_TRIM_THRESHOLD (128 * 1024)
632 #endif
635 M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
636 to keep before releasing via malloc_trim in free().
638 Automatic trimming is mainly useful in long-lived programs.
639 Because trimming via sbrk can be slow on some systems, and can
640 sometimes be wasteful (in cases where programs immediately
641 afterward allocate more large chunks) the value should be high
642 enough so that your overall system performance would improve by
643 releasing.
645 The trim threshold and the mmap control parameters (see below)
646 can be traded off with one another. Trimming and mmapping are
647 two different ways of releasing unused memory back to the
648 system. Between these two, it is often possible to keep
649 system-level demands of a long-lived program down to a bare
650 minimum. For example, in one test suite of sessions measuring
651 the XF86 X server on Linux, using a trim threshold of 128K and a
652 mmap threshold of 192K led to near-minimal long term resource
653 consumption.
655 If you are using this malloc in a long-lived program, it should
656 pay to experiment with these values. As a rough guide, you
657 might set to a value close to the average size of a process
658 (program) running on your system. Releasing this much memory
659 would allow such a process to run in memory. Generally, it's
660 worth it to tune for trimming rather than memory mapping when a
661 program undergoes phases where several large chunks are
662 allocated and released in ways that can reuse each other's
663 storage, perhaps mixed with phases where there are no such
664 chunks at all. And in well-behaved long-lived programs,
665 controlling release of large blocks via trimming versus mapping
666 is usually faster.
668 However, in most programs, these parameters serve mainly as
669 protection against the system-level effects of carrying around
670 massive amounts of unneeded memory. Since frequent calls to
671 sbrk, mmap, and munmap otherwise degrade performance, the default
672 parameters are set to relatively high values that serve only as
673 safeguards.
675 The default trim value is high enough to cause trimming only in
676 fairly extreme (by current memory consumption standards) cases.
677 It must be greater than page size to have any useful effect. To
678 disable trimming completely, you can set to (unsigned long)(-1);
684 #ifndef DEFAULT_TOP_PAD
685 #define DEFAULT_TOP_PAD (0)
686 #endif
689 M_TOP_PAD is the amount of extra `padding' space to allocate or
690 retain whenever sbrk is called. It is used in two ways internally:
692 * When sbrk is called to extend the top of the arena to satisfy
693 a new malloc request, this much padding is added to the sbrk
694 request.
696 * When malloc_trim is called automatically from free(),
697 it is used as the `pad' argument.
699 In both cases, the actual amount of padding is rounded
700 so that the end of the arena is always a system page boundary.
702 The main reason for using padding is to avoid calling sbrk so
703 often. Having even a small pad greatly reduces the likelihood
704 that nearly every malloc request during program start-up (or
705 after trimming) will invoke sbrk, which needlessly wastes
706 time.
708 Automatic rounding-up to page-size units is normally sufficient
709 to avoid measurable overhead, so the default is 0. However, in
710 systems where sbrk is relatively slow, it can pay to increase
711 this value, at the expense of carrying around more memory than
712 the program needs.
717 #ifndef DEFAULT_MMAP_THRESHOLD
718 #define DEFAULT_MMAP_THRESHOLD (128 * 1024)
719 #endif
723 M_MMAP_THRESHOLD is the request size threshold for using mmap()
724 to service a request. Requests of at least this size that cannot
725 be allocated using already-existing space will be serviced via mmap.
726 (If enough normal freed space already exists it is used instead.)
728 Using mmap segregates relatively large chunks of memory so that
729 they can be individually obtained and released from the host
730 system. A request serviced through mmap is never reused by any
731 other request (at least not directly; the system may just so
732 happen to remap successive requests to the same locations).
734 Segregating space in this way has the benefit that mmapped space
735 can ALWAYS be individually released back to the system, which
736 helps keep the system level memory demands of a long-lived
737 program low. Mapped memory can never become `locked' between
738 other chunks, as can happen with normally allocated chunks, which
739 menas that even trimming via malloc_trim would not release them.
741 However, it has the disadvantages that:
743 1. The space cannot be reclaimed, consolidated, and then
744 used to service later requests, as happens with normal chunks.
745 2. It can lead to more wastage because of mmap page alignment
746 requirements
747 3. It causes malloc performance to be more dependent on host
748 system memory management support routines which may vary in
749 implementation quality and may impose arbitrary
750 limitations. Generally, servicing a request via normal
751 malloc steps is faster than going through a system's mmap.
753 All together, these considerations should lead you to use mmap
754 only for relatively large requests.
761 #ifndef DEFAULT_MMAP_MAX
762 #if HAVE_MMAP
763 #define DEFAULT_MMAP_MAX (1024)
764 #else
765 #define DEFAULT_MMAP_MAX (0)
766 #endif
767 #endif
770 M_MMAP_MAX is the maximum number of requests to simultaneously
771 service using mmap. This parameter exists because:
773 1. Some systems have a limited number of internal tables for
774 use by mmap.
775 2. In most systems, overreliance on mmap can degrade overall
776 performance.
777 3. If a program allocates many large regions, it is probably
778 better off using normal sbrk-based allocation routines that
779 can reclaim and reallocate normal heap memory. Using a
780 small value allows transition into this mode after the
781 first few allocations.
783 Setting to 0 disables all use of mmap. If HAVE_MMAP is not set,
784 the default value is 0, and attempts to set it to non-zero values
785 in mallopt will fail.
790 #ifndef DEFAULT_CHECK_ACTION
791 #define DEFAULT_CHECK_ACTION 1
792 #endif
794 /* What to do if the standard debugging hooks are in place and a
795 corrupt pointer is detected: do nothing (0), print an error message
796 (1), or call abort() (2). */
800 #define HEAP_MIN_SIZE (32*1024)
801 #define HEAP_MAX_SIZE (1024*1024) /* must be a power of two */
803 /* HEAP_MIN_SIZE and HEAP_MAX_SIZE limit the size of mmap()ed heaps
804 that are dynamically created for multi-threaded programs. The
805 maximum size must be a power of two, for fast determination of
806 which heap belongs to a chunk. It should be much larger than
807 the mmap threshold, so that requests with a size just below that
808 threshold can be fulfilled without creating too many heaps.
813 #ifndef THREAD_STATS
814 #define THREAD_STATS 0
815 #endif
817 /* If THREAD_STATS is non-zero, some statistics on mutex locking are
818 computed. */
823 Special defines for the Linux/GNU C library.
828 #ifdef _LIBC
830 #if __STD_C
832 Void_t * __default_morecore (ptrdiff_t);
833 Void_t *(*__morecore)(ptrdiff_t) = __default_morecore;
835 #else
837 Void_t * __default_morecore ();
838 Void_t *(*__morecore)() = __default_morecore;
840 #endif
842 #define MORECORE (*__morecore)
843 #define MORECORE_FAILURE 0
844 #define MORECORE_CLEARS 1
845 #define mmap __mmap
846 #define munmap __munmap
847 #define mremap __mremap
848 #define mprotect __mprotect
849 #undef malloc_getpagesize
850 #define malloc_getpagesize __getpagesize()
852 #else /* _LIBC */
854 #if __STD_C
855 extern Void_t* sbrk(ptrdiff_t);
856 #else
857 extern Void_t* sbrk();
858 #endif
860 #ifndef MORECORE
861 #define MORECORE sbrk
862 #endif
864 #ifndef MORECORE_FAILURE
865 #define MORECORE_FAILURE -1
866 #endif
868 #ifndef MORECORE_CLEARS
869 #define MORECORE_CLEARS 1
870 #endif
872 #endif /* _LIBC */
874 #ifdef _LIBC
876 #define cALLOc __libc_calloc
877 #define fREe __libc_free
878 #define mALLOc __libc_malloc
879 #define mEMALIGn __libc_memalign
880 #define rEALLOc __libc_realloc
881 #define vALLOc __libc_valloc
882 #define pvALLOc __libc_pvalloc
883 #define mALLINFo __libc_mallinfo
884 #define mALLOPt __libc_mallopt
885 #define mALLOC_STATs __malloc_stats
886 #define mALLOC_USABLE_SIZe __malloc_usable_size
887 #define mALLOC_TRIm __malloc_trim
888 #define mALLOC_GET_STATe __malloc_get_state
889 #define mALLOC_SET_STATe __malloc_set_state
891 #else
893 #define cALLOc calloc
894 #define fREe free
895 #define mALLOc malloc
896 #define mEMALIGn memalign
897 #define rEALLOc realloc
898 #define vALLOc valloc
899 #define pvALLOc pvalloc
900 #define mALLINFo mallinfo
901 #define mALLOPt mallopt
902 #define mALLOC_STATs malloc_stats
903 #define mALLOC_USABLE_SIZe malloc_usable_size
904 #define mALLOC_TRIm malloc_trim
905 #define mALLOC_GET_STATe malloc_get_state
906 #define mALLOC_SET_STATe malloc_set_state
908 #endif
910 /* Public routines */
912 #if __STD_C
914 #ifndef _LIBC
915 void ptmalloc_init(void);
916 #endif
917 Void_t* mALLOc(size_t);
918 void fREe(Void_t*);
919 Void_t* rEALLOc(Void_t*, size_t);
920 Void_t* mEMALIGn(size_t, size_t);
921 Void_t* vALLOc(size_t);
922 Void_t* pvALLOc(size_t);
923 Void_t* cALLOc(size_t, size_t);
924 void cfree(Void_t*);
925 int mALLOC_TRIm(size_t);
926 size_t mALLOC_USABLE_SIZe(Void_t*);
927 void mALLOC_STATs(void);
928 int mALLOPt(int, int);
929 struct mallinfo mALLINFo(void);
930 Void_t* mALLOC_GET_STATe(void);
931 int mALLOC_SET_STATe(Void_t*);
933 #else /* !__STD_C */
935 #ifndef _LIBC
936 void ptmalloc_init();
937 #endif
938 Void_t* mALLOc();
939 void fREe();
940 Void_t* rEALLOc();
941 Void_t* mEMALIGn();
942 Void_t* vALLOc();
943 Void_t* pvALLOc();
944 Void_t* cALLOc();
945 void cfree();
946 int mALLOC_TRIm();
947 size_t mALLOC_USABLE_SIZe();
948 void mALLOC_STATs();
949 int mALLOPt();
950 struct mallinfo mALLINFo();
951 Void_t* mALLOC_GET_STATe();
952 int mALLOC_SET_STATe();
954 #endif /* __STD_C */
957 #ifdef __cplusplus
958 }; /* end of extern "C" */
959 #endif
961 #if !defined(NO_THREADS) && !HAVE_MMAP
962 "Can't have threads support without mmap"
963 #endif
967 Type declarations
971 struct malloc_chunk
973 INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
974 INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */
975 struct malloc_chunk* fd; /* double links -- used only if free. */
976 struct malloc_chunk* bk;
979 typedef struct malloc_chunk* mchunkptr;
983 malloc_chunk details:
985 (The following includes lightly edited explanations by Colin Plumb.)
987 Chunks of memory are maintained using a `boundary tag' method as
988 described in e.g., Knuth or Standish. (See the paper by Paul
989 Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
990 survey of such techniques.) Sizes of free chunks are stored both
991 in the front of each chunk and at the end. This makes
992 consolidating fragmented chunks into bigger chunks very fast. The
993 size fields also hold bits representing whether chunks are free or
994 in use.
996 An allocated chunk looks like this:
999 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1000 | Size of previous chunk, if allocated | |
1001 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1002 | Size of chunk, in bytes |P|
1003 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1004 | User data starts here... .
1006 . (malloc_usable_space() bytes) .
1008 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1009 | Size of chunk |
1010 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1013 Where "chunk" is the front of the chunk for the purpose of most of
1014 the malloc code, but "mem" is the pointer that is returned to the
1015 user. "Nextchunk" is the beginning of the next contiguous chunk.
1017 Chunks always begin on even word boundaries, so the mem portion
1018 (which is returned to the user) is also on an even word boundary, and
1019 thus double-word aligned.
1021 Free chunks are stored in circular doubly-linked lists, and look like this:
1023 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1024 | Size of previous chunk |
1025 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1026 `head:' | Size of chunk, in bytes |P|
1027 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1028 | Forward pointer to next chunk in list |
1029 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1030 | Back pointer to previous chunk in list |
1031 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1032 | Unused space (may be 0 bytes long) .
1035 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1036 `foot:' | Size of chunk, in bytes |
1037 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1039 The P (PREV_INUSE) bit, stored in the unused low-order bit of the
1040 chunk size (which is always a multiple of two words), is an in-use
1041 bit for the *previous* chunk. If that bit is *clear*, then the
1042 word before the current chunk size contains the previous chunk
1043 size, and can be used to find the front of the previous chunk.
1044 (The very first chunk allocated always has this bit set,
1045 preventing access to non-existent (or non-owned) memory.)
1047 Note that the `foot' of the current chunk is actually represented
1048 as the prev_size of the NEXT chunk. (This makes it easier to
1049 deal with alignments etc).
1051 The two exceptions to all this are
1053 1. The special chunk `top', which doesn't bother using the
1054 trailing size field since there is no
1055 next contiguous chunk that would have to index off it. (After
1056 initialization, `top' is forced to always exist. If it would
1057 become less than MINSIZE bytes long, it is replenished via
1058 malloc_extend_top.)
1060 2. Chunks allocated via mmap, which have the second-lowest-order
1061 bit (IS_MMAPPED) set in their size fields. Because they are
1062 never merged or traversed from any other chunk, they have no
1063 foot size or inuse information.
1065 Available chunks are kept in any of several places (all declared below):
1067 * `av': An array of chunks serving as bin headers for consolidated
1068 chunks. Each bin is doubly linked. The bins are approximately
1069 proportionally (log) spaced. There are a lot of these bins
1070 (128). This may look excessive, but works very well in
1071 practice. All procedures maintain the invariant that no
1072 consolidated chunk physically borders another one. Chunks in
1073 bins are kept in size order, with ties going to the
1074 approximately least recently used chunk.
1076 The chunks in each bin are maintained in decreasing sorted order by
1077 size. This is irrelevant for the small bins, which all contain
1078 the same-sized chunks, but facilitates best-fit allocation for
1079 larger chunks. (These lists are just sequential. Keeping them in
1080 order almost never requires enough traversal to warrant using
1081 fancier ordered data structures.) Chunks of the same size are
1082 linked with the most recently freed at the front, and allocations
1083 are taken from the back. This results in LRU or FIFO allocation
1084 order, which tends to give each chunk an equal opportunity to be
1085 consolidated with adjacent freed chunks, resulting in larger free
1086 chunks and less fragmentation.
1088 * `top': The top-most available chunk (i.e., the one bordering the
1089 end of available memory) is treated specially. It is never
1090 included in any bin, is used only if no other chunk is
1091 available, and is released back to the system if it is very
1092 large (see M_TRIM_THRESHOLD).
1094 * `last_remainder': A bin holding only the remainder of the
1095 most recently split (non-top) chunk. This bin is checked
1096 before other non-fitting chunks, so as to provide better
1097 locality for runs of sequentially allocated chunks.
1099 * Implicitly, through the host system's memory mapping tables.
1100 If supported, requests greater than a threshold are usually
1101 serviced via calls to mmap, and then later released via munmap.
1106 Bins
1108 The bins are an array of pairs of pointers serving as the
1109 heads of (initially empty) doubly-linked lists of chunks, laid out
1110 in a way so that each pair can be treated as if it were in a
1111 malloc_chunk. (This way, the fd/bk offsets for linking bin heads
1112 and chunks are the same).
1114 Bins for sizes < 512 bytes contain chunks of all the same size, spaced
1115 8 bytes apart. Larger bins are approximately logarithmically
1116 spaced. (See the table below.)
1118 Bin layout:
1120 64 bins of size 8
1121 32 bins of size 64
1122 16 bins of size 512
1123 8 bins of size 4096
1124 4 bins of size 32768
1125 2 bins of size 262144
1126 1 bin of size what's left
1128 There is actually a little bit of slop in the numbers in bin_index
1129 for the sake of speed. This makes no difference elsewhere.
1131 The special chunks `top' and `last_remainder' get their own bins,
1132 (this is implemented via yet more trickery with the av array),
1133 although `top' is never properly linked to its bin since it is
1134 always handled specially.
1138 #define NAV 128 /* number of bins */
1140 typedef struct malloc_chunk* mbinptr;
1142 /* An arena is a configuration of malloc_chunks together with an array
1143 of bins. With multiple threads, it must be locked via a mutex
1144 before changing its data structures. One or more `heaps' are
1145 associated with each arena, except for the main_arena, which is
1146 associated only with the `main heap', i.e. the conventional free
1147 store obtained with calls to MORECORE() (usually sbrk). The `av'
1148 array is never mentioned directly in the code, but instead used via
1149 bin access macros. */
1151 typedef struct _arena {
1152 mbinptr av[2*NAV + 2];
1153 struct _arena *next;
1154 size_t size;
1155 #if THREAD_STATS
1156 long stat_lock_direct, stat_lock_loop, stat_lock_wait;
1157 #endif
1158 mutex_t mutex;
1159 } arena;
1162 /* A heap is a single contiguous memory region holding (coalesceable)
1163 malloc_chunks. It is allocated with mmap() and always starts at an
1164 address aligned to HEAP_MAX_SIZE. Not used unless compiling for
1165 multiple threads. */
1167 typedef struct _heap_info {
1168 arena *ar_ptr; /* Arena for this heap. */
1169 struct _heap_info *prev; /* Previous heap. */
1170 size_t size; /* Current size in bytes. */
1171 size_t pad; /* Make sure the following data is properly aligned. */
1172 } heap_info;
1176 Static functions (forward declarations)
1179 #if __STD_C
1181 static void chunk_free(arena *ar_ptr, mchunkptr p) internal_function;
1182 static mchunkptr chunk_alloc(arena *ar_ptr, INTERNAL_SIZE_T size)
1183 internal_function;
1184 static mchunkptr chunk_realloc(arena *ar_ptr, mchunkptr oldp,
1185 INTERNAL_SIZE_T oldsize, INTERNAL_SIZE_T nb)
1186 internal_function;
1187 static mchunkptr chunk_align(arena *ar_ptr, INTERNAL_SIZE_T nb,
1188 size_t alignment) internal_function;
1189 static int main_trim(size_t pad) internal_function;
1190 #ifndef NO_THREADS
1191 static int heap_trim(heap_info *heap, size_t pad) internal_function;
1192 #endif
1193 #if defined _LIBC || defined MALLOC_HOOKS
1194 static Void_t* malloc_check(size_t sz, const Void_t *caller);
1195 static void free_check(Void_t* mem, const Void_t *caller);
1196 static Void_t* realloc_check(Void_t* oldmem, size_t bytes,
1197 const Void_t *caller);
1198 static Void_t* memalign_check(size_t alignment, size_t bytes,
1199 const Void_t *caller);
1200 #ifndef NO_THREADS
1201 static Void_t* malloc_starter(size_t sz, const Void_t *caller);
1202 static void free_starter(Void_t* mem, const Void_t *caller);
1203 static Void_t* malloc_atfork(size_t sz, const Void_t *caller);
1204 static void free_atfork(Void_t* mem, const Void_t *caller);
1205 #endif
1206 #endif
1208 #else
1210 static void chunk_free();
1211 static mchunkptr chunk_alloc();
1212 static mchunkptr chunk_realloc();
1213 static mchunkptr chunk_align();
1214 static int main_trim();
1215 #ifndef NO_THREADS
1216 static int heap_trim();
1217 #endif
1218 #if defined _LIBC || defined MALLOC_HOOKS
1219 static Void_t* malloc_check();
1220 static void free_check();
1221 static Void_t* realloc_check();
1222 static Void_t* memalign_check();
1223 #ifndef NO_THREADS
1224 static Void_t* malloc_starter();
1225 static void free_starter();
1226 static Void_t* malloc_atfork();
1227 static void free_atfork();
1228 #endif
1229 #endif
1231 #endif
1233 /* On some platforms we can compile internal, not exported functions better.
1234 Let the environment provide a macro and define it to be empty if it
1235 is not available. */
1236 #ifndef internal_function
1237 # define internal_function
1238 #endif
1242 /* sizes, alignments */
1244 #define SIZE_SZ (sizeof(INTERNAL_SIZE_T))
1245 #define MALLOC_ALIGNMENT (SIZE_SZ + SIZE_SZ)
1246 #define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)
1247 #define MINSIZE (sizeof(struct malloc_chunk))
1249 /* conversion from malloc headers to user pointers, and back */
1251 #define chunk2mem(p) ((Void_t*)((char*)(p) + 2*SIZE_SZ))
1252 #define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
1254 /* pad request bytes into a usable size */
1256 #define request2size(req) \
1257 (((long)((req) + (SIZE_SZ + MALLOC_ALIGN_MASK)) < \
1258 (long)(MINSIZE + MALLOC_ALIGN_MASK)) ? MINSIZE : \
1259 (((req) + (SIZE_SZ + MALLOC_ALIGN_MASK)) & ~(MALLOC_ALIGN_MASK)))
1261 /* Check if m has acceptable alignment */
1263 #define aligned_OK(m) (((unsigned long)((m)) & (MALLOC_ALIGN_MASK)) == 0)
1269 Physical chunk operations
1273 /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
1275 #define PREV_INUSE 0x1
1277 /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
1279 #define IS_MMAPPED 0x2
1281 /* Bits to mask off when extracting size */
1283 #define SIZE_BITS (PREV_INUSE|IS_MMAPPED)
1286 /* Ptr to next physical malloc_chunk. */
1288 #define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->size & ~PREV_INUSE) ))
1290 /* Ptr to previous physical malloc_chunk */
1292 #define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_size) ))
1295 /* Treat space at ptr + offset as a chunk */
1297 #define chunk_at_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
1303 Dealing with use bits
1306 /* extract p's inuse bit */
1308 #define inuse(p) \
1309 ((((mchunkptr)(((char*)(p))+((p)->size & ~PREV_INUSE)))->size) & PREV_INUSE)
1311 /* extract inuse bit of previous chunk */
1313 #define prev_inuse(p) ((p)->size & PREV_INUSE)
1315 /* check for mmap()'ed chunk */
1317 #define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
1319 /* set/clear chunk as in use without otherwise disturbing */
1321 #define set_inuse(p) \
1322 ((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size |= PREV_INUSE
1324 #define clear_inuse(p) \
1325 ((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size &= ~(PREV_INUSE)
1327 /* check/set/clear inuse bits in known places */
1329 #define inuse_bit_at_offset(p, s)\
1330 (((mchunkptr)(((char*)(p)) + (s)))->size & PREV_INUSE)
1332 #define set_inuse_bit_at_offset(p, s)\
1333 (((mchunkptr)(((char*)(p)) + (s)))->size |= PREV_INUSE)
1335 #define clear_inuse_bit_at_offset(p, s)\
1336 (((mchunkptr)(((char*)(p)) + (s)))->size &= ~(PREV_INUSE))
1342 Dealing with size fields
1345 /* Get size, ignoring use bits */
1347 #define chunksize(p) ((p)->size & ~(SIZE_BITS))
1349 /* Set size at head, without disturbing its use bit */
1351 #define set_head_size(p, s) ((p)->size = (((p)->size & PREV_INUSE) | (s)))
1353 /* Set size/use ignoring previous bits in header */
1355 #define set_head(p, s) ((p)->size = (s))
1357 /* Set size at footer (only when chunk is not in use) */
1359 #define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_size = (s))
1365 /* access macros */
1367 #define bin_at(a, i) ((mbinptr)((char*)&(((a)->av)[2*(i) + 2]) - 2*SIZE_SZ))
1368 #define init_bin(a, i) ((a)->av[2*i+2] = (a)->av[2*i+3] = bin_at((a), i))
1369 #define next_bin(b) ((mbinptr)((char*)(b) + 2 * sizeof(mbinptr)))
1370 #define prev_bin(b) ((mbinptr)((char*)(b) - 2 * sizeof(mbinptr)))
1373 The first 2 bins are never indexed. The corresponding av cells are instead
1374 used for bookkeeping. This is not to save space, but to simplify
1375 indexing, maintain locality, and avoid some initialization tests.
1378 #define binblocks(a) (bin_at(a,0)->size)/* bitvector of nonempty blocks */
1379 #define top(a) (bin_at(a,0)->fd) /* The topmost chunk */
1380 #define last_remainder(a) (bin_at(a,1)) /* remainder from last split */
1383 Because top initially points to its own bin with initial
1384 zero size, thus forcing extension on the first malloc request,
1385 we avoid having any special code in malloc to check whether
1386 it even exists yet. But we still need to in malloc_extend_top.
1389 #define initial_top(a) ((mchunkptr)bin_at(a, 0))
1393 /* field-extraction macros */
1395 #define first(b) ((b)->fd)
1396 #define last(b) ((b)->bk)
1399 Indexing into bins
1402 #define bin_index(sz) \
1403 (((((unsigned long)(sz)) >> 9) == 0) ? (((unsigned long)(sz)) >> 3):\
1404 ((((unsigned long)(sz)) >> 9) <= 4) ? 56 + (((unsigned long)(sz)) >> 6):\
1405 ((((unsigned long)(sz)) >> 9) <= 20) ? 91 + (((unsigned long)(sz)) >> 9):\
1406 ((((unsigned long)(sz)) >> 9) <= 84) ? 110 + (((unsigned long)(sz)) >> 12):\
1407 ((((unsigned long)(sz)) >> 9) <= 340) ? 119 + (((unsigned long)(sz)) >> 15):\
1408 ((((unsigned long)(sz)) >> 9) <= 1364) ? 124 + (((unsigned long)(sz)) >> 18):\
1409 126)
1411 bins for chunks < 512 are all spaced 8 bytes apart, and hold
1412 identically sized chunks. This is exploited in malloc.
1415 #define MAX_SMALLBIN 63
1416 #define MAX_SMALLBIN_SIZE 512
1417 #define SMALLBIN_WIDTH 8
1419 #define smallbin_index(sz) (((unsigned long)(sz)) >> 3)
1422 Requests are `small' if both the corresponding and the next bin are small
1425 #define is_small_request(nb) ((nb) < MAX_SMALLBIN_SIZE - SMALLBIN_WIDTH)
1430 To help compensate for the large number of bins, a one-level index
1431 structure is used for bin-by-bin searching. `binblocks' is a
1432 one-word bitvector recording whether groups of BINBLOCKWIDTH bins
1433 have any (possibly) non-empty bins, so they can be skipped over
1434 all at once during during traversals. The bits are NOT always
1435 cleared as soon as all bins in a block are empty, but instead only
1436 when all are noticed to be empty during traversal in malloc.
1439 #define BINBLOCKWIDTH 4 /* bins per block */
1441 /* bin<->block macros */
1443 #define idx2binblock(ix) ((unsigned)1 << ((ix) / BINBLOCKWIDTH))
1444 #define mark_binblock(a, ii) (binblocks(a) |= idx2binblock(ii))
1445 #define clear_binblock(a, ii) (binblocks(a) &= ~(idx2binblock(ii)))
1450 /* Static bookkeeping data */
1452 /* Helper macro to initialize bins */
1453 #define IAV(i) bin_at(&main_arena, i), bin_at(&main_arena, i)
1455 static arena main_arena = {
1457 0, 0,
1458 IAV(0), IAV(1), IAV(2), IAV(3), IAV(4), IAV(5), IAV(6), IAV(7),
1459 IAV(8), IAV(9), IAV(10), IAV(11), IAV(12), IAV(13), IAV(14), IAV(15),
1460 IAV(16), IAV(17), IAV(18), IAV(19), IAV(20), IAV(21), IAV(22), IAV(23),
1461 IAV(24), IAV(25), IAV(26), IAV(27), IAV(28), IAV(29), IAV(30), IAV(31),
1462 IAV(32), IAV(33), IAV(34), IAV(35), IAV(36), IAV(37), IAV(38), IAV(39),
1463 IAV(40), IAV(41), IAV(42), IAV(43), IAV(44), IAV(45), IAV(46), IAV(47),
1464 IAV(48), IAV(49), IAV(50), IAV(51), IAV(52), IAV(53), IAV(54), IAV(55),
1465 IAV(56), IAV(57), IAV(58), IAV(59), IAV(60), IAV(61), IAV(62), IAV(63),
1466 IAV(64), IAV(65), IAV(66), IAV(67), IAV(68), IAV(69), IAV(70), IAV(71),
1467 IAV(72), IAV(73), IAV(74), IAV(75), IAV(76), IAV(77), IAV(78), IAV(79),
1468 IAV(80), IAV(81), IAV(82), IAV(83), IAV(84), IAV(85), IAV(86), IAV(87),
1469 IAV(88), IAV(89), IAV(90), IAV(91), IAV(92), IAV(93), IAV(94), IAV(95),
1470 IAV(96), IAV(97), IAV(98), IAV(99), IAV(100), IAV(101), IAV(102), IAV(103),
1471 IAV(104), IAV(105), IAV(106), IAV(107), IAV(108), IAV(109), IAV(110), IAV(111),
1472 IAV(112), IAV(113), IAV(114), IAV(115), IAV(116), IAV(117), IAV(118), IAV(119),
1473 IAV(120), IAV(121), IAV(122), IAV(123), IAV(124), IAV(125), IAV(126), IAV(127)
1475 &main_arena, /* next */
1476 0, /* size */
1477 #if THREAD_STATS
1478 0, 0, 0, /* stat_lock_direct, stat_lock_loop, stat_lock_wait */
1479 #endif
1480 MUTEX_INITIALIZER /* mutex */
1483 #undef IAV
1485 /* Thread specific data */
1487 #ifndef NO_THREADS
1488 static tsd_key_t arena_key;
1489 static mutex_t list_lock = MUTEX_INITIALIZER;
1490 #endif
1492 #if THREAD_STATS
1493 static int stat_n_heaps = 0;
1494 #define THREAD_STAT(x) x
1495 #else
1496 #define THREAD_STAT(x) do ; while(0)
1497 #endif
1499 /* variables holding tunable values */
1501 static unsigned long trim_threshold = DEFAULT_TRIM_THRESHOLD;
1502 static unsigned long top_pad = DEFAULT_TOP_PAD;
1503 static unsigned int n_mmaps_max = DEFAULT_MMAP_MAX;
1504 static unsigned long mmap_threshold = DEFAULT_MMAP_THRESHOLD;
1505 static int check_action = DEFAULT_CHECK_ACTION;
1507 /* The first value returned from sbrk */
1508 static char* sbrk_base = (char*)(-1);
1510 /* The maximum memory obtained from system via sbrk */
1511 static unsigned long max_sbrked_mem = 0;
1513 /* The maximum via either sbrk or mmap (too difficult to track with threads) */
1514 #ifdef NO_THREADS
1515 static unsigned long max_total_mem = 0;
1516 #endif
1518 /* The total memory obtained from system via sbrk */
1519 #define sbrked_mem (main_arena.size)
1521 /* Tracking mmaps */
1523 static unsigned int n_mmaps = 0;
1524 static unsigned int max_n_mmaps = 0;
1525 static unsigned long mmapped_mem = 0;
1526 static unsigned long max_mmapped_mem = 0;
1530 #ifndef _LIBC
1531 #define weak_variable
1532 #else
1533 /* In GNU libc we want the hook variables to be weak definitions to
1534 avoid a problem with Emacs. */
1535 #define weak_variable weak_function
1536 #endif
1538 /* Already initialized? */
1539 int __malloc_initialized = -1;
1542 #ifndef NO_THREADS
1544 /* The following two functions are registered via thread_atfork() to
1545 make sure that the mutexes remain in a consistent state in the
1546 fork()ed version of a thread. Also adapt the malloc and free hooks
1547 temporarily, because the `atfork' handler mechanism may use
1548 malloc/free internally (e.g. in LinuxThreads). */
1550 #if defined _LIBC || defined MALLOC_HOOKS
1551 static __malloc_ptr_t (*save_malloc_hook) __MALLOC_P ((size_t __size,
1552 const __malloc_ptr_t));
1553 static void (*save_free_hook) __MALLOC_P ((__malloc_ptr_t __ptr,
1554 const __malloc_ptr_t));
1555 static Void_t* save_arena;
1556 #endif
1558 static void
1559 ptmalloc_lock_all __MALLOC_P((void))
1561 arena *ar_ptr;
1563 (void)mutex_lock(&list_lock);
1564 for(ar_ptr = &main_arena;;) {
1565 (void)mutex_lock(&ar_ptr->mutex);
1566 ar_ptr = ar_ptr->next;
1567 if(ar_ptr == &main_arena) break;
1569 #if defined _LIBC || defined MALLOC_HOOKS
1570 save_malloc_hook = __malloc_hook;
1571 save_free_hook = __free_hook;
1572 __malloc_hook = malloc_atfork;
1573 __free_hook = free_atfork;
1574 /* Only the current thread may perform malloc/free calls now. */
1575 tsd_getspecific(arena_key, save_arena);
1576 tsd_setspecific(arena_key, (Void_t*)0);
1577 #endif
1580 static void
1581 ptmalloc_unlock_all __MALLOC_P((void))
1583 arena *ar_ptr;
1585 #if defined _LIBC || defined MALLOC_HOOKS
1586 tsd_setspecific(arena_key, save_arena);
1587 __malloc_hook = save_malloc_hook;
1588 __free_hook = save_free_hook;
1589 #endif
1590 for(ar_ptr = &main_arena;;) {
1591 (void)mutex_unlock(&ar_ptr->mutex);
1592 ar_ptr = ar_ptr->next;
1593 if(ar_ptr == &main_arena) break;
1595 (void)mutex_unlock(&list_lock);
1598 static void
1599 ptmalloc_init_all __MALLOC_P((void))
1601 arena *ar_ptr;
1603 #if defined _LIBC || defined MALLOC_HOOKS
1604 tsd_setspecific(arena_key, save_arena);
1605 __malloc_hook = save_malloc_hook;
1606 __free_hook = save_free_hook;
1607 #endif
1608 for(ar_ptr = &main_arena;;) {
1609 (void)mutex_init(&ar_ptr->mutex);
1610 ar_ptr = ar_ptr->next;
1611 if(ar_ptr == &main_arena) break;
1613 (void)mutex_init(&list_lock);
1616 #endif
1618 /* Initialization routine. */
1619 #if defined(_LIBC)
1620 #if 0
1621 static void ptmalloc_init __MALLOC_P ((void)) __attribute__ ((constructor));
1622 #endif
1624 static void
1625 ptmalloc_init __MALLOC_P((void))
1626 #else
1627 void
1628 ptmalloc_init __MALLOC_P((void))
1629 #endif
1631 #if defined _LIBC || defined MALLOC_HOOKS
1632 const char* s;
1633 #endif
1635 if(__malloc_initialized >= 0) return;
1636 __malloc_initialized = 0;
1637 #ifndef NO_THREADS
1638 #if defined _LIBC || defined MALLOC_HOOKS
1639 /* With some threads implementations, creating thread-specific data
1640 or initializing a mutex may call malloc() itself. Provide a
1641 simple starter version (realloc() won't work). */
1642 save_malloc_hook = __malloc_hook;
1643 save_free_hook = __free_hook;
1644 __malloc_hook = malloc_starter;
1645 __free_hook = free_starter;
1646 #endif
1647 #ifdef _LIBC
1648 /* Initialize the pthreads interface. */
1649 if (__pthread_initialize != NULL)
1650 __pthread_initialize();
1651 #endif
1652 mutex_init(&main_arena.mutex);
1653 mutex_init(&list_lock);
1654 tsd_key_create(&arena_key, NULL);
1655 tsd_setspecific(arena_key, (Void_t *)&main_arena);
1656 thread_atfork(ptmalloc_lock_all, ptmalloc_unlock_all, ptmalloc_init_all);
1657 #endif /* !defined NO_THREADS */
1658 #if defined _LIBC || defined MALLOC_HOOKS
1659 if((s = getenv("MALLOC_TRIM_THRESHOLD_")))
1660 mALLOPt(M_TRIM_THRESHOLD, atoi(s));
1661 if((s = getenv("MALLOC_TOP_PAD_")))
1662 mALLOPt(M_TOP_PAD, atoi(s));
1663 if((s = getenv("MALLOC_MMAP_THRESHOLD_")))
1664 mALLOPt(M_MMAP_THRESHOLD, atoi(s));
1665 if((s = getenv("MALLOC_MMAP_MAX_")))
1666 mALLOPt(M_MMAP_MAX, atoi(s));
1667 s = getenv("MALLOC_CHECK_");
1668 #ifndef NO_THREADS
1669 __malloc_hook = save_malloc_hook;
1670 __free_hook = save_free_hook;
1671 #endif
1672 if(s) {
1673 if(s[0]) mALLOPt(M_CHECK_ACTION, (int)(s[0] - '0'));
1674 __malloc_check_init();
1676 if(__malloc_initialize_hook != NULL)
1677 (*__malloc_initialize_hook)();
1678 #endif
1679 __malloc_initialized = 1;
1682 /* There are platforms (e.g. Hurd) with a link-time hook mechanism. */
1683 #ifdef thread_atfork_static
1684 thread_atfork_static(ptmalloc_lock_all, ptmalloc_unlock_all, \
1685 ptmalloc_init_all)
1686 #endif
1688 #if defined _LIBC || defined MALLOC_HOOKS
1690 /* Hooks for debugging versions. The initial hooks just call the
1691 initialization routine, then do the normal work. */
1693 static Void_t*
1694 #if __STD_C
1695 malloc_hook_ini(size_t sz, const __malloc_ptr_t caller)
1696 #else
1697 malloc_hook_ini(sz, caller)
1698 size_t sz; const __malloc_ptr_t caller;
1699 #endif
1701 __malloc_hook = NULL;
1702 ptmalloc_init();
1703 return mALLOc(sz);
1706 static Void_t*
1707 #if __STD_C
1708 realloc_hook_ini(Void_t* ptr, size_t sz, const __malloc_ptr_t caller)
1709 #else
1710 realloc_hook_ini(ptr, sz, caller)
1711 Void_t* ptr; size_t sz; const __malloc_ptr_t caller;
1712 #endif
1714 __malloc_hook = NULL;
1715 __realloc_hook = NULL;
1716 ptmalloc_init();
1717 return rEALLOc(ptr, sz);
1720 static Void_t*
1721 #if __STD_C
1722 memalign_hook_ini(size_t sz, size_t alignment, const __malloc_ptr_t caller)
1723 #else
1724 memalign_hook_ini(sz, alignment, caller)
1725 size_t sz; size_t alignment; const __malloc_ptr_t caller;
1726 #endif
1728 __memalign_hook = NULL;
1729 ptmalloc_init();
1730 return mEMALIGn(sz, alignment);
1733 void weak_variable (*__malloc_initialize_hook) __MALLOC_P ((void)) = NULL;
1734 void weak_variable (*__free_hook) __MALLOC_P ((__malloc_ptr_t __ptr,
1735 const __malloc_ptr_t)) = NULL;
1736 __malloc_ptr_t weak_variable (*__malloc_hook)
1737 __MALLOC_P ((size_t __size, const __malloc_ptr_t)) = malloc_hook_ini;
1738 __malloc_ptr_t weak_variable (*__realloc_hook)
1739 __MALLOC_P ((__malloc_ptr_t __ptr, size_t __size, const __malloc_ptr_t))
1740 = realloc_hook_ini;
1741 __malloc_ptr_t weak_variable (*__memalign_hook)
1742 __MALLOC_P ((size_t __size, size_t __alignment, const __malloc_ptr_t))
1743 = memalign_hook_ini;
1744 void weak_variable (*__after_morecore_hook) __MALLOC_P ((void)) = NULL;
1746 /* Whether we are using malloc checking. */
1747 static int using_malloc_checking;
1749 /* A flag that is set by malloc_set_state, to signal that malloc checking
1750 must not be enabled on the request from the user (via the MALLOC_CHECK_
1751 environment variable). It is reset by __malloc_check_init to tell
1752 malloc_set_state that the user has requested malloc checking.
1754 The purpose of this flag is to make sure that malloc checking is not
1755 enabled when the heap to be restored was constructed without malloc
1756 checking, and thus does not contain the required magic bytes.
1757 Otherwise the heap would be corrupted by calls to free and realloc. If
1758 it turns out that the heap was created with malloc checking and the
1759 user has requested it malloc_set_state just calls __malloc_check_init
1760 again to enable it. On the other hand, reusing such a heap without
1761 further malloc checking is safe. */
1762 static int disallow_malloc_check;
1764 /* Activate a standard set of debugging hooks. */
1765 void
1766 __malloc_check_init()
1768 if (disallow_malloc_check) {
1769 disallow_malloc_check = 0;
1770 return;
1772 using_malloc_checking = 1;
1773 __malloc_hook = malloc_check;
1774 __free_hook = free_check;
1775 __realloc_hook = realloc_check;
1776 __memalign_hook = memalign_check;
1777 if(check_action == 1)
1778 fprintf(stderr, "malloc: using debugging hooks\n");
1781 #endif
1787 /* Routines dealing with mmap(). */
1789 #if HAVE_MMAP
1791 #ifndef MAP_ANONYMOUS
1793 static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */
1795 #define MMAP(addr, size, prot, flags) ((dev_zero_fd < 0) ? \
1796 (dev_zero_fd = open("/dev/zero", O_RDWR), \
1797 mmap((addr), (size), (prot), (flags), dev_zero_fd, 0)) : \
1798 mmap((addr), (size), (prot), (flags), dev_zero_fd, 0))
1800 #else
1802 #define MMAP(addr, size, prot, flags) \
1803 (mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS, -1, 0))
1805 #endif
1807 #if defined __GNUC__ && __GNUC__ >= 2
1808 /* This function is only called from one place, inline it. */
1809 inline
1810 #endif
1811 static mchunkptr
1812 internal_function
1813 #if __STD_C
1814 mmap_chunk(size_t size)
1815 #else
1816 mmap_chunk(size) size_t size;
1817 #endif
1819 size_t page_mask = malloc_getpagesize - 1;
1820 mchunkptr p;
1822 if(n_mmaps >= n_mmaps_max) return 0; /* too many regions */
1824 /* For mmapped chunks, the overhead is one SIZE_SZ unit larger, because
1825 * there is no following chunk whose prev_size field could be used.
1827 size = (size + SIZE_SZ + page_mask) & ~page_mask;
1829 p = (mchunkptr)MMAP(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE);
1830 if(p == (mchunkptr) MAP_FAILED) return 0;
1832 n_mmaps++;
1833 if (n_mmaps > max_n_mmaps) max_n_mmaps = n_mmaps;
1835 /* We demand that eight bytes into a page must be 8-byte aligned. */
1836 assert(aligned_OK(chunk2mem(p)));
1838 /* The offset to the start of the mmapped region is stored
1839 * in the prev_size field of the chunk; normally it is zero,
1840 * but that can be changed in memalign().
1842 p->prev_size = 0;
1843 set_head(p, size|IS_MMAPPED);
1845 mmapped_mem += size;
1846 if ((unsigned long)mmapped_mem > (unsigned long)max_mmapped_mem)
1847 max_mmapped_mem = mmapped_mem;
1848 #ifdef NO_THREADS
1849 if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
1850 max_total_mem = mmapped_mem + sbrked_mem;
1851 #endif
1852 return p;
1855 #if __STD_C
1856 static void munmap_chunk(mchunkptr p)
1857 #else
1858 static void munmap_chunk(p) mchunkptr p;
1859 #endif
1861 INTERNAL_SIZE_T size = chunksize(p);
1862 int ret;
1864 assert (chunk_is_mmapped(p));
1865 assert(! ((char*)p >= sbrk_base && (char*)p < sbrk_base + sbrked_mem));
1866 assert((n_mmaps > 0));
1867 assert(((p->prev_size + size) & (malloc_getpagesize-1)) == 0);
1869 n_mmaps--;
1870 mmapped_mem -= (size + p->prev_size);
1872 ret = munmap((char *)p - p->prev_size, size + p->prev_size);
1874 /* munmap returns non-zero on failure */
1875 assert(ret == 0);
1878 #if HAVE_MREMAP
1880 #if __STD_C
1881 static mchunkptr mremap_chunk(mchunkptr p, size_t new_size)
1882 #else
1883 static mchunkptr mremap_chunk(p, new_size) mchunkptr p; size_t new_size;
1884 #endif
1886 size_t page_mask = malloc_getpagesize - 1;
1887 INTERNAL_SIZE_T offset = p->prev_size;
1888 INTERNAL_SIZE_T size = chunksize(p);
1889 char *cp;
1891 assert (chunk_is_mmapped(p));
1892 assert(! ((char*)p >= sbrk_base && (char*)p < sbrk_base + sbrked_mem));
1893 assert((n_mmaps > 0));
1894 assert(((size + offset) & (malloc_getpagesize-1)) == 0);
1896 /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
1897 new_size = (new_size + offset + SIZE_SZ + page_mask) & ~page_mask;
1899 cp = (char *)mremap((char *)p - offset, size + offset, new_size,
1900 MREMAP_MAYMOVE);
1902 if (cp == (char *)-1) return 0;
1904 p = (mchunkptr)(cp + offset);
1906 assert(aligned_OK(chunk2mem(p)));
1908 assert((p->prev_size == offset));
1909 set_head(p, (new_size - offset)|IS_MMAPPED);
1911 mmapped_mem -= size + offset;
1912 mmapped_mem += new_size;
1913 if ((unsigned long)mmapped_mem > (unsigned long)max_mmapped_mem)
1914 max_mmapped_mem = mmapped_mem;
1915 #ifdef NO_THREADS
1916 if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
1917 max_total_mem = mmapped_mem + sbrked_mem;
1918 #endif
1919 return p;
1922 #endif /* HAVE_MREMAP */
1924 #endif /* HAVE_MMAP */
1928 /* Managing heaps and arenas (for concurrent threads) */
1930 #ifndef NO_THREADS
1932 /* Create a new heap. size is automatically rounded up to a multiple
1933 of the page size. */
1935 static heap_info *
1936 internal_function
1937 #if __STD_C
1938 new_heap(size_t size)
1939 #else
1940 new_heap(size) size_t size;
1941 #endif
1943 size_t page_mask = malloc_getpagesize - 1;
1944 char *p1, *p2;
1945 unsigned long ul;
1946 heap_info *h;
1948 if(size+top_pad < HEAP_MIN_SIZE)
1949 size = HEAP_MIN_SIZE;
1950 else if(size+top_pad <= HEAP_MAX_SIZE)
1951 size += top_pad;
1952 else if(size > HEAP_MAX_SIZE)
1953 return 0;
1954 else
1955 size = HEAP_MAX_SIZE;
1956 size = (size + page_mask) & ~page_mask;
1958 /* A memory region aligned to a multiple of HEAP_MAX_SIZE is needed.
1959 No swap space needs to be reserved for the following large
1960 mapping (on Linux, this is the case for all non-writable mappings
1961 anyway). */
1962 p1 = (char *)MMAP(0, HEAP_MAX_SIZE<<1, PROT_NONE, MAP_PRIVATE|MAP_NORESERVE);
1963 if(p1 == MAP_FAILED)
1964 return 0;
1965 p2 = (char *)(((unsigned long)p1 + HEAP_MAX_SIZE) & ~(HEAP_MAX_SIZE-1));
1966 ul = p2 - p1;
1967 munmap(p1, ul);
1968 munmap(p2 + HEAP_MAX_SIZE, HEAP_MAX_SIZE - ul);
1969 if(mprotect(p2, size, PROT_READ|PROT_WRITE) != 0) {
1970 munmap(p2, HEAP_MAX_SIZE);
1971 return 0;
1973 h = (heap_info *)p2;
1974 h->size = size;
1975 THREAD_STAT(stat_n_heaps++);
1976 return h;
1979 /* Grow or shrink a heap. size is automatically rounded up to a
1980 multiple of the page size if it is positive. */
1982 static int
1983 #if __STD_C
1984 grow_heap(heap_info *h, long diff)
1985 #else
1986 grow_heap(h, diff) heap_info *h; long diff;
1987 #endif
1989 size_t page_mask = malloc_getpagesize - 1;
1990 long new_size;
1992 if(diff >= 0) {
1993 diff = (diff + page_mask) & ~page_mask;
1994 new_size = (long)h->size + diff;
1995 if(new_size > HEAP_MAX_SIZE)
1996 return -1;
1997 if(mprotect((char *)h + h->size, diff, PROT_READ|PROT_WRITE) != 0)
1998 return -2;
1999 } else {
2000 new_size = (long)h->size + diff;
2001 if(new_size < (long)sizeof(*h))
2002 return -1;
2003 /* Try to re-map the extra heap space freshly to save memory, and
2004 make it inaccessible. */
2005 if((char *)MMAP((char *)h + new_size, -diff, PROT_NONE,
2006 MAP_PRIVATE|MAP_FIXED) == (char *) MAP_FAILED)
2007 return -2;
2009 h->size = new_size;
2010 return 0;
2013 /* Delete a heap. */
2015 #define delete_heap(heap) munmap((char*)(heap), HEAP_MAX_SIZE)
2017 /* arena_get() acquires an arena and locks the corresponding mutex.
2018 First, try the one last locked successfully by this thread. (This
2019 is the common case and handled with a macro for speed.) Then, loop
2020 once over the circularly linked list of arenas. If no arena is
2021 readily available, create a new one. */
2023 #define arena_get(ptr, size) do { \
2024 Void_t *vptr = NULL; \
2025 ptr = (arena *)tsd_getspecific(arena_key, vptr); \
2026 if(ptr && !mutex_trylock(&ptr->mutex)) { \
2027 THREAD_STAT(++(ptr->stat_lock_direct)); \
2028 } else \
2029 ptr = arena_get2(ptr, (size)); \
2030 } while(0)
2032 static arena *
2033 internal_function
2034 #if __STD_C
2035 arena_get2(arena *a_tsd, size_t size)
2036 #else
2037 arena_get2(a_tsd, size) arena *a_tsd; size_t size;
2038 #endif
2040 arena *a;
2041 heap_info *h;
2042 char *ptr;
2043 int i;
2044 unsigned long misalign;
2046 if(!a_tsd)
2047 a = a_tsd = &main_arena;
2048 else {
2049 a = a_tsd->next;
2050 if(!a) {
2051 /* This can only happen while initializing the new arena. */
2052 (void)mutex_lock(&main_arena.mutex);
2053 THREAD_STAT(++(main_arena.stat_lock_wait));
2054 return &main_arena;
2058 /* Check the global, circularly linked list for available arenas. */
2059 repeat:
2060 do {
2061 if(!mutex_trylock(&a->mutex)) {
2062 THREAD_STAT(++(a->stat_lock_loop));
2063 tsd_setspecific(arena_key, (Void_t *)a);
2064 return a;
2066 a = a->next;
2067 } while(a != a_tsd);
2069 /* If not even the list_lock can be obtained, try again. This can
2070 happen during `atfork', or for example on systems where thread
2071 creation makes it temporarily impossible to obtain _any_
2072 locks. */
2073 if(mutex_trylock(&list_lock)) {
2074 a = a_tsd;
2075 goto repeat;
2077 (void)mutex_unlock(&list_lock);
2079 /* Nothing immediately available, so generate a new arena. */
2080 h = new_heap(size + (sizeof(*h) + sizeof(*a) + MALLOC_ALIGNMENT));
2081 if(!h)
2082 return 0;
2083 a = h->ar_ptr = (arena *)(h+1);
2084 for(i=0; i<NAV; i++)
2085 init_bin(a, i);
2086 a->next = NULL;
2087 a->size = h->size;
2088 tsd_setspecific(arena_key, (Void_t *)a);
2089 mutex_init(&a->mutex);
2090 i = mutex_lock(&a->mutex); /* remember result */
2092 /* Set up the top chunk, with proper alignment. */
2093 ptr = (char *)(a + 1);
2094 misalign = (unsigned long)chunk2mem(ptr) & MALLOC_ALIGN_MASK;
2095 if (misalign > 0)
2096 ptr += MALLOC_ALIGNMENT - misalign;
2097 top(a) = (mchunkptr)ptr;
2098 set_head(top(a), (((char*)h + h->size) - ptr) | PREV_INUSE);
2100 /* Add the new arena to the list. */
2101 (void)mutex_lock(&list_lock);
2102 a->next = main_arena.next;
2103 main_arena.next = a;
2104 (void)mutex_unlock(&list_lock);
2106 if(i) /* locking failed; keep arena for further attempts later */
2107 return 0;
2109 THREAD_STAT(++(a->stat_lock_loop));
2110 return a;
2113 /* find the heap and corresponding arena for a given ptr */
2115 #define heap_for_ptr(ptr) \
2116 ((heap_info *)((unsigned long)(ptr) & ~(HEAP_MAX_SIZE-1)))
2117 #define arena_for_ptr(ptr) \
2118 (((mchunkptr)(ptr) < top(&main_arena) && (char *)(ptr) >= sbrk_base) ? \
2119 &main_arena : heap_for_ptr(ptr)->ar_ptr)
2121 #else /* defined(NO_THREADS) */
2123 /* Without concurrent threads, there is only one arena. */
2125 #define arena_get(ptr, sz) (ptr = &main_arena)
2126 #define arena_for_ptr(ptr) (&main_arena)
2128 #endif /* !defined(NO_THREADS) */
2133 Debugging support
2136 #if MALLOC_DEBUG
2140 These routines make a number of assertions about the states
2141 of data structures that should be true at all times. If any
2142 are not true, it's very likely that a user program has somehow
2143 trashed memory. (It's also possible that there is a coding error
2144 in malloc. In which case, please report it!)
2147 #if __STD_C
2148 static void do_check_chunk(arena *ar_ptr, mchunkptr p)
2149 #else
2150 static void do_check_chunk(ar_ptr, p) arena *ar_ptr; mchunkptr p;
2151 #endif
2153 INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
2155 /* No checkable chunk is mmapped */
2156 assert(!chunk_is_mmapped(p));
2158 #ifndef NO_THREADS
2159 if(ar_ptr != &main_arena) {
2160 heap_info *heap = heap_for_ptr(p);
2161 assert(heap->ar_ptr == ar_ptr);
2162 if(p != top(ar_ptr))
2163 assert((char *)p + sz <= (char *)heap + heap->size);
2164 else
2165 assert((char *)p + sz == (char *)heap + heap->size);
2166 return;
2168 #endif
2170 /* Check for legal address ... */
2171 assert((char*)p >= sbrk_base);
2172 if (p != top(ar_ptr))
2173 assert((char*)p + sz <= (char*)top(ar_ptr));
2174 else
2175 assert((char*)p + sz <= sbrk_base + sbrked_mem);
2180 #if __STD_C
2181 static void do_check_free_chunk(arena *ar_ptr, mchunkptr p)
2182 #else
2183 static void do_check_free_chunk(ar_ptr, p) arena *ar_ptr; mchunkptr p;
2184 #endif
2186 INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
2187 mchunkptr next = chunk_at_offset(p, sz);
2189 do_check_chunk(ar_ptr, p);
2191 /* Check whether it claims to be free ... */
2192 assert(!inuse(p));
2194 /* Must have OK size and fields */
2195 assert((long)sz >= (long)MINSIZE);
2196 assert((sz & MALLOC_ALIGN_MASK) == 0);
2197 assert(aligned_OK(chunk2mem(p)));
2198 /* ... matching footer field */
2199 assert(next->prev_size == sz);
2200 /* ... and is fully consolidated */
2201 assert(prev_inuse(p));
2202 assert (next == top(ar_ptr) || inuse(next));
2204 /* ... and has minimally sane links */
2205 assert(p->fd->bk == p);
2206 assert(p->bk->fd == p);
2209 #if __STD_C
2210 static void do_check_inuse_chunk(arena *ar_ptr, mchunkptr p)
2211 #else
2212 static void do_check_inuse_chunk(ar_ptr, p) arena *ar_ptr; mchunkptr p;
2213 #endif
2215 mchunkptr next = next_chunk(p);
2216 do_check_chunk(ar_ptr, p);
2218 /* Check whether it claims to be in use ... */
2219 assert(inuse(p));
2221 /* ... whether its size is OK (it might be a fencepost) ... */
2222 assert(chunksize(p) >= MINSIZE || next->size == (0|PREV_INUSE));
2224 /* ... and is surrounded by OK chunks.
2225 Since more things can be checked with free chunks than inuse ones,
2226 if an inuse chunk borders them and debug is on, it's worth doing them.
2228 if (!prev_inuse(p))
2230 mchunkptr prv = prev_chunk(p);
2231 assert(next_chunk(prv) == p);
2232 do_check_free_chunk(ar_ptr, prv);
2234 if (next == top(ar_ptr))
2236 assert(prev_inuse(next));
2237 assert(chunksize(next) >= MINSIZE);
2239 else if (!inuse(next))
2240 do_check_free_chunk(ar_ptr, next);
2244 #if __STD_C
2245 static void do_check_malloced_chunk(arena *ar_ptr,
2246 mchunkptr p, INTERNAL_SIZE_T s)
2247 #else
2248 static void do_check_malloced_chunk(ar_ptr, p, s)
2249 arena *ar_ptr; mchunkptr p; INTERNAL_SIZE_T s;
2250 #endif
2252 INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
2253 long room = sz - s;
2255 do_check_inuse_chunk(ar_ptr, p);
2257 /* Legal size ... */
2258 assert((long)sz >= (long)MINSIZE);
2259 assert((sz & MALLOC_ALIGN_MASK) == 0);
2260 assert(room >= 0);
2261 assert(room < (long)MINSIZE);
2263 /* ... and alignment */
2264 assert(aligned_OK(chunk2mem(p)));
2267 /* ... and was allocated at front of an available chunk */
2268 assert(prev_inuse(p));
2273 #define check_free_chunk(A,P) do_check_free_chunk(A,P)
2274 #define check_inuse_chunk(A,P) do_check_inuse_chunk(A,P)
2275 #define check_chunk(A,P) do_check_chunk(A,P)
2276 #define check_malloced_chunk(A,P,N) do_check_malloced_chunk(A,P,N)
2277 #else
2278 #define check_free_chunk(A,P)
2279 #define check_inuse_chunk(A,P)
2280 #define check_chunk(A,P)
2281 #define check_malloced_chunk(A,P,N)
2282 #endif
2287 Macro-based internal utilities
2292 Linking chunks in bin lists.
2293 Call these only with variables, not arbitrary expressions, as arguments.
2297 Place chunk p of size s in its bin, in size order,
2298 putting it ahead of others of same size.
2302 #define frontlink(A, P, S, IDX, BK, FD) \
2304 if (S < MAX_SMALLBIN_SIZE) \
2306 IDX = smallbin_index(S); \
2307 mark_binblock(A, IDX); \
2308 BK = bin_at(A, IDX); \
2309 FD = BK->fd; \
2310 P->bk = BK; \
2311 P->fd = FD; \
2312 FD->bk = BK->fd = P; \
2314 else \
2316 IDX = bin_index(S); \
2317 BK = bin_at(A, IDX); \
2318 FD = BK->fd; \
2319 if (FD == BK) mark_binblock(A, IDX); \
2320 else \
2322 while (FD != BK && S < chunksize(FD)) FD = FD->fd; \
2323 BK = FD->bk; \
2325 P->bk = BK; \
2326 P->fd = FD; \
2327 FD->bk = BK->fd = P; \
2332 /* take a chunk off a list */
2334 #define unlink(P, BK, FD) \
2336 BK = P->bk; \
2337 FD = P->fd; \
2338 FD->bk = BK; \
2339 BK->fd = FD; \
2342 /* Place p as the last remainder */
2344 #define link_last_remainder(A, P) \
2346 last_remainder(A)->fd = last_remainder(A)->bk = P; \
2347 P->fd = P->bk = last_remainder(A); \
2350 /* Clear the last_remainder bin */
2352 #define clear_last_remainder(A) \
2353 (last_remainder(A)->fd = last_remainder(A)->bk = last_remainder(A))
2360 Extend the top-most chunk by obtaining memory from system.
2361 Main interface to sbrk (but see also malloc_trim).
2364 #if defined __GNUC__ && __GNUC__ >= 2
2365 /* This function is called only from one place, inline it. */
2366 inline
2367 #endif
2368 static void
2369 internal_function
2370 #if __STD_C
2371 malloc_extend_top(arena *ar_ptr, INTERNAL_SIZE_T nb)
2372 #else
2373 malloc_extend_top(ar_ptr, nb) arena *ar_ptr; INTERNAL_SIZE_T nb;
2374 #endif
2376 unsigned long pagesz = malloc_getpagesize;
2377 mchunkptr old_top = top(ar_ptr); /* Record state of old top */
2378 INTERNAL_SIZE_T old_top_size = chunksize(old_top);
2379 INTERNAL_SIZE_T top_size; /* new size of top chunk */
2381 #ifndef NO_THREADS
2382 if(ar_ptr == &main_arena) {
2383 #endif
2385 char* brk; /* return value from sbrk */
2386 INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of sbrked space */
2387 INTERNAL_SIZE_T correction; /* bytes for 2nd sbrk call */
2388 char* new_brk; /* return of 2nd sbrk call */
2389 char* old_end = (char*)(chunk_at_offset(old_top, old_top_size));
2391 /* Pad request with top_pad plus minimal overhead */
2392 INTERNAL_SIZE_T sbrk_size = nb + top_pad + MINSIZE;
2394 /* If not the first time through, round to preserve page boundary */
2395 /* Otherwise, we need to correct to a page size below anyway. */
2396 /* (We also correct below if an intervening foreign sbrk call.) */
2398 if (sbrk_base != (char*)(-1))
2399 sbrk_size = (sbrk_size + (pagesz - 1)) & ~(pagesz - 1);
2401 brk = (char*)(MORECORE (sbrk_size));
2403 /* Fail if sbrk failed or if a foreign sbrk call killed our space */
2404 if (brk == (char*)(MORECORE_FAILURE) ||
2405 (brk < old_end && old_top != initial_top(&main_arena)))
2406 return;
2408 #if defined _LIBC || defined MALLOC_HOOKS
2409 /* Call the `morecore' hook if necessary. */
2410 if (__after_morecore_hook)
2411 (*__after_morecore_hook) ();
2412 #endif
2414 sbrked_mem += sbrk_size;
2416 if (brk == old_end) { /* can just add bytes to current top */
2417 top_size = sbrk_size + old_top_size;
2418 set_head(old_top, top_size | PREV_INUSE);
2419 old_top = 0; /* don't free below */
2420 } else {
2421 if (sbrk_base == (char*)(-1)) /* First time through. Record base */
2422 sbrk_base = brk;
2423 else
2424 /* Someone else called sbrk(). Count those bytes as sbrked_mem. */
2425 sbrked_mem += brk - (char*)old_end;
2427 /* Guarantee alignment of first new chunk made from this space */
2428 front_misalign = (unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK;
2429 if (front_misalign > 0) {
2430 correction = (MALLOC_ALIGNMENT) - front_misalign;
2431 brk += correction;
2432 } else
2433 correction = 0;
2435 /* Guarantee the next brk will be at a page boundary */
2436 correction += pagesz - ((unsigned long)(brk + sbrk_size) & (pagesz - 1));
2438 /* Allocate correction */
2439 new_brk = (char*)(MORECORE (correction));
2440 if (new_brk == (char*)(MORECORE_FAILURE)) return;
2442 #if defined _LIBC || defined MALLOC_HOOKS
2443 /* Call the `morecore' hook if necessary. */
2444 if (__after_morecore_hook)
2445 (*__after_morecore_hook) ();
2446 #endif
2448 sbrked_mem += correction;
2450 top(&main_arena) = (mchunkptr)brk;
2451 top_size = new_brk - brk + correction;
2452 set_head(top(&main_arena), top_size | PREV_INUSE);
2454 if (old_top == initial_top(&main_arena))
2455 old_top = 0; /* don't free below */
2458 if ((unsigned long)sbrked_mem > (unsigned long)max_sbrked_mem)
2459 max_sbrked_mem = sbrked_mem;
2460 #ifdef NO_THREADS
2461 if ((unsigned long)(mmapped_mem + sbrked_mem) >
2462 (unsigned long)max_total_mem)
2463 max_total_mem = mmapped_mem + sbrked_mem;
2464 #endif
2466 #ifndef NO_THREADS
2467 } else { /* ar_ptr != &main_arena */
2468 heap_info *old_heap, *heap;
2469 size_t old_heap_size;
2471 if(old_top_size < MINSIZE) /* this should never happen */
2472 return;
2474 /* First try to extend the current heap. */
2475 if(MINSIZE + nb <= old_top_size)
2476 return;
2477 old_heap = heap_for_ptr(old_top);
2478 old_heap_size = old_heap->size;
2479 if(grow_heap(old_heap, MINSIZE + nb - old_top_size) == 0) {
2480 ar_ptr->size += old_heap->size - old_heap_size;
2481 top_size = ((char *)old_heap + old_heap->size) - (char *)old_top;
2482 set_head(old_top, top_size | PREV_INUSE);
2483 return;
2486 /* A new heap must be created. */
2487 heap = new_heap(nb + (MINSIZE + sizeof(*heap)));
2488 if(!heap)
2489 return;
2490 heap->ar_ptr = ar_ptr;
2491 heap->prev = old_heap;
2492 ar_ptr->size += heap->size;
2494 /* Set up the new top, so we can safely use chunk_free() below. */
2495 top(ar_ptr) = chunk_at_offset(heap, sizeof(*heap));
2496 top_size = heap->size - sizeof(*heap);
2497 set_head(top(ar_ptr), top_size | PREV_INUSE);
2499 #endif /* !defined(NO_THREADS) */
2501 /* We always land on a page boundary */
2502 assert(((unsigned long)((char*)top(ar_ptr) + top_size) & (pagesz-1)) == 0);
2504 /* Setup fencepost and free the old top chunk. */
2505 if(old_top) {
2506 /* The fencepost takes at least MINSIZE bytes, because it might
2507 become the top chunk again later. Note that a footer is set
2508 up, too, although the chunk is marked in use. */
2509 old_top_size -= MINSIZE;
2510 set_head(chunk_at_offset(old_top, old_top_size + 2*SIZE_SZ), 0|PREV_INUSE);
2511 if(old_top_size >= MINSIZE) {
2512 set_head(chunk_at_offset(old_top, old_top_size), (2*SIZE_SZ)|PREV_INUSE);
2513 set_foot(chunk_at_offset(old_top, old_top_size), (2*SIZE_SZ));
2514 set_head_size(old_top, old_top_size);
2515 chunk_free(ar_ptr, old_top);
2516 } else {
2517 set_head(old_top, (old_top_size + 2*SIZE_SZ)|PREV_INUSE);
2518 set_foot(old_top, (old_top_size + 2*SIZE_SZ));
2526 /* Main public routines */
2530 Malloc Algorithm:
2532 The requested size is first converted into a usable form, `nb'.
2533 This currently means to add 4 bytes overhead plus possibly more to
2534 obtain 8-byte alignment and/or to obtain a size of at least
2535 MINSIZE (currently 16, 24, or 32 bytes), the smallest allocatable
2536 size. (All fits are considered `exact' if they are within MINSIZE
2537 bytes.)
2539 From there, the first successful of the following steps is taken:
2541 1. The bin corresponding to the request size is scanned, and if
2542 a chunk of exactly the right size is found, it is taken.
2544 2. The most recently remaindered chunk is used if it is big
2545 enough. This is a form of (roving) first fit, used only in
2546 the absence of exact fits. Runs of consecutive requests use
2547 the remainder of the chunk used for the previous such request
2548 whenever possible. This limited use of a first-fit style
2549 allocation strategy tends to give contiguous chunks
2550 coextensive lifetimes, which improves locality and can reduce
2551 fragmentation in the long run.
2553 3. Other bins are scanned in increasing size order, using a
2554 chunk big enough to fulfill the request, and splitting off
2555 any remainder. This search is strictly by best-fit; i.e.,
2556 the smallest (with ties going to approximately the least
2557 recently used) chunk that fits is selected.
2559 4. If large enough, the chunk bordering the end of memory
2560 (`top') is split off. (This use of `top' is in accord with
2561 the best-fit search rule. In effect, `top' is treated as
2562 larger (and thus less well fitting) than any other available
2563 chunk since it can be extended to be as large as necessary
2564 (up to system limitations).
2566 5. If the request size meets the mmap threshold and the
2567 system supports mmap, and there are few enough currently
2568 allocated mmapped regions, and a call to mmap succeeds,
2569 the request is allocated via direct memory mapping.
2571 6. Otherwise, the top of memory is extended by
2572 obtaining more space from the system (normally using sbrk,
2573 but definable to anything else via the MORECORE macro).
2574 Memory is gathered from the system (in system page-sized
2575 units) in a way that allows chunks obtained across different
2576 sbrk calls to be consolidated, but does not require
2577 contiguous memory. Thus, it should be safe to intersperse
2578 mallocs with other sbrk calls.
2581 All allocations are made from the `lowest' part of any found
2582 chunk. (The implementation invariant is that prev_inuse is
2583 always true of any allocated chunk; i.e., that each allocated
2584 chunk borders either a previously allocated and still in-use chunk,
2585 or the base of its memory arena.)
2589 #if __STD_C
2590 Void_t* mALLOc(size_t bytes)
2591 #else
2592 Void_t* mALLOc(bytes) size_t bytes;
2593 #endif
2595 arena *ar_ptr;
2596 INTERNAL_SIZE_T nb; /* padded request size */
2597 mchunkptr victim;
2599 #if defined _LIBC || defined MALLOC_HOOKS
2600 if (__malloc_hook != NULL) {
2601 Void_t* result;
2603 #if defined __GNUC__ && __GNUC__ >= 2
2604 result = (*__malloc_hook)(bytes, __builtin_return_address (0));
2605 #else
2606 result = (*__malloc_hook)(bytes, NULL);
2607 #endif
2608 return result;
2610 #endif
2612 nb = request2size(bytes);
2613 arena_get(ar_ptr, nb);
2614 if(!ar_ptr)
2615 return 0;
2616 victim = chunk_alloc(ar_ptr, nb);
2617 (void)mutex_unlock(&ar_ptr->mutex);
2618 if(!victim) {
2619 /* Maybe the failure is due to running out of mmapped areas. */
2620 if(ar_ptr != &main_arena) {
2621 (void)mutex_lock(&main_arena.mutex);
2622 victim = chunk_alloc(&main_arena, nb);
2623 (void)mutex_unlock(&main_arena.mutex);
2625 if(!victim) return 0;
2627 return chunk2mem(victim);
2630 static mchunkptr
2631 internal_function
2632 #if __STD_C
2633 chunk_alloc(arena *ar_ptr, INTERNAL_SIZE_T nb)
2634 #else
2635 chunk_alloc(ar_ptr, nb) arena *ar_ptr; INTERNAL_SIZE_T nb;
2636 #endif
2638 mchunkptr victim; /* inspected/selected chunk */
2639 INTERNAL_SIZE_T victim_size; /* its size */
2640 int idx; /* index for bin traversal */
2641 mbinptr bin; /* associated bin */
2642 mchunkptr remainder; /* remainder from a split */
2643 long remainder_size; /* its size */
2644 int remainder_index; /* its bin index */
2645 unsigned long block; /* block traverser bit */
2646 int startidx; /* first bin of a traversed block */
2647 mchunkptr fwd; /* misc temp for linking */
2648 mchunkptr bck; /* misc temp for linking */
2649 mbinptr q; /* misc temp */
2652 /* Check for exact match in a bin */
2654 if (is_small_request(nb)) /* Faster version for small requests */
2656 idx = smallbin_index(nb);
2658 /* No traversal or size check necessary for small bins. */
2660 q = bin_at(ar_ptr, idx);
2661 victim = last(q);
2663 /* Also scan the next one, since it would have a remainder < MINSIZE */
2664 if (victim == q)
2666 q = next_bin(q);
2667 victim = last(q);
2669 if (victim != q)
2671 victim_size = chunksize(victim);
2672 unlink(victim, bck, fwd);
2673 set_inuse_bit_at_offset(victim, victim_size);
2674 check_malloced_chunk(ar_ptr, victim, nb);
2675 return victim;
2678 idx += 2; /* Set for bin scan below. We've already scanned 2 bins. */
2681 else
2683 idx = bin_index(nb);
2684 bin = bin_at(ar_ptr, idx);
2686 for (victim = last(bin); victim != bin; victim = victim->bk)
2688 victim_size = chunksize(victim);
2689 remainder_size = victim_size - nb;
2691 if (remainder_size >= (long)MINSIZE) /* too big */
2693 --idx; /* adjust to rescan below after checking last remainder */
2694 break;
2697 else if (remainder_size >= 0) /* exact fit */
2699 unlink(victim, bck, fwd);
2700 set_inuse_bit_at_offset(victim, victim_size);
2701 check_malloced_chunk(ar_ptr, victim, nb);
2702 return victim;
2706 ++idx;
2710 /* Try to use the last split-off remainder */
2712 if ( (victim = last_remainder(ar_ptr)->fd) != last_remainder(ar_ptr))
2714 victim_size = chunksize(victim);
2715 remainder_size = victim_size - nb;
2717 if (remainder_size >= (long)MINSIZE) /* re-split */
2719 remainder = chunk_at_offset(victim, nb);
2720 set_head(victim, nb | PREV_INUSE);
2721 link_last_remainder(ar_ptr, remainder);
2722 set_head(remainder, remainder_size | PREV_INUSE);
2723 set_foot(remainder, remainder_size);
2724 check_malloced_chunk(ar_ptr, victim, nb);
2725 return victim;
2728 clear_last_remainder(ar_ptr);
2730 if (remainder_size >= 0) /* exhaust */
2732 set_inuse_bit_at_offset(victim, victim_size);
2733 check_malloced_chunk(ar_ptr, victim, nb);
2734 return victim;
2737 /* Else place in bin */
2739 frontlink(ar_ptr, victim, victim_size, remainder_index, bck, fwd);
2743 If there are any possibly nonempty big-enough blocks,
2744 search for best fitting chunk by scanning bins in blockwidth units.
2747 if ( (block = idx2binblock(idx)) <= binblocks(ar_ptr))
2750 /* Get to the first marked block */
2752 if ( (block & binblocks(ar_ptr)) == 0)
2754 /* force to an even block boundary */
2755 idx = (idx & ~(BINBLOCKWIDTH - 1)) + BINBLOCKWIDTH;
2756 block <<= 1;
2757 while ((block & binblocks(ar_ptr)) == 0)
2759 idx += BINBLOCKWIDTH;
2760 block <<= 1;
2764 /* For each possibly nonempty block ... */
2765 for (;;)
2767 startidx = idx; /* (track incomplete blocks) */
2768 q = bin = bin_at(ar_ptr, idx);
2770 /* For each bin in this block ... */
2773 /* Find and use first big enough chunk ... */
2775 for (victim = last(bin); victim != bin; victim = victim->bk)
2777 victim_size = chunksize(victim);
2778 remainder_size = victim_size - nb;
2780 if (remainder_size >= (long)MINSIZE) /* split */
2782 remainder = chunk_at_offset(victim, nb);
2783 set_head(victim, nb | PREV_INUSE);
2784 unlink(victim, bck, fwd);
2785 link_last_remainder(ar_ptr, remainder);
2786 set_head(remainder, remainder_size | PREV_INUSE);
2787 set_foot(remainder, remainder_size);
2788 check_malloced_chunk(ar_ptr, victim, nb);
2789 return victim;
2792 else if (remainder_size >= 0) /* take */
2794 set_inuse_bit_at_offset(victim, victim_size);
2795 unlink(victim, bck, fwd);
2796 check_malloced_chunk(ar_ptr, victim, nb);
2797 return victim;
2802 bin = next_bin(bin);
2804 } while ((++idx & (BINBLOCKWIDTH - 1)) != 0);
2806 /* Clear out the block bit. */
2808 do /* Possibly backtrack to try to clear a partial block */
2810 if ((startidx & (BINBLOCKWIDTH - 1)) == 0)
2812 binblocks(ar_ptr) &= ~block;
2813 break;
2815 --startidx;
2816 q = prev_bin(q);
2817 } while (first(q) == q);
2819 /* Get to the next possibly nonempty block */
2821 if ( (block <<= 1) <= binblocks(ar_ptr) && (block != 0) )
2823 while ((block & binblocks(ar_ptr)) == 0)
2825 idx += BINBLOCKWIDTH;
2826 block <<= 1;
2829 else
2830 break;
2835 /* Try to use top chunk */
2837 /* Require that there be a remainder, ensuring top always exists */
2838 if ( (remainder_size = chunksize(top(ar_ptr)) - nb) < (long)MINSIZE)
2841 #if HAVE_MMAP
2842 /* If big and would otherwise need to extend, try to use mmap instead */
2843 if ((unsigned long)nb >= (unsigned long)mmap_threshold &&
2844 (victim = mmap_chunk(nb)) != 0)
2845 return victim;
2846 #endif
2848 /* Try to extend */
2849 malloc_extend_top(ar_ptr, nb);
2850 if ((remainder_size = chunksize(top(ar_ptr)) - nb) < (long)MINSIZE)
2851 return 0; /* propagate failure */
2854 victim = top(ar_ptr);
2855 set_head(victim, nb | PREV_INUSE);
2856 top(ar_ptr) = chunk_at_offset(victim, nb);
2857 set_head(top(ar_ptr), remainder_size | PREV_INUSE);
2858 check_malloced_chunk(ar_ptr, victim, nb);
2859 return victim;
2868 free() algorithm :
2870 cases:
2872 1. free(0) has no effect.
2874 2. If the chunk was allocated via mmap, it is released via munmap().
2876 3. If a returned chunk borders the current high end of memory,
2877 it is consolidated into the top, and if the total unused
2878 topmost memory exceeds the trim threshold, malloc_trim is
2879 called.
2881 4. Other chunks are consolidated as they arrive, and
2882 placed in corresponding bins. (This includes the case of
2883 consolidating with the current `last_remainder').
2888 #if __STD_C
2889 void fREe(Void_t* mem)
2890 #else
2891 void fREe(mem) Void_t* mem;
2892 #endif
2894 arena *ar_ptr;
2895 mchunkptr p; /* chunk corresponding to mem */
2897 #if defined _LIBC || defined MALLOC_HOOKS
2898 if (__free_hook != NULL) {
2899 #if defined __GNUC__ && __GNUC__ >= 2
2900 (*__free_hook)(mem, __builtin_return_address (0));
2901 #else
2902 (*__free_hook)(mem, NULL);
2903 #endif
2904 return;
2906 #endif
2908 if (mem == 0) /* free(0) has no effect */
2909 return;
2911 p = mem2chunk(mem);
2913 #if HAVE_MMAP
2914 if (chunk_is_mmapped(p)) /* release mmapped memory. */
2916 munmap_chunk(p);
2917 return;
2919 #endif
2921 ar_ptr = arena_for_ptr(p);
2922 #if THREAD_STATS
2923 if(!mutex_trylock(&ar_ptr->mutex))
2924 ++(ar_ptr->stat_lock_direct);
2925 else {
2926 (void)mutex_lock(&ar_ptr->mutex);
2927 ++(ar_ptr->stat_lock_wait);
2929 #else
2930 (void)mutex_lock(&ar_ptr->mutex);
2931 #endif
2932 chunk_free(ar_ptr, p);
2933 (void)mutex_unlock(&ar_ptr->mutex);
2936 static void
2937 internal_function
2938 #if __STD_C
2939 chunk_free(arena *ar_ptr, mchunkptr p)
2940 #else
2941 chunk_free(ar_ptr, p) arena *ar_ptr; mchunkptr p;
2942 #endif
2944 INTERNAL_SIZE_T hd = p->size; /* its head field */
2945 INTERNAL_SIZE_T sz; /* its size */
2946 int idx; /* its bin index */
2947 mchunkptr next; /* next contiguous chunk */
2948 INTERNAL_SIZE_T nextsz; /* its size */
2949 INTERNAL_SIZE_T prevsz; /* size of previous contiguous chunk */
2950 mchunkptr bck; /* misc temp for linking */
2951 mchunkptr fwd; /* misc temp for linking */
2952 int islr; /* track whether merging with last_remainder */
2954 check_inuse_chunk(ar_ptr, p);
2956 sz = hd & ~PREV_INUSE;
2957 next = chunk_at_offset(p, sz);
2958 nextsz = chunksize(next);
2960 if (next == top(ar_ptr)) /* merge with top */
2962 sz += nextsz;
2964 if (!(hd & PREV_INUSE)) /* consolidate backward */
2966 prevsz = p->prev_size;
2967 p = chunk_at_offset(p, -prevsz);
2968 sz += prevsz;
2969 unlink(p, bck, fwd);
2972 set_head(p, sz | PREV_INUSE);
2973 top(ar_ptr) = p;
2975 #ifndef NO_THREADS
2976 if(ar_ptr == &main_arena) {
2977 #endif
2978 if ((unsigned long)(sz) >= (unsigned long)trim_threshold)
2979 main_trim(top_pad);
2980 #ifndef NO_THREADS
2981 } else {
2982 heap_info *heap = heap_for_ptr(p);
2984 assert(heap->ar_ptr == ar_ptr);
2986 /* Try to get rid of completely empty heaps, if possible. */
2987 if((unsigned long)(sz) >= (unsigned long)trim_threshold ||
2988 p == chunk_at_offset(heap, sizeof(*heap)))
2989 heap_trim(heap, top_pad);
2991 #endif
2992 return;
2995 islr = 0;
2997 if (!(hd & PREV_INUSE)) /* consolidate backward */
2999 prevsz = p->prev_size;
3000 p = chunk_at_offset(p, -prevsz);
3001 sz += prevsz;
3003 if (p->fd == last_remainder(ar_ptr)) /* keep as last_remainder */
3004 islr = 1;
3005 else
3006 unlink(p, bck, fwd);
3009 if (!(inuse_bit_at_offset(next, nextsz))) /* consolidate forward */
3011 sz += nextsz;
3013 if (!islr && next->fd == last_remainder(ar_ptr))
3014 /* re-insert last_remainder */
3016 islr = 1;
3017 link_last_remainder(ar_ptr, p);
3019 else
3020 unlink(next, bck, fwd);
3022 next = chunk_at_offset(p, sz);
3024 else
3025 set_head(next, nextsz); /* clear inuse bit */
3027 set_head(p, sz | PREV_INUSE);
3028 next->prev_size = sz;
3029 if (!islr)
3030 frontlink(ar_ptr, p, sz, idx, bck, fwd);
3032 #ifndef NO_THREADS
3033 /* Check whether the heap containing top can go away now. */
3034 if(next->size < MINSIZE &&
3035 (unsigned long)sz > trim_threshold &&
3036 ar_ptr != &main_arena) { /* fencepost */
3037 heap_info* heap = heap_for_ptr(top(ar_ptr));
3039 if(top(ar_ptr) == chunk_at_offset(heap, sizeof(*heap)) &&
3040 heap->prev == heap_for_ptr(p))
3041 heap_trim(heap, top_pad);
3043 #endif
3052 Realloc algorithm:
3054 Chunks that were obtained via mmap cannot be extended or shrunk
3055 unless HAVE_MREMAP is defined, in which case mremap is used.
3056 Otherwise, if their reallocation is for additional space, they are
3057 copied. If for less, they are just left alone.
3059 Otherwise, if the reallocation is for additional space, and the
3060 chunk can be extended, it is, else a malloc-copy-free sequence is
3061 taken. There are several different ways that a chunk could be
3062 extended. All are tried:
3064 * Extending forward into following adjacent free chunk.
3065 * Shifting backwards, joining preceding adjacent space
3066 * Both shifting backwards and extending forward.
3067 * Extending into newly sbrked space
3069 Unless the #define REALLOC_ZERO_BYTES_FREES is set, realloc with a
3070 size argument of zero (re)allocates a minimum-sized chunk.
3072 If the reallocation is for less space, and the new request is for
3073 a `small' (<512 bytes) size, then the newly unused space is lopped
3074 off and freed.
3076 The old unix realloc convention of allowing the last-free'd chunk
3077 to be used as an argument to realloc is no longer supported.
3078 I don't know of any programs still relying on this feature,
3079 and allowing it would also allow too many other incorrect
3080 usages of realloc to be sensible.
3086 #if __STD_C
3087 Void_t* rEALLOc(Void_t* oldmem, size_t bytes)
3088 #else
3089 Void_t* rEALLOc(oldmem, bytes) Void_t* oldmem; size_t bytes;
3090 #endif
3092 arena *ar_ptr;
3093 INTERNAL_SIZE_T nb; /* padded request size */
3095 mchunkptr oldp; /* chunk corresponding to oldmem */
3096 INTERNAL_SIZE_T oldsize; /* its size */
3098 mchunkptr newp; /* chunk to return */
3100 #if defined _LIBC || defined MALLOC_HOOKS
3101 if (__realloc_hook != NULL) {
3102 Void_t* result;
3104 #if defined __GNUC__ && __GNUC__ >= 2
3105 result = (*__realloc_hook)(oldmem, bytes, __builtin_return_address (0));
3106 #else
3107 result = (*__realloc_hook)(oldmem, bytes, NULL);
3108 #endif
3109 return result;
3111 #endif
3113 #ifdef REALLOC_ZERO_BYTES_FREES
3114 if (bytes == 0 && oldmem != NULL) { fREe(oldmem); return 0; }
3115 #endif
3117 /* realloc of null is supposed to be same as malloc */
3118 if (oldmem == 0) return mALLOc(bytes);
3120 oldp = mem2chunk(oldmem);
3121 oldsize = chunksize(oldp);
3123 nb = request2size(bytes);
3125 #if HAVE_MMAP
3126 if (chunk_is_mmapped(oldp))
3128 Void_t* newmem;
3130 #if HAVE_MREMAP
3131 newp = mremap_chunk(oldp, nb);
3132 if(newp) return chunk2mem(newp);
3133 #endif
3134 /* Note the extra SIZE_SZ overhead. */
3135 if(oldsize - SIZE_SZ >= nb) return oldmem; /* do nothing */
3136 /* Must alloc, copy, free. */
3137 newmem = mALLOc(bytes);
3138 if (newmem == 0) return 0; /* propagate failure */
3139 MALLOC_COPY(newmem, oldmem, oldsize - 2*SIZE_SZ);
3140 munmap_chunk(oldp);
3141 return newmem;
3143 #endif
3145 ar_ptr = arena_for_ptr(oldp);
3146 #if THREAD_STATS
3147 if(!mutex_trylock(&ar_ptr->mutex))
3148 ++(ar_ptr->stat_lock_direct);
3149 else {
3150 (void)mutex_lock(&ar_ptr->mutex);
3151 ++(ar_ptr->stat_lock_wait);
3153 #else
3154 (void)mutex_lock(&ar_ptr->mutex);
3155 #endif
3157 #ifndef NO_THREADS
3158 /* As in malloc(), remember this arena for the next allocation. */
3159 tsd_setspecific(arena_key, (Void_t *)ar_ptr);
3160 #endif
3162 newp = chunk_realloc(ar_ptr, oldp, oldsize, nb);
3164 (void)mutex_unlock(&ar_ptr->mutex);
3165 return newp ? chunk2mem(newp) : NULL;
3168 static mchunkptr
3169 internal_function
3170 #if __STD_C
3171 chunk_realloc(arena* ar_ptr, mchunkptr oldp, INTERNAL_SIZE_T oldsize,
3172 INTERNAL_SIZE_T nb)
3173 #else
3174 chunk_realloc(ar_ptr, oldp, oldsize, nb)
3175 arena* ar_ptr; mchunkptr oldp; INTERNAL_SIZE_T oldsize, nb;
3176 #endif
3178 mchunkptr newp = oldp; /* chunk to return */
3179 INTERNAL_SIZE_T newsize = oldsize; /* its size */
3181 mchunkptr next; /* next contiguous chunk after oldp */
3182 INTERNAL_SIZE_T nextsize; /* its size */
3184 mchunkptr prev; /* previous contiguous chunk before oldp */
3185 INTERNAL_SIZE_T prevsize; /* its size */
3187 mchunkptr remainder; /* holds split off extra space from newp */
3188 INTERNAL_SIZE_T remainder_size; /* its size */
3190 mchunkptr bck; /* misc temp for linking */
3191 mchunkptr fwd; /* misc temp for linking */
3193 check_inuse_chunk(ar_ptr, oldp);
3195 if ((long)(oldsize) < (long)(nb))
3198 /* Try expanding forward */
3200 next = chunk_at_offset(oldp, oldsize);
3201 if (next == top(ar_ptr) || !inuse(next))
3203 nextsize = chunksize(next);
3205 /* Forward into top only if a remainder */
3206 if (next == top(ar_ptr))
3208 if ((long)(nextsize + newsize) >= (long)(nb + MINSIZE))
3210 newsize += nextsize;
3211 top(ar_ptr) = chunk_at_offset(oldp, nb);
3212 set_head(top(ar_ptr), (newsize - nb) | PREV_INUSE);
3213 set_head_size(oldp, nb);
3214 return oldp;
3218 /* Forward into next chunk */
3219 else if (((long)(nextsize + newsize) >= (long)(nb)))
3221 unlink(next, bck, fwd);
3222 newsize += nextsize;
3223 goto split;
3226 else
3228 next = 0;
3229 nextsize = 0;
3232 /* Try shifting backwards. */
3234 if (!prev_inuse(oldp))
3236 prev = prev_chunk(oldp);
3237 prevsize = chunksize(prev);
3239 /* try forward + backward first to save a later consolidation */
3241 if (next != 0)
3243 /* into top */
3244 if (next == top(ar_ptr))
3246 if ((long)(nextsize + prevsize + newsize) >= (long)(nb + MINSIZE))
3248 unlink(prev, bck, fwd);
3249 newp = prev;
3250 newsize += prevsize + nextsize;
3251 MALLOC_COPY(chunk2mem(newp), chunk2mem(oldp), oldsize - SIZE_SZ);
3252 top(ar_ptr) = chunk_at_offset(newp, nb);
3253 set_head(top(ar_ptr), (newsize - nb) | PREV_INUSE);
3254 set_head_size(newp, nb);
3255 return newp;
3259 /* into next chunk */
3260 else if (((long)(nextsize + prevsize + newsize) >= (long)(nb)))
3262 unlink(next, bck, fwd);
3263 unlink(prev, bck, fwd);
3264 newp = prev;
3265 newsize += nextsize + prevsize;
3266 MALLOC_COPY(chunk2mem(newp), chunk2mem(oldp), oldsize - SIZE_SZ);
3267 goto split;
3271 /* backward only */
3272 if (prev != 0 && (long)(prevsize + newsize) >= (long)nb)
3274 unlink(prev, bck, fwd);
3275 newp = prev;
3276 newsize += prevsize;
3277 MALLOC_COPY(chunk2mem(newp), chunk2mem(oldp), oldsize - SIZE_SZ);
3278 goto split;
3282 /* Must allocate */
3284 newp = chunk_alloc (ar_ptr, nb);
3286 if (newp == 0) {
3287 /* Maybe the failure is due to running out of mmapped areas. */
3288 if (ar_ptr != &main_arena) {
3289 (void)mutex_lock(&main_arena.mutex);
3290 newp = chunk_alloc(&main_arena, nb);
3291 (void)mutex_unlock(&main_arena.mutex);
3293 if (newp == 0) /* propagate failure */
3294 return 0;
3297 /* Avoid copy if newp is next chunk after oldp. */
3298 /* (This can only happen when new chunk is sbrk'ed.) */
3300 if ( newp == next_chunk(oldp))
3302 newsize += chunksize(newp);
3303 newp = oldp;
3304 goto split;
3307 /* Otherwise copy, free, and exit */
3308 MALLOC_COPY(chunk2mem(newp), chunk2mem(oldp), oldsize - SIZE_SZ);
3309 chunk_free(ar_ptr, oldp);
3310 return newp;
3314 split: /* split off extra room in old or expanded chunk */
3316 if (newsize - nb >= MINSIZE) /* split off remainder */
3318 remainder = chunk_at_offset(newp, nb);
3319 remainder_size = newsize - nb;
3320 set_head_size(newp, nb);
3321 set_head(remainder, remainder_size | PREV_INUSE);
3322 set_inuse_bit_at_offset(remainder, remainder_size);
3323 chunk_free(ar_ptr, remainder);
3325 else
3327 set_head_size(newp, newsize);
3328 set_inuse_bit_at_offset(newp, newsize);
3331 check_inuse_chunk(ar_ptr, newp);
3332 return newp;
3340 memalign algorithm:
3342 memalign requests more than enough space from malloc, finds a spot
3343 within that chunk that meets the alignment request, and then
3344 possibly frees the leading and trailing space.
3346 The alignment argument must be a power of two. This property is not
3347 checked by memalign, so misuse may result in random runtime errors.
3349 8-byte alignment is guaranteed by normal malloc calls, so don't
3350 bother calling memalign with an argument of 8 or less.
3352 Overreliance on memalign is a sure way to fragment space.
3357 #if __STD_C
3358 Void_t* mEMALIGn(size_t alignment, size_t bytes)
3359 #else
3360 Void_t* mEMALIGn(alignment, bytes) size_t alignment; size_t bytes;
3361 #endif
3363 arena *ar_ptr;
3364 INTERNAL_SIZE_T nb; /* padded request size */
3365 mchunkptr p;
3367 #if defined _LIBC || defined MALLOC_HOOKS
3368 if (__memalign_hook != NULL) {
3369 Void_t* result;
3371 #if defined __GNUC__ && __GNUC__ >= 2
3372 result = (*__memalign_hook)(alignment, bytes,
3373 __builtin_return_address (0));
3374 #else
3375 result = (*__memalign_hook)(alignment, bytes, NULL);
3376 #endif
3377 return result;
3379 #endif
3381 /* If need less alignment than we give anyway, just relay to malloc */
3383 if (alignment <= MALLOC_ALIGNMENT) return mALLOc(bytes);
3385 /* Otherwise, ensure that it is at least a minimum chunk size */
3387 if (alignment < MINSIZE) alignment = MINSIZE;
3389 nb = request2size(bytes);
3390 arena_get(ar_ptr, nb + alignment + MINSIZE);
3391 if(!ar_ptr)
3392 return 0;
3393 p = chunk_align(ar_ptr, nb, alignment);
3394 (void)mutex_unlock(&ar_ptr->mutex);
3395 if(!p) {
3396 /* Maybe the failure is due to running out of mmapped areas. */
3397 if(ar_ptr != &main_arena) {
3398 (void)mutex_lock(&main_arena.mutex);
3399 p = chunk_align(&main_arena, nb, alignment);
3400 (void)mutex_unlock(&main_arena.mutex);
3402 if(!p) return 0;
3404 return chunk2mem(p);
3407 static mchunkptr
3408 internal_function
3409 #if __STD_C
3410 chunk_align(arena* ar_ptr, INTERNAL_SIZE_T nb, size_t alignment)
3411 #else
3412 chunk_align(ar_ptr, nb, alignment)
3413 arena* ar_ptr; INTERNAL_SIZE_T nb; size_t alignment;
3414 #endif
3416 char* m; /* memory returned by malloc call */
3417 mchunkptr p; /* corresponding chunk */
3418 char* brk; /* alignment point within p */
3419 mchunkptr newp; /* chunk to return */
3420 INTERNAL_SIZE_T newsize; /* its size */
3421 INTERNAL_SIZE_T leadsize; /* leading space befor alignment point */
3422 mchunkptr remainder; /* spare room at end to split off */
3423 long remainder_size; /* its size */
3425 /* Call chunk_alloc with worst case padding to hit alignment. */
3426 p = chunk_alloc(ar_ptr, nb + alignment + MINSIZE);
3427 if (p == 0)
3428 return 0; /* propagate failure */
3430 m = chunk2mem(p);
3432 if ((((unsigned long)(m)) % alignment) == 0) /* aligned */
3434 #if HAVE_MMAP
3435 if(chunk_is_mmapped(p)) {
3436 return p; /* nothing more to do */
3438 #endif
3440 else /* misaligned */
3443 Find an aligned spot inside chunk.
3444 Since we need to give back leading space in a chunk of at
3445 least MINSIZE, if the first calculation places us at
3446 a spot with less than MINSIZE leader, we can move to the
3447 next aligned spot -- we've allocated enough total room so that
3448 this is always possible.
3451 brk = (char*)mem2chunk(((unsigned long)(m + alignment - 1)) & -alignment);
3452 if ((long)(brk - (char*)(p)) < (long)MINSIZE) brk += alignment;
3454 newp = (mchunkptr)brk;
3455 leadsize = brk - (char*)(p);
3456 newsize = chunksize(p) - leadsize;
3458 #if HAVE_MMAP
3459 if(chunk_is_mmapped(p))
3461 newp->prev_size = p->prev_size + leadsize;
3462 set_head(newp, newsize|IS_MMAPPED);
3463 return newp;
3465 #endif
3467 /* give back leader, use the rest */
3469 set_head(newp, newsize | PREV_INUSE);
3470 set_inuse_bit_at_offset(newp, newsize);
3471 set_head_size(p, leadsize);
3472 chunk_free(ar_ptr, p);
3473 p = newp;
3475 assert (newsize>=nb && (((unsigned long)(chunk2mem(p))) % alignment) == 0);
3478 /* Also give back spare room at the end */
3480 remainder_size = chunksize(p) - nb;
3482 if (remainder_size >= (long)MINSIZE)
3484 remainder = chunk_at_offset(p, nb);
3485 set_head(remainder, remainder_size | PREV_INUSE);
3486 set_head_size(p, nb);
3487 chunk_free(ar_ptr, remainder);
3490 check_inuse_chunk(ar_ptr, p);
3491 return p;
3498 valloc just invokes memalign with alignment argument equal
3499 to the page size of the system (or as near to this as can
3500 be figured out from all the includes/defines above.)
3503 #if __STD_C
3504 Void_t* vALLOc(size_t bytes)
3505 #else
3506 Void_t* vALLOc(bytes) size_t bytes;
3507 #endif
3509 return mEMALIGn (malloc_getpagesize, bytes);
3513 pvalloc just invokes valloc for the nearest pagesize
3514 that will accommodate request
3518 #if __STD_C
3519 Void_t* pvALLOc(size_t bytes)
3520 #else
3521 Void_t* pvALLOc(bytes) size_t bytes;
3522 #endif
3524 size_t pagesize = malloc_getpagesize;
3525 return mEMALIGn (pagesize, (bytes + pagesize - 1) & ~(pagesize - 1));
3530 calloc calls chunk_alloc, then zeroes out the allocated chunk.
3534 #if __STD_C
3535 Void_t* cALLOc(size_t n, size_t elem_size)
3536 #else
3537 Void_t* cALLOc(n, elem_size) size_t n; size_t elem_size;
3538 #endif
3540 arena *ar_ptr;
3541 mchunkptr p, oldtop;
3542 INTERNAL_SIZE_T sz, csz, oldtopsize;
3543 Void_t* mem;
3545 #if defined _LIBC || defined MALLOC_HOOKS
3546 if (__malloc_hook != NULL) {
3547 sz = n * elem_size;
3548 #if defined __GNUC__ && __GNUC__ >= 2
3549 mem = (*__malloc_hook)(sz, __builtin_return_address (0));
3550 #else
3551 mem = (*__malloc_hook)(sz, NULL);
3552 #endif
3553 if(mem == 0)
3554 return 0;
3555 #ifdef HAVE_MEMSET
3556 return memset(mem, 0, sz);
3557 #else
3558 while(sz > 0) ((char*)mem)[--sz] = 0; /* rather inefficient */
3559 return mem;
3560 #endif
3562 #endif
3564 sz = request2size(n * elem_size);
3565 arena_get(ar_ptr, sz);
3566 if(!ar_ptr)
3567 return 0;
3569 /* check if expand_top called, in which case don't need to clear */
3570 #if MORECORE_CLEARS
3571 oldtop = top(ar_ptr);
3572 oldtopsize = chunksize(top(ar_ptr));
3573 #endif
3574 p = chunk_alloc (ar_ptr, sz);
3576 /* Only clearing follows, so we can unlock early. */
3577 (void)mutex_unlock(&ar_ptr->mutex);
3579 if (p == 0) {
3580 /* Maybe the failure is due to running out of mmapped areas. */
3581 if(ar_ptr != &main_arena) {
3582 (void)mutex_lock(&main_arena.mutex);
3583 p = chunk_alloc(&main_arena, sz);
3584 (void)mutex_unlock(&main_arena.mutex);
3586 if (p == 0) return 0;
3588 mem = chunk2mem(p);
3590 /* Two optional cases in which clearing not necessary */
3592 #if HAVE_MMAP
3593 if (chunk_is_mmapped(p)) return mem;
3594 #endif
3596 csz = chunksize(p);
3598 #if MORECORE_CLEARS
3599 if (p == oldtop && csz > oldtopsize) {
3600 /* clear only the bytes from non-freshly-sbrked memory */
3601 csz = oldtopsize;
3603 #endif
3605 MALLOC_ZERO(mem, csz - SIZE_SZ);
3606 return mem;
3611 cfree just calls free. It is needed/defined on some systems
3612 that pair it with calloc, presumably for odd historical reasons.
3616 #if !defined(_LIBC)
3617 #if __STD_C
3618 void cfree(Void_t *mem)
3619 #else
3620 void cfree(mem) Void_t *mem;
3621 #endif
3623 free(mem);
3625 #endif
3631 Malloc_trim gives memory back to the system (via negative
3632 arguments to sbrk) if there is unused memory at the `high' end of
3633 the malloc pool. You can call this after freeing large blocks of
3634 memory to potentially reduce the system-level memory requirements
3635 of a program. However, it cannot guarantee to reduce memory. Under
3636 some allocation patterns, some large free blocks of memory will be
3637 locked between two used chunks, so they cannot be given back to
3638 the system.
3640 The `pad' argument to malloc_trim represents the amount of free
3641 trailing space to leave untrimmed. If this argument is zero,
3642 only the minimum amount of memory to maintain internal data
3643 structures will be left (one page or less). Non-zero arguments
3644 can be supplied to maintain enough trailing space to service
3645 future expected allocations without having to re-obtain memory
3646 from the system.
3648 Malloc_trim returns 1 if it actually released any memory, else 0.
3652 #if __STD_C
3653 int mALLOC_TRIm(size_t pad)
3654 #else
3655 int mALLOC_TRIm(pad) size_t pad;
3656 #endif
3658 int res;
3660 (void)mutex_lock(&main_arena.mutex);
3661 res = main_trim(pad);
3662 (void)mutex_unlock(&main_arena.mutex);
3663 return res;
3666 /* Trim the main arena. */
3668 static int
3669 internal_function
3670 #if __STD_C
3671 main_trim(size_t pad)
3672 #else
3673 main_trim(pad) size_t pad;
3674 #endif
3676 mchunkptr top_chunk; /* The current top chunk */
3677 long top_size; /* Amount of top-most memory */
3678 long extra; /* Amount to release */
3679 char* current_brk; /* address returned by pre-check sbrk call */
3680 char* new_brk; /* address returned by negative sbrk call */
3682 unsigned long pagesz = malloc_getpagesize;
3684 top_chunk = top(&main_arena);
3685 top_size = chunksize(top_chunk);
3686 extra = ((top_size - pad - MINSIZE + (pagesz-1)) / pagesz - 1) * pagesz;
3688 if (extra < (long)pagesz) /* Not enough memory to release */
3689 return 0;
3691 /* Test to make sure no one else called sbrk */
3692 current_brk = (char*)(MORECORE (0));
3693 if (current_brk != (char*)(top_chunk) + top_size)
3694 return 0; /* Apparently we don't own memory; must fail */
3696 new_brk = (char*)(MORECORE (-extra));
3698 #if defined _LIBC || defined MALLOC_HOOKS
3699 /* Call the `morecore' hook if necessary. */
3700 if (__after_morecore_hook)
3701 (*__after_morecore_hook) ();
3702 #endif
3704 if (new_brk == (char*)(MORECORE_FAILURE)) { /* sbrk failed? */
3705 /* Try to figure out what we have */
3706 current_brk = (char*)(MORECORE (0));
3707 top_size = current_brk - (char*)top_chunk;
3708 if (top_size >= (long)MINSIZE) /* if not, we are very very dead! */
3710 sbrked_mem = current_brk - sbrk_base;
3711 set_head(top_chunk, top_size | PREV_INUSE);
3713 check_chunk(&main_arena, top_chunk);
3714 return 0;
3716 sbrked_mem -= extra;
3718 /* Success. Adjust top accordingly. */
3719 set_head(top_chunk, (top_size - extra) | PREV_INUSE);
3720 check_chunk(&main_arena, top_chunk);
3721 return 1;
3724 #ifndef NO_THREADS
3726 static int
3727 internal_function
3728 #if __STD_C
3729 heap_trim(heap_info *heap, size_t pad)
3730 #else
3731 heap_trim(heap, pad) heap_info *heap; size_t pad;
3732 #endif
3734 unsigned long pagesz = malloc_getpagesize;
3735 arena *ar_ptr = heap->ar_ptr;
3736 mchunkptr top_chunk = top(ar_ptr), p, bck, fwd;
3737 heap_info *prev_heap;
3738 long new_size, top_size, extra;
3740 /* Can this heap go away completely ? */
3741 while(top_chunk == chunk_at_offset(heap, sizeof(*heap))) {
3742 prev_heap = heap->prev;
3743 p = chunk_at_offset(prev_heap, prev_heap->size - (MINSIZE-2*SIZE_SZ));
3744 assert(p->size == (0|PREV_INUSE)); /* must be fencepost */
3745 p = prev_chunk(p);
3746 new_size = chunksize(p) + (MINSIZE-2*SIZE_SZ);
3747 assert(new_size>0 && new_size<(long)(2*MINSIZE));
3748 if(!prev_inuse(p))
3749 new_size += p->prev_size;
3750 assert(new_size>0 && new_size<HEAP_MAX_SIZE);
3751 if(new_size + (HEAP_MAX_SIZE - prev_heap->size) < pad + MINSIZE + pagesz)
3752 break;
3753 ar_ptr->size -= heap->size;
3754 delete_heap(heap);
3755 heap = prev_heap;
3756 if(!prev_inuse(p)) { /* consolidate backward */
3757 p = prev_chunk(p);
3758 unlink(p, bck, fwd);
3760 assert(((unsigned long)((char*)p + new_size) & (pagesz-1)) == 0);
3761 assert( ((char*)p + new_size) == ((char*)heap + heap->size) );
3762 top(ar_ptr) = top_chunk = p;
3763 set_head(top_chunk, new_size | PREV_INUSE);
3764 check_chunk(ar_ptr, top_chunk);
3766 top_size = chunksize(top_chunk);
3767 extra = ((top_size - pad - MINSIZE + (pagesz-1))/pagesz - 1) * pagesz;
3768 if(extra < (long)pagesz)
3769 return 0;
3770 /* Try to shrink. */
3771 if(grow_heap(heap, -extra) != 0)
3772 return 0;
3773 ar_ptr->size -= extra;
3775 /* Success. Adjust top accordingly. */
3776 set_head(top_chunk, (top_size - extra) | PREV_INUSE);
3777 check_chunk(ar_ptr, top_chunk);
3778 return 1;
3781 #endif
3786 malloc_usable_size:
3788 This routine tells you how many bytes you can actually use in an
3789 allocated chunk, which may be more than you requested (although
3790 often not). You can use this many bytes without worrying about
3791 overwriting other allocated objects. Not a particularly great
3792 programming practice, but still sometimes useful.
3796 #if __STD_C
3797 size_t mALLOC_USABLE_SIZe(Void_t* mem)
3798 #else
3799 size_t mALLOC_USABLE_SIZe(mem) Void_t* mem;
3800 #endif
3802 mchunkptr p;
3804 if (mem == 0)
3805 return 0;
3806 else
3808 p = mem2chunk(mem);
3809 if(!chunk_is_mmapped(p))
3811 if (!inuse(p)) return 0;
3812 check_inuse_chunk(arena_for_ptr(mem), p);
3813 return chunksize(p) - SIZE_SZ;
3815 return chunksize(p) - 2*SIZE_SZ;
3822 /* Utility to update mallinfo for malloc_stats() and mallinfo() */
3824 static void
3825 #if __STD_C
3826 malloc_update_mallinfo(arena *ar_ptr, struct mallinfo *mi)
3827 #else
3828 malloc_update_mallinfo(ar_ptr, mi) arena *ar_ptr; struct mallinfo *mi;
3829 #endif
3831 int i, navail;
3832 mbinptr b;
3833 mchunkptr p;
3834 #if MALLOC_DEBUG
3835 mchunkptr q;
3836 #endif
3837 INTERNAL_SIZE_T avail;
3839 (void)mutex_lock(&ar_ptr->mutex);
3840 avail = chunksize(top(ar_ptr));
3841 navail = ((long)(avail) >= (long)MINSIZE)? 1 : 0;
3843 for (i = 1; i < NAV; ++i)
3845 b = bin_at(ar_ptr, i);
3846 for (p = last(b); p != b; p = p->bk)
3848 #if MALLOC_DEBUG
3849 check_free_chunk(ar_ptr, p);
3850 for (q = next_chunk(p);
3851 q != top(ar_ptr) && inuse(q) && (long)chunksize(q) > 0;
3852 q = next_chunk(q))
3853 check_inuse_chunk(ar_ptr, q);
3854 #endif
3855 avail += chunksize(p);
3856 navail++;
3860 mi->arena = ar_ptr->size;
3861 mi->ordblks = navail;
3862 mi->smblks = mi->usmblks = mi->fsmblks = 0; /* clear unused fields */
3863 mi->uordblks = ar_ptr->size - avail;
3864 mi->fordblks = avail;
3865 mi->hblks = n_mmaps;
3866 mi->hblkhd = mmapped_mem;
3867 mi->keepcost = chunksize(top(ar_ptr));
3869 (void)mutex_unlock(&ar_ptr->mutex);
3872 #if !defined(NO_THREADS) && MALLOC_DEBUG > 1
3874 /* Print the complete contents of a single heap to stderr. */
3876 static void
3877 #if __STD_C
3878 dump_heap(heap_info *heap)
3879 #else
3880 dump_heap(heap) heap_info *heap;
3881 #endif
3883 char *ptr;
3884 mchunkptr p;
3886 fprintf(stderr, "Heap %p, size %10lx:\n", heap, (long)heap->size);
3887 ptr = (heap->ar_ptr != (arena*)(heap+1)) ?
3888 (char*)(heap + 1) : (char*)(heap + 1) + sizeof(arena);
3889 p = (mchunkptr)(((unsigned long)ptr + MALLOC_ALIGN_MASK) &
3890 ~MALLOC_ALIGN_MASK);
3891 for(;;) {
3892 fprintf(stderr, "chunk %p size %10lx", p, (long)p->size);
3893 if(p == top(heap->ar_ptr)) {
3894 fprintf(stderr, " (top)\n");
3895 break;
3896 } else if(p->size == (0|PREV_INUSE)) {
3897 fprintf(stderr, " (fence)\n");
3898 break;
3900 fprintf(stderr, "\n");
3901 p = next_chunk(p);
3905 #endif
3911 malloc_stats:
3913 For all arenas separately and in total, prints on stderr the
3914 amount of space obtained from the system, and the current number
3915 of bytes allocated via malloc (or realloc, etc) but not yet
3916 freed. (Note that this is the number of bytes allocated, not the
3917 number requested. It will be larger than the number requested
3918 because of alignment and bookkeeping overhead.) When not compiled
3919 for multiple threads, the maximum amount of allocated memory
3920 (which may be more than current if malloc_trim and/or munmap got
3921 called) is also reported. When using mmap(), prints the maximum
3922 number of simultaneous mmap regions used, too.
3926 void mALLOC_STATs()
3928 int i;
3929 arena *ar_ptr;
3930 struct mallinfo mi;
3931 unsigned int in_use_b = mmapped_mem, system_b = in_use_b;
3932 #if THREAD_STATS
3933 long stat_lock_direct = 0, stat_lock_loop = 0, stat_lock_wait = 0;
3934 #endif
3936 for(i=0, ar_ptr = &main_arena;; i++) {
3937 malloc_update_mallinfo(ar_ptr, &mi);
3938 fprintf(stderr, "Arena %d:\n", i);
3939 fprintf(stderr, "system bytes = %10u\n", (unsigned int)mi.arena);
3940 fprintf(stderr, "in use bytes = %10u\n", (unsigned int)mi.uordblks);
3941 system_b += mi.arena;
3942 in_use_b += mi.uordblks;
3943 #if THREAD_STATS
3944 stat_lock_direct += ar_ptr->stat_lock_direct;
3945 stat_lock_loop += ar_ptr->stat_lock_loop;
3946 stat_lock_wait += ar_ptr->stat_lock_wait;
3947 #endif
3948 #if !defined(NO_THREADS) && MALLOC_DEBUG > 1
3949 if(ar_ptr != &main_arena) {
3950 heap_info *heap;
3951 (void)mutex_lock(&ar_ptr->mutex);
3952 heap = heap_for_ptr(top(ar_ptr));
3953 while(heap) { dump_heap(heap); heap = heap->prev; }
3954 (void)mutex_unlock(&ar_ptr->mutex);
3956 #endif
3957 ar_ptr = ar_ptr->next;
3958 if(ar_ptr == &main_arena) break;
3960 #if HAVE_MMAP
3961 fprintf(stderr, "Total (incl. mmap):\n");
3962 #else
3963 fprintf(stderr, "Total:\n");
3964 #endif
3965 fprintf(stderr, "system bytes = %10u\n", system_b);
3966 fprintf(stderr, "in use bytes = %10u\n", in_use_b);
3967 #ifdef NO_THREADS
3968 fprintf(stderr, "max system bytes = %10u\n", (unsigned int)max_total_mem);
3969 #endif
3970 #if HAVE_MMAP
3971 fprintf(stderr, "max mmap regions = %10u\n", (unsigned int)max_n_mmaps);
3972 fprintf(stderr, "max mmap bytes = %10lu\n", max_mmapped_mem);
3973 #endif
3974 #if THREAD_STATS
3975 fprintf(stderr, "heaps created = %10d\n", stat_n_heaps);
3976 fprintf(stderr, "locked directly = %10ld\n", stat_lock_direct);
3977 fprintf(stderr, "locked in loop = %10ld\n", stat_lock_loop);
3978 fprintf(stderr, "locked waiting = %10ld\n", stat_lock_wait);
3979 fprintf(stderr, "locked total = %10ld\n",
3980 stat_lock_direct + stat_lock_loop + stat_lock_wait);
3981 #endif
3985 mallinfo returns a copy of updated current mallinfo.
3986 The information reported is for the arena last used by the thread.
3989 struct mallinfo mALLINFo()
3991 struct mallinfo mi;
3992 Void_t *vptr = NULL;
3994 #ifndef NO_THREADS
3995 tsd_getspecific(arena_key, vptr);
3996 #endif
3997 malloc_update_mallinfo((vptr ? (arena*)vptr : &main_arena), &mi);
3998 return mi;
4005 mallopt:
4007 mallopt is the general SVID/XPG interface to tunable parameters.
4008 The format is to provide a (parameter-number, parameter-value) pair.
4009 mallopt then sets the corresponding parameter to the argument
4010 value if it can (i.e., so long as the value is meaningful),
4011 and returns 1 if successful else 0.
4013 See descriptions of tunable parameters above.
4017 #if __STD_C
4018 int mALLOPt(int param_number, int value)
4019 #else
4020 int mALLOPt(param_number, value) int param_number; int value;
4021 #endif
4023 switch(param_number)
4025 case M_TRIM_THRESHOLD:
4026 trim_threshold = value; return 1;
4027 case M_TOP_PAD:
4028 top_pad = value; return 1;
4029 case M_MMAP_THRESHOLD:
4030 #ifndef NO_THREADS
4031 /* Forbid setting the threshold too high. */
4032 if((unsigned long)value > HEAP_MAX_SIZE/2) return 0;
4033 #endif
4034 mmap_threshold = value; return 1;
4035 case M_MMAP_MAX:
4036 #if HAVE_MMAP
4037 n_mmaps_max = value; return 1;
4038 #else
4039 if (value != 0) return 0; else n_mmaps_max = value; return 1;
4040 #endif
4041 case M_CHECK_ACTION:
4042 check_action = value; return 1;
4044 default:
4045 return 0;
4051 /* Get/set state: malloc_get_state() records the current state of all
4052 malloc variables (_except_ for the actual heap contents and `hook'
4053 function pointers) in a system dependent, opaque data structure.
4054 This data structure is dynamically allocated and can be free()d
4055 after use. malloc_set_state() restores the state of all malloc
4056 variables to the previously obtained state. This is especially
4057 useful when using this malloc as part of a shared library, and when
4058 the heap contents are saved/restored via some other method. The
4059 primary example for this is GNU Emacs with its `dumping' procedure.
4060 `Hook' function pointers are never saved or restored by these
4061 functions. */
4063 #define MALLOC_STATE_MAGIC 0x444c4541l
4064 #define MALLOC_STATE_VERSION (0*0x100l + 1l) /* major*0x100 + minor */
4066 struct malloc_state {
4067 long magic;
4068 long version;
4069 mbinptr av[NAV * 2 + 2];
4070 char* sbrk_base;
4071 int sbrked_mem_bytes;
4072 unsigned long trim_threshold;
4073 unsigned long top_pad;
4074 unsigned int n_mmaps_max;
4075 unsigned long mmap_threshold;
4076 int check_action;
4077 unsigned long max_sbrked_mem;
4078 unsigned long max_total_mem;
4079 unsigned int n_mmaps;
4080 unsigned int max_n_mmaps;
4081 unsigned long mmapped_mem;
4082 unsigned long max_mmapped_mem;
4083 int using_malloc_checking;
4086 Void_t*
4087 mALLOC_GET_STATe()
4089 struct malloc_state* ms;
4090 int i;
4091 mbinptr b;
4093 ms = (struct malloc_state*)mALLOc(sizeof(*ms));
4094 if (!ms)
4095 return 0;
4096 (void)mutex_lock(&main_arena.mutex);
4097 ms->magic = MALLOC_STATE_MAGIC;
4098 ms->version = MALLOC_STATE_VERSION;
4099 ms->av[0] = main_arena.av[0];
4100 ms->av[1] = main_arena.av[1];
4101 for(i=0; i<NAV; i++) {
4102 b = bin_at(&main_arena, i);
4103 if(first(b) == b)
4104 ms->av[2*i+2] = ms->av[2*i+3] = 0; /* empty bin (or initial top) */
4105 else {
4106 ms->av[2*i+2] = first(b);
4107 ms->av[2*i+3] = last(b);
4110 ms->sbrk_base = sbrk_base;
4111 ms->sbrked_mem_bytes = sbrked_mem;
4112 ms->trim_threshold = trim_threshold;
4113 ms->top_pad = top_pad;
4114 ms->n_mmaps_max = n_mmaps_max;
4115 ms->mmap_threshold = mmap_threshold;
4116 ms->check_action = check_action;
4117 ms->max_sbrked_mem = max_sbrked_mem;
4118 #ifdef NO_THREADS
4119 ms->max_total_mem = max_total_mem;
4120 #else
4121 ms->max_total_mem = 0;
4122 #endif
4123 ms->n_mmaps = n_mmaps;
4124 ms->max_n_mmaps = max_n_mmaps;
4125 ms->mmapped_mem = mmapped_mem;
4126 ms->max_mmapped_mem = max_mmapped_mem;
4127 #if defined _LIBC || defined MALLOC_HOOKS
4128 ms->using_malloc_checking = using_malloc_checking;
4129 #else
4130 ms->using_malloc_checking = 0;
4131 #endif
4132 (void)mutex_unlock(&main_arena.mutex);
4133 return (Void_t*)ms;
4137 #if __STD_C
4138 mALLOC_SET_STATe(Void_t* msptr)
4139 #else
4140 mALLOC_SET_STATe(msptr) Void_t* msptr;
4141 #endif
4143 struct malloc_state* ms = (struct malloc_state*)msptr;
4144 int i;
4145 mbinptr b;
4147 #if defined _LIBC || defined MALLOC_HOOKS
4148 disallow_malloc_check = 1;
4149 #endif
4150 ptmalloc_init();
4151 if(ms->magic != MALLOC_STATE_MAGIC) return -1;
4152 /* Must fail if the major version is too high. */
4153 if((ms->version & ~0xffl) > (MALLOC_STATE_VERSION & ~0xffl)) return -2;
4154 (void)mutex_lock(&main_arena.mutex);
4155 main_arena.av[0] = ms->av[0];
4156 main_arena.av[1] = ms->av[1];
4157 for(i=0; i<NAV; i++) {
4158 b = bin_at(&main_arena, i);
4159 if(ms->av[2*i+2] == 0)
4160 first(b) = last(b) = b;
4161 else {
4162 first(b) = ms->av[2*i+2];
4163 last(b) = ms->av[2*i+3];
4164 if(i > 0) {
4165 /* Make sure the links to the `av'-bins in the heap are correct. */
4166 first(b)->bk = b;
4167 last(b)->fd = b;
4171 sbrk_base = ms->sbrk_base;
4172 sbrked_mem = ms->sbrked_mem_bytes;
4173 trim_threshold = ms->trim_threshold;
4174 top_pad = ms->top_pad;
4175 n_mmaps_max = ms->n_mmaps_max;
4176 mmap_threshold = ms->mmap_threshold;
4177 check_action = ms->check_action;
4178 max_sbrked_mem = ms->max_sbrked_mem;
4179 #ifdef NO_THREADS
4180 max_total_mem = ms->max_total_mem;
4181 #endif
4182 n_mmaps = ms->n_mmaps;
4183 max_n_mmaps = ms->max_n_mmaps;
4184 mmapped_mem = ms->mmapped_mem;
4185 max_mmapped_mem = ms->max_mmapped_mem;
4186 /* add version-dependent code here */
4187 if (ms->version >= 1) {
4188 #if defined _LIBC || defined MALLOC_HOOKS
4189 /* Check whether it is safe to enable malloc checking. */
4190 if (ms->using_malloc_checking && !using_malloc_checking &&
4191 !disallow_malloc_check)
4192 __malloc_check_init ();
4193 #endif
4196 (void)mutex_unlock(&main_arena.mutex);
4197 return 0;
4202 #if defined _LIBC || defined MALLOC_HOOKS
4204 /* A simple, standard set of debugging hooks. Overhead is `only' one
4205 byte per chunk; still this will catch most cases of double frees or
4206 overruns. The goal here is to avoid obscure crashes due to invalid
4207 usage, unlike in the MALLOC_DEBUG code. */
4209 #define MAGICBYTE(p) ( ( ((size_t)p >> 3) ^ ((size_t)p >> 11)) & 0xFF )
4211 /* Instrument a chunk with overrun detector byte(s) and convert it
4212 into a user pointer with requested size sz. */
4214 static Void_t*
4215 #if __STD_C
4216 chunk2mem_check(mchunkptr p, size_t sz)
4217 #else
4218 chunk2mem_check(p, sz) mchunkptr p; size_t sz;
4219 #endif
4221 unsigned char* m_ptr = (unsigned char*)chunk2mem(p);
4222 size_t i;
4224 for(i = chunksize(p) - (chunk_is_mmapped(p) ? 2*SIZE_SZ+1 : SIZE_SZ+1);
4225 i > sz;
4226 i -= 0xFF) {
4227 if(i-sz < 0x100) {
4228 m_ptr[i] = (unsigned char)(i-sz);
4229 break;
4231 m_ptr[i] = 0xFF;
4233 m_ptr[sz] = MAGICBYTE(p);
4234 return (Void_t*)m_ptr;
4237 /* Convert a pointer to be free()d or realloc()ed to a valid chunk
4238 pointer. If the provided pointer is not valid, return NULL. */
4240 static mchunkptr
4241 internal_function
4242 #if __STD_C
4243 mem2chunk_check(Void_t* mem)
4244 #else
4245 mem2chunk_check(mem) Void_t* mem;
4246 #endif
4248 mchunkptr p;
4249 INTERNAL_SIZE_T sz, c;
4250 unsigned char magic;
4252 p = mem2chunk(mem);
4253 if(!aligned_OK(p)) return NULL;
4254 if( (char*)p>=sbrk_base && (char*)p<(sbrk_base+sbrked_mem) ) {
4255 /* Must be a chunk in conventional heap memory. */
4256 if(chunk_is_mmapped(p) ||
4257 ( (sz = chunksize(p)), ((char*)p + sz)>=(sbrk_base+sbrked_mem) ) ||
4258 sz<MINSIZE || sz&MALLOC_ALIGN_MASK || !inuse(p) ||
4259 ( !prev_inuse(p) && (p->prev_size&MALLOC_ALIGN_MASK ||
4260 (long)prev_chunk(p)<(long)sbrk_base ||
4261 next_chunk(prev_chunk(p))!=p) ))
4262 return NULL;
4263 magic = MAGICBYTE(p);
4264 for(sz += SIZE_SZ-1; (c = ((unsigned char*)p)[sz]) != magic; sz -= c) {
4265 if(c<=0 || sz<(c+2*SIZE_SZ)) return NULL;
4267 ((unsigned char*)p)[sz] ^= 0xFF;
4268 } else {
4269 unsigned long offset, page_mask = malloc_getpagesize-1;
4271 /* mmap()ed chunks have MALLOC_ALIGNMENT or higher power-of-two
4272 alignment relative to the beginning of a page. Check this
4273 first. */
4274 offset = (unsigned long)mem & page_mask;
4275 if((offset!=MALLOC_ALIGNMENT && offset!=0 && offset!=0x10 &&
4276 offset!=0x20 && offset!=0x40 && offset!=0x80 && offset!=0x100 &&
4277 offset!=0x200 && offset!=0x400 && offset!=0x800 && offset!=0x1000 &&
4278 offset<0x2000) ||
4279 !chunk_is_mmapped(p) || (p->size & PREV_INUSE) ||
4280 ( (((unsigned long)p - p->prev_size) & page_mask) != 0 ) ||
4281 ( (sz = chunksize(p)), ((p->prev_size + sz) & page_mask) != 0 ) )
4282 return NULL;
4283 magic = MAGICBYTE(p);
4284 for(sz -= 1; (c = ((unsigned char*)p)[sz]) != magic; sz -= c) {
4285 if(c<=0 || sz<(c+2*SIZE_SZ)) return NULL;
4287 ((unsigned char*)p)[sz] ^= 0xFF;
4289 return p;
4292 /* Check for corruption of the top chunk, and try to recover if
4293 necessary. */
4295 static int
4296 #if __STD_C
4297 top_check(void)
4298 #else
4299 top_check()
4300 #endif
4302 mchunkptr t = top(&main_arena);
4303 char* brk, * new_brk;
4304 INTERNAL_SIZE_T front_misalign, sbrk_size;
4305 unsigned long pagesz = malloc_getpagesize;
4307 if((char*)t + chunksize(t) == sbrk_base + sbrked_mem ||
4308 t == initial_top(&main_arena)) return 0;
4310 switch(check_action) {
4311 case 1:
4312 fprintf(stderr, "malloc: top chunk is corrupt\n");
4313 break;
4314 case 2:
4315 abort();
4317 /* Try to set up a new top chunk. */
4318 brk = MORECORE(0);
4319 front_misalign = (unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK;
4320 if (front_misalign > 0)
4321 front_misalign = MALLOC_ALIGNMENT - front_misalign;
4322 sbrk_size = front_misalign + top_pad + MINSIZE;
4323 sbrk_size += pagesz - ((unsigned long)(brk + sbrk_size) & (pagesz - 1));
4324 new_brk = (char*)(MORECORE (sbrk_size));
4325 if (new_brk == (char*)(MORECORE_FAILURE)) return -1;
4326 sbrked_mem = (new_brk - sbrk_base) + sbrk_size;
4328 top(&main_arena) = (mchunkptr)(brk + front_misalign);
4329 set_head(top(&main_arena), (sbrk_size - front_misalign) | PREV_INUSE);
4331 return 0;
4334 static Void_t*
4335 #if __STD_C
4336 malloc_check(size_t sz, const Void_t *caller)
4337 #else
4338 malloc_check(sz, caller) size_t sz; const Void_t *caller;
4339 #endif
4341 mchunkptr victim;
4342 INTERNAL_SIZE_T nb = request2size(sz + 1);
4344 (void)mutex_lock(&main_arena.mutex);
4345 victim = (top_check() >= 0) ? chunk_alloc(&main_arena, nb) : NULL;
4346 (void)mutex_unlock(&main_arena.mutex);
4347 if(!victim) return NULL;
4348 return chunk2mem_check(victim, sz);
4351 static void
4352 #if __STD_C
4353 free_check(Void_t* mem, const Void_t *caller)
4354 #else
4355 free_check(mem, caller) Void_t* mem; const Void_t *caller;
4356 #endif
4358 mchunkptr p;
4360 if(!mem) return;
4361 (void)mutex_lock(&main_arena.mutex);
4362 p = mem2chunk_check(mem);
4363 if(!p) {
4364 (void)mutex_unlock(&main_arena.mutex);
4365 switch(check_action) {
4366 case 1:
4367 fprintf(stderr, "free(): invalid pointer %p!\n", mem);
4368 break;
4369 case 2:
4370 abort();
4372 return;
4374 #if HAVE_MMAP
4375 if (chunk_is_mmapped(p)) {
4376 (void)mutex_unlock(&main_arena.mutex);
4377 munmap_chunk(p);
4378 return;
4380 #endif
4381 #if 0 /* Erase freed memory. */
4382 memset(mem, 0, chunksize(p) - (SIZE_SZ+1));
4383 #endif
4384 chunk_free(&main_arena, p);
4385 (void)mutex_unlock(&main_arena.mutex);
4388 static Void_t*
4389 #if __STD_C
4390 realloc_check(Void_t* oldmem, size_t bytes, const Void_t *caller)
4391 #else
4392 realloc_check(oldmem, bytes, caller)
4393 Void_t* oldmem; size_t bytes; const Void_t *caller;
4394 #endif
4396 mchunkptr oldp, newp;
4397 INTERNAL_SIZE_T nb, oldsize;
4399 if (oldmem == 0) return malloc_check(bytes, NULL);
4400 (void)mutex_lock(&main_arena.mutex);
4401 oldp = mem2chunk_check(oldmem);
4402 if(!oldp) {
4403 (void)mutex_unlock(&main_arena.mutex);
4404 switch(check_action) {
4405 case 1:
4406 fprintf(stderr, "realloc(): invalid pointer %p!\n", oldmem);
4407 break;
4408 case 2:
4409 abort();
4411 return malloc_check(bytes, NULL);
4413 oldsize = chunksize(oldp);
4415 nb = request2size(bytes+1);
4417 #if HAVE_MMAP
4418 if (chunk_is_mmapped(oldp)) {
4419 #if HAVE_MREMAP
4420 newp = mremap_chunk(oldp, nb);
4421 if(!newp) {
4422 #endif
4423 /* Note the extra SIZE_SZ overhead. */
4424 if(oldsize - SIZE_SZ >= nb) newp = oldp; /* do nothing */
4425 else {
4426 /* Must alloc, copy, free. */
4427 newp = (top_check() >= 0) ? chunk_alloc(&main_arena, nb) : NULL;
4428 if (newp) {
4429 MALLOC_COPY(chunk2mem(newp), oldmem, oldsize - 2*SIZE_SZ);
4430 munmap_chunk(oldp);
4433 #if HAVE_MREMAP
4435 #endif
4436 } else {
4437 #endif /* HAVE_MMAP */
4438 newp = (top_check() >= 0) ?
4439 chunk_realloc(&main_arena, oldp, oldsize, nb) : NULL;
4440 #if 0 /* Erase freed memory. */
4441 nb = chunksize(newp);
4442 if(oldp<newp || oldp>=chunk_at_offset(newp, nb)) {
4443 memset((char*)oldmem + 2*sizeof(mbinptr), 0,
4444 oldsize - (2*sizeof(mbinptr)+2*SIZE_SZ+1));
4445 } else if(nb > oldsize+SIZE_SZ) {
4446 memset((char*)chunk2mem(newp) + oldsize, 0, nb - (oldsize+SIZE_SZ));
4448 #endif
4449 #if HAVE_MMAP
4451 #endif
4452 (void)mutex_unlock(&main_arena.mutex);
4454 if(!newp) return NULL;
4455 return chunk2mem_check(newp, bytes);
4458 static Void_t*
4459 #if __STD_C
4460 memalign_check(size_t alignment, size_t bytes, const Void_t *caller)
4461 #else
4462 memalign_check(alignment, bytes, caller)
4463 size_t alignment; size_t bytes; const Void_t *caller;
4464 #endif
4466 INTERNAL_SIZE_T nb;
4467 mchunkptr p;
4469 if (alignment <= MALLOC_ALIGNMENT) return malloc_check(bytes, NULL);
4470 if (alignment < MINSIZE) alignment = MINSIZE;
4472 nb = request2size(bytes+1);
4473 (void)mutex_lock(&main_arena.mutex);
4474 p = (top_check() >= 0) ? chunk_align(&main_arena, nb, alignment) : NULL;
4475 (void)mutex_unlock(&main_arena.mutex);
4476 if(!p) return NULL;
4477 return chunk2mem_check(p, bytes);
4480 #ifndef NO_THREADS
4482 /* The following hooks are used when the global initialization in
4483 ptmalloc_init() hasn't completed yet. */
4485 static Void_t*
4486 #if __STD_C
4487 malloc_starter(size_t sz, const Void_t *caller)
4488 #else
4489 malloc_starter(sz, caller) size_t sz; const Void_t *caller;
4490 #endif
4492 mchunkptr victim = chunk_alloc(&main_arena, request2size(sz));
4494 return victim ? chunk2mem(victim) : 0;
4497 static void
4498 #if __STD_C
4499 free_starter(Void_t* mem, const Void_t *caller)
4500 #else
4501 free_starter(mem, caller) Void_t* mem; const Void_t *caller;
4502 #endif
4504 mchunkptr p;
4506 if(!mem) return;
4507 p = mem2chunk(mem);
4508 #if HAVE_MMAP
4509 if (chunk_is_mmapped(p)) {
4510 munmap_chunk(p);
4511 return;
4513 #endif
4514 chunk_free(&main_arena, p);
4517 /* The following hooks are used while the `atfork' handling mechanism
4518 is active. */
4520 static Void_t*
4521 #if __STD_C
4522 malloc_atfork (size_t sz, const Void_t *caller)
4523 #else
4524 malloc_atfork(sz, caller) size_t sz; const Void_t *caller;
4525 #endif
4527 Void_t *vptr = NULL;
4529 tsd_getspecific(arena_key, vptr);
4530 if(!vptr) {
4531 mchunkptr victim = chunk_alloc(&main_arena, request2size(sz));
4532 return victim ? chunk2mem(victim) : 0;
4533 } else {
4534 /* Suspend the thread until the `atfork' handlers have completed.
4535 By that time, the hooks will have been reset as well, so that
4536 mALLOc() can be used again. */
4537 (void)mutex_lock(&list_lock);
4538 (void)mutex_unlock(&list_lock);
4539 return mALLOc(sz);
4543 static void
4544 #if __STD_C
4545 free_atfork(Void_t* mem, const Void_t *caller)
4546 #else
4547 free_atfork(mem, caller) Void_t* mem; const Void_t *caller;
4548 #endif
4550 Void_t *vptr = NULL;
4551 arena *ar_ptr;
4552 mchunkptr p; /* chunk corresponding to mem */
4554 if (mem == 0) /* free(0) has no effect */
4555 return;
4557 p = mem2chunk(mem);
4559 #if HAVE_MMAP
4560 if (chunk_is_mmapped(p)) /* release mmapped memory. */
4562 munmap_chunk(p);
4563 return;
4565 #endif
4567 ar_ptr = arena_for_ptr(p);
4568 tsd_getspecific(arena_key, vptr);
4569 if(vptr)
4570 (void)mutex_lock(&ar_ptr->mutex);
4571 chunk_free(ar_ptr, p);
4572 if(vptr)
4573 (void)mutex_unlock(&ar_ptr->mutex);
4576 #endif
4578 #endif /* defined _LIBC || defined MALLOC_HOOKS */
4582 #ifdef _LIBC
4583 weak_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)
4584 weak_alias (__libc_free, __cfree) weak_alias (__libc_free, cfree)
4585 weak_alias (__libc_free, __free) weak_alias (__libc_free, free)
4586 weak_alias (__libc_malloc, __malloc) weak_alias (__libc_malloc, malloc)
4587 weak_alias (__libc_memalign, __memalign) weak_alias (__libc_memalign, memalign)
4588 weak_alias (__libc_realloc, __realloc) weak_alias (__libc_realloc, realloc)
4589 weak_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)
4590 weak_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)
4591 weak_alias (__libc_mallinfo, __mallinfo) weak_alias (__libc_mallinfo, mallinfo)
4592 weak_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)
4594 weak_alias (__malloc_stats, malloc_stats)
4595 weak_alias (__malloc_usable_size, malloc_usable_size)
4596 weak_alias (__malloc_trim, malloc_trim)
4597 weak_alias (__malloc_get_state, malloc_get_state)
4598 weak_alias (__malloc_set_state, malloc_set_state)
4599 #endif
4603 History:
4605 V2.6.4-pt3 Thu Feb 20 1997 Wolfram Gloger (wmglo@dent.med.uni-muenchen.de)
4606 * Added malloc_get/set_state() (mainly for use in GNU emacs),
4607 using interface from Marcus Daniels
4608 * All parameters are now adjustable via environment variables
4610 V2.6.4-pt2 Sat Dec 14 1996 Wolfram Gloger (wmglo@dent.med.uni-muenchen.de)
4611 * Added debugging hooks
4612 * Fixed possible deadlock in realloc() when out of memory
4613 * Don't pollute namespace in glibc: use __getpagesize, __mmap, etc.
4615 V2.6.4-pt Wed Dec 4 1996 Wolfram Gloger (wmglo@dent.med.uni-muenchen.de)
4616 * Very minor updates from the released 2.6.4 version.
4617 * Trimmed include file down to exported data structures.
4618 * Changes from H.J. Lu for glibc-2.0.
4620 V2.6.3i-pt Sep 16 1996 Wolfram Gloger (wmglo@dent.med.uni-muenchen.de)
4621 * Many changes for multiple threads
4622 * Introduced arenas and heaps
4624 V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee)
4625 * Added pvalloc, as recommended by H.J. Liu
4626 * Added 64bit pointer support mainly from Wolfram Gloger
4627 * Added anonymously donated WIN32 sbrk emulation
4628 * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
4629 * malloc_extend_top: fix mask error that caused wastage after
4630 foreign sbrks
4631 * Add linux mremap support code from HJ Liu
4633 V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee)
4634 * Integrated most documentation with the code.
4635 * Add support for mmap, with help from
4636 Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
4637 * Use last_remainder in more cases.
4638 * Pack bins using idea from colin@nyx10.cs.du.edu
4639 * Use ordered bins instead of best-fit threshold
4640 * Eliminate block-local decls to simplify tracing and debugging.
4641 * Support another case of realloc via move into top
4642 * Fix error occurring when initial sbrk_base not word-aligned.
4643 * Rely on page size for units instead of SBRK_UNIT to
4644 avoid surprises about sbrk alignment conventions.
4645 * Add mallinfo, mallopt. Thanks to Raymond Nijssen
4646 (raymond@es.ele.tue.nl) for the suggestion.
4647 * Add `pad' argument to malloc_trim and top_pad mallopt parameter.
4648 * More precautions for cases where other routines call sbrk,
4649 courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
4650 * Added macros etc., allowing use in linux libc from
4651 H.J. Lu (hjl@gnu.ai.mit.edu)
4652 * Inverted this history list
4654 V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee)
4655 * Re-tuned and fixed to behave more nicely with V2.6.0 changes.
4656 * Removed all preallocation code since under current scheme
4657 the work required to undo bad preallocations exceeds
4658 the work saved in good cases for most test programs.
4659 * No longer use return list or unconsolidated bins since
4660 no scheme using them consistently outperforms those that don't
4661 given above changes.
4662 * Use best fit for very large chunks to prevent some worst-cases.
4663 * Added some support for debugging
4665 V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee)
4666 * Removed footers when chunks are in use. Thanks to
4667 Paul Wilson (wilson@cs.texas.edu) for the suggestion.
4669 V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee)
4670 * Added malloc_trim, with help from Wolfram Gloger
4671 (wmglo@Dent.MED.Uni-Muenchen.DE).
4673 V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g)
4675 V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g)
4676 * realloc: try to expand in both directions
4677 * malloc: swap order of clean-bin strategy;
4678 * realloc: only conditionally expand backwards
4679 * Try not to scavenge used bins
4680 * Use bin counts as a guide to preallocation
4681 * Occasionally bin return list chunks in first scan
4682 * Add a few optimizations from colin@nyx10.cs.du.edu
4684 V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g)
4685 * faster bin computation & slightly different binning
4686 * merged all consolidations to one part of malloc proper
4687 (eliminating old malloc_find_space & malloc_clean_bin)
4688 * Scan 2 returns chunks (not just 1)
4689 * Propagate failure in realloc if malloc returns 0
4690 * Add stuff to allow compilation on non-ANSI compilers
4691 from kpv@research.att.com
4693 V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu)
4694 * removed potential for odd address access in prev_chunk
4695 * removed dependency on getpagesize.h
4696 * misc cosmetics and a bit more internal documentation
4697 * anticosmetics: mangled names in macros to evade debugger strangeness
4698 * tested on sparc, hp-700, dec-mips, rs6000
4699 with gcc & native cc (hp, dec only) allowing
4700 Detlefs & Zorn comparison study (in SIGPLAN Notices.)
4702 Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu)
4703 * Based loosely on libg++-1.2X malloc. (It retains some of the overall
4704 structure of old version, but most details differ.)