Update.
[glibc.git] / malloc / malloc.c
blob43d89d43da49093c8ef206564793f389b3c82b2a
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: defined)
186 Define this if you think that realloc(p, 0) should be equivalent
187 to free(p). (The C standard requires this behaviour, therefore
188 it is the default.) Otherwise, since malloc returns a unique
189 pointer for malloc(0), so does realloc(p, 0).
190 HAVE_MEMCPY (default: defined)
191 Define if you are not otherwise using ANSI STD C, but still
192 have memcpy and memset in your C library and want to use them.
193 Otherwise, simple internal versions are supplied.
194 USE_MEMCPY (default: 1 if HAVE_MEMCPY is defined, 0 otherwise)
195 Define as 1 if you want the C library versions of memset and
196 memcpy called in realloc and calloc (otherwise macro versions are used).
197 At least on some platforms, the simple macro versions usually
198 outperform libc versions.
199 HAVE_MMAP (default: defined as 1)
200 Define to non-zero to optionally make malloc() use mmap() to
201 allocate very large blocks.
202 HAVE_MREMAP (default: defined as 0 unless Linux libc set)
203 Define to non-zero to optionally make realloc() use mremap() to
204 reallocate very large blocks.
205 malloc_getpagesize (default: derived from system #includes)
206 Either a constant or routine call returning the system page size.
207 HAVE_USR_INCLUDE_MALLOC_H (default: NOT defined)
208 Optionally define if you are on a system with a /usr/include/malloc.h
209 that declares struct mallinfo. It is not at all necessary to
210 define this even if you do, but will ensure consistency.
211 INTERNAL_SIZE_T (default: size_t)
212 Define to a 32-bit type (probably `unsigned int') if you are on a
213 64-bit machine, yet do not want or need to allow malloc requests of
214 greater than 2^31 to be handled. This saves space, especially for
215 very small chunks.
216 _LIBC (default: NOT defined)
217 Defined only when compiled as part of the Linux libc/glibc.
218 Also note that there is some odd internal name-mangling via defines
219 (for example, internally, `malloc' is named `mALLOc') needed
220 when compiling in this case. These look funny but don't otherwise
221 affect anything.
222 LACKS_UNISTD_H (default: undefined)
223 Define this if your system does not have a <unistd.h>.
224 MORECORE (default: sbrk)
225 The name of the routine to call to obtain more memory from the system.
226 MORECORE_FAILURE (default: -1)
227 The value returned upon failure of MORECORE.
228 MORECORE_CLEARS (default 1)
229 True (1) if the routine mapped to MORECORE zeroes out memory (which
230 holds for sbrk).
231 DEFAULT_TRIM_THRESHOLD
232 DEFAULT_TOP_PAD
233 DEFAULT_MMAP_THRESHOLD
234 DEFAULT_MMAP_MAX
235 Default values of tunable parameters (described in detail below)
236 controlling interaction with host system routines (sbrk, mmap, etc).
237 These values may also be changed dynamically via mallopt(). The
238 preset defaults are those that give best performance for typical
239 programs/systems.
240 DEFAULT_CHECK_ACTION
241 When the standard debugging hooks are in place, and a pointer is
242 detected as corrupt, do nothing (0), print an error message (1),
243 or call abort() (2).
250 * Compile-time options for multiple threads:
252 USE_PTHREADS, USE_THR, USE_SPROC
253 Define one of these as 1 to select the thread interface:
254 POSIX threads, Solaris threads or SGI sproc's, respectively.
255 If none of these is defined as non-zero, you get a `normal'
256 malloc implementation which is not thread-safe. Support for
257 multiple threads requires HAVE_MMAP=1. As an exception, when
258 compiling for GNU libc, i.e. when _LIBC is defined, then none of
259 the USE_... symbols have to be defined.
261 HEAP_MIN_SIZE
262 HEAP_MAX_SIZE
263 When thread support is enabled, additional `heap's are created
264 with mmap calls. These are limited in size; HEAP_MIN_SIZE should
265 be a multiple of the page size, while HEAP_MAX_SIZE must be a power
266 of two for alignment reasons. HEAP_MAX_SIZE should be at least
267 twice as large as the mmap threshold.
268 THREAD_STATS
269 When this is defined as non-zero, some statistics on mutex locking
270 are computed.
277 /* Preliminaries */
279 #ifndef __STD_C
280 #if defined (__STDC__)
281 #define __STD_C 1
282 #else
283 #if __cplusplus
284 #define __STD_C 1
285 #else
286 #define __STD_C 0
287 #endif /*__cplusplus*/
288 #endif /*__STDC__*/
289 #endif /*__STD_C*/
291 #ifndef Void_t
292 #if __STD_C
293 #define Void_t void
294 #else
295 #define Void_t char
296 #endif
297 #endif /*Void_t*/
299 #if __STD_C
300 # include <stddef.h> /* for size_t */
301 # if defined _LIBC || defined MALLOC_HOOKS
302 # include <stdlib.h> /* for getenv(), abort() */
303 # endif
304 #else
305 # include <sys/types.h>
306 #endif
308 /* Macros for handling mutexes and thread-specific data. This is
309 included early, because some thread-related header files (such as
310 pthread.h) should be included before any others. */
311 #include "thread-m.h"
313 #ifdef __cplusplus
314 extern "C" {
315 #endif
317 #include <stdio.h> /* needed for malloc_stats */
321 Compile-time options
326 Debugging:
328 Because freed chunks may be overwritten with link fields, this
329 malloc will often die when freed memory is overwritten by user
330 programs. This can be very effective (albeit in an annoying way)
331 in helping track down dangling pointers.
333 If you compile with -DMALLOC_DEBUG, a number of assertion checks are
334 enabled that will catch more memory errors. You probably won't be
335 able to make much sense of the actual assertion errors, but they
336 should help you locate incorrectly overwritten memory. The
337 checking is fairly extensive, and will slow down execution
338 noticeably. Calling malloc_stats or mallinfo with MALLOC_DEBUG set will
339 attempt to check every non-mmapped allocated and free chunk in the
340 course of computing the summaries. (By nature, mmapped regions
341 cannot be checked very much automatically.)
343 Setting MALLOC_DEBUG may also be helpful if you are trying to modify
344 this code. The assertions in the check routines spell out in more
345 detail the assumptions and invariants underlying the algorithms.
349 #if MALLOC_DEBUG
350 #include <assert.h>
351 #else
352 #define assert(x) ((void)0)
353 #endif
357 INTERNAL_SIZE_T is the word-size used for internal bookkeeping
358 of chunk sizes. On a 64-bit machine, you can reduce malloc
359 overhead by defining INTERNAL_SIZE_T to be a 32 bit `unsigned int'
360 at the expense of not being able to handle requests greater than
361 2^31. This limitation is hardly ever a concern; you are encouraged
362 to set this. However, the default version is the same as size_t.
365 #ifndef INTERNAL_SIZE_T
366 #define INTERNAL_SIZE_T size_t
367 #endif
370 REALLOC_ZERO_BYTES_FREES should be set if a call to realloc with
371 zero bytes should be the same as a call to free. The C standard
372 requires this. Otherwise, since this malloc returns a unique pointer
373 for malloc(0), so does realloc(p, 0).
377 #define REALLOC_ZERO_BYTES_FREES
381 HAVE_MEMCPY should be defined if you are not otherwise using
382 ANSI STD C, but still have memcpy and memset in your C library
383 and want to use them in calloc and realloc. Otherwise simple
384 macro versions are defined here.
386 USE_MEMCPY should be defined as 1 if you actually want to
387 have memset and memcpy called. People report that the macro
388 versions are often enough faster than libc versions on many
389 systems that it is better to use them.
393 #define HAVE_MEMCPY 1
395 #ifndef USE_MEMCPY
396 #ifdef HAVE_MEMCPY
397 #define USE_MEMCPY 1
398 #else
399 #define USE_MEMCPY 0
400 #endif
401 #endif
403 #if (__STD_C || defined(HAVE_MEMCPY))
405 #if __STD_C
406 void* memset(void*, int, size_t);
407 void* memcpy(void*, const void*, size_t);
408 #else
409 Void_t* memset();
410 Void_t* memcpy();
411 #endif
412 #endif
414 #if USE_MEMCPY
416 /* The following macros are only invoked with (2n+1)-multiples of
417 INTERNAL_SIZE_T units, with a positive integer n. This is exploited
418 for fast inline execution when n is small. */
420 #define MALLOC_ZERO(charp, nbytes) \
421 do { \
422 INTERNAL_SIZE_T mzsz = (nbytes); \
423 if(mzsz <= 9*sizeof(mzsz)) { \
424 INTERNAL_SIZE_T* mz = (INTERNAL_SIZE_T*) (charp); \
425 if(mzsz >= 5*sizeof(mzsz)) { *mz++ = 0; \
426 *mz++ = 0; \
427 if(mzsz >= 7*sizeof(mzsz)) { *mz++ = 0; \
428 *mz++ = 0; \
429 if(mzsz >= 9*sizeof(mzsz)) { *mz++ = 0; \
430 *mz++ = 0; }}} \
431 *mz++ = 0; \
432 *mz++ = 0; \
433 *mz = 0; \
434 } else memset((charp), 0, mzsz); \
435 } while(0)
437 #define MALLOC_COPY(dest,src,nbytes) \
438 do { \
439 INTERNAL_SIZE_T mcsz = (nbytes); \
440 if(mcsz <= 9*sizeof(mcsz)) { \
441 INTERNAL_SIZE_T* mcsrc = (INTERNAL_SIZE_T*) (src); \
442 INTERNAL_SIZE_T* mcdst = (INTERNAL_SIZE_T*) (dest); \
443 if(mcsz >= 5*sizeof(mcsz)) { *mcdst++ = *mcsrc++; \
444 *mcdst++ = *mcsrc++; \
445 if(mcsz >= 7*sizeof(mcsz)) { *mcdst++ = *mcsrc++; \
446 *mcdst++ = *mcsrc++; \
447 if(mcsz >= 9*sizeof(mcsz)) { *mcdst++ = *mcsrc++; \
448 *mcdst++ = *mcsrc++; }}} \
449 *mcdst++ = *mcsrc++; \
450 *mcdst++ = *mcsrc++; \
451 *mcdst = *mcsrc ; \
452 } else memcpy(dest, src, mcsz); \
453 } while(0)
455 #else /* !USE_MEMCPY */
457 /* Use Duff's device for good zeroing/copying performance. */
459 #define MALLOC_ZERO(charp, nbytes) \
460 do { \
461 INTERNAL_SIZE_T* mzp = (INTERNAL_SIZE_T*)(charp); \
462 long mctmp = (nbytes)/sizeof(INTERNAL_SIZE_T), mcn; \
463 if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp %= 8; } \
464 switch (mctmp) { \
465 case 0: for(;;) { *mzp++ = 0; \
466 case 7: *mzp++ = 0; \
467 case 6: *mzp++ = 0; \
468 case 5: *mzp++ = 0; \
469 case 4: *mzp++ = 0; \
470 case 3: *mzp++ = 0; \
471 case 2: *mzp++ = 0; \
472 case 1: *mzp++ = 0; if(mcn <= 0) break; mcn--; } \
474 } while(0)
476 #define MALLOC_COPY(dest,src,nbytes) \
477 do { \
478 INTERNAL_SIZE_T* mcsrc = (INTERNAL_SIZE_T*) src; \
479 INTERNAL_SIZE_T* mcdst = (INTERNAL_SIZE_T*) dest; \
480 long mctmp = (nbytes)/sizeof(INTERNAL_SIZE_T), mcn; \
481 if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp %= 8; } \
482 switch (mctmp) { \
483 case 0: for(;;) { *mcdst++ = *mcsrc++; \
484 case 7: *mcdst++ = *mcsrc++; \
485 case 6: *mcdst++ = *mcsrc++; \
486 case 5: *mcdst++ = *mcsrc++; \
487 case 4: *mcdst++ = *mcsrc++; \
488 case 3: *mcdst++ = *mcsrc++; \
489 case 2: *mcdst++ = *mcsrc++; \
490 case 1: *mcdst++ = *mcsrc++; if(mcn <= 0) break; mcn--; } \
492 } while(0)
494 #endif
497 #ifndef LACKS_UNISTD_H
498 # include <unistd.h>
499 #endif
502 Define HAVE_MMAP to optionally make malloc() use mmap() to
503 allocate very large blocks. These will be returned to the
504 operating system immediately after a free().
507 #ifndef HAVE_MMAP
508 # ifdef _POSIX_MAPPED_FILES
509 # define HAVE_MMAP 1
510 # endif
511 #endif
514 Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
515 large blocks. This is currently only possible on Linux with
516 kernel versions newer than 1.3.77.
519 #ifndef HAVE_MREMAP
520 #define HAVE_MREMAP defined(__linux__) && !defined(__arm__)
521 #endif
523 #if HAVE_MMAP
525 #include <unistd.h>
526 #include <fcntl.h>
527 #include <sys/mman.h>
529 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
530 #define MAP_ANONYMOUS MAP_ANON
531 #endif
532 #if !defined(MAP_FAILED)
533 #define MAP_FAILED ((char*)-1)
534 #endif
536 #ifndef MAP_NORESERVE
537 # ifdef MAP_AUTORESRV
538 # define MAP_NORESERVE MAP_AUTORESRV
539 # else
540 # define MAP_NORESERVE 0
541 # endif
542 #endif
544 #endif /* HAVE_MMAP */
547 Access to system page size. To the extent possible, this malloc
548 manages memory from the system in page-size units.
550 The following mechanics for getpagesize were adapted from
551 bsd/gnu getpagesize.h
554 #ifndef malloc_getpagesize
555 # ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */
556 # ifndef _SC_PAGE_SIZE
557 # define _SC_PAGE_SIZE _SC_PAGESIZE
558 # endif
559 # endif
560 # ifdef _SC_PAGE_SIZE
561 # define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
562 # else
563 # if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
564 extern size_t getpagesize();
565 # define malloc_getpagesize getpagesize()
566 # else
567 # include <sys/param.h>
568 # ifdef EXEC_PAGESIZE
569 # define malloc_getpagesize EXEC_PAGESIZE
570 # else
571 # ifdef NBPG
572 # ifndef CLSIZE
573 # define malloc_getpagesize NBPG
574 # else
575 # define malloc_getpagesize (NBPG * CLSIZE)
576 # endif
577 # else
578 # ifdef NBPC
579 # define malloc_getpagesize NBPC
580 # else
581 # ifdef PAGESIZE
582 # define malloc_getpagesize PAGESIZE
583 # else
584 # define malloc_getpagesize (4096) /* just guess */
585 # endif
586 # endif
587 # endif
588 # endif
589 # endif
590 # endif
591 #endif
597 This version of malloc supports the standard SVID/XPG mallinfo
598 routine that returns a struct containing the same kind of
599 information you can get from malloc_stats. It should work on
600 any SVID/XPG compliant system that has a /usr/include/malloc.h
601 defining struct mallinfo. (If you'd like to install such a thing
602 yourself, cut out the preliminary declarations as described above
603 and below and save them in a malloc.h file. But there's no
604 compelling reason to bother to do this.)
606 The main declaration needed is the mallinfo struct that is returned
607 (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
608 bunch of fields, most of which are not even meaningful in this
609 version of malloc. Some of these fields are are instead filled by
610 mallinfo() with other numbers that might possibly be of interest.
612 HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
613 /usr/include/malloc.h file that includes a declaration of struct
614 mallinfo. If so, it is included; else an SVID2/XPG2 compliant
615 version is declared below. These must be precisely the same for
616 mallinfo() to work.
620 /* #define HAVE_USR_INCLUDE_MALLOC_H */
622 #if HAVE_USR_INCLUDE_MALLOC_H
623 # include "/usr/include/malloc.h"
624 #else
625 # ifdef _LIBC
626 # include "malloc.h"
627 # else
628 # include "ptmalloc.h"
629 # endif
630 #endif
634 #ifndef DEFAULT_TRIM_THRESHOLD
635 #define DEFAULT_TRIM_THRESHOLD (128 * 1024)
636 #endif
639 M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
640 to keep before releasing via malloc_trim in free().
642 Automatic trimming is mainly useful in long-lived programs.
643 Because trimming via sbrk can be slow on some systems, and can
644 sometimes be wasteful (in cases where programs immediately
645 afterward allocate more large chunks) the value should be high
646 enough so that your overall system performance would improve by
647 releasing.
649 The trim threshold and the mmap control parameters (see below)
650 can be traded off with one another. Trimming and mmapping are
651 two different ways of releasing unused memory back to the
652 system. Between these two, it is often possible to keep
653 system-level demands of a long-lived program down to a bare
654 minimum. For example, in one test suite of sessions measuring
655 the XF86 X server on Linux, using a trim threshold of 128K and a
656 mmap threshold of 192K led to near-minimal long term resource
657 consumption.
659 If you are using this malloc in a long-lived program, it should
660 pay to experiment with these values. As a rough guide, you
661 might set to a value close to the average size of a process
662 (program) running on your system. Releasing this much memory
663 would allow such a process to run in memory. Generally, it's
664 worth it to tune for trimming rather than memory mapping when a
665 program undergoes phases where several large chunks are
666 allocated and released in ways that can reuse each other's
667 storage, perhaps mixed with phases where there are no such
668 chunks at all. And in well-behaved long-lived programs,
669 controlling release of large blocks via trimming versus mapping
670 is usually faster.
672 However, in most programs, these parameters serve mainly as
673 protection against the system-level effects of carrying around
674 massive amounts of unneeded memory. Since frequent calls to
675 sbrk, mmap, and munmap otherwise degrade performance, the default
676 parameters are set to relatively high values that serve only as
677 safeguards.
679 The default trim value is high enough to cause trimming only in
680 fairly extreme (by current memory consumption standards) cases.
681 It must be greater than page size to have any useful effect. To
682 disable trimming completely, you can set to (unsigned long)(-1);
688 #ifndef DEFAULT_TOP_PAD
689 #define DEFAULT_TOP_PAD (0)
690 #endif
693 M_TOP_PAD is the amount of extra `padding' space to allocate or
694 retain whenever sbrk is called. It is used in two ways internally:
696 * When sbrk is called to extend the top of the arena to satisfy
697 a new malloc request, this much padding is added to the sbrk
698 request.
700 * When malloc_trim is called automatically from free(),
701 it is used as the `pad' argument.
703 In both cases, the actual amount of padding is rounded
704 so that the end of the arena is always a system page boundary.
706 The main reason for using padding is to avoid calling sbrk so
707 often. Having even a small pad greatly reduces the likelihood
708 that nearly every malloc request during program start-up (or
709 after trimming) will invoke sbrk, which needlessly wastes
710 time.
712 Automatic rounding-up to page-size units is normally sufficient
713 to avoid measurable overhead, so the default is 0. However, in
714 systems where sbrk is relatively slow, it can pay to increase
715 this value, at the expense of carrying around more memory than
716 the program needs.
721 #ifndef DEFAULT_MMAP_THRESHOLD
722 #define DEFAULT_MMAP_THRESHOLD (128 * 1024)
723 #endif
727 M_MMAP_THRESHOLD is the request size threshold for using mmap()
728 to service a request. Requests of at least this size that cannot
729 be allocated using already-existing space will be serviced via mmap.
730 (If enough normal freed space already exists it is used instead.)
732 Using mmap segregates relatively large chunks of memory so that
733 they can be individually obtained and released from the host
734 system. A request serviced through mmap is never reused by any
735 other request (at least not directly; the system may just so
736 happen to remap successive requests to the same locations).
738 Segregating space in this way has the benefit that mmapped space
739 can ALWAYS be individually released back to the system, which
740 helps keep the system level memory demands of a long-lived
741 program low. Mapped memory can never become `locked' between
742 other chunks, as can happen with normally allocated chunks, which
743 menas that even trimming via malloc_trim would not release them.
745 However, it has the disadvantages that:
747 1. The space cannot be reclaimed, consolidated, and then
748 used to service later requests, as happens with normal chunks.
749 2. It can lead to more wastage because of mmap page alignment
750 requirements
751 3. It causes malloc performance to be more dependent on host
752 system memory management support routines which may vary in
753 implementation quality and may impose arbitrary
754 limitations. Generally, servicing a request via normal
755 malloc steps is faster than going through a system's mmap.
757 All together, these considerations should lead you to use mmap
758 only for relatively large requests.
765 #ifndef DEFAULT_MMAP_MAX
766 #if HAVE_MMAP
767 #define DEFAULT_MMAP_MAX (1024)
768 #else
769 #define DEFAULT_MMAP_MAX (0)
770 #endif
771 #endif
774 M_MMAP_MAX is the maximum number of requests to simultaneously
775 service using mmap. This parameter exists because:
777 1. Some systems have a limited number of internal tables for
778 use by mmap.
779 2. In most systems, overreliance on mmap can degrade overall
780 performance.
781 3. If a program allocates many large regions, it is probably
782 better off using normal sbrk-based allocation routines that
783 can reclaim and reallocate normal heap memory. Using a
784 small value allows transition into this mode after the
785 first few allocations.
787 Setting to 0 disables all use of mmap. If HAVE_MMAP is not set,
788 the default value is 0, and attempts to set it to non-zero values
789 in mallopt will fail.
794 #ifndef DEFAULT_CHECK_ACTION
795 #define DEFAULT_CHECK_ACTION 1
796 #endif
798 /* What to do if the standard debugging hooks are in place and a
799 corrupt pointer is detected: do nothing (0), print an error message
800 (1), or call abort() (2). */
804 #define HEAP_MIN_SIZE (32*1024)
805 #define HEAP_MAX_SIZE (1024*1024) /* must be a power of two */
807 /* HEAP_MIN_SIZE and HEAP_MAX_SIZE limit the size of mmap()ed heaps
808 that are dynamically created for multi-threaded programs. The
809 maximum size must be a power of two, for fast determination of
810 which heap belongs to a chunk. It should be much larger than
811 the mmap threshold, so that requests with a size just below that
812 threshold can be fulfilled without creating too many heaps.
817 #ifndef THREAD_STATS
818 #define THREAD_STATS 0
819 #endif
821 /* If THREAD_STATS is non-zero, some statistics on mutex locking are
822 computed. */
826 /* On some platforms we can compile internal, not exported functions better.
827 Let the environment provide a macro and define it to be empty if it
828 is not available. */
829 #ifndef internal_function
830 # define internal_function
831 #endif
836 Special defines for the Linux/GNU C library.
841 #ifdef _LIBC
843 #if __STD_C
845 Void_t * __default_morecore (ptrdiff_t);
846 Void_t *(*__morecore)(ptrdiff_t) = __default_morecore;
848 #else
850 Void_t * __default_morecore ();
851 Void_t *(*__morecore)() = __default_morecore;
853 #endif
855 #define MORECORE (*__morecore)
856 #define MORECORE_FAILURE 0
857 #define MORECORE_CLEARS 1
858 #define mmap __mmap
859 #define munmap __munmap
860 #define mremap __mremap
861 #define mprotect __mprotect
862 #undef malloc_getpagesize
863 #define malloc_getpagesize __getpagesize()
865 #else /* _LIBC */
867 #if __STD_C
868 extern Void_t* sbrk(ptrdiff_t);
869 #else
870 extern Void_t* sbrk();
871 #endif
873 #ifndef MORECORE
874 #define MORECORE sbrk
875 #endif
877 #ifndef MORECORE_FAILURE
878 #define MORECORE_FAILURE -1
879 #endif
881 #ifndef MORECORE_CLEARS
882 #define MORECORE_CLEARS 1
883 #endif
885 #endif /* _LIBC */
887 #ifdef _LIBC
889 #define cALLOc __libc_calloc
890 #define fREe __libc_free
891 #define mALLOc __libc_malloc
892 #define mEMALIGn __libc_memalign
893 #define rEALLOc __libc_realloc
894 #define vALLOc __libc_valloc
895 #define pvALLOc __libc_pvalloc
896 #define mALLINFo __libc_mallinfo
897 #define mALLOPt __libc_mallopt
898 #define mALLOC_STATs __malloc_stats
899 #define mALLOC_USABLE_SIZe __malloc_usable_size
900 #define mALLOC_TRIm __malloc_trim
901 #define mALLOC_GET_STATe __malloc_get_state
902 #define mALLOC_SET_STATe __malloc_set_state
904 #else
906 #define cALLOc calloc
907 #define fREe free
908 #define mALLOc malloc
909 #define mEMALIGn memalign
910 #define rEALLOc realloc
911 #define vALLOc valloc
912 #define pvALLOc pvalloc
913 #define mALLINFo mallinfo
914 #define mALLOPt mallopt
915 #define mALLOC_STATs malloc_stats
916 #define mALLOC_USABLE_SIZe malloc_usable_size
917 #define mALLOC_TRIm malloc_trim
918 #define mALLOC_GET_STATe malloc_get_state
919 #define mALLOC_SET_STATe malloc_set_state
921 #endif
923 /* Public routines */
925 #if __STD_C
927 #ifndef _LIBC
928 void ptmalloc_init(void);
929 #endif
930 Void_t* mALLOc(size_t);
931 void fREe(Void_t*);
932 Void_t* rEALLOc(Void_t*, size_t);
933 Void_t* mEMALIGn(size_t, size_t);
934 Void_t* vALLOc(size_t);
935 Void_t* pvALLOc(size_t);
936 Void_t* cALLOc(size_t, size_t);
937 void cfree(Void_t*);
938 int mALLOC_TRIm(size_t);
939 size_t mALLOC_USABLE_SIZe(Void_t*);
940 void mALLOC_STATs(void);
941 int mALLOPt(int, int);
942 struct mallinfo mALLINFo(void);
943 Void_t* mALLOC_GET_STATe(void);
944 int mALLOC_SET_STATe(Void_t*);
946 #else /* !__STD_C */
948 #ifndef _LIBC
949 void ptmalloc_init();
950 #endif
951 Void_t* mALLOc();
952 void fREe();
953 Void_t* rEALLOc();
954 Void_t* mEMALIGn();
955 Void_t* vALLOc();
956 Void_t* pvALLOc();
957 Void_t* cALLOc();
958 void cfree();
959 int mALLOC_TRIm();
960 size_t mALLOC_USABLE_SIZe();
961 void mALLOC_STATs();
962 int mALLOPt();
963 struct mallinfo mALLINFo();
964 Void_t* mALLOC_GET_STATe();
965 int mALLOC_SET_STATe();
967 #endif /* __STD_C */
970 #ifdef __cplusplus
971 }; /* end of extern "C" */
972 #endif
974 #if !defined(NO_THREADS) && !HAVE_MMAP
975 "Can't have threads support without mmap"
976 #endif
980 Type declarations
984 struct malloc_chunk
986 INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
987 INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */
988 struct malloc_chunk* fd; /* double links -- used only if free. */
989 struct malloc_chunk* bk;
992 typedef struct malloc_chunk* mchunkptr;
996 malloc_chunk details:
998 (The following includes lightly edited explanations by Colin Plumb.)
1000 Chunks of memory are maintained using a `boundary tag' method as
1001 described in e.g., Knuth or Standish. (See the paper by Paul
1002 Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
1003 survey of such techniques.) Sizes of free chunks are stored both
1004 in the front of each chunk and at the end. This makes
1005 consolidating fragmented chunks into bigger chunks very fast. The
1006 size fields also hold bits representing whether chunks are free or
1007 in use.
1009 An allocated chunk looks like this:
1012 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1013 | Size of previous chunk, if allocated | |
1014 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1015 | Size of chunk, in bytes |P|
1016 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1017 | User data starts here... .
1019 . (malloc_usable_space() bytes) .
1021 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1022 | Size of chunk |
1023 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1026 Where "chunk" is the front of the chunk for the purpose of most of
1027 the malloc code, but "mem" is the pointer that is returned to the
1028 user. "Nextchunk" is the beginning of the next contiguous chunk.
1030 Chunks always begin on even word boundaries, so the mem portion
1031 (which is returned to the user) is also on an even word boundary, and
1032 thus double-word aligned.
1034 Free chunks are stored in circular doubly-linked lists, and look like this:
1036 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1037 | Size of previous chunk |
1038 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1039 `head:' | Size of chunk, in bytes |P|
1040 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1041 | Forward pointer to next chunk in list |
1042 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1043 | Back pointer to previous chunk in list |
1044 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1045 | Unused space (may be 0 bytes long) .
1048 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1049 `foot:' | Size of chunk, in bytes |
1050 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1052 The P (PREV_INUSE) bit, stored in the unused low-order bit of the
1053 chunk size (which is always a multiple of two words), is an in-use
1054 bit for the *previous* chunk. If that bit is *clear*, then the
1055 word before the current chunk size contains the previous chunk
1056 size, and can be used to find the front of the previous chunk.
1057 (The very first chunk allocated always has this bit set,
1058 preventing access to non-existent (or non-owned) memory.)
1060 Note that the `foot' of the current chunk is actually represented
1061 as the prev_size of the NEXT chunk. (This makes it easier to
1062 deal with alignments etc).
1064 The two exceptions to all this are
1066 1. The special chunk `top', which doesn't bother using the
1067 trailing size field since there is no
1068 next contiguous chunk that would have to index off it. (After
1069 initialization, `top' is forced to always exist. If it would
1070 become less than MINSIZE bytes long, it is replenished via
1071 malloc_extend_top.)
1073 2. Chunks allocated via mmap, which have the second-lowest-order
1074 bit (IS_MMAPPED) set in their size fields. Because they are
1075 never merged or traversed from any other chunk, they have no
1076 foot size or inuse information.
1078 Available chunks are kept in any of several places (all declared below):
1080 * `av': An array of chunks serving as bin headers for consolidated
1081 chunks. Each bin is doubly linked. The bins are approximately
1082 proportionally (log) spaced. There are a lot of these bins
1083 (128). This may look excessive, but works very well in
1084 practice. All procedures maintain the invariant that no
1085 consolidated chunk physically borders another one. Chunks in
1086 bins are kept in size order, with ties going to the
1087 approximately least recently used chunk.
1089 The chunks in each bin are maintained in decreasing sorted order by
1090 size. This is irrelevant for the small bins, which all contain
1091 the same-sized chunks, but facilitates best-fit allocation for
1092 larger chunks. (These lists are just sequential. Keeping them in
1093 order almost never requires enough traversal to warrant using
1094 fancier ordered data structures.) Chunks of the same size are
1095 linked with the most recently freed at the front, and allocations
1096 are taken from the back. This results in LRU or FIFO allocation
1097 order, which tends to give each chunk an equal opportunity to be
1098 consolidated with adjacent freed chunks, resulting in larger free
1099 chunks and less fragmentation.
1101 * `top': The top-most available chunk (i.e., the one bordering the
1102 end of available memory) is treated specially. It is never
1103 included in any bin, is used only if no other chunk is
1104 available, and is released back to the system if it is very
1105 large (see M_TRIM_THRESHOLD).
1107 * `last_remainder': A bin holding only the remainder of the
1108 most recently split (non-top) chunk. This bin is checked
1109 before other non-fitting chunks, so as to provide better
1110 locality for runs of sequentially allocated chunks.
1112 * Implicitly, through the host system's memory mapping tables.
1113 If supported, requests greater than a threshold are usually
1114 serviced via calls to mmap, and then later released via munmap.
1119 Bins
1121 The bins are an array of pairs of pointers serving as the
1122 heads of (initially empty) doubly-linked lists of chunks, laid out
1123 in a way so that each pair can be treated as if it were in a
1124 malloc_chunk. (This way, the fd/bk offsets for linking bin heads
1125 and chunks are the same).
1127 Bins for sizes < 512 bytes contain chunks of all the same size, spaced
1128 8 bytes apart. Larger bins are approximately logarithmically
1129 spaced. (See the table below.)
1131 Bin layout:
1133 64 bins of size 8
1134 32 bins of size 64
1135 16 bins of size 512
1136 8 bins of size 4096
1137 4 bins of size 32768
1138 2 bins of size 262144
1139 1 bin of size what's left
1141 There is actually a little bit of slop in the numbers in bin_index
1142 for the sake of speed. This makes no difference elsewhere.
1144 The special chunks `top' and `last_remainder' get their own bins,
1145 (this is implemented via yet more trickery with the av array),
1146 although `top' is never properly linked to its bin since it is
1147 always handled specially.
1151 #define NAV 128 /* number of bins */
1153 typedef struct malloc_chunk* mbinptr;
1155 /* An arena is a configuration of malloc_chunks together with an array
1156 of bins. With multiple threads, it must be locked via a mutex
1157 before changing its data structures. One or more `heaps' are
1158 associated with each arena, except for the main_arena, which is
1159 associated only with the `main heap', i.e. the conventional free
1160 store obtained with calls to MORECORE() (usually sbrk). The `av'
1161 array is never mentioned directly in the code, but instead used via
1162 bin access macros. */
1164 typedef struct _arena {
1165 mbinptr av[2*NAV + 2];
1166 struct _arena *next;
1167 size_t size;
1168 #if THREAD_STATS
1169 long stat_lock_direct, stat_lock_loop, stat_lock_wait;
1170 #endif
1171 mutex_t mutex;
1172 } arena;
1175 /* A heap is a single contiguous memory region holding (coalesceable)
1176 malloc_chunks. It is allocated with mmap() and always starts at an
1177 address aligned to HEAP_MAX_SIZE. Not used unless compiling for
1178 multiple threads. */
1180 typedef struct _heap_info {
1181 arena *ar_ptr; /* Arena for this heap. */
1182 struct _heap_info *prev; /* Previous heap. */
1183 size_t size; /* Current size in bytes. */
1184 size_t pad; /* Make sure the following data is properly aligned. */
1185 } heap_info;
1189 Static functions (forward declarations)
1192 #if __STD_C
1194 static void chunk_free(arena *ar_ptr, mchunkptr p) internal_function;
1195 static mchunkptr chunk_alloc(arena *ar_ptr, INTERNAL_SIZE_T size)
1196 internal_function;
1197 static mchunkptr chunk_realloc(arena *ar_ptr, mchunkptr oldp,
1198 INTERNAL_SIZE_T oldsize, INTERNAL_SIZE_T nb)
1199 internal_function;
1200 static mchunkptr chunk_align(arena *ar_ptr, INTERNAL_SIZE_T nb,
1201 size_t alignment) internal_function;
1202 static int main_trim(size_t pad) internal_function;
1203 #ifndef NO_THREADS
1204 static int heap_trim(heap_info *heap, size_t pad) internal_function;
1205 #endif
1206 #if defined _LIBC || defined MALLOC_HOOKS
1207 static Void_t* malloc_check(size_t sz, const Void_t *caller);
1208 static void free_check(Void_t* mem, const Void_t *caller);
1209 static Void_t* realloc_check(Void_t* oldmem, size_t bytes,
1210 const Void_t *caller);
1211 static Void_t* memalign_check(size_t alignment, size_t bytes,
1212 const Void_t *caller);
1213 #ifndef NO_THREADS
1214 static Void_t* malloc_starter(size_t sz, const Void_t *caller);
1215 static void free_starter(Void_t* mem, const Void_t *caller);
1216 static Void_t* malloc_atfork(size_t sz, const Void_t *caller);
1217 static void free_atfork(Void_t* mem, const Void_t *caller);
1218 #endif
1219 #endif
1221 #else
1223 static void chunk_free();
1224 static mchunkptr chunk_alloc();
1225 static mchunkptr chunk_realloc();
1226 static mchunkptr chunk_align();
1227 static int main_trim();
1228 #ifndef NO_THREADS
1229 static int heap_trim();
1230 #endif
1231 #if defined _LIBC || defined MALLOC_HOOKS
1232 static Void_t* malloc_check();
1233 static void free_check();
1234 static Void_t* realloc_check();
1235 static Void_t* memalign_check();
1236 #ifndef NO_THREADS
1237 static Void_t* malloc_starter();
1238 static void free_starter();
1239 static Void_t* malloc_atfork();
1240 static void free_atfork();
1241 #endif
1242 #endif
1244 #endif
1248 /* sizes, alignments */
1250 #define SIZE_SZ (sizeof(INTERNAL_SIZE_T))
1251 #define MALLOC_ALIGNMENT (SIZE_SZ + SIZE_SZ)
1252 #define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)
1253 #define MINSIZE (sizeof(struct malloc_chunk))
1255 /* conversion from malloc headers to user pointers, and back */
1257 #define chunk2mem(p) ((Void_t*)((char*)(p) + 2*SIZE_SZ))
1258 #define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
1260 /* pad request bytes into a usable size */
1262 #define request2size(req) \
1263 (((long)((req) + (SIZE_SZ + MALLOC_ALIGN_MASK)) < \
1264 (long)(MINSIZE + MALLOC_ALIGN_MASK)) ? MINSIZE : \
1265 (((req) + (SIZE_SZ + MALLOC_ALIGN_MASK)) & ~(MALLOC_ALIGN_MASK)))
1267 /* Check if m has acceptable alignment */
1269 #define aligned_OK(m) (((unsigned long)((m)) & (MALLOC_ALIGN_MASK)) == 0)
1275 Physical chunk operations
1279 /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
1281 #define PREV_INUSE 0x1
1283 /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
1285 #define IS_MMAPPED 0x2
1287 /* Bits to mask off when extracting size */
1289 #define SIZE_BITS (PREV_INUSE|IS_MMAPPED)
1292 /* Ptr to next physical malloc_chunk. */
1294 #define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->size & ~PREV_INUSE) ))
1296 /* Ptr to previous physical malloc_chunk */
1298 #define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_size) ))
1301 /* Treat space at ptr + offset as a chunk */
1303 #define chunk_at_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
1309 Dealing with use bits
1312 /* extract p's inuse bit */
1314 #define inuse(p) \
1315 ((((mchunkptr)(((char*)(p))+((p)->size & ~PREV_INUSE)))->size) & PREV_INUSE)
1317 /* extract inuse bit of previous chunk */
1319 #define prev_inuse(p) ((p)->size & PREV_INUSE)
1321 /* check for mmap()'ed chunk */
1323 #define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
1325 /* set/clear chunk as in use without otherwise disturbing */
1327 #define set_inuse(p) \
1328 ((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size |= PREV_INUSE
1330 #define clear_inuse(p) \
1331 ((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size &= ~(PREV_INUSE)
1333 /* check/set/clear inuse bits in known places */
1335 #define inuse_bit_at_offset(p, s)\
1336 (((mchunkptr)(((char*)(p)) + (s)))->size & PREV_INUSE)
1338 #define set_inuse_bit_at_offset(p, s)\
1339 (((mchunkptr)(((char*)(p)) + (s)))->size |= PREV_INUSE)
1341 #define clear_inuse_bit_at_offset(p, s)\
1342 (((mchunkptr)(((char*)(p)) + (s)))->size &= ~(PREV_INUSE))
1348 Dealing with size fields
1351 /* Get size, ignoring use bits */
1353 #define chunksize(p) ((p)->size & ~(SIZE_BITS))
1355 /* Set size at head, without disturbing its use bit */
1357 #define set_head_size(p, s) ((p)->size = (((p)->size & PREV_INUSE) | (s)))
1359 /* Set size/use ignoring previous bits in header */
1361 #define set_head(p, s) ((p)->size = (s))
1363 /* Set size at footer (only when chunk is not in use) */
1365 #define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_size = (s))
1371 /* access macros */
1373 #define bin_at(a, i) ((mbinptr)((char*)&(((a)->av)[2*(i) + 2]) - 2*SIZE_SZ))
1374 #define init_bin(a, i) ((a)->av[2*i+2] = (a)->av[2*i+3] = bin_at((a), i))
1375 #define next_bin(b) ((mbinptr)((char*)(b) + 2 * sizeof(mbinptr)))
1376 #define prev_bin(b) ((mbinptr)((char*)(b) - 2 * sizeof(mbinptr)))
1379 The first 2 bins are never indexed. The corresponding av cells are instead
1380 used for bookkeeping. This is not to save space, but to simplify
1381 indexing, maintain locality, and avoid some initialization tests.
1384 #define binblocks(a) (bin_at(a,0)->size)/* bitvector of nonempty blocks */
1385 #define top(a) (bin_at(a,0)->fd) /* The topmost chunk */
1386 #define last_remainder(a) (bin_at(a,1)) /* remainder from last split */
1389 Because top initially points to its own bin with initial
1390 zero size, thus forcing extension on the first malloc request,
1391 we avoid having any special code in malloc to check whether
1392 it even exists yet. But we still need to in malloc_extend_top.
1395 #define initial_top(a) ((mchunkptr)bin_at(a, 0))
1399 /* field-extraction macros */
1401 #define first(b) ((b)->fd)
1402 #define last(b) ((b)->bk)
1405 Indexing into bins
1408 #define bin_index(sz) \
1409 (((((unsigned long)(sz)) >> 9) == 0) ? (((unsigned long)(sz)) >> 3):\
1410 ((((unsigned long)(sz)) >> 9) <= 4) ? 56 + (((unsigned long)(sz)) >> 6):\
1411 ((((unsigned long)(sz)) >> 9) <= 20) ? 91 + (((unsigned long)(sz)) >> 9):\
1412 ((((unsigned long)(sz)) >> 9) <= 84) ? 110 + (((unsigned long)(sz)) >> 12):\
1413 ((((unsigned long)(sz)) >> 9) <= 340) ? 119 + (((unsigned long)(sz)) >> 15):\
1414 ((((unsigned long)(sz)) >> 9) <= 1364) ? 124 + (((unsigned long)(sz)) >> 18):\
1415 126)
1417 bins for chunks < 512 are all spaced 8 bytes apart, and hold
1418 identically sized chunks. This is exploited in malloc.
1421 #define MAX_SMALLBIN 63
1422 #define MAX_SMALLBIN_SIZE 512
1423 #define SMALLBIN_WIDTH 8
1425 #define smallbin_index(sz) (((unsigned long)(sz)) >> 3)
1428 Requests are `small' if both the corresponding and the next bin are small
1431 #define is_small_request(nb) ((nb) < MAX_SMALLBIN_SIZE - SMALLBIN_WIDTH)
1436 To help compensate for the large number of bins, a one-level index
1437 structure is used for bin-by-bin searching. `binblocks' is a
1438 one-word bitvector recording whether groups of BINBLOCKWIDTH bins
1439 have any (possibly) non-empty bins, so they can be skipped over
1440 all at once during during traversals. The bits are NOT always
1441 cleared as soon as all bins in a block are empty, but instead only
1442 when all are noticed to be empty during traversal in malloc.
1445 #define BINBLOCKWIDTH 4 /* bins per block */
1447 /* bin<->block macros */
1449 #define idx2binblock(ix) ((unsigned)1 << ((ix) / BINBLOCKWIDTH))
1450 #define mark_binblock(a, ii) (binblocks(a) |= idx2binblock(ii))
1451 #define clear_binblock(a, ii) (binblocks(a) &= ~(idx2binblock(ii)))
1456 /* Static bookkeeping data */
1458 /* Helper macro to initialize bins */
1459 #define IAV(i) bin_at(&main_arena, i), bin_at(&main_arena, i)
1461 static arena main_arena = {
1463 0, 0,
1464 IAV(0), IAV(1), IAV(2), IAV(3), IAV(4), IAV(5), IAV(6), IAV(7),
1465 IAV(8), IAV(9), IAV(10), IAV(11), IAV(12), IAV(13), IAV(14), IAV(15),
1466 IAV(16), IAV(17), IAV(18), IAV(19), IAV(20), IAV(21), IAV(22), IAV(23),
1467 IAV(24), IAV(25), IAV(26), IAV(27), IAV(28), IAV(29), IAV(30), IAV(31),
1468 IAV(32), IAV(33), IAV(34), IAV(35), IAV(36), IAV(37), IAV(38), IAV(39),
1469 IAV(40), IAV(41), IAV(42), IAV(43), IAV(44), IAV(45), IAV(46), IAV(47),
1470 IAV(48), IAV(49), IAV(50), IAV(51), IAV(52), IAV(53), IAV(54), IAV(55),
1471 IAV(56), IAV(57), IAV(58), IAV(59), IAV(60), IAV(61), IAV(62), IAV(63),
1472 IAV(64), IAV(65), IAV(66), IAV(67), IAV(68), IAV(69), IAV(70), IAV(71),
1473 IAV(72), IAV(73), IAV(74), IAV(75), IAV(76), IAV(77), IAV(78), IAV(79),
1474 IAV(80), IAV(81), IAV(82), IAV(83), IAV(84), IAV(85), IAV(86), IAV(87),
1475 IAV(88), IAV(89), IAV(90), IAV(91), IAV(92), IAV(93), IAV(94), IAV(95),
1476 IAV(96), IAV(97), IAV(98), IAV(99), IAV(100), IAV(101), IAV(102), IAV(103),
1477 IAV(104), IAV(105), IAV(106), IAV(107), IAV(108), IAV(109), IAV(110), IAV(111),
1478 IAV(112), IAV(113), IAV(114), IAV(115), IAV(116), IAV(117), IAV(118), IAV(119),
1479 IAV(120), IAV(121), IAV(122), IAV(123), IAV(124), IAV(125), IAV(126), IAV(127)
1481 &main_arena, /* next */
1482 0, /* size */
1483 #if THREAD_STATS
1484 0, 0, 0, /* stat_lock_direct, stat_lock_loop, stat_lock_wait */
1485 #endif
1486 MUTEX_INITIALIZER /* mutex */
1489 #undef IAV
1491 /* Thread specific data */
1493 #ifndef NO_THREADS
1494 static tsd_key_t arena_key;
1495 static mutex_t list_lock = MUTEX_INITIALIZER;
1496 #endif
1498 #if THREAD_STATS
1499 static int stat_n_heaps = 0;
1500 #define THREAD_STAT(x) x
1501 #else
1502 #define THREAD_STAT(x) do ; while(0)
1503 #endif
1505 /* variables holding tunable values */
1507 static unsigned long trim_threshold = DEFAULT_TRIM_THRESHOLD;
1508 static unsigned long top_pad = DEFAULT_TOP_PAD;
1509 static unsigned int n_mmaps_max = DEFAULT_MMAP_MAX;
1510 static unsigned long mmap_threshold = DEFAULT_MMAP_THRESHOLD;
1511 static int check_action = DEFAULT_CHECK_ACTION;
1513 /* The first value returned from sbrk */
1514 static char* sbrk_base = (char*)(-1);
1516 /* The maximum memory obtained from system via sbrk */
1517 static unsigned long max_sbrked_mem = 0;
1519 /* The maximum via either sbrk or mmap (too difficult to track with threads) */
1520 #ifdef NO_THREADS
1521 static unsigned long max_total_mem = 0;
1522 #endif
1524 /* The total memory obtained from system via sbrk */
1525 #define sbrked_mem (main_arena.size)
1527 /* Tracking mmaps */
1529 static unsigned int n_mmaps = 0;
1530 static unsigned int max_n_mmaps = 0;
1531 static unsigned long mmapped_mem = 0;
1532 static unsigned long max_mmapped_mem = 0;
1536 #ifndef _LIBC
1537 #define weak_variable
1538 #else
1539 /* In GNU libc we want the hook variables to be weak definitions to
1540 avoid a problem with Emacs. */
1541 #define weak_variable weak_function
1542 #endif
1544 /* Already initialized? */
1545 int __malloc_initialized = -1;
1548 #ifndef NO_THREADS
1550 /* The following two functions are registered via thread_atfork() to
1551 make sure that the mutexes remain in a consistent state in the
1552 fork()ed version of a thread. Also adapt the malloc and free hooks
1553 temporarily, because the `atfork' handler mechanism may use
1554 malloc/free internally (e.g. in LinuxThreads). */
1556 #if defined _LIBC || defined MALLOC_HOOKS
1557 static __malloc_ptr_t (*save_malloc_hook) __MALLOC_P ((size_t __size,
1558 const __malloc_ptr_t));
1559 static void (*save_free_hook) __MALLOC_P ((__malloc_ptr_t __ptr,
1560 const __malloc_ptr_t));
1561 static Void_t* save_arena;
1562 #endif
1564 static void
1565 ptmalloc_lock_all __MALLOC_P((void))
1567 arena *ar_ptr;
1569 (void)mutex_lock(&list_lock);
1570 for(ar_ptr = &main_arena;;) {
1571 (void)mutex_lock(&ar_ptr->mutex);
1572 ar_ptr = ar_ptr->next;
1573 if(ar_ptr == &main_arena) break;
1575 #if defined _LIBC || defined MALLOC_HOOKS
1576 save_malloc_hook = __malloc_hook;
1577 save_free_hook = __free_hook;
1578 __malloc_hook = malloc_atfork;
1579 __free_hook = free_atfork;
1580 /* Only the current thread may perform malloc/free calls now. */
1581 tsd_getspecific(arena_key, save_arena);
1582 tsd_setspecific(arena_key, (Void_t*)0);
1583 #endif
1586 static void
1587 ptmalloc_unlock_all __MALLOC_P((void))
1589 arena *ar_ptr;
1591 #if defined _LIBC || defined MALLOC_HOOKS
1592 tsd_setspecific(arena_key, save_arena);
1593 __malloc_hook = save_malloc_hook;
1594 __free_hook = save_free_hook;
1595 #endif
1596 for(ar_ptr = &main_arena;;) {
1597 (void)mutex_unlock(&ar_ptr->mutex);
1598 ar_ptr = ar_ptr->next;
1599 if(ar_ptr == &main_arena) break;
1601 (void)mutex_unlock(&list_lock);
1604 static void
1605 ptmalloc_init_all __MALLOC_P((void))
1607 arena *ar_ptr;
1609 #if defined _LIBC || defined MALLOC_HOOKS
1610 tsd_setspecific(arena_key, save_arena);
1611 __malloc_hook = save_malloc_hook;
1612 __free_hook = save_free_hook;
1613 #endif
1614 for(ar_ptr = &main_arena;;) {
1615 (void)mutex_init(&ar_ptr->mutex);
1616 ar_ptr = ar_ptr->next;
1617 if(ar_ptr == &main_arena) break;
1619 (void)mutex_init(&list_lock);
1622 #endif /* !defined NO_THREADS */
1624 /* Initialization routine. */
1625 #if defined(_LIBC)
1626 #if 0
1627 static void ptmalloc_init __MALLOC_P ((void)) __attribute__ ((constructor));
1628 #endif
1630 static void
1631 ptmalloc_init __MALLOC_P((void))
1632 #else
1633 void
1634 ptmalloc_init __MALLOC_P((void))
1635 #endif
1637 #if defined _LIBC || defined MALLOC_HOOKS
1638 const char* s;
1639 #endif
1641 if(__malloc_initialized >= 0) return;
1642 __malloc_initialized = 0;
1643 #ifndef NO_THREADS
1644 #if defined _LIBC || defined MALLOC_HOOKS
1645 /* With some threads implementations, creating thread-specific data
1646 or initializing a mutex may call malloc() itself. Provide a
1647 simple starter version (realloc() won't work). */
1648 save_malloc_hook = __malloc_hook;
1649 save_free_hook = __free_hook;
1650 __malloc_hook = malloc_starter;
1651 __free_hook = free_starter;
1652 #endif
1653 #ifdef _LIBC
1654 /* Initialize the pthreads interface. */
1655 if (__pthread_initialize != NULL)
1656 __pthread_initialize();
1657 #endif
1658 mutex_init(&main_arena.mutex);
1659 mutex_init(&list_lock);
1660 tsd_key_create(&arena_key, NULL);
1661 tsd_setspecific(arena_key, (Void_t *)&main_arena);
1662 thread_atfork(ptmalloc_lock_all, ptmalloc_unlock_all, ptmalloc_init_all);
1663 #endif /* !defined NO_THREADS */
1664 #if defined _LIBC || defined MALLOC_HOOKS
1665 if((s = getenv("MALLOC_TRIM_THRESHOLD_")))
1666 mALLOPt(M_TRIM_THRESHOLD, atoi(s));
1667 if((s = getenv("MALLOC_TOP_PAD_")))
1668 mALLOPt(M_TOP_PAD, atoi(s));
1669 if((s = getenv("MALLOC_MMAP_THRESHOLD_")))
1670 mALLOPt(M_MMAP_THRESHOLD, atoi(s));
1671 if((s = getenv("MALLOC_MMAP_MAX_")))
1672 mALLOPt(M_MMAP_MAX, atoi(s));
1673 s = getenv("MALLOC_CHECK_");
1674 #ifndef NO_THREADS
1675 __malloc_hook = save_malloc_hook;
1676 __free_hook = save_free_hook;
1677 #endif
1678 if(s) {
1679 if(s[0]) mALLOPt(M_CHECK_ACTION, (int)(s[0] - '0'));
1680 __malloc_check_init();
1682 if(__malloc_initialize_hook != NULL)
1683 (*__malloc_initialize_hook)();
1684 #endif
1685 __malloc_initialized = 1;
1688 /* There are platforms (e.g. Hurd) with a link-time hook mechanism. */
1689 #ifdef thread_atfork_static
1690 thread_atfork_static(ptmalloc_lock_all, ptmalloc_unlock_all, \
1691 ptmalloc_init_all)
1692 #endif
1694 #if defined _LIBC || defined MALLOC_HOOKS
1696 /* Hooks for debugging versions. The initial hooks just call the
1697 initialization routine, then do the normal work. */
1699 static Void_t*
1700 #if __STD_C
1701 malloc_hook_ini(size_t sz, const __malloc_ptr_t caller)
1702 #else
1703 malloc_hook_ini(sz, caller)
1704 size_t sz; const __malloc_ptr_t caller;
1705 #endif
1707 __malloc_hook = NULL;
1708 ptmalloc_init();
1709 return mALLOc(sz);
1712 static Void_t*
1713 #if __STD_C
1714 realloc_hook_ini(Void_t* ptr, size_t sz, const __malloc_ptr_t caller)
1715 #else
1716 realloc_hook_ini(ptr, sz, caller)
1717 Void_t* ptr; size_t sz; const __malloc_ptr_t caller;
1718 #endif
1720 __malloc_hook = NULL;
1721 __realloc_hook = NULL;
1722 ptmalloc_init();
1723 return rEALLOc(ptr, sz);
1726 static Void_t*
1727 #if __STD_C
1728 memalign_hook_ini(size_t sz, size_t alignment, const __malloc_ptr_t caller)
1729 #else
1730 memalign_hook_ini(sz, alignment, caller)
1731 size_t sz; size_t alignment; const __malloc_ptr_t caller;
1732 #endif
1734 __memalign_hook = NULL;
1735 ptmalloc_init();
1736 return mEMALIGn(sz, alignment);
1739 void weak_variable (*__malloc_initialize_hook) __MALLOC_P ((void)) = NULL;
1740 void weak_variable (*__free_hook) __MALLOC_P ((__malloc_ptr_t __ptr,
1741 const __malloc_ptr_t)) = NULL;
1742 __malloc_ptr_t weak_variable (*__malloc_hook)
1743 __MALLOC_P ((size_t __size, const __malloc_ptr_t)) = malloc_hook_ini;
1744 __malloc_ptr_t weak_variable (*__realloc_hook)
1745 __MALLOC_P ((__malloc_ptr_t __ptr, size_t __size, const __malloc_ptr_t))
1746 = realloc_hook_ini;
1747 __malloc_ptr_t weak_variable (*__memalign_hook)
1748 __MALLOC_P ((size_t __size, size_t __alignment, const __malloc_ptr_t))
1749 = memalign_hook_ini;
1750 void weak_variable (*__after_morecore_hook) __MALLOC_P ((void)) = NULL;
1752 /* Whether we are using malloc checking. */
1753 static int using_malloc_checking;
1755 /* A flag that is set by malloc_set_state, to signal that malloc checking
1756 must not be enabled on the request from the user (via the MALLOC_CHECK_
1757 environment variable). It is reset by __malloc_check_init to tell
1758 malloc_set_state that the user has requested malloc checking.
1760 The purpose of this flag is to make sure that malloc checking is not
1761 enabled when the heap to be restored was constructed without malloc
1762 checking, and thus does not contain the required magic bytes.
1763 Otherwise the heap would be corrupted by calls to free and realloc. If
1764 it turns out that the heap was created with malloc checking and the
1765 user has requested it malloc_set_state just calls __malloc_check_init
1766 again to enable it. On the other hand, reusing such a heap without
1767 further malloc checking is safe. */
1768 static int disallow_malloc_check;
1770 /* Activate a standard set of debugging hooks. */
1771 void
1772 __malloc_check_init()
1774 if (disallow_malloc_check) {
1775 disallow_malloc_check = 0;
1776 return;
1778 using_malloc_checking = 1;
1779 __malloc_hook = malloc_check;
1780 __free_hook = free_check;
1781 __realloc_hook = realloc_check;
1782 __memalign_hook = memalign_check;
1783 if(check_action == 1)
1784 fprintf(stderr, "malloc: using debugging hooks\n");
1787 #endif
1793 /* Routines dealing with mmap(). */
1795 #if HAVE_MMAP
1797 #ifndef MAP_ANONYMOUS
1799 static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */
1801 #define MMAP(addr, size, prot, flags) ((dev_zero_fd < 0) ? \
1802 (dev_zero_fd = open("/dev/zero", O_RDWR), \
1803 mmap((addr), (size), (prot), (flags), dev_zero_fd, 0)) : \
1804 mmap((addr), (size), (prot), (flags), dev_zero_fd, 0))
1806 #else
1808 #define MMAP(addr, size, prot, flags) \
1809 (mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS, -1, 0))
1811 #endif
1813 #if defined __GNUC__ && __GNUC__ >= 2
1814 /* This function is only called from one place, inline it. */
1815 inline
1816 #endif
1817 static mchunkptr
1818 internal_function
1819 #if __STD_C
1820 mmap_chunk(size_t size)
1821 #else
1822 mmap_chunk(size) size_t size;
1823 #endif
1825 size_t page_mask = malloc_getpagesize - 1;
1826 mchunkptr p;
1828 if(n_mmaps >= n_mmaps_max) return 0; /* too many regions */
1830 /* For mmapped chunks, the overhead is one SIZE_SZ unit larger, because
1831 * there is no following chunk whose prev_size field could be used.
1833 size = (size + SIZE_SZ + page_mask) & ~page_mask;
1835 p = (mchunkptr)MMAP(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE);
1836 if(p == (mchunkptr) MAP_FAILED) return 0;
1838 n_mmaps++;
1839 if (n_mmaps > max_n_mmaps) max_n_mmaps = n_mmaps;
1841 /* We demand that eight bytes into a page must be 8-byte aligned. */
1842 assert(aligned_OK(chunk2mem(p)));
1844 /* The offset to the start of the mmapped region is stored
1845 * in the prev_size field of the chunk; normally it is zero,
1846 * but that can be changed in memalign().
1848 p->prev_size = 0;
1849 set_head(p, size|IS_MMAPPED);
1851 mmapped_mem += size;
1852 if ((unsigned long)mmapped_mem > (unsigned long)max_mmapped_mem)
1853 max_mmapped_mem = mmapped_mem;
1854 #ifdef NO_THREADS
1855 if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
1856 max_total_mem = mmapped_mem + sbrked_mem;
1857 #endif
1858 return p;
1861 static void
1862 internal_function
1863 #if __STD_C
1864 munmap_chunk(mchunkptr p)
1865 #else
1866 munmap_chunk(p) mchunkptr p;
1867 #endif
1869 INTERNAL_SIZE_T size = chunksize(p);
1870 int ret;
1872 assert (chunk_is_mmapped(p));
1873 assert(! ((char*)p >= sbrk_base && (char*)p < sbrk_base + sbrked_mem));
1874 assert((n_mmaps > 0));
1875 assert(((p->prev_size + size) & (malloc_getpagesize-1)) == 0);
1877 n_mmaps--;
1878 mmapped_mem -= (size + p->prev_size);
1880 ret = munmap((char *)p - p->prev_size, size + p->prev_size);
1882 /* munmap returns non-zero on failure */
1883 assert(ret == 0);
1886 #if HAVE_MREMAP
1888 static mchunkptr
1889 internal_function
1890 #if __STD_C
1891 mremap_chunk(mchunkptr p, size_t new_size)
1892 #else
1893 mremap_chunk(p, new_size) mchunkptr p; size_t new_size;
1894 #endif
1896 size_t page_mask = malloc_getpagesize - 1;
1897 INTERNAL_SIZE_T offset = p->prev_size;
1898 INTERNAL_SIZE_T size = chunksize(p);
1899 char *cp;
1901 assert (chunk_is_mmapped(p));
1902 assert(! ((char*)p >= sbrk_base && (char*)p < sbrk_base + sbrked_mem));
1903 assert((n_mmaps > 0));
1904 assert(((size + offset) & (malloc_getpagesize-1)) == 0);
1906 /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
1907 new_size = (new_size + offset + SIZE_SZ + page_mask) & ~page_mask;
1909 cp = (char *)mremap((char *)p - offset, size + offset, new_size,
1910 MREMAP_MAYMOVE);
1912 if (cp == MAP_FAILED) return 0;
1914 p = (mchunkptr)(cp + offset);
1916 assert(aligned_OK(chunk2mem(p)));
1918 assert((p->prev_size == offset));
1919 set_head(p, (new_size - offset)|IS_MMAPPED);
1921 mmapped_mem -= size + offset;
1922 mmapped_mem += new_size;
1923 if ((unsigned long)mmapped_mem > (unsigned long)max_mmapped_mem)
1924 max_mmapped_mem = mmapped_mem;
1925 #ifdef NO_THREADS
1926 if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
1927 max_total_mem = mmapped_mem + sbrked_mem;
1928 #endif
1929 return p;
1932 #endif /* HAVE_MREMAP */
1934 #endif /* HAVE_MMAP */
1938 /* Managing heaps and arenas (for concurrent threads) */
1940 #ifndef NO_THREADS
1942 /* Create a new heap. size is automatically rounded up to a multiple
1943 of the page size. */
1945 static heap_info *
1946 internal_function
1947 #if __STD_C
1948 new_heap(size_t size)
1949 #else
1950 new_heap(size) size_t size;
1951 #endif
1953 size_t page_mask = malloc_getpagesize - 1;
1954 char *p1, *p2;
1955 unsigned long ul;
1956 heap_info *h;
1958 if(size+top_pad < HEAP_MIN_SIZE)
1959 size = HEAP_MIN_SIZE;
1960 else if(size+top_pad <= HEAP_MAX_SIZE)
1961 size += top_pad;
1962 else if(size > HEAP_MAX_SIZE)
1963 return 0;
1964 else
1965 size = HEAP_MAX_SIZE;
1966 size = (size + page_mask) & ~page_mask;
1968 /* A memory region aligned to a multiple of HEAP_MAX_SIZE is needed.
1969 No swap space needs to be reserved for the following large
1970 mapping (on Linux, this is the case for all non-writable mappings
1971 anyway). */
1972 p1 = (char *)MMAP(0, HEAP_MAX_SIZE<<1, PROT_NONE, MAP_PRIVATE|MAP_NORESERVE);
1973 if(p1 == MAP_FAILED)
1974 return 0;
1975 p2 = (char *)(((unsigned long)p1 + HEAP_MAX_SIZE) & ~(HEAP_MAX_SIZE-1));
1976 ul = p2 - p1;
1977 munmap(p1, ul);
1978 munmap(p2 + HEAP_MAX_SIZE, HEAP_MAX_SIZE - ul);
1979 if(mprotect(p2, size, PROT_READ|PROT_WRITE) != 0) {
1980 munmap(p2, HEAP_MAX_SIZE);
1981 return 0;
1983 h = (heap_info *)p2;
1984 h->size = size;
1985 THREAD_STAT(stat_n_heaps++);
1986 return h;
1989 /* Grow or shrink a heap. size is automatically rounded up to a
1990 multiple of the page size if it is positive. */
1992 static int
1993 #if __STD_C
1994 grow_heap(heap_info *h, long diff)
1995 #else
1996 grow_heap(h, diff) heap_info *h; long diff;
1997 #endif
1999 size_t page_mask = malloc_getpagesize - 1;
2000 long new_size;
2002 if(diff >= 0) {
2003 diff = (diff + page_mask) & ~page_mask;
2004 new_size = (long)h->size + diff;
2005 if(new_size > HEAP_MAX_SIZE)
2006 return -1;
2007 if(mprotect((char *)h + h->size, diff, PROT_READ|PROT_WRITE) != 0)
2008 return -2;
2009 } else {
2010 new_size = (long)h->size + diff;
2011 if(new_size < (long)sizeof(*h))
2012 return -1;
2013 /* Try to re-map the extra heap space freshly to save memory, and
2014 make it inaccessible. */
2015 if((char *)MMAP((char *)h + new_size, -diff, PROT_NONE,
2016 MAP_PRIVATE|MAP_FIXED) == (char *) MAP_FAILED)
2017 return -2;
2019 h->size = new_size;
2020 return 0;
2023 /* Delete a heap. */
2025 #define delete_heap(heap) munmap((char*)(heap), HEAP_MAX_SIZE)
2027 /* arena_get() acquires an arena and locks the corresponding mutex.
2028 First, try the one last locked successfully by this thread. (This
2029 is the common case and handled with a macro for speed.) Then, loop
2030 once over the circularly linked list of arenas. If no arena is
2031 readily available, create a new one. */
2033 #define arena_get(ptr, size) do { \
2034 Void_t *vptr = NULL; \
2035 ptr = (arena *)tsd_getspecific(arena_key, vptr); \
2036 if(ptr && !mutex_trylock(&ptr->mutex)) { \
2037 THREAD_STAT(++(ptr->stat_lock_direct)); \
2038 } else \
2039 ptr = arena_get2(ptr, (size)); \
2040 } while(0)
2042 static arena *
2043 internal_function
2044 #if __STD_C
2045 arena_get2(arena *a_tsd, size_t size)
2046 #else
2047 arena_get2(a_tsd, size) arena *a_tsd; size_t size;
2048 #endif
2050 arena *a;
2051 heap_info *h;
2052 char *ptr;
2053 int i;
2054 unsigned long misalign;
2056 if(!a_tsd)
2057 a = a_tsd = &main_arena;
2058 else {
2059 a = a_tsd->next;
2060 if(!a) {
2061 /* This can only happen while initializing the new arena. */
2062 (void)mutex_lock(&main_arena.mutex);
2063 THREAD_STAT(++(main_arena.stat_lock_wait));
2064 return &main_arena;
2068 /* Check the global, circularly linked list for available arenas. */
2069 repeat:
2070 do {
2071 if(!mutex_trylock(&a->mutex)) {
2072 THREAD_STAT(++(a->stat_lock_loop));
2073 tsd_setspecific(arena_key, (Void_t *)a);
2074 return a;
2076 a = a->next;
2077 } while(a != a_tsd);
2079 /* If not even the list_lock can be obtained, try again. This can
2080 happen during `atfork', or for example on systems where thread
2081 creation makes it temporarily impossible to obtain _any_
2082 locks. */
2083 if(mutex_trylock(&list_lock)) {
2084 a = a_tsd;
2085 goto repeat;
2087 (void)mutex_unlock(&list_lock);
2089 /* Nothing immediately available, so generate a new arena. */
2090 h = new_heap(size + (sizeof(*h) + sizeof(*a) + MALLOC_ALIGNMENT));
2091 if(!h)
2092 return 0;
2093 a = h->ar_ptr = (arena *)(h+1);
2094 for(i=0; i<NAV; i++)
2095 init_bin(a, i);
2096 a->next = NULL;
2097 a->size = h->size;
2098 tsd_setspecific(arena_key, (Void_t *)a);
2099 mutex_init(&a->mutex);
2100 i = mutex_lock(&a->mutex); /* remember result */
2102 /* Set up the top chunk, with proper alignment. */
2103 ptr = (char *)(a + 1);
2104 misalign = (unsigned long)chunk2mem(ptr) & MALLOC_ALIGN_MASK;
2105 if (misalign > 0)
2106 ptr += MALLOC_ALIGNMENT - misalign;
2107 top(a) = (mchunkptr)ptr;
2108 set_head(top(a), (((char*)h + h->size) - ptr) | PREV_INUSE);
2110 /* Add the new arena to the list. */
2111 (void)mutex_lock(&list_lock);
2112 a->next = main_arena.next;
2113 main_arena.next = a;
2114 (void)mutex_unlock(&list_lock);
2116 if(i) /* locking failed; keep arena for further attempts later */
2117 return 0;
2119 THREAD_STAT(++(a->stat_lock_loop));
2120 return a;
2123 /* find the heap and corresponding arena for a given ptr */
2125 #define heap_for_ptr(ptr) \
2126 ((heap_info *)((unsigned long)(ptr) & ~(HEAP_MAX_SIZE-1)))
2127 #define arena_for_ptr(ptr) \
2128 (((mchunkptr)(ptr) < top(&main_arena) && (char *)(ptr) >= sbrk_base) ? \
2129 &main_arena : heap_for_ptr(ptr)->ar_ptr)
2131 #else /* defined(NO_THREADS) */
2133 /* Without concurrent threads, there is only one arena. */
2135 #define arena_get(ptr, sz) (ptr = &main_arena)
2136 #define arena_for_ptr(ptr) (&main_arena)
2138 #endif /* !defined(NO_THREADS) */
2143 Debugging support
2146 #if MALLOC_DEBUG
2150 These routines make a number of assertions about the states
2151 of data structures that should be true at all times. If any
2152 are not true, it's very likely that a user program has somehow
2153 trashed memory. (It's also possible that there is a coding error
2154 in malloc. In which case, please report it!)
2157 #if __STD_C
2158 static void do_check_chunk(arena *ar_ptr, mchunkptr p)
2159 #else
2160 static void do_check_chunk(ar_ptr, p) arena *ar_ptr; mchunkptr p;
2161 #endif
2163 INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
2165 /* No checkable chunk is mmapped */
2166 assert(!chunk_is_mmapped(p));
2168 #ifndef NO_THREADS
2169 if(ar_ptr != &main_arena) {
2170 heap_info *heap = heap_for_ptr(p);
2171 assert(heap->ar_ptr == ar_ptr);
2172 if(p != top(ar_ptr))
2173 assert((char *)p + sz <= (char *)heap + heap->size);
2174 else
2175 assert((char *)p + sz == (char *)heap + heap->size);
2176 return;
2178 #endif
2180 /* Check for legal address ... */
2181 assert((char*)p >= sbrk_base);
2182 if (p != top(ar_ptr))
2183 assert((char*)p + sz <= (char*)top(ar_ptr));
2184 else
2185 assert((char*)p + sz <= sbrk_base + sbrked_mem);
2190 #if __STD_C
2191 static void do_check_free_chunk(arena *ar_ptr, mchunkptr p)
2192 #else
2193 static void do_check_free_chunk(ar_ptr, p) arena *ar_ptr; mchunkptr p;
2194 #endif
2196 INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
2197 mchunkptr next = chunk_at_offset(p, sz);
2199 do_check_chunk(ar_ptr, p);
2201 /* Check whether it claims to be free ... */
2202 assert(!inuse(p));
2204 /* Must have OK size and fields */
2205 assert((long)sz >= (long)MINSIZE);
2206 assert((sz & MALLOC_ALIGN_MASK) == 0);
2207 assert(aligned_OK(chunk2mem(p)));
2208 /* ... matching footer field */
2209 assert(next->prev_size == sz);
2210 /* ... and is fully consolidated */
2211 assert(prev_inuse(p));
2212 assert (next == top(ar_ptr) || inuse(next));
2214 /* ... and has minimally sane links */
2215 assert(p->fd->bk == p);
2216 assert(p->bk->fd == p);
2219 #if __STD_C
2220 static void do_check_inuse_chunk(arena *ar_ptr, mchunkptr p)
2221 #else
2222 static void do_check_inuse_chunk(ar_ptr, p) arena *ar_ptr; mchunkptr p;
2223 #endif
2225 mchunkptr next = next_chunk(p);
2226 do_check_chunk(ar_ptr, p);
2228 /* Check whether it claims to be in use ... */
2229 assert(inuse(p));
2231 /* ... whether its size is OK (it might be a fencepost) ... */
2232 assert(chunksize(p) >= MINSIZE || next->size == (0|PREV_INUSE));
2234 /* ... and is surrounded by OK chunks.
2235 Since more things can be checked with free chunks than inuse ones,
2236 if an inuse chunk borders them and debug is on, it's worth doing them.
2238 if (!prev_inuse(p))
2240 mchunkptr prv = prev_chunk(p);
2241 assert(next_chunk(prv) == p);
2242 do_check_free_chunk(ar_ptr, prv);
2244 if (next == top(ar_ptr))
2246 assert(prev_inuse(next));
2247 assert(chunksize(next) >= MINSIZE);
2249 else if (!inuse(next))
2250 do_check_free_chunk(ar_ptr, next);
2254 #if __STD_C
2255 static void do_check_malloced_chunk(arena *ar_ptr,
2256 mchunkptr p, INTERNAL_SIZE_T s)
2257 #else
2258 static void do_check_malloced_chunk(ar_ptr, p, s)
2259 arena *ar_ptr; mchunkptr p; INTERNAL_SIZE_T s;
2260 #endif
2262 INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
2263 long room = sz - s;
2265 do_check_inuse_chunk(ar_ptr, p);
2267 /* Legal size ... */
2268 assert((long)sz >= (long)MINSIZE);
2269 assert((sz & MALLOC_ALIGN_MASK) == 0);
2270 assert(room >= 0);
2271 assert(room < (long)MINSIZE);
2273 /* ... and alignment */
2274 assert(aligned_OK(chunk2mem(p)));
2277 /* ... and was allocated at front of an available chunk */
2278 assert(prev_inuse(p));
2283 #define check_free_chunk(A,P) do_check_free_chunk(A,P)
2284 #define check_inuse_chunk(A,P) do_check_inuse_chunk(A,P)
2285 #define check_chunk(A,P) do_check_chunk(A,P)
2286 #define check_malloced_chunk(A,P,N) do_check_malloced_chunk(A,P,N)
2287 #else
2288 #define check_free_chunk(A,P)
2289 #define check_inuse_chunk(A,P)
2290 #define check_chunk(A,P)
2291 #define check_malloced_chunk(A,P,N)
2292 #endif
2297 Macro-based internal utilities
2302 Linking chunks in bin lists.
2303 Call these only with variables, not arbitrary expressions, as arguments.
2307 Place chunk p of size s in its bin, in size order,
2308 putting it ahead of others of same size.
2312 #define frontlink(A, P, S, IDX, BK, FD) \
2314 if (S < MAX_SMALLBIN_SIZE) \
2316 IDX = smallbin_index(S); \
2317 mark_binblock(A, IDX); \
2318 BK = bin_at(A, IDX); \
2319 FD = BK->fd; \
2320 P->bk = BK; \
2321 P->fd = FD; \
2322 FD->bk = BK->fd = P; \
2324 else \
2326 IDX = bin_index(S); \
2327 BK = bin_at(A, IDX); \
2328 FD = BK->fd; \
2329 if (FD == BK) mark_binblock(A, IDX); \
2330 else \
2332 while (FD != BK && S < chunksize(FD)) FD = FD->fd; \
2333 BK = FD->bk; \
2335 P->bk = BK; \
2336 P->fd = FD; \
2337 FD->bk = BK->fd = P; \
2342 /* take a chunk off a list */
2344 #define unlink(P, BK, FD) \
2346 BK = P->bk; \
2347 FD = P->fd; \
2348 FD->bk = BK; \
2349 BK->fd = FD; \
2352 /* Place p as the last remainder */
2354 #define link_last_remainder(A, P) \
2356 last_remainder(A)->fd = last_remainder(A)->bk = P; \
2357 P->fd = P->bk = last_remainder(A); \
2360 /* Clear the last_remainder bin */
2362 #define clear_last_remainder(A) \
2363 (last_remainder(A)->fd = last_remainder(A)->bk = last_remainder(A))
2370 Extend the top-most chunk by obtaining memory from system.
2371 Main interface to sbrk (but see also malloc_trim).
2374 #if defined __GNUC__ && __GNUC__ >= 2
2375 /* This function is called only from one place, inline it. */
2376 inline
2377 #endif
2378 static void
2379 internal_function
2380 #if __STD_C
2381 malloc_extend_top(arena *ar_ptr, INTERNAL_SIZE_T nb)
2382 #else
2383 malloc_extend_top(ar_ptr, nb) arena *ar_ptr; INTERNAL_SIZE_T nb;
2384 #endif
2386 unsigned long pagesz = malloc_getpagesize;
2387 mchunkptr old_top = top(ar_ptr); /* Record state of old top */
2388 INTERNAL_SIZE_T old_top_size = chunksize(old_top);
2389 INTERNAL_SIZE_T top_size; /* new size of top chunk */
2391 #ifndef NO_THREADS
2392 if(ar_ptr == &main_arena) {
2393 #endif
2395 char* brk; /* return value from sbrk */
2396 INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of sbrked space */
2397 INTERNAL_SIZE_T correction; /* bytes for 2nd sbrk call */
2398 char* new_brk; /* return of 2nd sbrk call */
2399 char* old_end = (char*)(chunk_at_offset(old_top, old_top_size));
2401 /* Pad request with top_pad plus minimal overhead */
2402 INTERNAL_SIZE_T sbrk_size = nb + top_pad + MINSIZE;
2404 /* If not the first time through, round to preserve page boundary */
2405 /* Otherwise, we need to correct to a page size below anyway. */
2406 /* (We also correct below if an intervening foreign sbrk call.) */
2408 if (sbrk_base != (char*)(-1))
2409 sbrk_size = (sbrk_size + (pagesz - 1)) & ~(pagesz - 1);
2411 brk = (char*)(MORECORE (sbrk_size));
2413 /* Fail if sbrk failed or if a foreign sbrk call killed our space */
2414 if (brk == (char*)(MORECORE_FAILURE) ||
2415 (brk < old_end && old_top != initial_top(&main_arena)))
2416 return;
2418 #if defined _LIBC || defined MALLOC_HOOKS
2419 /* Call the `morecore' hook if necessary. */
2420 if (__after_morecore_hook)
2421 (*__after_morecore_hook) ();
2422 #endif
2424 sbrked_mem += sbrk_size;
2426 if (brk == old_end) { /* can just add bytes to current top */
2427 top_size = sbrk_size + old_top_size;
2428 set_head(old_top, top_size | PREV_INUSE);
2429 old_top = 0; /* don't free below */
2430 } else {
2431 if (sbrk_base == (char*)(-1)) /* First time through. Record base */
2432 sbrk_base = brk;
2433 else
2434 /* Someone else called sbrk(). Count those bytes as sbrked_mem. */
2435 sbrked_mem += brk - (char*)old_end;
2437 /* Guarantee alignment of first new chunk made from this space */
2438 front_misalign = (unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK;
2439 if (front_misalign > 0) {
2440 correction = (MALLOC_ALIGNMENT) - front_misalign;
2441 brk += correction;
2442 } else
2443 correction = 0;
2445 /* Guarantee the next brk will be at a page boundary */
2446 correction += pagesz - ((unsigned long)(brk + sbrk_size) & (pagesz - 1));
2448 /* Allocate correction */
2449 new_brk = (char*)(MORECORE (correction));
2450 if (new_brk == (char*)(MORECORE_FAILURE)) return;
2452 #if defined _LIBC || defined MALLOC_HOOKS
2453 /* Call the `morecore' hook if necessary. */
2454 if (__after_morecore_hook)
2455 (*__after_morecore_hook) ();
2456 #endif
2458 sbrked_mem += correction;
2460 top(&main_arena) = (mchunkptr)brk;
2461 top_size = new_brk - brk + correction;
2462 set_head(top(&main_arena), top_size | PREV_INUSE);
2464 if (old_top == initial_top(&main_arena))
2465 old_top = 0; /* don't free below */
2468 if ((unsigned long)sbrked_mem > (unsigned long)max_sbrked_mem)
2469 max_sbrked_mem = sbrked_mem;
2470 #ifdef NO_THREADS
2471 if ((unsigned long)(mmapped_mem + sbrked_mem) >
2472 (unsigned long)max_total_mem)
2473 max_total_mem = mmapped_mem + sbrked_mem;
2474 #endif
2476 #ifndef NO_THREADS
2477 } else { /* ar_ptr != &main_arena */
2478 heap_info *old_heap, *heap;
2479 size_t old_heap_size;
2481 if(old_top_size < MINSIZE) /* this should never happen */
2482 return;
2484 /* First try to extend the current heap. */
2485 if(MINSIZE + nb <= old_top_size)
2486 return;
2487 old_heap = heap_for_ptr(old_top);
2488 old_heap_size = old_heap->size;
2489 if(grow_heap(old_heap, MINSIZE + nb - old_top_size) == 0) {
2490 ar_ptr->size += old_heap->size - old_heap_size;
2491 top_size = ((char *)old_heap + old_heap->size) - (char *)old_top;
2492 set_head(old_top, top_size | PREV_INUSE);
2493 return;
2496 /* A new heap must be created. */
2497 heap = new_heap(nb + (MINSIZE + sizeof(*heap)));
2498 if(!heap)
2499 return;
2500 heap->ar_ptr = ar_ptr;
2501 heap->prev = old_heap;
2502 ar_ptr->size += heap->size;
2504 /* Set up the new top, so we can safely use chunk_free() below. */
2505 top(ar_ptr) = chunk_at_offset(heap, sizeof(*heap));
2506 top_size = heap->size - sizeof(*heap);
2507 set_head(top(ar_ptr), top_size | PREV_INUSE);
2509 #endif /* !defined(NO_THREADS) */
2511 /* We always land on a page boundary */
2512 assert(((unsigned long)((char*)top(ar_ptr) + top_size) & (pagesz-1)) == 0);
2514 /* Setup fencepost and free the old top chunk. */
2515 if(old_top) {
2516 /* The fencepost takes at least MINSIZE bytes, because it might
2517 become the top chunk again later. Note that a footer is set
2518 up, too, although the chunk is marked in use. */
2519 old_top_size -= MINSIZE;
2520 set_head(chunk_at_offset(old_top, old_top_size + 2*SIZE_SZ), 0|PREV_INUSE);
2521 if(old_top_size >= MINSIZE) {
2522 set_head(chunk_at_offset(old_top, old_top_size), (2*SIZE_SZ)|PREV_INUSE);
2523 set_foot(chunk_at_offset(old_top, old_top_size), (2*SIZE_SZ));
2524 set_head_size(old_top, old_top_size);
2525 chunk_free(ar_ptr, old_top);
2526 } else {
2527 set_head(old_top, (old_top_size + 2*SIZE_SZ)|PREV_INUSE);
2528 set_foot(old_top, (old_top_size + 2*SIZE_SZ));
2536 /* Main public routines */
2540 Malloc Algorithm:
2542 The requested size is first converted into a usable form, `nb'.
2543 This currently means to add 4 bytes overhead plus possibly more to
2544 obtain 8-byte alignment and/or to obtain a size of at least
2545 MINSIZE (currently 16, 24, or 32 bytes), the smallest allocatable
2546 size. (All fits are considered `exact' if they are within MINSIZE
2547 bytes.)
2549 From there, the first successful of the following steps is taken:
2551 1. The bin corresponding to the request size is scanned, and if
2552 a chunk of exactly the right size is found, it is taken.
2554 2. The most recently remaindered chunk is used if it is big
2555 enough. This is a form of (roving) first fit, used only in
2556 the absence of exact fits. Runs of consecutive requests use
2557 the remainder of the chunk used for the previous such request
2558 whenever possible. This limited use of a first-fit style
2559 allocation strategy tends to give contiguous chunks
2560 coextensive lifetimes, which improves locality and can reduce
2561 fragmentation in the long run.
2563 3. Other bins are scanned in increasing size order, using a
2564 chunk big enough to fulfill the request, and splitting off
2565 any remainder. This search is strictly by best-fit; i.e.,
2566 the smallest (with ties going to approximately the least
2567 recently used) chunk that fits is selected.
2569 4. If large enough, the chunk bordering the end of memory
2570 (`top') is split off. (This use of `top' is in accord with
2571 the best-fit search rule. In effect, `top' is treated as
2572 larger (and thus less well fitting) than any other available
2573 chunk since it can be extended to be as large as necessary
2574 (up to system limitations).
2576 5. If the request size meets the mmap threshold and the
2577 system supports mmap, and there are few enough currently
2578 allocated mmapped regions, and a call to mmap succeeds,
2579 the request is allocated via direct memory mapping.
2581 6. Otherwise, the top of memory is extended by
2582 obtaining more space from the system (normally using sbrk,
2583 but definable to anything else via the MORECORE macro).
2584 Memory is gathered from the system (in system page-sized
2585 units) in a way that allows chunks obtained across different
2586 sbrk calls to be consolidated, but does not require
2587 contiguous memory. Thus, it should be safe to intersperse
2588 mallocs with other sbrk calls.
2591 All allocations are made from the `lowest' part of any found
2592 chunk. (The implementation invariant is that prev_inuse is
2593 always true of any allocated chunk; i.e., that each allocated
2594 chunk borders either a previously allocated and still in-use chunk,
2595 or the base of its memory arena.)
2599 #if __STD_C
2600 Void_t* mALLOc(size_t bytes)
2601 #else
2602 Void_t* mALLOc(bytes) size_t bytes;
2603 #endif
2605 arena *ar_ptr;
2606 INTERNAL_SIZE_T nb; /* padded request size */
2607 mchunkptr victim;
2609 #if defined _LIBC || defined MALLOC_HOOKS
2610 if (__malloc_hook != NULL) {
2611 Void_t* result;
2613 #if defined __GNUC__ && __GNUC__ >= 2
2614 result = (*__malloc_hook)(bytes, __builtin_return_address (0));
2615 #else
2616 result = (*__malloc_hook)(bytes, NULL);
2617 #endif
2618 return result;
2620 #endif
2622 nb = request2size(bytes);
2623 arena_get(ar_ptr, nb);
2624 if(!ar_ptr)
2625 return 0;
2626 victim = chunk_alloc(ar_ptr, nb);
2627 (void)mutex_unlock(&ar_ptr->mutex);
2628 if(!victim) {
2629 /* Maybe the failure is due to running out of mmapped areas. */
2630 if(ar_ptr != &main_arena) {
2631 (void)mutex_lock(&main_arena.mutex);
2632 victim = chunk_alloc(&main_arena, nb);
2633 (void)mutex_unlock(&main_arena.mutex);
2635 if(!victim) return 0;
2637 return chunk2mem(victim);
2640 static mchunkptr
2641 internal_function
2642 #if __STD_C
2643 chunk_alloc(arena *ar_ptr, INTERNAL_SIZE_T nb)
2644 #else
2645 chunk_alloc(ar_ptr, nb) arena *ar_ptr; INTERNAL_SIZE_T nb;
2646 #endif
2648 mchunkptr victim; /* inspected/selected chunk */
2649 INTERNAL_SIZE_T victim_size; /* its size */
2650 int idx; /* index for bin traversal */
2651 mbinptr bin; /* associated bin */
2652 mchunkptr remainder; /* remainder from a split */
2653 long remainder_size; /* its size */
2654 int remainder_index; /* its bin index */
2655 unsigned long block; /* block traverser bit */
2656 int startidx; /* first bin of a traversed block */
2657 mchunkptr fwd; /* misc temp for linking */
2658 mchunkptr bck; /* misc temp for linking */
2659 mbinptr q; /* misc temp */
2662 /* Check for exact match in a bin */
2664 if (is_small_request(nb)) /* Faster version for small requests */
2666 idx = smallbin_index(nb);
2668 /* No traversal or size check necessary for small bins. */
2670 q = bin_at(ar_ptr, idx);
2671 victim = last(q);
2673 /* Also scan the next one, since it would have a remainder < MINSIZE */
2674 if (victim == q)
2676 q = next_bin(q);
2677 victim = last(q);
2679 if (victim != q)
2681 victim_size = chunksize(victim);
2682 unlink(victim, bck, fwd);
2683 set_inuse_bit_at_offset(victim, victim_size);
2684 check_malloced_chunk(ar_ptr, victim, nb);
2685 return victim;
2688 idx += 2; /* Set for bin scan below. We've already scanned 2 bins. */
2691 else
2693 idx = bin_index(nb);
2694 bin = bin_at(ar_ptr, idx);
2696 for (victim = last(bin); victim != bin; victim = victim->bk)
2698 victim_size = chunksize(victim);
2699 remainder_size = victim_size - nb;
2701 if (remainder_size >= (long)MINSIZE) /* too big */
2703 --idx; /* adjust to rescan below after checking last remainder */
2704 break;
2707 else if (remainder_size >= 0) /* exact fit */
2709 unlink(victim, bck, fwd);
2710 set_inuse_bit_at_offset(victim, victim_size);
2711 check_malloced_chunk(ar_ptr, victim, nb);
2712 return victim;
2716 ++idx;
2720 /* Try to use the last split-off remainder */
2722 if ( (victim = last_remainder(ar_ptr)->fd) != last_remainder(ar_ptr))
2724 victim_size = chunksize(victim);
2725 remainder_size = victim_size - nb;
2727 if (remainder_size >= (long)MINSIZE) /* re-split */
2729 remainder = chunk_at_offset(victim, nb);
2730 set_head(victim, nb | PREV_INUSE);
2731 link_last_remainder(ar_ptr, remainder);
2732 set_head(remainder, remainder_size | PREV_INUSE);
2733 set_foot(remainder, remainder_size);
2734 check_malloced_chunk(ar_ptr, victim, nb);
2735 return victim;
2738 clear_last_remainder(ar_ptr);
2740 if (remainder_size >= 0) /* exhaust */
2742 set_inuse_bit_at_offset(victim, victim_size);
2743 check_malloced_chunk(ar_ptr, victim, nb);
2744 return victim;
2747 /* Else place in bin */
2749 frontlink(ar_ptr, victim, victim_size, remainder_index, bck, fwd);
2753 If there are any possibly nonempty big-enough blocks,
2754 search for best fitting chunk by scanning bins in blockwidth units.
2757 if ( (block = idx2binblock(idx)) <= binblocks(ar_ptr))
2760 /* Get to the first marked block */
2762 if ( (block & binblocks(ar_ptr)) == 0)
2764 /* force to an even block boundary */
2765 idx = (idx & ~(BINBLOCKWIDTH - 1)) + BINBLOCKWIDTH;
2766 block <<= 1;
2767 while ((block & binblocks(ar_ptr)) == 0)
2769 idx += BINBLOCKWIDTH;
2770 block <<= 1;
2774 /* For each possibly nonempty block ... */
2775 for (;;)
2777 startidx = idx; /* (track incomplete blocks) */
2778 q = bin = bin_at(ar_ptr, idx);
2780 /* For each bin in this block ... */
2783 /* Find and use first big enough chunk ... */
2785 for (victim = last(bin); victim != bin; victim = victim->bk)
2787 victim_size = chunksize(victim);
2788 remainder_size = victim_size - nb;
2790 if (remainder_size >= (long)MINSIZE) /* split */
2792 remainder = chunk_at_offset(victim, nb);
2793 set_head(victim, nb | PREV_INUSE);
2794 unlink(victim, bck, fwd);
2795 link_last_remainder(ar_ptr, remainder);
2796 set_head(remainder, remainder_size | PREV_INUSE);
2797 set_foot(remainder, remainder_size);
2798 check_malloced_chunk(ar_ptr, victim, nb);
2799 return victim;
2802 else if (remainder_size >= 0) /* take */
2804 set_inuse_bit_at_offset(victim, victim_size);
2805 unlink(victim, bck, fwd);
2806 check_malloced_chunk(ar_ptr, victim, nb);
2807 return victim;
2812 bin = next_bin(bin);
2814 } while ((++idx & (BINBLOCKWIDTH - 1)) != 0);
2816 /* Clear out the block bit. */
2818 do /* Possibly backtrack to try to clear a partial block */
2820 if ((startidx & (BINBLOCKWIDTH - 1)) == 0)
2822 binblocks(ar_ptr) &= ~block;
2823 break;
2825 --startidx;
2826 q = prev_bin(q);
2827 } while (first(q) == q);
2829 /* Get to the next possibly nonempty block */
2831 if ( (block <<= 1) <= binblocks(ar_ptr) && (block != 0) )
2833 while ((block & binblocks(ar_ptr)) == 0)
2835 idx += BINBLOCKWIDTH;
2836 block <<= 1;
2839 else
2840 break;
2845 /* Try to use top chunk */
2847 /* Require that there be a remainder, ensuring top always exists */
2848 if ( (remainder_size = chunksize(top(ar_ptr)) - nb) < (long)MINSIZE)
2851 #if HAVE_MMAP
2852 /* If big and would otherwise need to extend, try to use mmap instead */
2853 if ((unsigned long)nb >= (unsigned long)mmap_threshold &&
2854 (victim = mmap_chunk(nb)) != 0)
2855 return victim;
2856 #endif
2858 /* Try to extend */
2859 malloc_extend_top(ar_ptr, nb);
2860 if ((remainder_size = chunksize(top(ar_ptr)) - nb) < (long)MINSIZE)
2861 return 0; /* propagate failure */
2864 victim = top(ar_ptr);
2865 set_head(victim, nb | PREV_INUSE);
2866 top(ar_ptr) = chunk_at_offset(victim, nb);
2867 set_head(top(ar_ptr), remainder_size | PREV_INUSE);
2868 check_malloced_chunk(ar_ptr, victim, nb);
2869 return victim;
2878 free() algorithm :
2880 cases:
2882 1. free(0) has no effect.
2884 2. If the chunk was allocated via mmap, it is released via munmap().
2886 3. If a returned chunk borders the current high end of memory,
2887 it is consolidated into the top, and if the total unused
2888 topmost memory exceeds the trim threshold, malloc_trim is
2889 called.
2891 4. Other chunks are consolidated as they arrive, and
2892 placed in corresponding bins. (This includes the case of
2893 consolidating with the current `last_remainder').
2898 #if __STD_C
2899 void fREe(Void_t* mem)
2900 #else
2901 void fREe(mem) Void_t* mem;
2902 #endif
2904 arena *ar_ptr;
2905 mchunkptr p; /* chunk corresponding to mem */
2907 #if defined _LIBC || defined MALLOC_HOOKS
2908 if (__free_hook != NULL) {
2909 #if defined __GNUC__ && __GNUC__ >= 2
2910 (*__free_hook)(mem, __builtin_return_address (0));
2911 #else
2912 (*__free_hook)(mem, NULL);
2913 #endif
2914 return;
2916 #endif
2918 if (mem == 0) /* free(0) has no effect */
2919 return;
2921 p = mem2chunk(mem);
2923 #if HAVE_MMAP
2924 if (chunk_is_mmapped(p)) /* release mmapped memory. */
2926 munmap_chunk(p);
2927 return;
2929 #endif
2931 ar_ptr = arena_for_ptr(p);
2932 #if THREAD_STATS
2933 if(!mutex_trylock(&ar_ptr->mutex))
2934 ++(ar_ptr->stat_lock_direct);
2935 else {
2936 (void)mutex_lock(&ar_ptr->mutex);
2937 ++(ar_ptr->stat_lock_wait);
2939 #else
2940 (void)mutex_lock(&ar_ptr->mutex);
2941 #endif
2942 chunk_free(ar_ptr, p);
2943 (void)mutex_unlock(&ar_ptr->mutex);
2946 static void
2947 internal_function
2948 #if __STD_C
2949 chunk_free(arena *ar_ptr, mchunkptr p)
2950 #else
2951 chunk_free(ar_ptr, p) arena *ar_ptr; mchunkptr p;
2952 #endif
2954 INTERNAL_SIZE_T hd = p->size; /* its head field */
2955 INTERNAL_SIZE_T sz; /* its size */
2956 int idx; /* its bin index */
2957 mchunkptr next; /* next contiguous chunk */
2958 INTERNAL_SIZE_T nextsz; /* its size */
2959 INTERNAL_SIZE_T prevsz; /* size of previous contiguous chunk */
2960 mchunkptr bck; /* misc temp for linking */
2961 mchunkptr fwd; /* misc temp for linking */
2962 int islr; /* track whether merging with last_remainder */
2964 check_inuse_chunk(ar_ptr, p);
2966 sz = hd & ~PREV_INUSE;
2967 next = chunk_at_offset(p, sz);
2968 nextsz = chunksize(next);
2970 if (next == top(ar_ptr)) /* merge with top */
2972 sz += nextsz;
2974 if (!(hd & PREV_INUSE)) /* consolidate backward */
2976 prevsz = p->prev_size;
2977 p = chunk_at_offset(p, -prevsz);
2978 sz += prevsz;
2979 unlink(p, bck, fwd);
2982 set_head(p, sz | PREV_INUSE);
2983 top(ar_ptr) = p;
2985 #ifndef NO_THREADS
2986 if(ar_ptr == &main_arena) {
2987 #endif
2988 if ((unsigned long)(sz) >= (unsigned long)trim_threshold)
2989 main_trim(top_pad);
2990 #ifndef NO_THREADS
2991 } else {
2992 heap_info *heap = heap_for_ptr(p);
2994 assert(heap->ar_ptr == ar_ptr);
2996 /* Try to get rid of completely empty heaps, if possible. */
2997 if((unsigned long)(sz) >= (unsigned long)trim_threshold ||
2998 p == chunk_at_offset(heap, sizeof(*heap)))
2999 heap_trim(heap, top_pad);
3001 #endif
3002 return;
3005 islr = 0;
3007 if (!(hd & PREV_INUSE)) /* consolidate backward */
3009 prevsz = p->prev_size;
3010 p = chunk_at_offset(p, -prevsz);
3011 sz += prevsz;
3013 if (p->fd == last_remainder(ar_ptr)) /* keep as last_remainder */
3014 islr = 1;
3015 else
3016 unlink(p, bck, fwd);
3019 if (!(inuse_bit_at_offset(next, nextsz))) /* consolidate forward */
3021 sz += nextsz;
3023 if (!islr && next->fd == last_remainder(ar_ptr))
3024 /* re-insert last_remainder */
3026 islr = 1;
3027 link_last_remainder(ar_ptr, p);
3029 else
3030 unlink(next, bck, fwd);
3032 next = chunk_at_offset(p, sz);
3034 else
3035 set_head(next, nextsz); /* clear inuse bit */
3037 set_head(p, sz | PREV_INUSE);
3038 next->prev_size = sz;
3039 if (!islr)
3040 frontlink(ar_ptr, p, sz, idx, bck, fwd);
3042 #ifndef NO_THREADS
3043 /* Check whether the heap containing top can go away now. */
3044 if(next->size < MINSIZE &&
3045 (unsigned long)sz > trim_threshold &&
3046 ar_ptr != &main_arena) { /* fencepost */
3047 heap_info *heap = heap_for_ptr(top(ar_ptr));
3049 if(top(ar_ptr) == chunk_at_offset(heap, sizeof(*heap)) &&
3050 heap->prev == heap_for_ptr(p))
3051 heap_trim(heap, top_pad);
3053 #endif
3062 Realloc algorithm:
3064 Chunks that were obtained via mmap cannot be extended or shrunk
3065 unless HAVE_MREMAP is defined, in which case mremap is used.
3066 Otherwise, if their reallocation is for additional space, they are
3067 copied. If for less, they are just left alone.
3069 Otherwise, if the reallocation is for additional space, and the
3070 chunk can be extended, it is, else a malloc-copy-free sequence is
3071 taken. There are several different ways that a chunk could be
3072 extended. All are tried:
3074 * Extending forward into following adjacent free chunk.
3075 * Shifting backwards, joining preceding adjacent space
3076 * Both shifting backwards and extending forward.
3077 * Extending into newly sbrked space
3079 Unless the #define REALLOC_ZERO_BYTES_FREES is set, realloc with a
3080 size argument of zero (re)allocates a minimum-sized chunk.
3082 If the reallocation is for less space, and the new request is for
3083 a `small' (<512 bytes) size, then the newly unused space is lopped
3084 off and freed.
3086 The old unix realloc convention of allowing the last-free'd chunk
3087 to be used as an argument to realloc is no longer supported.
3088 I don't know of any programs still relying on this feature,
3089 and allowing it would also allow too many other incorrect
3090 usages of realloc to be sensible.
3096 #if __STD_C
3097 Void_t* rEALLOc(Void_t* oldmem, size_t bytes)
3098 #else
3099 Void_t* rEALLOc(oldmem, bytes) Void_t* oldmem; size_t bytes;
3100 #endif
3102 arena *ar_ptr;
3103 INTERNAL_SIZE_T nb; /* padded request size */
3105 mchunkptr oldp; /* chunk corresponding to oldmem */
3106 INTERNAL_SIZE_T oldsize; /* its size */
3108 mchunkptr newp; /* chunk to return */
3110 #if defined _LIBC || defined MALLOC_HOOKS
3111 if (__realloc_hook != NULL) {
3112 Void_t* result;
3114 #if defined __GNUC__ && __GNUC__ >= 2
3115 result = (*__realloc_hook)(oldmem, bytes, __builtin_return_address (0));
3116 #else
3117 result = (*__realloc_hook)(oldmem, bytes, NULL);
3118 #endif
3119 return result;
3121 #endif
3123 #ifdef REALLOC_ZERO_BYTES_FREES
3124 if (bytes == 0 && oldmem != NULL) { fREe(oldmem); return 0; }
3125 #endif
3127 /* realloc of null is supposed to be same as malloc */
3128 if (oldmem == 0) return mALLOc(bytes);
3130 oldp = mem2chunk(oldmem);
3131 oldsize = chunksize(oldp);
3133 nb = request2size(bytes);
3135 #if HAVE_MMAP
3136 if (chunk_is_mmapped(oldp))
3138 Void_t* newmem;
3140 #if HAVE_MREMAP
3141 newp = mremap_chunk(oldp, nb);
3142 if(newp) return chunk2mem(newp);
3143 #endif
3144 /* Note the extra SIZE_SZ overhead. */
3145 if(oldsize - SIZE_SZ >= nb) return oldmem; /* do nothing */
3146 /* Must alloc, copy, free. */
3147 newmem = mALLOc(bytes);
3148 if (newmem == 0) return 0; /* propagate failure */
3149 MALLOC_COPY(newmem, oldmem, oldsize - 2*SIZE_SZ);
3150 munmap_chunk(oldp);
3151 return newmem;
3153 #endif
3155 ar_ptr = arena_for_ptr(oldp);
3156 #if THREAD_STATS
3157 if(!mutex_trylock(&ar_ptr->mutex))
3158 ++(ar_ptr->stat_lock_direct);
3159 else {
3160 (void)mutex_lock(&ar_ptr->mutex);
3161 ++(ar_ptr->stat_lock_wait);
3163 #else
3164 (void)mutex_lock(&ar_ptr->mutex);
3165 #endif
3167 #ifndef NO_THREADS
3168 /* As in malloc(), remember this arena for the next allocation. */
3169 tsd_setspecific(arena_key, (Void_t *)ar_ptr);
3170 #endif
3172 newp = chunk_realloc(ar_ptr, oldp, oldsize, nb);
3174 (void)mutex_unlock(&ar_ptr->mutex);
3175 return newp ? chunk2mem(newp) : NULL;
3178 static mchunkptr
3179 internal_function
3180 #if __STD_C
3181 chunk_realloc(arena* ar_ptr, mchunkptr oldp, INTERNAL_SIZE_T oldsize,
3182 INTERNAL_SIZE_T nb)
3183 #else
3184 chunk_realloc(ar_ptr, oldp, oldsize, nb)
3185 arena* ar_ptr; mchunkptr oldp; INTERNAL_SIZE_T oldsize, nb;
3186 #endif
3188 mchunkptr newp = oldp; /* chunk to return */
3189 INTERNAL_SIZE_T newsize = oldsize; /* its size */
3191 mchunkptr next; /* next contiguous chunk after oldp */
3192 INTERNAL_SIZE_T nextsize; /* its size */
3194 mchunkptr prev; /* previous contiguous chunk before oldp */
3195 INTERNAL_SIZE_T prevsize; /* its size */
3197 mchunkptr remainder; /* holds split off extra space from newp */
3198 INTERNAL_SIZE_T remainder_size; /* its size */
3200 mchunkptr bck; /* misc temp for linking */
3201 mchunkptr fwd; /* misc temp for linking */
3203 check_inuse_chunk(ar_ptr, oldp);
3205 if ((long)(oldsize) < (long)(nb))
3208 /* Try expanding forward */
3210 next = chunk_at_offset(oldp, oldsize);
3211 if (next == top(ar_ptr) || !inuse(next))
3213 nextsize = chunksize(next);
3215 /* Forward into top only if a remainder */
3216 if (next == top(ar_ptr))
3218 if ((long)(nextsize + newsize) >= (long)(nb + MINSIZE))
3220 newsize += nextsize;
3221 top(ar_ptr) = chunk_at_offset(oldp, nb);
3222 set_head(top(ar_ptr), (newsize - nb) | PREV_INUSE);
3223 set_head_size(oldp, nb);
3224 return oldp;
3228 /* Forward into next chunk */
3229 else if (((long)(nextsize + newsize) >= (long)(nb)))
3231 unlink(next, bck, fwd);
3232 newsize += nextsize;
3233 goto split;
3236 else
3238 next = 0;
3239 nextsize = 0;
3242 /* Try shifting backwards. */
3244 if (!prev_inuse(oldp))
3246 prev = prev_chunk(oldp);
3247 prevsize = chunksize(prev);
3249 /* try forward + backward first to save a later consolidation */
3251 if (next != 0)
3253 /* into top */
3254 if (next == top(ar_ptr))
3256 if ((long)(nextsize + prevsize + newsize) >= (long)(nb + MINSIZE))
3258 unlink(prev, bck, fwd);
3259 newp = prev;
3260 newsize += prevsize + nextsize;
3261 MALLOC_COPY(chunk2mem(newp), chunk2mem(oldp), oldsize - SIZE_SZ);
3262 top(ar_ptr) = chunk_at_offset(newp, nb);
3263 set_head(top(ar_ptr), (newsize - nb) | PREV_INUSE);
3264 set_head_size(newp, nb);
3265 return newp;
3269 /* into next chunk */
3270 else if (((long)(nextsize + prevsize + newsize) >= (long)(nb)))
3272 unlink(next, bck, fwd);
3273 unlink(prev, bck, fwd);
3274 newp = prev;
3275 newsize += nextsize + prevsize;
3276 MALLOC_COPY(chunk2mem(newp), chunk2mem(oldp), oldsize - SIZE_SZ);
3277 goto split;
3281 /* backward only */
3282 if (prev != 0 && (long)(prevsize + newsize) >= (long)nb)
3284 unlink(prev, bck, fwd);
3285 newp = prev;
3286 newsize += prevsize;
3287 MALLOC_COPY(chunk2mem(newp), chunk2mem(oldp), oldsize - SIZE_SZ);
3288 goto split;
3292 /* Must allocate */
3294 newp = chunk_alloc (ar_ptr, nb);
3296 if (newp == 0) {
3297 /* Maybe the failure is due to running out of mmapped areas. */
3298 if (ar_ptr != &main_arena) {
3299 (void)mutex_lock(&main_arena.mutex);
3300 newp = chunk_alloc(&main_arena, nb);
3301 (void)mutex_unlock(&main_arena.mutex);
3303 if (newp == 0) /* propagate failure */
3304 return 0;
3307 /* Avoid copy if newp is next chunk after oldp. */
3308 /* (This can only happen when new chunk is sbrk'ed.) */
3310 if ( newp == next_chunk(oldp))
3312 newsize += chunksize(newp);
3313 newp = oldp;
3314 goto split;
3317 /* Otherwise copy, free, and exit */
3318 MALLOC_COPY(chunk2mem(newp), chunk2mem(oldp), oldsize - SIZE_SZ);
3319 chunk_free(ar_ptr, oldp);
3320 return newp;
3324 split: /* split off extra room in old or expanded chunk */
3326 if (newsize - nb >= MINSIZE) /* split off remainder */
3328 remainder = chunk_at_offset(newp, nb);
3329 remainder_size = newsize - nb;
3330 set_head_size(newp, nb);
3331 set_head(remainder, remainder_size | PREV_INUSE);
3332 set_inuse_bit_at_offset(remainder, remainder_size);
3333 chunk_free(ar_ptr, remainder);
3335 else
3337 set_head_size(newp, newsize);
3338 set_inuse_bit_at_offset(newp, newsize);
3341 check_inuse_chunk(ar_ptr, newp);
3342 return newp;
3350 memalign algorithm:
3352 memalign requests more than enough space from malloc, finds a spot
3353 within that chunk that meets the alignment request, and then
3354 possibly frees the leading and trailing space.
3356 The alignment argument must be a power of two. This property is not
3357 checked by memalign, so misuse may result in random runtime errors.
3359 8-byte alignment is guaranteed by normal malloc calls, so don't
3360 bother calling memalign with an argument of 8 or less.
3362 Overreliance on memalign is a sure way to fragment space.
3367 #if __STD_C
3368 Void_t* mEMALIGn(size_t alignment, size_t bytes)
3369 #else
3370 Void_t* mEMALIGn(alignment, bytes) size_t alignment; size_t bytes;
3371 #endif
3373 arena *ar_ptr;
3374 INTERNAL_SIZE_T nb; /* padded request size */
3375 mchunkptr p;
3377 #if defined _LIBC || defined MALLOC_HOOKS
3378 if (__memalign_hook != NULL) {
3379 Void_t* result;
3381 #if defined __GNUC__ && __GNUC__ >= 2
3382 result = (*__memalign_hook)(alignment, bytes,
3383 __builtin_return_address (0));
3384 #else
3385 result = (*__memalign_hook)(alignment, bytes, NULL);
3386 #endif
3387 return result;
3389 #endif
3391 /* If need less alignment than we give anyway, just relay to malloc */
3393 if (alignment <= MALLOC_ALIGNMENT) return mALLOc(bytes);
3395 /* Otherwise, ensure that it is at least a minimum chunk size */
3397 if (alignment < MINSIZE) alignment = MINSIZE;
3399 nb = request2size(bytes);
3400 arena_get(ar_ptr, nb + alignment + MINSIZE);
3401 if(!ar_ptr)
3402 return 0;
3403 p = chunk_align(ar_ptr, nb, alignment);
3404 (void)mutex_unlock(&ar_ptr->mutex);
3405 if(!p) {
3406 /* Maybe the failure is due to running out of mmapped areas. */
3407 if(ar_ptr != &main_arena) {
3408 (void)mutex_lock(&main_arena.mutex);
3409 p = chunk_align(&main_arena, nb, alignment);
3410 (void)mutex_unlock(&main_arena.mutex);
3412 if(!p) return 0;
3414 return chunk2mem(p);
3417 static mchunkptr
3418 internal_function
3419 #if __STD_C
3420 chunk_align(arena* ar_ptr, INTERNAL_SIZE_T nb, size_t alignment)
3421 #else
3422 chunk_align(ar_ptr, nb, alignment)
3423 arena* ar_ptr; INTERNAL_SIZE_T nb; size_t alignment;
3424 #endif
3426 char* m; /* memory returned by malloc call */
3427 mchunkptr p; /* corresponding chunk */
3428 char* brk; /* alignment point within p */
3429 mchunkptr newp; /* chunk to return */
3430 INTERNAL_SIZE_T newsize; /* its size */
3431 INTERNAL_SIZE_T leadsize; /* leading space befor alignment point */
3432 mchunkptr remainder; /* spare room at end to split off */
3433 long remainder_size; /* its size */
3435 /* Call chunk_alloc with worst case padding to hit alignment. */
3436 p = chunk_alloc(ar_ptr, nb + alignment + MINSIZE);
3437 if (p == 0)
3438 return 0; /* propagate failure */
3440 m = chunk2mem(p);
3442 if ((((unsigned long)(m)) % alignment) == 0) /* aligned */
3444 #if HAVE_MMAP
3445 if(chunk_is_mmapped(p)) {
3446 return p; /* nothing more to do */
3448 #endif
3450 else /* misaligned */
3453 Find an aligned spot inside chunk.
3454 Since we need to give back leading space in a chunk of at
3455 least MINSIZE, if the first calculation places us at
3456 a spot with less than MINSIZE leader, we can move to the
3457 next aligned spot -- we've allocated enough total room so that
3458 this is always possible.
3461 brk = (char*)mem2chunk(((unsigned long)(m + alignment - 1)) & -alignment);
3462 if ((long)(brk - (char*)(p)) < (long)MINSIZE) brk += alignment;
3464 newp = (mchunkptr)brk;
3465 leadsize = brk - (char*)(p);
3466 newsize = chunksize(p) - leadsize;
3468 #if HAVE_MMAP
3469 if(chunk_is_mmapped(p))
3471 newp->prev_size = p->prev_size + leadsize;
3472 set_head(newp, newsize|IS_MMAPPED);
3473 return newp;
3475 #endif
3477 /* give back leader, use the rest */
3479 set_head(newp, newsize | PREV_INUSE);
3480 set_inuse_bit_at_offset(newp, newsize);
3481 set_head_size(p, leadsize);
3482 chunk_free(ar_ptr, p);
3483 p = newp;
3485 assert (newsize>=nb && (((unsigned long)(chunk2mem(p))) % alignment) == 0);
3488 /* Also give back spare room at the end */
3490 remainder_size = chunksize(p) - nb;
3492 if (remainder_size >= (long)MINSIZE)
3494 remainder = chunk_at_offset(p, nb);
3495 set_head(remainder, remainder_size | PREV_INUSE);
3496 set_head_size(p, nb);
3497 chunk_free(ar_ptr, remainder);
3500 check_inuse_chunk(ar_ptr, p);
3501 return p;
3508 valloc just invokes memalign with alignment argument equal
3509 to the page size of the system (or as near to this as can
3510 be figured out from all the includes/defines above.)
3513 #if __STD_C
3514 Void_t* vALLOc(size_t bytes)
3515 #else
3516 Void_t* vALLOc(bytes) size_t bytes;
3517 #endif
3519 return mEMALIGn (malloc_getpagesize, bytes);
3523 pvalloc just invokes valloc for the nearest pagesize
3524 that will accommodate request
3528 #if __STD_C
3529 Void_t* pvALLOc(size_t bytes)
3530 #else
3531 Void_t* pvALLOc(bytes) size_t bytes;
3532 #endif
3534 size_t pagesize = malloc_getpagesize;
3535 return mEMALIGn (pagesize, (bytes + pagesize - 1) & ~(pagesize - 1));
3540 calloc calls chunk_alloc, then zeroes out the allocated chunk.
3544 #if __STD_C
3545 Void_t* cALLOc(size_t n, size_t elem_size)
3546 #else
3547 Void_t* cALLOc(n, elem_size) size_t n; size_t elem_size;
3548 #endif
3550 arena *ar_ptr;
3551 mchunkptr p, oldtop;
3552 INTERNAL_SIZE_T sz, csz, oldtopsize;
3553 Void_t* mem;
3555 #if defined _LIBC || defined MALLOC_HOOKS
3556 if (__malloc_hook != NULL) {
3557 sz = n * elem_size;
3558 #if defined __GNUC__ && __GNUC__ >= 2
3559 mem = (*__malloc_hook)(sz, __builtin_return_address (0));
3560 #else
3561 mem = (*__malloc_hook)(sz, NULL);
3562 #endif
3563 if(mem == 0)
3564 return 0;
3565 #ifdef HAVE_MEMSET
3566 return memset(mem, 0, sz);
3567 #else
3568 while(sz > 0) ((char*)mem)[--sz] = 0; /* rather inefficient */
3569 return mem;
3570 #endif
3572 #endif
3574 sz = request2size(n * elem_size);
3575 arena_get(ar_ptr, sz);
3576 if(!ar_ptr)
3577 return 0;
3579 /* check if expand_top called, in which case don't need to clear */
3580 #if MORECORE_CLEARS
3581 oldtop = top(ar_ptr);
3582 oldtopsize = chunksize(top(ar_ptr));
3583 #endif
3584 p = chunk_alloc (ar_ptr, sz);
3586 /* Only clearing follows, so we can unlock early. */
3587 (void)mutex_unlock(&ar_ptr->mutex);
3589 if (p == 0) {
3590 /* Maybe the failure is due to running out of mmapped areas. */
3591 if(ar_ptr != &main_arena) {
3592 (void)mutex_lock(&main_arena.mutex);
3593 p = chunk_alloc(&main_arena, sz);
3594 (void)mutex_unlock(&main_arena.mutex);
3596 if (p == 0) return 0;
3598 mem = chunk2mem(p);
3600 /* Two optional cases in which clearing not necessary */
3602 #if HAVE_MMAP
3603 if (chunk_is_mmapped(p)) return mem;
3604 #endif
3606 csz = chunksize(p);
3608 #if MORECORE_CLEARS
3609 if (p == oldtop && csz > oldtopsize) {
3610 /* clear only the bytes from non-freshly-sbrked memory */
3611 csz = oldtopsize;
3613 #endif
3615 MALLOC_ZERO(mem, csz - SIZE_SZ);
3616 return mem;
3621 cfree just calls free. It is needed/defined on some systems
3622 that pair it with calloc, presumably for odd historical reasons.
3626 #if !defined(_LIBC)
3627 #if __STD_C
3628 void cfree(Void_t *mem)
3629 #else
3630 void cfree(mem) Void_t *mem;
3631 #endif
3633 free(mem);
3635 #endif
3641 Malloc_trim gives memory back to the system (via negative
3642 arguments to sbrk) if there is unused memory at the `high' end of
3643 the malloc pool. You can call this after freeing large blocks of
3644 memory to potentially reduce the system-level memory requirements
3645 of a program. However, it cannot guarantee to reduce memory. Under
3646 some allocation patterns, some large free blocks of memory will be
3647 locked between two used chunks, so they cannot be given back to
3648 the system.
3650 The `pad' argument to malloc_trim represents the amount of free
3651 trailing space to leave untrimmed. If this argument is zero,
3652 only the minimum amount of memory to maintain internal data
3653 structures will be left (one page or less). Non-zero arguments
3654 can be supplied to maintain enough trailing space to service
3655 future expected allocations without having to re-obtain memory
3656 from the system.
3658 Malloc_trim returns 1 if it actually released any memory, else 0.
3662 #if __STD_C
3663 int mALLOC_TRIm(size_t pad)
3664 #else
3665 int mALLOC_TRIm(pad) size_t pad;
3666 #endif
3668 int res;
3670 (void)mutex_lock(&main_arena.mutex);
3671 res = main_trim(pad);
3672 (void)mutex_unlock(&main_arena.mutex);
3673 return res;
3676 /* Trim the main arena. */
3678 static int
3679 internal_function
3680 #if __STD_C
3681 main_trim(size_t pad)
3682 #else
3683 main_trim(pad) size_t pad;
3684 #endif
3686 mchunkptr top_chunk; /* The current top chunk */
3687 long top_size; /* Amount of top-most memory */
3688 long extra; /* Amount to release */
3689 char* current_brk; /* address returned by pre-check sbrk call */
3690 char* new_brk; /* address returned by negative sbrk call */
3692 unsigned long pagesz = malloc_getpagesize;
3694 top_chunk = top(&main_arena);
3695 top_size = chunksize(top_chunk);
3696 extra = ((top_size - pad - MINSIZE + (pagesz-1)) / pagesz - 1) * pagesz;
3698 if (extra < (long)pagesz) /* Not enough memory to release */
3699 return 0;
3701 /* Test to make sure no one else called sbrk */
3702 current_brk = (char*)(MORECORE (0));
3703 if (current_brk != (char*)(top_chunk) + top_size)
3704 return 0; /* Apparently we don't own memory; must fail */
3706 new_brk = (char*)(MORECORE (-extra));
3708 #if defined _LIBC || defined MALLOC_HOOKS
3709 /* Call the `morecore' hook if necessary. */
3710 if (__after_morecore_hook)
3711 (*__after_morecore_hook) ();
3712 #endif
3714 if (new_brk == (char*)(MORECORE_FAILURE)) { /* sbrk failed? */
3715 /* Try to figure out what we have */
3716 current_brk = (char*)(MORECORE (0));
3717 top_size = current_brk - (char*)top_chunk;
3718 if (top_size >= (long)MINSIZE) /* if not, we are very very dead! */
3720 sbrked_mem = current_brk - sbrk_base;
3721 set_head(top_chunk, top_size | PREV_INUSE);
3723 check_chunk(&main_arena, top_chunk);
3724 return 0;
3726 sbrked_mem -= extra;
3728 /* Success. Adjust top accordingly. */
3729 set_head(top_chunk, (top_size - extra) | PREV_INUSE);
3730 check_chunk(&main_arena, top_chunk);
3731 return 1;
3734 #ifndef NO_THREADS
3736 static int
3737 internal_function
3738 #if __STD_C
3739 heap_trim(heap_info *heap, size_t pad)
3740 #else
3741 heap_trim(heap, pad) heap_info *heap; size_t pad;
3742 #endif
3744 unsigned long pagesz = malloc_getpagesize;
3745 arena *ar_ptr = heap->ar_ptr;
3746 mchunkptr top_chunk = top(ar_ptr), p, bck, fwd;
3747 heap_info *prev_heap;
3748 long new_size, top_size, extra;
3750 /* Can this heap go away completely ? */
3751 while(top_chunk == chunk_at_offset(heap, sizeof(*heap))) {
3752 prev_heap = heap->prev;
3753 p = chunk_at_offset(prev_heap, prev_heap->size - (MINSIZE-2*SIZE_SZ));
3754 assert(p->size == (0|PREV_INUSE)); /* must be fencepost */
3755 p = prev_chunk(p);
3756 new_size = chunksize(p) + (MINSIZE-2*SIZE_SZ);
3757 assert(new_size>0 && new_size<(long)(2*MINSIZE));
3758 if(!prev_inuse(p))
3759 new_size += p->prev_size;
3760 assert(new_size>0 && new_size<HEAP_MAX_SIZE);
3761 if(new_size + (HEAP_MAX_SIZE - prev_heap->size) < pad + MINSIZE + pagesz)
3762 break;
3763 ar_ptr->size -= heap->size;
3764 delete_heap(heap);
3765 heap = prev_heap;
3766 if(!prev_inuse(p)) { /* consolidate backward */
3767 p = prev_chunk(p);
3768 unlink(p, bck, fwd);
3770 assert(((unsigned long)((char*)p + new_size) & (pagesz-1)) == 0);
3771 assert( ((char*)p + new_size) == ((char*)heap + heap->size) );
3772 top(ar_ptr) = top_chunk = p;
3773 set_head(top_chunk, new_size | PREV_INUSE);
3774 check_chunk(ar_ptr, top_chunk);
3776 top_size = chunksize(top_chunk);
3777 extra = ((top_size - pad - MINSIZE + (pagesz-1))/pagesz - 1) * pagesz;
3778 if(extra < (long)pagesz)
3779 return 0;
3780 /* Try to shrink. */
3781 if(grow_heap(heap, -extra) != 0)
3782 return 0;
3783 ar_ptr->size -= extra;
3785 /* Success. Adjust top accordingly. */
3786 set_head(top_chunk, (top_size - extra) | PREV_INUSE);
3787 check_chunk(ar_ptr, top_chunk);
3788 return 1;
3791 #endif
3796 malloc_usable_size:
3798 This routine tells you how many bytes you can actually use in an
3799 allocated chunk, which may be more than you requested (although
3800 often not). You can use this many bytes without worrying about
3801 overwriting other allocated objects. Not a particularly great
3802 programming practice, but still sometimes useful.
3806 #if __STD_C
3807 size_t mALLOC_USABLE_SIZe(Void_t* mem)
3808 #else
3809 size_t mALLOC_USABLE_SIZe(mem) Void_t* mem;
3810 #endif
3812 mchunkptr p;
3814 if (mem == 0)
3815 return 0;
3816 else
3818 p = mem2chunk(mem);
3819 if(!chunk_is_mmapped(p))
3821 if (!inuse(p)) return 0;
3822 check_inuse_chunk(arena_for_ptr(mem), p);
3823 return chunksize(p) - SIZE_SZ;
3825 return chunksize(p) - 2*SIZE_SZ;
3832 /* Utility to update mallinfo for malloc_stats() and mallinfo() */
3834 static void
3835 #if __STD_C
3836 malloc_update_mallinfo(arena *ar_ptr, struct mallinfo *mi)
3837 #else
3838 malloc_update_mallinfo(ar_ptr, mi) arena *ar_ptr; struct mallinfo *mi;
3839 #endif
3841 int i, navail;
3842 mbinptr b;
3843 mchunkptr p;
3844 #if MALLOC_DEBUG
3845 mchunkptr q;
3846 #endif
3847 INTERNAL_SIZE_T avail;
3849 (void)mutex_lock(&ar_ptr->mutex);
3850 avail = chunksize(top(ar_ptr));
3851 navail = ((long)(avail) >= (long)MINSIZE)? 1 : 0;
3853 for (i = 1; i < NAV; ++i)
3855 b = bin_at(ar_ptr, i);
3856 for (p = last(b); p != b; p = p->bk)
3858 #if MALLOC_DEBUG
3859 check_free_chunk(ar_ptr, p);
3860 for (q = next_chunk(p);
3861 q != top(ar_ptr) && inuse(q) && (long)chunksize(q) > 0;
3862 q = next_chunk(q))
3863 check_inuse_chunk(ar_ptr, q);
3864 #endif
3865 avail += chunksize(p);
3866 navail++;
3870 mi->arena = ar_ptr->size;
3871 mi->ordblks = navail;
3872 mi->smblks = mi->usmblks = mi->fsmblks = 0; /* clear unused fields */
3873 mi->uordblks = ar_ptr->size - avail;
3874 mi->fordblks = avail;
3875 mi->hblks = n_mmaps;
3876 mi->hblkhd = mmapped_mem;
3877 mi->keepcost = chunksize(top(ar_ptr));
3879 (void)mutex_unlock(&ar_ptr->mutex);
3882 #if !defined(NO_THREADS) && MALLOC_DEBUG > 1
3884 /* Print the complete contents of a single heap to stderr. */
3886 static void
3887 #if __STD_C
3888 dump_heap(heap_info *heap)
3889 #else
3890 dump_heap(heap) heap_info *heap;
3891 #endif
3893 char *ptr;
3894 mchunkptr p;
3896 fprintf(stderr, "Heap %p, size %10lx:\n", heap, (long)heap->size);
3897 ptr = (heap->ar_ptr != (arena*)(heap+1)) ?
3898 (char*)(heap + 1) : (char*)(heap + 1) + sizeof(arena);
3899 p = (mchunkptr)(((unsigned long)ptr + MALLOC_ALIGN_MASK) &
3900 ~MALLOC_ALIGN_MASK);
3901 for(;;) {
3902 fprintf(stderr, "chunk %p size %10lx", p, (long)p->size);
3903 if(p == top(heap->ar_ptr)) {
3904 fprintf(stderr, " (top)\n");
3905 break;
3906 } else if(p->size == (0|PREV_INUSE)) {
3907 fprintf(stderr, " (fence)\n");
3908 break;
3910 fprintf(stderr, "\n");
3911 p = next_chunk(p);
3915 #endif
3921 malloc_stats:
3923 For all arenas separately and in total, prints on stderr the
3924 amount of space obtained from the system, and the current number
3925 of bytes allocated via malloc (or realloc, etc) but not yet
3926 freed. (Note that this is the number of bytes allocated, not the
3927 number requested. It will be larger than the number requested
3928 because of alignment and bookkeeping overhead.) When not compiled
3929 for multiple threads, the maximum amount of allocated memory
3930 (which may be more than current if malloc_trim and/or munmap got
3931 called) is also reported. When using mmap(), prints the maximum
3932 number of simultaneous mmap regions used, too.
3936 void mALLOC_STATs()
3938 int i;
3939 arena *ar_ptr;
3940 struct mallinfo mi;
3941 unsigned int in_use_b = mmapped_mem, system_b = in_use_b;
3942 #if THREAD_STATS
3943 long stat_lock_direct = 0, stat_lock_loop = 0, stat_lock_wait = 0;
3944 #endif
3946 for(i=0, ar_ptr = &main_arena;; i++) {
3947 malloc_update_mallinfo(ar_ptr, &mi);
3948 fprintf(stderr, "Arena %d:\n", i);
3949 fprintf(stderr, "system bytes = %10u\n", (unsigned int)mi.arena);
3950 fprintf(stderr, "in use bytes = %10u\n", (unsigned int)mi.uordblks);
3951 system_b += mi.arena;
3952 in_use_b += mi.uordblks;
3953 #if THREAD_STATS
3954 stat_lock_direct += ar_ptr->stat_lock_direct;
3955 stat_lock_loop += ar_ptr->stat_lock_loop;
3956 stat_lock_wait += ar_ptr->stat_lock_wait;
3957 #endif
3958 #if !defined(NO_THREADS) && MALLOC_DEBUG > 1
3959 if(ar_ptr != &main_arena) {
3960 heap_info *heap;
3961 (void)mutex_lock(&ar_ptr->mutex);
3962 heap = heap_for_ptr(top(ar_ptr));
3963 while(heap) { dump_heap(heap); heap = heap->prev; }
3964 (void)mutex_unlock(&ar_ptr->mutex);
3966 #endif
3967 ar_ptr = ar_ptr->next;
3968 if(ar_ptr == &main_arena) break;
3970 #if HAVE_MMAP
3971 fprintf(stderr, "Total (incl. mmap):\n");
3972 #else
3973 fprintf(stderr, "Total:\n");
3974 #endif
3975 fprintf(stderr, "system bytes = %10u\n", system_b);
3976 fprintf(stderr, "in use bytes = %10u\n", in_use_b);
3977 #ifdef NO_THREADS
3978 fprintf(stderr, "max system bytes = %10u\n", (unsigned int)max_total_mem);
3979 #endif
3980 #if HAVE_MMAP
3981 fprintf(stderr, "max mmap regions = %10u\n", (unsigned int)max_n_mmaps);
3982 fprintf(stderr, "max mmap bytes = %10lu\n", max_mmapped_mem);
3983 #endif
3984 #if THREAD_STATS
3985 fprintf(stderr, "heaps created = %10d\n", stat_n_heaps);
3986 fprintf(stderr, "locked directly = %10ld\n", stat_lock_direct);
3987 fprintf(stderr, "locked in loop = %10ld\n", stat_lock_loop);
3988 fprintf(stderr, "locked waiting = %10ld\n", stat_lock_wait);
3989 fprintf(stderr, "locked total = %10ld\n",
3990 stat_lock_direct + stat_lock_loop + stat_lock_wait);
3991 #endif
3995 mallinfo returns a copy of updated current mallinfo.
3996 The information reported is for the arena last used by the thread.
3999 struct mallinfo mALLINFo()
4001 struct mallinfo mi;
4002 Void_t *vptr = NULL;
4004 #ifndef NO_THREADS
4005 tsd_getspecific(arena_key, vptr);
4006 #endif
4007 malloc_update_mallinfo((vptr ? (arena*)vptr : &main_arena), &mi);
4008 return mi;
4015 mallopt:
4017 mallopt is the general SVID/XPG interface to tunable parameters.
4018 The format is to provide a (parameter-number, parameter-value) pair.
4019 mallopt then sets the corresponding parameter to the argument
4020 value if it can (i.e., so long as the value is meaningful),
4021 and returns 1 if successful else 0.
4023 See descriptions of tunable parameters above.
4027 #if __STD_C
4028 int mALLOPt(int param_number, int value)
4029 #else
4030 int mALLOPt(param_number, value) int param_number; int value;
4031 #endif
4033 switch(param_number)
4035 case M_TRIM_THRESHOLD:
4036 trim_threshold = value; return 1;
4037 case M_TOP_PAD:
4038 top_pad = value; return 1;
4039 case M_MMAP_THRESHOLD:
4040 #ifndef NO_THREADS
4041 /* Forbid setting the threshold too high. */
4042 if((unsigned long)value > HEAP_MAX_SIZE/2) return 0;
4043 #endif
4044 mmap_threshold = value; return 1;
4045 case M_MMAP_MAX:
4046 #if HAVE_MMAP
4047 n_mmaps_max = value; return 1;
4048 #else
4049 if (value != 0) return 0; else n_mmaps_max = value; return 1;
4050 #endif
4051 case M_CHECK_ACTION:
4052 check_action = value; return 1;
4054 default:
4055 return 0;
4061 /* Get/set state: malloc_get_state() records the current state of all
4062 malloc variables (_except_ for the actual heap contents and `hook'
4063 function pointers) in a system dependent, opaque data structure.
4064 This data structure is dynamically allocated and can be free()d
4065 after use. malloc_set_state() restores the state of all malloc
4066 variables to the previously obtained state. This is especially
4067 useful when using this malloc as part of a shared library, and when
4068 the heap contents are saved/restored via some other method. The
4069 primary example for this is GNU Emacs with its `dumping' procedure.
4070 `Hook' function pointers are never saved or restored by these
4071 functions. */
4073 #define MALLOC_STATE_MAGIC 0x444c4541l
4074 #define MALLOC_STATE_VERSION (0*0x100l + 1l) /* major*0x100 + minor */
4076 struct malloc_state {
4077 long magic;
4078 long version;
4079 mbinptr av[NAV * 2 + 2];
4080 char* sbrk_base;
4081 int sbrked_mem_bytes;
4082 unsigned long trim_threshold;
4083 unsigned long top_pad;
4084 unsigned int n_mmaps_max;
4085 unsigned long mmap_threshold;
4086 int check_action;
4087 unsigned long max_sbrked_mem;
4088 unsigned long max_total_mem;
4089 unsigned int n_mmaps;
4090 unsigned int max_n_mmaps;
4091 unsigned long mmapped_mem;
4092 unsigned long max_mmapped_mem;
4093 int using_malloc_checking;
4096 Void_t*
4097 mALLOC_GET_STATe()
4099 struct malloc_state* ms;
4100 int i;
4101 mbinptr b;
4103 ms = (struct malloc_state*)mALLOc(sizeof(*ms));
4104 if (!ms)
4105 return 0;
4106 (void)mutex_lock(&main_arena.mutex);
4107 ms->magic = MALLOC_STATE_MAGIC;
4108 ms->version = MALLOC_STATE_VERSION;
4109 ms->av[0] = main_arena.av[0];
4110 ms->av[1] = main_arena.av[1];
4111 for(i=0; i<NAV; i++) {
4112 b = bin_at(&main_arena, i);
4113 if(first(b) == b)
4114 ms->av[2*i+2] = ms->av[2*i+3] = 0; /* empty bin (or initial top) */
4115 else {
4116 ms->av[2*i+2] = first(b);
4117 ms->av[2*i+3] = last(b);
4120 ms->sbrk_base = sbrk_base;
4121 ms->sbrked_mem_bytes = sbrked_mem;
4122 ms->trim_threshold = trim_threshold;
4123 ms->top_pad = top_pad;
4124 ms->n_mmaps_max = n_mmaps_max;
4125 ms->mmap_threshold = mmap_threshold;
4126 ms->check_action = check_action;
4127 ms->max_sbrked_mem = max_sbrked_mem;
4128 #ifdef NO_THREADS
4129 ms->max_total_mem = max_total_mem;
4130 #else
4131 ms->max_total_mem = 0;
4132 #endif
4133 ms->n_mmaps = n_mmaps;
4134 ms->max_n_mmaps = max_n_mmaps;
4135 ms->mmapped_mem = mmapped_mem;
4136 ms->max_mmapped_mem = max_mmapped_mem;
4137 #if defined _LIBC || defined MALLOC_HOOKS
4138 ms->using_malloc_checking = using_malloc_checking;
4139 #else
4140 ms->using_malloc_checking = 0;
4141 #endif
4142 (void)mutex_unlock(&main_arena.mutex);
4143 return (Void_t*)ms;
4147 #if __STD_C
4148 mALLOC_SET_STATe(Void_t* msptr)
4149 #else
4150 mALLOC_SET_STATe(msptr) Void_t* msptr;
4151 #endif
4153 struct malloc_state* ms = (struct malloc_state*)msptr;
4154 int i;
4155 mbinptr b;
4157 #if defined _LIBC || defined MALLOC_HOOKS
4158 disallow_malloc_check = 1;
4159 #endif
4160 ptmalloc_init();
4161 if(ms->magic != MALLOC_STATE_MAGIC) return -1;
4162 /* Must fail if the major version is too high. */
4163 if((ms->version & ~0xffl) > (MALLOC_STATE_VERSION & ~0xffl)) return -2;
4164 (void)mutex_lock(&main_arena.mutex);
4165 main_arena.av[0] = ms->av[0];
4166 main_arena.av[1] = ms->av[1];
4167 for(i=0; i<NAV; i++) {
4168 b = bin_at(&main_arena, i);
4169 if(ms->av[2*i+2] == 0)
4170 first(b) = last(b) = b;
4171 else {
4172 first(b) = ms->av[2*i+2];
4173 last(b) = ms->av[2*i+3];
4174 if(i > 0) {
4175 /* Make sure the links to the `av'-bins in the heap are correct. */
4176 first(b)->bk = b;
4177 last(b)->fd = b;
4181 sbrk_base = ms->sbrk_base;
4182 sbrked_mem = ms->sbrked_mem_bytes;
4183 trim_threshold = ms->trim_threshold;
4184 top_pad = ms->top_pad;
4185 n_mmaps_max = ms->n_mmaps_max;
4186 mmap_threshold = ms->mmap_threshold;
4187 check_action = ms->check_action;
4188 max_sbrked_mem = ms->max_sbrked_mem;
4189 #ifdef NO_THREADS
4190 max_total_mem = ms->max_total_mem;
4191 #endif
4192 n_mmaps = ms->n_mmaps;
4193 max_n_mmaps = ms->max_n_mmaps;
4194 mmapped_mem = ms->mmapped_mem;
4195 max_mmapped_mem = ms->max_mmapped_mem;
4196 /* add version-dependent code here */
4197 if (ms->version >= 1) {
4198 #if defined _LIBC || defined MALLOC_HOOKS
4199 /* Check whether it is safe to enable malloc checking. */
4200 if (ms->using_malloc_checking && !using_malloc_checking &&
4201 !disallow_malloc_check)
4202 __malloc_check_init ();
4203 #endif
4206 (void)mutex_unlock(&main_arena.mutex);
4207 return 0;
4212 #if defined _LIBC || defined MALLOC_HOOKS
4214 /* A simple, standard set of debugging hooks. Overhead is `only' one
4215 byte per chunk; still this will catch most cases of double frees or
4216 overruns. The goal here is to avoid obscure crashes due to invalid
4217 usage, unlike in the MALLOC_DEBUG code. */
4219 #define MAGICBYTE(p) ( ( ((size_t)p >> 3) ^ ((size_t)p >> 11)) & 0xFF )
4221 /* Instrument a chunk with overrun detector byte(s) and convert it
4222 into a user pointer with requested size sz. */
4224 static Void_t*
4225 internal_function
4226 #if __STD_C
4227 chunk2mem_check(mchunkptr p, size_t sz)
4228 #else
4229 chunk2mem_check(p, sz) mchunkptr p; size_t sz;
4230 #endif
4232 unsigned char* m_ptr = (unsigned char*)chunk2mem(p);
4233 size_t i;
4235 for(i = chunksize(p) - (chunk_is_mmapped(p) ? 2*SIZE_SZ+1 : SIZE_SZ+1);
4236 i > sz;
4237 i -= 0xFF) {
4238 if(i-sz < 0x100) {
4239 m_ptr[i] = (unsigned char)(i-sz);
4240 break;
4242 m_ptr[i] = 0xFF;
4244 m_ptr[sz] = MAGICBYTE(p);
4245 return (Void_t*)m_ptr;
4248 /* Convert a pointer to be free()d or realloc()ed to a valid chunk
4249 pointer. If the provided pointer is not valid, return NULL. */
4251 static mchunkptr
4252 internal_function
4253 #if __STD_C
4254 mem2chunk_check(Void_t* mem)
4255 #else
4256 mem2chunk_check(mem) Void_t* mem;
4257 #endif
4259 mchunkptr p;
4260 INTERNAL_SIZE_T sz, c;
4261 unsigned char magic;
4263 p = mem2chunk(mem);
4264 if(!aligned_OK(p)) return NULL;
4265 if( (char*)p>=sbrk_base && (char*)p<(sbrk_base+sbrked_mem) ) {
4266 /* Must be a chunk in conventional heap memory. */
4267 if(chunk_is_mmapped(p) ||
4268 ( (sz = chunksize(p)), ((char*)p + sz)>=(sbrk_base+sbrked_mem) ) ||
4269 sz<MINSIZE || sz&MALLOC_ALIGN_MASK || !inuse(p) ||
4270 ( !prev_inuse(p) && (p->prev_size&MALLOC_ALIGN_MASK ||
4271 (long)prev_chunk(p)<(long)sbrk_base ||
4272 next_chunk(prev_chunk(p))!=p) ))
4273 return NULL;
4274 magic = MAGICBYTE(p);
4275 for(sz += SIZE_SZ-1; (c = ((unsigned char*)p)[sz]) != magic; sz -= c) {
4276 if(c<=0 || sz<(c+2*SIZE_SZ)) return NULL;
4278 ((unsigned char*)p)[sz] ^= 0xFF;
4279 } else {
4280 unsigned long offset, page_mask = malloc_getpagesize-1;
4282 /* mmap()ed chunks have MALLOC_ALIGNMENT or higher power-of-two
4283 alignment relative to the beginning of a page. Check this
4284 first. */
4285 offset = (unsigned long)mem & page_mask;
4286 if((offset!=MALLOC_ALIGNMENT && offset!=0 && offset!=0x10 &&
4287 offset!=0x20 && offset!=0x40 && offset!=0x80 && offset!=0x100 &&
4288 offset!=0x200 && offset!=0x400 && offset!=0x800 && offset!=0x1000 &&
4289 offset<0x2000) ||
4290 !chunk_is_mmapped(p) || (p->size & PREV_INUSE) ||
4291 ( (((unsigned long)p - p->prev_size) & page_mask) != 0 ) ||
4292 ( (sz = chunksize(p)), ((p->prev_size + sz) & page_mask) != 0 ) )
4293 return NULL;
4294 magic = MAGICBYTE(p);
4295 for(sz -= 1; (c = ((unsigned char*)p)[sz]) != magic; sz -= c) {
4296 if(c<=0 || sz<(c+2*SIZE_SZ)) return NULL;
4298 ((unsigned char*)p)[sz] ^= 0xFF;
4300 return p;
4303 /* Check for corruption of the top chunk, and try to recover if
4304 necessary. */
4306 static int
4307 internal_function
4308 #if __STD_C
4309 top_check(void)
4310 #else
4311 top_check()
4312 #endif
4314 mchunkptr t = top(&main_arena);
4315 char* brk, * new_brk;
4316 INTERNAL_SIZE_T front_misalign, sbrk_size;
4317 unsigned long pagesz = malloc_getpagesize;
4319 if((char*)t + chunksize(t) == sbrk_base + sbrked_mem ||
4320 t == initial_top(&main_arena)) return 0;
4322 switch(check_action) {
4323 case 1:
4324 fprintf(stderr, "malloc: top chunk is corrupt\n");
4325 break;
4326 case 2:
4327 abort();
4329 /* Try to set up a new top chunk. */
4330 brk = MORECORE(0);
4331 front_misalign = (unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK;
4332 if (front_misalign > 0)
4333 front_misalign = MALLOC_ALIGNMENT - front_misalign;
4334 sbrk_size = front_misalign + top_pad + MINSIZE;
4335 sbrk_size += pagesz - ((unsigned long)(brk + sbrk_size) & (pagesz - 1));
4336 new_brk = (char*)(MORECORE (sbrk_size));
4337 if (new_brk == (char*)(MORECORE_FAILURE)) return -1;
4338 sbrked_mem = (new_brk - sbrk_base) + sbrk_size;
4340 top(&main_arena) = (mchunkptr)(brk + front_misalign);
4341 set_head(top(&main_arena), (sbrk_size - front_misalign) | PREV_INUSE);
4343 return 0;
4346 static Void_t*
4347 #if __STD_C
4348 malloc_check(size_t sz, const Void_t *caller)
4349 #else
4350 malloc_check(sz, caller) size_t sz; const Void_t *caller;
4351 #endif
4353 mchunkptr victim;
4354 INTERNAL_SIZE_T nb = request2size(sz + 1);
4356 (void)mutex_lock(&main_arena.mutex);
4357 victim = (top_check() >= 0) ? chunk_alloc(&main_arena, nb) : NULL;
4358 (void)mutex_unlock(&main_arena.mutex);
4359 if(!victim) return NULL;
4360 return chunk2mem_check(victim, sz);
4363 static void
4364 #if __STD_C
4365 free_check(Void_t* mem, const Void_t *caller)
4366 #else
4367 free_check(mem, caller) Void_t* mem; const Void_t *caller;
4368 #endif
4370 mchunkptr p;
4372 if(!mem) return;
4373 (void)mutex_lock(&main_arena.mutex);
4374 p = mem2chunk_check(mem);
4375 if(!p) {
4376 (void)mutex_unlock(&main_arena.mutex);
4377 switch(check_action) {
4378 case 1:
4379 fprintf(stderr, "free(): invalid pointer %p!\n", mem);
4380 break;
4381 case 2:
4382 abort();
4384 return;
4386 #if HAVE_MMAP
4387 if (chunk_is_mmapped(p)) {
4388 (void)mutex_unlock(&main_arena.mutex);
4389 munmap_chunk(p);
4390 return;
4392 #endif
4393 #if 0 /* Erase freed memory. */
4394 memset(mem, 0, chunksize(p) - (SIZE_SZ+1));
4395 #endif
4396 chunk_free(&main_arena, p);
4397 (void)mutex_unlock(&main_arena.mutex);
4400 static Void_t*
4401 #if __STD_C
4402 realloc_check(Void_t* oldmem, size_t bytes, const Void_t *caller)
4403 #else
4404 realloc_check(oldmem, bytes, caller)
4405 Void_t* oldmem; size_t bytes; const Void_t *caller;
4406 #endif
4408 mchunkptr oldp, newp;
4409 INTERNAL_SIZE_T nb, oldsize;
4411 if (oldmem == 0) return malloc_check(bytes, NULL);
4412 (void)mutex_lock(&main_arena.mutex);
4413 oldp = mem2chunk_check(oldmem);
4414 if(!oldp) {
4415 (void)mutex_unlock(&main_arena.mutex);
4416 switch(check_action) {
4417 case 1:
4418 fprintf(stderr, "realloc(): invalid pointer %p!\n", oldmem);
4419 break;
4420 case 2:
4421 abort();
4423 return malloc_check(bytes, NULL);
4425 oldsize = chunksize(oldp);
4427 nb = request2size(bytes+1);
4429 #if HAVE_MMAP
4430 if (chunk_is_mmapped(oldp)) {
4431 #if HAVE_MREMAP
4432 newp = mremap_chunk(oldp, nb);
4433 if(!newp) {
4434 #endif
4435 /* Note the extra SIZE_SZ overhead. */
4436 if(oldsize - SIZE_SZ >= nb) newp = oldp; /* do nothing */
4437 else {
4438 /* Must alloc, copy, free. */
4439 newp = (top_check() >= 0) ? chunk_alloc(&main_arena, nb) : NULL;
4440 if (newp) {
4441 MALLOC_COPY(chunk2mem(newp), oldmem, oldsize - 2*SIZE_SZ);
4442 munmap_chunk(oldp);
4445 #if HAVE_MREMAP
4447 #endif
4448 } else {
4449 #endif /* HAVE_MMAP */
4450 newp = (top_check() >= 0) ?
4451 chunk_realloc(&main_arena, oldp, oldsize, nb) : NULL;
4452 #if 0 /* Erase freed memory. */
4453 nb = chunksize(newp);
4454 if(oldp<newp || oldp>=chunk_at_offset(newp, nb)) {
4455 memset((char*)oldmem + 2*sizeof(mbinptr), 0,
4456 oldsize - (2*sizeof(mbinptr)+2*SIZE_SZ+1));
4457 } else if(nb > oldsize+SIZE_SZ) {
4458 memset((char*)chunk2mem(newp) + oldsize, 0, nb - (oldsize+SIZE_SZ));
4460 #endif
4461 #if HAVE_MMAP
4463 #endif
4464 (void)mutex_unlock(&main_arena.mutex);
4466 if(!newp) return NULL;
4467 return chunk2mem_check(newp, bytes);
4470 static Void_t*
4471 #if __STD_C
4472 memalign_check(size_t alignment, size_t bytes, const Void_t *caller)
4473 #else
4474 memalign_check(alignment, bytes, caller)
4475 size_t alignment; size_t bytes; const Void_t *caller;
4476 #endif
4478 INTERNAL_SIZE_T nb;
4479 mchunkptr p;
4481 if (alignment <= MALLOC_ALIGNMENT) return malloc_check(bytes, NULL);
4482 if (alignment < MINSIZE) alignment = MINSIZE;
4484 nb = request2size(bytes+1);
4485 (void)mutex_lock(&main_arena.mutex);
4486 p = (top_check() >= 0) ? chunk_align(&main_arena, nb, alignment) : NULL;
4487 (void)mutex_unlock(&main_arena.mutex);
4488 if(!p) return NULL;
4489 return chunk2mem_check(p, bytes);
4492 #ifndef NO_THREADS
4494 /* The following hooks are used when the global initialization in
4495 ptmalloc_init() hasn't completed yet. */
4497 static Void_t*
4498 #if __STD_C
4499 malloc_starter(size_t sz, const Void_t *caller)
4500 #else
4501 malloc_starter(sz, caller) size_t sz; const Void_t *caller;
4502 #endif
4504 mchunkptr victim = chunk_alloc(&main_arena, request2size(sz));
4506 return victim ? chunk2mem(victim) : 0;
4509 static void
4510 #if __STD_C
4511 free_starter(Void_t* mem, const Void_t *caller)
4512 #else
4513 free_starter(mem, caller) Void_t* mem; const Void_t *caller;
4514 #endif
4516 mchunkptr p;
4518 if(!mem) return;
4519 p = mem2chunk(mem);
4520 #if HAVE_MMAP
4521 if (chunk_is_mmapped(p)) {
4522 munmap_chunk(p);
4523 return;
4525 #endif
4526 chunk_free(&main_arena, p);
4529 /* The following hooks are used while the `atfork' handling mechanism
4530 is active. */
4532 static Void_t*
4533 #if __STD_C
4534 malloc_atfork (size_t sz, const Void_t *caller)
4535 #else
4536 malloc_atfork(sz, caller) size_t sz; const Void_t *caller;
4537 #endif
4539 Void_t *vptr = NULL;
4540 mchunkptr victim;
4542 tsd_getspecific(arena_key, vptr);
4543 if(!vptr) {
4544 if(save_malloc_hook != malloc_check) {
4545 victim = chunk_alloc(&main_arena, request2size(sz));
4546 return victim ? chunk2mem(victim) : 0;
4547 } else {
4548 if(top_check() < 0) return 0;
4549 victim = chunk_alloc(&main_arena, request2size(sz+1));
4550 return victim ? chunk2mem_check(victim, sz) : 0;
4552 } else {
4553 /* Suspend the thread until the `atfork' handlers have completed.
4554 By that time, the hooks will have been reset as well, so that
4555 mALLOc() can be used again. */
4556 (void)mutex_lock(&list_lock);
4557 (void)mutex_unlock(&list_lock);
4558 return mALLOc(sz);
4562 static void
4563 #if __STD_C
4564 free_atfork(Void_t* mem, const Void_t *caller)
4565 #else
4566 free_atfork(mem, caller) Void_t* mem; const Void_t *caller;
4567 #endif
4569 Void_t *vptr = NULL;
4570 arena *ar_ptr;
4571 mchunkptr p; /* chunk corresponding to mem */
4573 if (mem == 0) /* free(0) has no effect */
4574 return;
4576 p = mem2chunk(mem); /* do not bother to replicate free_check here */
4578 #if HAVE_MMAP
4579 if (chunk_is_mmapped(p)) /* release mmapped memory. */
4581 munmap_chunk(p);
4582 return;
4584 #endif
4586 ar_ptr = arena_for_ptr(p);
4587 tsd_getspecific(arena_key, vptr);
4588 if(vptr)
4589 (void)mutex_lock(&ar_ptr->mutex);
4590 chunk_free(ar_ptr, p);
4591 if(vptr)
4592 (void)mutex_unlock(&ar_ptr->mutex);
4595 #endif /* !defined NO_THREADS */
4597 #endif /* defined _LIBC || defined MALLOC_HOOKS */
4601 #ifdef _LIBC
4602 weak_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)
4603 weak_alias (__libc_free, __cfree) weak_alias (__libc_free, cfree)
4604 weak_alias (__libc_free, __free) weak_alias (__libc_free, free)
4605 weak_alias (__libc_malloc, __malloc) weak_alias (__libc_malloc, malloc)
4606 weak_alias (__libc_memalign, __memalign) weak_alias (__libc_memalign, memalign)
4607 weak_alias (__libc_realloc, __realloc) weak_alias (__libc_realloc, realloc)
4608 weak_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)
4609 weak_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)
4610 weak_alias (__libc_mallinfo, __mallinfo) weak_alias (__libc_mallinfo, mallinfo)
4611 weak_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)
4613 weak_alias (__malloc_stats, malloc_stats)
4614 weak_alias (__malloc_usable_size, malloc_usable_size)
4615 weak_alias (__malloc_trim, malloc_trim)
4616 weak_alias (__malloc_get_state, malloc_get_state)
4617 weak_alias (__malloc_set_state, malloc_set_state)
4618 #endif
4622 History:
4624 V2.6.4-pt3 Thu Feb 20 1997 Wolfram Gloger (wmglo@dent.med.uni-muenchen.de)
4625 * Added malloc_get/set_state() (mainly for use in GNU emacs),
4626 using interface from Marcus Daniels
4627 * All parameters are now adjustable via environment variables
4629 V2.6.4-pt2 Sat Dec 14 1996 Wolfram Gloger (wmglo@dent.med.uni-muenchen.de)
4630 * Added debugging hooks
4631 * Fixed possible deadlock in realloc() when out of memory
4632 * Don't pollute namespace in glibc: use __getpagesize, __mmap, etc.
4634 V2.6.4-pt Wed Dec 4 1996 Wolfram Gloger (wmglo@dent.med.uni-muenchen.de)
4635 * Very minor updates from the released 2.6.4 version.
4636 * Trimmed include file down to exported data structures.
4637 * Changes from H.J. Lu for glibc-2.0.
4639 V2.6.3i-pt Sep 16 1996 Wolfram Gloger (wmglo@dent.med.uni-muenchen.de)
4640 * Many changes for multiple threads
4641 * Introduced arenas and heaps
4643 V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee)
4644 * Added pvalloc, as recommended by H.J. Liu
4645 * Added 64bit pointer support mainly from Wolfram Gloger
4646 * Added anonymously donated WIN32 sbrk emulation
4647 * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
4648 * malloc_extend_top: fix mask error that caused wastage after
4649 foreign sbrks
4650 * Add linux mremap support code from HJ Liu
4652 V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee)
4653 * Integrated most documentation with the code.
4654 * Add support for mmap, with help from
4655 Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
4656 * Use last_remainder in more cases.
4657 * Pack bins using idea from colin@nyx10.cs.du.edu
4658 * Use ordered bins instead of best-fit threshold
4659 * Eliminate block-local decls to simplify tracing and debugging.
4660 * Support another case of realloc via move into top
4661 * Fix error occurring when initial sbrk_base not word-aligned.
4662 * Rely on page size for units instead of SBRK_UNIT to
4663 avoid surprises about sbrk alignment conventions.
4664 * Add mallinfo, mallopt. Thanks to Raymond Nijssen
4665 (raymond@es.ele.tue.nl) for the suggestion.
4666 * Add `pad' argument to malloc_trim and top_pad mallopt parameter.
4667 * More precautions for cases where other routines call sbrk,
4668 courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
4669 * Added macros etc., allowing use in linux libc from
4670 H.J. Lu (hjl@gnu.ai.mit.edu)
4671 * Inverted this history list
4673 V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee)
4674 * Re-tuned and fixed to behave more nicely with V2.6.0 changes.
4675 * Removed all preallocation code since under current scheme
4676 the work required to undo bad preallocations exceeds
4677 the work saved in good cases for most test programs.
4678 * No longer use return list or unconsolidated bins since
4679 no scheme using them consistently outperforms those that don't
4680 given above changes.
4681 * Use best fit for very large chunks to prevent some worst-cases.
4682 * Added some support for debugging
4684 V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee)
4685 * Removed footers when chunks are in use. Thanks to
4686 Paul Wilson (wilson@cs.texas.edu) for the suggestion.
4688 V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee)
4689 * Added malloc_trim, with help from Wolfram Gloger
4690 (wmglo@Dent.MED.Uni-Muenchen.DE).
4692 V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g)
4694 V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g)
4695 * realloc: try to expand in both directions
4696 * malloc: swap order of clean-bin strategy;
4697 * realloc: only conditionally expand backwards
4698 * Try not to scavenge used bins
4699 * Use bin counts as a guide to preallocation
4700 * Occasionally bin return list chunks in first scan
4701 * Add a few optimizations from colin@nyx10.cs.du.edu
4703 V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g)
4704 * faster bin computation & slightly different binning
4705 * merged all consolidations to one part of malloc proper
4706 (eliminating old malloc_find_space & malloc_clean_bin)
4707 * Scan 2 returns chunks (not just 1)
4708 * Propagate failure in realloc if malloc returns 0
4709 * Add stuff to allow compilation on non-ANSI compilers
4710 from kpv@research.att.com
4712 V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu)
4713 * removed potential for odd address access in prev_chunk
4714 * removed dependency on getpagesize.h
4715 * misc cosmetics and a bit more internal documentation
4716 * anticosmetics: mangled names in macros to evade debugger strangeness
4717 * tested on sparc, hp-700, dec-mips, rs6000
4718 with gcc & native cc (hp, dec only) allowing
4719 Detlefs & Zorn comparison study (in SIGPLAN Notices.)
4721 Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu)
4722 * Based loosely on libg++-1.2X malloc. (It retains some of the overall
4723 structure of old version, but most details differ.)