* sysdeps/m68k/fpu/libm-test-ulps: Updated for fixed cbrtl
[glibc.git] / malloc / malloc.c
blob8279ddaf22e4239e309dd9ec45f5c249d25a8265
1 /* Malloc implementation for multiple threads without lock contention.
2 Copyright (C) 1996,1997,1998,1999,2000,2001 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 Lesser General Public
9 License as published by the Free Software Foundation; either
10 version 2.1 of the License, or (at your option) any later version.
12 The GNU C Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public
18 License along with the GNU C Library; if not, write to the Free
19 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20 02111-1307 USA. */
22 /* $Id$
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 USE_ARENAS (default: the same as HAVE_MMAP)
206 Enable support for multiple arenas, allocated using mmap().
207 malloc_getpagesize (default: derived from system #includes)
208 Either a constant or routine call returning the system page size.
209 HAVE_USR_INCLUDE_MALLOC_H (default: NOT defined)
210 Optionally define if you are on a system with a /usr/include/malloc.h
211 that declares struct mallinfo. It is not at all necessary to
212 define this even if you do, but will ensure consistency.
213 INTERNAL_SIZE_T (default: size_t)
214 Define to a 32-bit type (probably `unsigned int') if you are on a
215 64-bit machine, yet do not want or need to allow malloc requests of
216 greater than 2^31 to be handled. This saves space, especially for
217 very small chunks.
218 _LIBC (default: NOT defined)
219 Defined only when compiled as part of the Linux libc/glibc.
220 Also note that there is some odd internal name-mangling via defines
221 (for example, internally, `malloc' is named `mALLOc') needed
222 when compiling in this case. These look funny but don't otherwise
223 affect anything.
224 LACKS_UNISTD_H (default: undefined)
225 Define this if your system does not have a <unistd.h>.
226 MORECORE (default: sbrk)
227 The name of the routine to call to obtain more memory from the system.
228 MORECORE_FAILURE (default: -1)
229 The value returned upon failure of MORECORE.
230 MORECORE_CLEARS (default 1)
231 The degree to which the routine mapped to MORECORE zeroes out
232 memory: never (0), only for newly allocated space (1) or always
233 (2). The distinction between (1) and (2) is necessary because on
234 some systems, if the application first decrements and then
235 increments the break value, the contents of the reallocated space
236 are unspecified.
237 DEFAULT_TRIM_THRESHOLD
238 DEFAULT_TOP_PAD
239 DEFAULT_MMAP_THRESHOLD
240 DEFAULT_MMAP_MAX
241 Default values of tunable parameters (described in detail below)
242 controlling interaction with host system routines (sbrk, mmap, etc).
243 These values may also be changed dynamically via mallopt(). The
244 preset defaults are those that give best performance for typical
245 programs/systems.
246 DEFAULT_CHECK_ACTION
247 When the standard debugging hooks are in place, and a pointer is
248 detected as corrupt, do nothing (0), print an error message (1),
249 or call abort() (2).
256 * Compile-time options for multiple threads:
258 USE_PTHREADS, USE_THR, USE_SPROC
259 Define one of these as 1 to select the thread interface:
260 POSIX threads, Solaris threads or SGI sproc's, respectively.
261 If none of these is defined as non-zero, you get a `normal'
262 malloc implementation which is not thread-safe. Support for
263 multiple threads requires HAVE_MMAP=1. As an exception, when
264 compiling for GNU libc, i.e. when _LIBC is defined, then none of
265 the USE_... symbols have to be defined.
267 HEAP_MIN_SIZE
268 HEAP_MAX_SIZE
269 When thread support is enabled, additional `heap's are created
270 with mmap calls. These are limited in size; HEAP_MIN_SIZE should
271 be a multiple of the page size, while HEAP_MAX_SIZE must be a power
272 of two for alignment reasons. HEAP_MAX_SIZE should be at least
273 twice as large as the mmap threshold.
274 THREAD_STATS
275 When this is defined as non-zero, some statistics on mutex locking
276 are computed.
283 /* Preliminaries */
285 #ifndef __STD_C
286 #if defined (__STDC__)
287 #define __STD_C 1
288 #else
289 #if __cplusplus
290 #define __STD_C 1
291 #else
292 #define __STD_C 0
293 #endif /*__cplusplus*/
294 #endif /*__STDC__*/
295 #endif /*__STD_C*/
297 #ifndef Void_t
298 #if __STD_C
299 #define Void_t void
300 #else
301 #define Void_t char
302 #endif
303 #endif /*Void_t*/
305 #if __STD_C
306 # include <stddef.h> /* for size_t */
307 # if defined _LIBC || defined MALLOC_HOOKS
308 # include <stdlib.h> /* for getenv(), abort() */
309 # endif
310 #else
311 # include <sys/types.h>
312 # if defined _LIBC || defined MALLOC_HOOKS
313 extern char* getenv();
314 # endif
315 #endif
317 /* Macros for handling mutexes and thread-specific data. This is
318 included early, because some thread-related header files (such as
319 pthread.h) should be included before any others. */
320 #include "thread-m.h"
322 #ifdef __cplusplus
323 extern "C" {
324 #endif
326 #include <errno.h>
327 #include <stdio.h> /* needed for malloc_stats */
331 Compile-time options
336 Debugging:
338 Because freed chunks may be overwritten with link fields, this
339 malloc will often die when freed memory is overwritten by user
340 programs. This can be very effective (albeit in an annoying way)
341 in helping track down dangling pointers.
343 If you compile with -DMALLOC_DEBUG, a number of assertion checks are
344 enabled that will catch more memory errors. You probably won't be
345 able to make much sense of the actual assertion errors, but they
346 should help you locate incorrectly overwritten memory. The
347 checking is fairly extensive, and will slow down execution
348 noticeably. Calling malloc_stats or mallinfo with MALLOC_DEBUG set will
349 attempt to check every non-mmapped allocated and free chunk in the
350 course of computing the summaries. (By nature, mmapped regions
351 cannot be checked very much automatically.)
353 Setting MALLOC_DEBUG may also be helpful if you are trying to modify
354 this code. The assertions in the check routines spell out in more
355 detail the assumptions and invariants underlying the algorithms.
359 #if MALLOC_DEBUG
360 #include <assert.h>
361 #else
362 #define assert(x) ((void)0)
363 #endif
367 INTERNAL_SIZE_T is the word-size used for internal bookkeeping
368 of chunk sizes. On a 64-bit machine, you can reduce malloc
369 overhead by defining INTERNAL_SIZE_T to be a 32 bit `unsigned int'
370 at the expense of not being able to handle requests greater than
371 2^31. This limitation is hardly ever a concern; you are encouraged
372 to set this. However, the default version is the same as size_t.
375 #ifndef INTERNAL_SIZE_T
376 #define INTERNAL_SIZE_T size_t
377 #endif
380 REALLOC_ZERO_BYTES_FREES should be set if a call to realloc with
381 zero bytes should be the same as a call to free. The C standard
382 requires this. Otherwise, since this malloc returns a unique pointer
383 for malloc(0), so does realloc(p, 0).
387 #define REALLOC_ZERO_BYTES_FREES
391 HAVE_MEMCPY should be defined if you are not otherwise using
392 ANSI STD C, but still have memcpy and memset in your C library
393 and want to use them in calloc and realloc. Otherwise simple
394 macro versions are defined here.
396 USE_MEMCPY should be defined as 1 if you actually want to
397 have memset and memcpy called. People report that the macro
398 versions are often enough faster than libc versions on many
399 systems that it is better to use them.
403 #define HAVE_MEMCPY 1
405 #ifndef USE_MEMCPY
406 #ifdef HAVE_MEMCPY
407 #define USE_MEMCPY 1
408 #else
409 #define USE_MEMCPY 0
410 #endif
411 #endif
413 #if (__STD_C || defined(HAVE_MEMCPY))
415 #if __STD_C
416 void* memset(void*, int, size_t);
417 void* memcpy(void*, const void*, size_t);
418 void* memmove(void*, const void*, size_t);
419 #else
420 Void_t* memset();
421 Void_t* memcpy();
422 Void_t* memmove();
423 #endif
424 #endif
426 /* The following macros are only invoked with (2n+1)-multiples of
427 INTERNAL_SIZE_T units, with a positive integer n. This is exploited
428 for fast inline execution when n is small. If the regions to be
429 copied do overlap, the destination lies always _below_ the source. */
431 #if USE_MEMCPY
433 #define MALLOC_ZERO(charp, nbytes) \
434 do { \
435 INTERNAL_SIZE_T mzsz = (nbytes); \
436 if(mzsz <= 9*sizeof(mzsz)) { \
437 INTERNAL_SIZE_T* mz = (INTERNAL_SIZE_T*) (charp); \
438 if(mzsz >= 5*sizeof(mzsz)) { *mz++ = 0; \
439 *mz++ = 0; \
440 if(mzsz >= 7*sizeof(mzsz)) { *mz++ = 0; \
441 *mz++ = 0; \
442 if(mzsz >= 9*sizeof(mzsz)) { *mz++ = 0; \
443 *mz++ = 0; }}} \
444 *mz++ = 0; \
445 *mz++ = 0; \
446 *mz = 0; \
447 } else memset((charp), 0, mzsz); \
448 } while(0)
450 /* If the regions overlap, dest is always _below_ src. */
452 #define MALLOC_COPY(dest,src,nbytes,overlap) \
453 do { \
454 INTERNAL_SIZE_T mcsz = (nbytes); \
455 if(mcsz <= 9*sizeof(mcsz)) { \
456 INTERNAL_SIZE_T* mcsrc = (INTERNAL_SIZE_T*) (src); \
457 INTERNAL_SIZE_T* mcdst = (INTERNAL_SIZE_T*) (dest); \
458 if(mcsz >= 5*sizeof(mcsz)) { *mcdst++ = *mcsrc++; \
459 *mcdst++ = *mcsrc++; \
460 if(mcsz >= 7*sizeof(mcsz)) { *mcdst++ = *mcsrc++; \
461 *mcdst++ = *mcsrc++; \
462 if(mcsz >= 9*sizeof(mcsz)) { *mcdst++ = *mcsrc++; \
463 *mcdst++ = *mcsrc++; }}} \
464 *mcdst++ = *mcsrc++; \
465 *mcdst++ = *mcsrc++; \
466 *mcdst = *mcsrc ; \
467 } else if(overlap) \
468 memmove(dest, src, mcsz); \
469 else \
470 memcpy(dest, src, mcsz); \
471 } while(0)
473 #else /* !USE_MEMCPY */
475 /* Use Duff's device for good zeroing/copying performance. */
477 #define MALLOC_ZERO(charp, nbytes) \
478 do { \
479 INTERNAL_SIZE_T* mzp = (INTERNAL_SIZE_T*)(charp); \
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(;;) { *mzp++ = 0; \
484 case 7: *mzp++ = 0; \
485 case 6: *mzp++ = 0; \
486 case 5: *mzp++ = 0; \
487 case 4: *mzp++ = 0; \
488 case 3: *mzp++ = 0; \
489 case 2: *mzp++ = 0; \
490 case 1: *mzp++ = 0; if(mcn <= 0) break; mcn--; } \
492 } while(0)
494 /* If the regions overlap, dest is always _below_ src. */
496 #define MALLOC_COPY(dest,src,nbytes,overlap) \
497 do { \
498 INTERNAL_SIZE_T* mcsrc = (INTERNAL_SIZE_T*) src; \
499 INTERNAL_SIZE_T* mcdst = (INTERNAL_SIZE_T*) dest; \
500 long mctmp = (nbytes)/sizeof(INTERNAL_SIZE_T), mcn; \
501 if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp %= 8; } \
502 switch (mctmp) { \
503 case 0: for(;;) { *mcdst++ = *mcsrc++; \
504 case 7: *mcdst++ = *mcsrc++; \
505 case 6: *mcdst++ = *mcsrc++; \
506 case 5: *mcdst++ = *mcsrc++; \
507 case 4: *mcdst++ = *mcsrc++; \
508 case 3: *mcdst++ = *mcsrc++; \
509 case 2: *mcdst++ = *mcsrc++; \
510 case 1: *mcdst++ = *mcsrc++; if(mcn <= 0) break; mcn--; } \
512 } while(0)
514 #endif
517 #ifndef LACKS_UNISTD_H
518 # include <unistd.h>
519 #endif
522 Define HAVE_MMAP to optionally make malloc() use mmap() to allocate
523 very large blocks. These will be returned to the operating system
524 immediately after a free(). HAVE_MMAP is also a prerequisite to
525 support multiple `arenas' (see USE_ARENAS below).
528 #ifndef HAVE_MMAP
529 # ifdef _POSIX_MAPPED_FILES
530 # define HAVE_MMAP 1
531 # endif
532 #endif
535 Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
536 large blocks. This is currently only possible on Linux with
537 kernel versions newer than 1.3.77.
540 #ifndef HAVE_MREMAP
541 #define HAVE_MREMAP defined(__linux__)
542 #endif
544 /* Define USE_ARENAS to enable support for multiple `arenas'. These
545 are allocated using mmap(), are necessary for threads and
546 occasionally useful to overcome address space limitations affecting
547 sbrk(). */
549 #ifndef USE_ARENAS
550 #define USE_ARENAS HAVE_MMAP
551 #endif
553 #if HAVE_MMAP
555 #include <unistd.h>
556 #include <fcntl.h>
557 #include <sys/mman.h>
559 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
560 #define MAP_ANONYMOUS MAP_ANON
561 #endif
562 #if !defined(MAP_FAILED)
563 #define MAP_FAILED ((char*)-1)
564 #endif
566 #ifndef MAP_NORESERVE
567 # ifdef MAP_AUTORESRV
568 # define MAP_NORESERVE MAP_AUTORESRV
569 # else
570 # define MAP_NORESERVE 0
571 # endif
572 #endif
574 #endif /* HAVE_MMAP */
577 Access to system page size. To the extent possible, this malloc
578 manages memory from the system in page-size units.
580 The following mechanics for getpagesize were adapted from
581 bsd/gnu getpagesize.h
584 #ifndef malloc_getpagesize
585 # ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */
586 # ifndef _SC_PAGE_SIZE
587 # define _SC_PAGE_SIZE _SC_PAGESIZE
588 # endif
589 # endif
590 # ifdef _SC_PAGE_SIZE
591 # define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
592 # else
593 # if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
594 extern size_t getpagesize();
595 # define malloc_getpagesize getpagesize()
596 # else
597 # include <sys/param.h>
598 # ifdef EXEC_PAGESIZE
599 # define malloc_getpagesize EXEC_PAGESIZE
600 # else
601 # ifdef NBPG
602 # ifndef CLSIZE
603 # define malloc_getpagesize NBPG
604 # else
605 # define malloc_getpagesize (NBPG * CLSIZE)
606 # endif
607 # else
608 # ifdef NBPC
609 # define malloc_getpagesize NBPC
610 # else
611 # ifdef PAGESIZE
612 # define malloc_getpagesize PAGESIZE
613 # else
614 # define malloc_getpagesize (4096) /* just guess */
615 # endif
616 # endif
617 # endif
618 # endif
619 # endif
620 # endif
621 #endif
627 This version of malloc supports the standard SVID/XPG mallinfo
628 routine that returns a struct containing the same kind of
629 information you can get from malloc_stats. It should work on
630 any SVID/XPG compliant system that has a /usr/include/malloc.h
631 defining struct mallinfo. (If you'd like to install such a thing
632 yourself, cut out the preliminary declarations as described above
633 and below and save them in a malloc.h file. But there's no
634 compelling reason to bother to do this.)
636 The main declaration needed is the mallinfo struct that is returned
637 (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
638 bunch of fields, most of which are not even meaningful in this
639 version of malloc. Some of these fields are are instead filled by
640 mallinfo() with other numbers that might possibly be of interest.
642 HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
643 /usr/include/malloc.h file that includes a declaration of struct
644 mallinfo. If so, it is included; else an SVID2/XPG2 compliant
645 version is declared below. These must be precisely the same for
646 mallinfo() to work.
650 /* #define HAVE_USR_INCLUDE_MALLOC_H */
652 #if HAVE_USR_INCLUDE_MALLOC_H
653 # include "/usr/include/malloc.h"
654 #else
655 # ifdef _LIBC
656 # include "malloc.h"
657 # else
658 # include "ptmalloc.h"
659 # endif
660 #endif
662 #include <bp-checks.h>
664 #ifndef DEFAULT_TRIM_THRESHOLD
665 #define DEFAULT_TRIM_THRESHOLD (128 * 1024)
666 #endif
669 M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
670 to keep before releasing via malloc_trim in free().
672 Automatic trimming is mainly useful in long-lived programs.
673 Because trimming via sbrk can be slow on some systems, and can
674 sometimes be wasteful (in cases where programs immediately
675 afterward allocate more large chunks) the value should be high
676 enough so that your overall system performance would improve by
677 releasing.
679 The trim threshold and the mmap control parameters (see below)
680 can be traded off with one another. Trimming and mmapping are
681 two different ways of releasing unused memory back to the
682 system. Between these two, it is often possible to keep
683 system-level demands of a long-lived program down to a bare
684 minimum. For example, in one test suite of sessions measuring
685 the XF86 X server on Linux, using a trim threshold of 128K and a
686 mmap threshold of 192K led to near-minimal long term resource
687 consumption.
689 If you are using this malloc in a long-lived program, it should
690 pay to experiment with these values. As a rough guide, you
691 might set to a value close to the average size of a process
692 (program) running on your system. Releasing this much memory
693 would allow such a process to run in memory. Generally, it's
694 worth it to tune for trimming rather than memory mapping when a
695 program undergoes phases where several large chunks are
696 allocated and released in ways that can reuse each other's
697 storage, perhaps mixed with phases where there are no such
698 chunks at all. And in well-behaved long-lived programs,
699 controlling release of large blocks via trimming versus mapping
700 is usually faster.
702 However, in most programs, these parameters serve mainly as
703 protection against the system-level effects of carrying around
704 massive amounts of unneeded memory. Since frequent calls to
705 sbrk, mmap, and munmap otherwise degrade performance, the default
706 parameters are set to relatively high values that serve only as
707 safeguards.
709 The default trim value is high enough to cause trimming only in
710 fairly extreme (by current memory consumption standards) cases.
711 It must be greater than page size to have any useful effect. To
712 disable trimming completely, you can set to (unsigned long)(-1);
718 #ifndef DEFAULT_TOP_PAD
719 #define DEFAULT_TOP_PAD (0)
720 #endif
723 M_TOP_PAD is the amount of extra `padding' space to allocate or
724 retain whenever sbrk is called. It is used in two ways internally:
726 * When sbrk is called to extend the top of the arena to satisfy
727 a new malloc request, this much padding is added to the sbrk
728 request.
730 * When malloc_trim is called automatically from free(),
731 it is used as the `pad' argument.
733 In both cases, the actual amount of padding is rounded
734 so that the end of the arena is always a system page boundary.
736 The main reason for using padding is to avoid calling sbrk so
737 often. Having even a small pad greatly reduces the likelihood
738 that nearly every malloc request during program start-up (or
739 after trimming) will invoke sbrk, which needlessly wastes
740 time.
742 Automatic rounding-up to page-size units is normally sufficient
743 to avoid measurable overhead, so the default is 0. However, in
744 systems where sbrk is relatively slow, it can pay to increase
745 this value, at the expense of carrying around more memory than
746 the program needs.
751 #ifndef DEFAULT_MMAP_THRESHOLD
752 #define DEFAULT_MMAP_THRESHOLD (128 * 1024)
753 #endif
757 M_MMAP_THRESHOLD is the request size threshold for using mmap()
758 to service a request. Requests of at least this size that cannot
759 be allocated using already-existing space will be serviced via mmap.
760 (If enough normal freed space already exists it is used instead.)
762 Using mmap segregates relatively large chunks of memory so that
763 they can be individually obtained and released from the host
764 system. A request serviced through mmap is never reused by any
765 other request (at least not directly; the system may just so
766 happen to remap successive requests to the same locations).
768 Segregating space in this way has the benefit that mmapped space
769 can ALWAYS be individually released back to the system, which
770 helps keep the system level memory demands of a long-lived
771 program low. Mapped memory can never become `locked' between
772 other chunks, as can happen with normally allocated chunks, which
773 menas that even trimming via malloc_trim would not release them.
775 However, it has the disadvantages that:
777 1. The space cannot be reclaimed, consolidated, and then
778 used to service later requests, as happens with normal chunks.
779 2. It can lead to more wastage because of mmap page alignment
780 requirements
781 3. It causes malloc performance to be more dependent on host
782 system memory management support routines which may vary in
783 implementation quality and may impose arbitrary
784 limitations. Generally, servicing a request via normal
785 malloc steps is faster than going through a system's mmap.
787 All together, these considerations should lead you to use mmap
788 only for relatively large requests.
795 #ifndef DEFAULT_MMAP_MAX
796 #if HAVE_MMAP
797 #define DEFAULT_MMAP_MAX (1024)
798 #else
799 #define DEFAULT_MMAP_MAX (0)
800 #endif
801 #endif
804 M_MMAP_MAX is the maximum number of requests to simultaneously
805 service using mmap. This parameter exists because:
807 1. Some systems have a limited number of internal tables for
808 use by mmap.
809 2. In most systems, overreliance on mmap can degrade overall
810 performance.
811 3. If a program allocates many large regions, it is probably
812 better off using normal sbrk-based allocation routines that
813 can reclaim and reallocate normal heap memory. Using a
814 small value allows transition into this mode after the
815 first few allocations.
817 Setting to 0 disables all use of mmap. If HAVE_MMAP is not set,
818 the default value is 0, and attempts to set it to non-zero values
819 in mallopt will fail.
824 #ifndef DEFAULT_CHECK_ACTION
825 #define DEFAULT_CHECK_ACTION 1
826 #endif
828 /* What to do if the standard debugging hooks are in place and a
829 corrupt pointer is detected: do nothing (0), print an error message
830 (1), or call abort() (2). */
834 #define HEAP_MIN_SIZE (32*1024)
835 #define HEAP_MAX_SIZE (1024*1024) /* must be a power of two */
837 /* HEAP_MIN_SIZE and HEAP_MAX_SIZE limit the size of mmap()ed heaps
838 that are dynamically created for multi-threaded programs. The
839 maximum size must be a power of two, for fast determination of
840 which heap belongs to a chunk. It should be much larger than
841 the mmap threshold, so that requests with a size just below that
842 threshold can be fulfilled without creating too many heaps.
847 #ifndef THREAD_STATS
848 #define THREAD_STATS 0
849 #endif
851 /* If THREAD_STATS is non-zero, some statistics on mutex locking are
852 computed. */
855 /* Macro to set errno. */
856 #ifndef __set_errno
857 # define __set_errno(val) errno = (val)
858 #endif
860 /* On some platforms we can compile internal, not exported functions better.
861 Let the environment provide a macro and define it to be empty if it
862 is not available. */
863 #ifndef internal_function
864 # define internal_function
865 #endif
870 Special defines for the Linux/GNU C library.
875 #ifdef _LIBC
877 #if __STD_C
879 Void_t * __default_morecore (ptrdiff_t);
880 Void_t *(*__morecore)(ptrdiff_t) = __default_morecore;
882 #else
884 Void_t * __default_morecore ();
885 Void_t *(*__morecore)() = __default_morecore;
887 #endif
889 #define MORECORE (*__morecore)
890 #define MORECORE_FAILURE 0
892 #ifndef MORECORE_CLEARS
893 #define MORECORE_CLEARS 1
894 #endif
896 static size_t __libc_pagesize;
898 #define access __access
899 #define mmap __mmap
900 #define munmap __munmap
901 #define mremap __mremap
902 #define mprotect __mprotect
903 #undef malloc_getpagesize
904 #define malloc_getpagesize __libc_pagesize
906 #else /* _LIBC */
908 #if __STD_C
909 extern Void_t* sbrk(ptrdiff_t);
910 #else
911 extern Void_t* sbrk();
912 #endif
914 #ifndef MORECORE
915 #define MORECORE sbrk
916 #endif
918 #ifndef MORECORE_FAILURE
919 #define MORECORE_FAILURE -1
920 #endif
922 #ifndef MORECORE_CLEARS
923 #define MORECORE_CLEARS 1
924 #endif
926 #endif /* _LIBC */
928 #ifdef _LIBC
930 #define cALLOc __libc_calloc
931 #define fREe __libc_free
932 #define mALLOc __libc_malloc
933 #define mEMALIGn __libc_memalign
934 #define rEALLOc __libc_realloc
935 #define vALLOc __libc_valloc
936 #define pvALLOc __libc_pvalloc
937 #define mALLINFo __libc_mallinfo
938 #define mALLOPt __libc_mallopt
939 #define mALLOC_STATs __malloc_stats
940 #define mALLOC_USABLE_SIZe __malloc_usable_size
941 #define mALLOC_TRIm __malloc_trim
942 #define mALLOC_GET_STATe __malloc_get_state
943 #define mALLOC_SET_STATe __malloc_set_state
945 #else
947 #define cALLOc calloc
948 #define fREe free
949 #define mALLOc malloc
950 #define mEMALIGn memalign
951 #define rEALLOc realloc
952 #define vALLOc valloc
953 #define pvALLOc pvalloc
954 #define mALLINFo mallinfo
955 #define mALLOPt mallopt
956 #define mALLOC_STATs malloc_stats
957 #define mALLOC_USABLE_SIZe malloc_usable_size
958 #define mALLOC_TRIm malloc_trim
959 #define mALLOC_GET_STATe malloc_get_state
960 #define mALLOC_SET_STATe malloc_set_state
962 #endif
964 /* Public routines */
966 #if __STD_C
968 #ifndef _LIBC
969 void ptmalloc_init(void);
970 #endif
971 Void_t* mALLOc(size_t);
972 void fREe(Void_t*);
973 Void_t* rEALLOc(Void_t*, size_t);
974 Void_t* mEMALIGn(size_t, size_t);
975 Void_t* vALLOc(size_t);
976 Void_t* pvALLOc(size_t);
977 Void_t* cALLOc(size_t, size_t);
978 void cfree(Void_t*);
979 int mALLOC_TRIm(size_t);
980 size_t mALLOC_USABLE_SIZe(Void_t*);
981 void mALLOC_STATs(void);
982 int mALLOPt(int, int);
983 struct mallinfo mALLINFo(void);
984 Void_t* mALLOC_GET_STATe(void);
985 int mALLOC_SET_STATe(Void_t*);
987 #else /* !__STD_C */
989 #ifndef _LIBC
990 void ptmalloc_init();
991 #endif
992 Void_t* mALLOc();
993 void fREe();
994 Void_t* rEALLOc();
995 Void_t* mEMALIGn();
996 Void_t* vALLOc();
997 Void_t* pvALLOc();
998 Void_t* cALLOc();
999 void cfree();
1000 int mALLOC_TRIm();
1001 size_t mALLOC_USABLE_SIZe();
1002 void mALLOC_STATs();
1003 int mALLOPt();
1004 struct mallinfo mALLINFo();
1005 Void_t* mALLOC_GET_STATe();
1006 int mALLOC_SET_STATe();
1008 #endif /* __STD_C */
1011 #ifdef __cplusplus
1012 } /* end of extern "C" */
1013 #endif
1015 #if !defined(NO_THREADS) && !HAVE_MMAP
1016 "Can't have threads support without mmap"
1017 #endif
1018 #if USE_ARENAS && !HAVE_MMAP
1019 "Can't have multiple arenas without mmap"
1020 #endif
1024 Type declarations
1028 struct malloc_chunk
1030 INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
1031 INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */
1032 struct malloc_chunk* fd; /* double links -- used only if free. */
1033 struct malloc_chunk* bk;
1036 typedef struct malloc_chunk* mchunkptr;
1040 malloc_chunk details:
1042 (The following includes lightly edited explanations by Colin Plumb.)
1044 Chunks of memory are maintained using a `boundary tag' method as
1045 described in e.g., Knuth or Standish. (See the paper by Paul
1046 Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
1047 survey of such techniques.) Sizes of free chunks are stored both
1048 in the front of each chunk and at the end. This makes
1049 consolidating fragmented chunks into bigger chunks very fast. The
1050 size fields also hold bits representing whether chunks are free or
1051 in use.
1053 An allocated chunk looks like this:
1056 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1057 | Size of previous chunk, if allocated | |
1058 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1059 | Size of chunk, in bytes |P|
1060 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1061 | User data starts here... .
1063 . (malloc_usable_space() bytes) .
1065 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1066 | Size of chunk |
1067 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1070 Where "chunk" is the front of the chunk for the purpose of most of
1071 the malloc code, but "mem" is the pointer that is returned to the
1072 user. "Nextchunk" is the beginning of the next contiguous chunk.
1074 Chunks always begin on even word boundaries, so the mem portion
1075 (which is returned to the user) is also on an even word boundary, and
1076 thus double-word aligned.
1078 Free chunks are stored in circular doubly-linked lists, and look like this:
1080 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1081 | Size of previous chunk |
1082 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1083 `head:' | Size of chunk, in bytes |P|
1084 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1085 | Forward pointer to next chunk in list |
1086 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1087 | Back pointer to previous chunk in list |
1088 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1089 | Unused space (may be 0 bytes long) .
1092 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1093 `foot:' | Size of chunk, in bytes |
1094 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1096 The P (PREV_INUSE) bit, stored in the unused low-order bit of the
1097 chunk size (which is always a multiple of two words), is an in-use
1098 bit for the *previous* chunk. If that bit is *clear*, then the
1099 word before the current chunk size contains the previous chunk
1100 size, and can be used to find the front of the previous chunk.
1101 (The very first chunk allocated always has this bit set,
1102 preventing access to non-existent (or non-owned) memory.)
1104 Note that the `foot' of the current chunk is actually represented
1105 as the prev_size of the NEXT chunk. (This makes it easier to
1106 deal with alignments etc).
1108 The two exceptions to all this are
1110 1. The special chunk `top', which doesn't bother using the
1111 trailing size field since there is no
1112 next contiguous chunk that would have to index off it. (After
1113 initialization, `top' is forced to always exist. If it would
1114 become less than MINSIZE bytes long, it is replenished via
1115 malloc_extend_top.)
1117 2. Chunks allocated via mmap, which have the second-lowest-order
1118 bit (IS_MMAPPED) set in their size fields. Because they are
1119 never merged or traversed from any other chunk, they have no
1120 foot size or inuse information.
1122 Available chunks are kept in any of several places (all declared below):
1124 * `av': An array of chunks serving as bin headers for consolidated
1125 chunks. Each bin is doubly linked. The bins are approximately
1126 proportionally (log) spaced. There are a lot of these bins
1127 (128). This may look excessive, but works very well in
1128 practice. All procedures maintain the invariant that no
1129 consolidated chunk physically borders another one. Chunks in
1130 bins are kept in size order, with ties going to the
1131 approximately least recently used chunk.
1133 The chunks in each bin are maintained in decreasing sorted order by
1134 size. This is irrelevant for the small bins, which all contain
1135 the same-sized chunks, but facilitates best-fit allocation for
1136 larger chunks. (These lists are just sequential. Keeping them in
1137 order almost never requires enough traversal to warrant using
1138 fancier ordered data structures.) Chunks of the same size are
1139 linked with the most recently freed at the front, and allocations
1140 are taken from the back. This results in LRU or FIFO allocation
1141 order, which tends to give each chunk an equal opportunity to be
1142 consolidated with adjacent freed chunks, resulting in larger free
1143 chunks and less fragmentation.
1145 * `top': The top-most available chunk (i.e., the one bordering the
1146 end of available memory) is treated specially. It is never
1147 included in any bin, is used only if no other chunk is
1148 available, and is released back to the system if it is very
1149 large (see M_TRIM_THRESHOLD).
1151 * `last_remainder': A bin holding only the remainder of the
1152 most recently split (non-top) chunk. This bin is checked
1153 before other non-fitting chunks, so as to provide better
1154 locality for runs of sequentially allocated chunks.
1156 * Implicitly, through the host system's memory mapping tables.
1157 If supported, requests greater than a threshold are usually
1158 serviced via calls to mmap, and then later released via munmap.
1163 Bins
1165 The bins are an array of pairs of pointers serving as the
1166 heads of (initially empty) doubly-linked lists of chunks, laid out
1167 in a way so that each pair can be treated as if it were in a
1168 malloc_chunk. (This way, the fd/bk offsets for linking bin heads
1169 and chunks are the same).
1171 Bins for sizes < 512 bytes contain chunks of all the same size, spaced
1172 8 bytes apart. Larger bins are approximately logarithmically
1173 spaced. (See the table below.)
1175 Bin layout:
1177 64 bins of size 8
1178 32 bins of size 64
1179 16 bins of size 512
1180 8 bins of size 4096
1181 4 bins of size 32768
1182 2 bins of size 262144
1183 1 bin of size what's left
1185 There is actually a little bit of slop in the numbers in bin_index
1186 for the sake of speed. This makes no difference elsewhere.
1188 The special chunks `top' and `last_remainder' get their own bins,
1189 (this is implemented via yet more trickery with the av array),
1190 although `top' is never properly linked to its bin since it is
1191 always handled specially.
1195 #define NAV 128 /* number of bins */
1197 typedef struct malloc_chunk* mbinptr;
1199 /* An arena is a configuration of malloc_chunks together with an array
1200 of bins. With multiple threads, it must be locked via a mutex
1201 before changing its data structures. One or more `heaps' are
1202 associated with each arena, except for the main_arena, which is
1203 associated only with the `main heap', i.e. the conventional free
1204 store obtained with calls to MORECORE() (usually sbrk). The `av'
1205 array is never mentioned directly in the code, but instead used via
1206 bin access macros. */
1208 typedef struct _arena {
1209 mbinptr av[2*NAV + 2];
1210 struct _arena *next;
1211 size_t size;
1212 #if THREAD_STATS
1213 long stat_lock_direct, stat_lock_loop, stat_lock_wait;
1214 #endif
1215 mutex_t mutex;
1216 } arena;
1219 /* A heap is a single contiguous memory region holding (coalesceable)
1220 malloc_chunks. It is allocated with mmap() and always starts at an
1221 address aligned to HEAP_MAX_SIZE. Not used unless compiling with
1222 USE_ARENAS. */
1224 typedef struct _heap_info {
1225 arena *ar_ptr; /* Arena for this heap. */
1226 struct _heap_info *prev; /* Previous heap. */
1227 size_t size; /* Current size in bytes. */
1228 size_t pad; /* Make sure the following data is properly aligned. */
1229 } heap_info;
1233 Static functions (forward declarations)
1236 #if __STD_C
1238 static void chunk_free(arena *ar_ptr, mchunkptr p) internal_function;
1239 static mchunkptr chunk_alloc(arena *ar_ptr, INTERNAL_SIZE_T size)
1240 internal_function;
1241 static mchunkptr chunk_realloc(arena *ar_ptr, mchunkptr oldp,
1242 INTERNAL_SIZE_T oldsize, INTERNAL_SIZE_T nb)
1243 internal_function;
1244 static mchunkptr chunk_align(arena *ar_ptr, INTERNAL_SIZE_T nb,
1245 size_t alignment) internal_function;
1246 static int main_trim(size_t pad) internal_function;
1247 #if USE_ARENAS
1248 static int heap_trim(heap_info *heap, size_t pad) internal_function;
1249 #endif
1250 #if defined _LIBC || defined MALLOC_HOOKS
1251 static Void_t* malloc_check(size_t sz, const Void_t *caller);
1252 static void free_check(Void_t* mem, const Void_t *caller);
1253 static Void_t* realloc_check(Void_t* oldmem, size_t bytes,
1254 const Void_t *caller);
1255 static Void_t* memalign_check(size_t alignment, size_t bytes,
1256 const Void_t *caller);
1257 #ifndef NO_THREADS
1258 static Void_t* malloc_starter(size_t sz, const Void_t *caller);
1259 static void free_starter(Void_t* mem, const Void_t *caller);
1260 static Void_t* malloc_atfork(size_t sz, const Void_t *caller);
1261 static void free_atfork(Void_t* mem, const Void_t *caller);
1262 #endif
1263 #endif
1265 #else
1267 static void chunk_free();
1268 static mchunkptr chunk_alloc();
1269 static mchunkptr chunk_realloc();
1270 static mchunkptr chunk_align();
1271 static int main_trim();
1272 #if USE_ARENAS
1273 static int heap_trim();
1274 #endif
1275 #if defined _LIBC || defined MALLOC_HOOKS
1276 static Void_t* malloc_check();
1277 static void free_check();
1278 static Void_t* realloc_check();
1279 static Void_t* memalign_check();
1280 #ifndef NO_THREADS
1281 static Void_t* malloc_starter();
1282 static void free_starter();
1283 static Void_t* malloc_atfork();
1284 static void free_atfork();
1285 #endif
1286 #endif
1288 #endif
1292 /* sizes, alignments */
1294 #define SIZE_SZ (sizeof(INTERNAL_SIZE_T))
1295 /* Allow the default to be overwritten on the compiler command line. */
1296 #ifndef MALLOC_ALIGNMENT
1297 # define MALLOC_ALIGNMENT (SIZE_SZ + SIZE_SZ)
1298 #endif
1299 #define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)
1300 #define MINSIZE (sizeof(struct malloc_chunk))
1302 /* conversion from malloc headers to user pointers, and back */
1304 #define chunk2mem(p) ((Void_t*)((char*)(p) + 2*SIZE_SZ))
1305 #define mem2chunk(mem) chunk_at_offset((mem), -2*SIZE_SZ)
1307 /* pad request bytes into a usable size, return non-zero on overflow */
1309 #define request2size(req, nb) \
1310 ((nb = (req) + (SIZE_SZ + MALLOC_ALIGN_MASK)),\
1311 ((long)nb <= 0 || nb < (INTERNAL_SIZE_T) (req) \
1312 ? (__set_errno (ENOMEM), 1) \
1313 : ((nb < (MINSIZE + MALLOC_ALIGN_MASK) \
1314 ? (nb = MINSIZE) : (nb &= ~MALLOC_ALIGN_MASK)), 0)))
1316 /* Check if m has acceptable alignment */
1318 #define aligned_OK(m) (((unsigned long)((m)) & (MALLOC_ALIGN_MASK)) == 0)
1324 Physical chunk operations
1328 /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
1330 #define PREV_INUSE 0x1UL
1332 /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
1334 #define IS_MMAPPED 0x2UL
1336 /* Bits to mask off when extracting size */
1338 #define SIZE_BITS (PREV_INUSE|IS_MMAPPED)
1341 /* Ptr to next physical malloc_chunk. */
1343 #define next_chunk(p) chunk_at_offset((p), (p)->size & ~PREV_INUSE)
1345 /* Ptr to previous physical malloc_chunk */
1347 #define prev_chunk(p) chunk_at_offset((p), -(p)->prev_size)
1350 /* Treat space at ptr + offset as a chunk */
1352 #define chunk_at_offset(p, s) BOUNDED_1((mchunkptr)(((char*)(p)) + (s)))
1358 Dealing with use bits
1361 /* extract p's inuse bit */
1363 #define inuse(p) (next_chunk(p)->size & PREV_INUSE)
1365 /* extract inuse bit of previous chunk */
1367 #define prev_inuse(p) ((p)->size & PREV_INUSE)
1369 /* check for mmap()'ed chunk */
1371 #define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
1373 /* set/clear chunk as in use without otherwise disturbing */
1375 #define set_inuse(p) (next_chunk(p)->size |= PREV_INUSE)
1377 #define clear_inuse(p) (next_chunk(p)->size &= ~PREV_INUSE)
1379 /* check/set/clear inuse bits in known places */
1381 #define inuse_bit_at_offset(p, s) \
1382 (chunk_at_offset((p), (s))->size & PREV_INUSE)
1384 #define set_inuse_bit_at_offset(p, s) \
1385 (chunk_at_offset((p), (s))->size |= PREV_INUSE)
1387 #define clear_inuse_bit_at_offset(p, s) \
1388 (chunk_at_offset((p), (s))->size &= ~(PREV_INUSE))
1394 Dealing with size fields
1397 /* Get size, ignoring use bits */
1399 #define chunksize(p) ((p)->size & ~(SIZE_BITS))
1401 /* Set size at head, without disturbing its use bit */
1403 #define set_head_size(p, s) ((p)->size = (((p)->size & PREV_INUSE) | (s)))
1405 /* Set size/use ignoring previous bits in header */
1407 #define set_head(p, s) ((p)->size = (s))
1409 /* Set size at footer (only when chunk is not in use) */
1411 #define set_foot(p, s) (chunk_at_offset(p, s)->prev_size = (s))
1417 /* access macros */
1419 #define bin_at(a, i) BOUNDED_1(_bin_at(a, i))
1420 #define _bin_at(a, i) ((mbinptr)((char*)&(((a)->av)[2*(i)+2]) - 2*SIZE_SZ))
1421 #define init_bin(a, i) ((a)->av[2*(i)+2] = (a)->av[2*(i)+3] = bin_at((a), (i)))
1422 #define next_bin(b) ((mbinptr)((char*)(b) + 2 * sizeof(((arena*)0)->av[0])))
1423 #define prev_bin(b) ((mbinptr)((char*)(b) - 2 * sizeof(((arena*)0)->av[0])))
1426 The first 2 bins are never indexed. The corresponding av cells are instead
1427 used for bookkeeping. This is not to save space, but to simplify
1428 indexing, maintain locality, and avoid some initialization tests.
1431 #define binblocks(a) (bin_at(a,0)->size)/* bitvector of nonempty blocks */
1432 #define top(a) (bin_at(a,0)->fd) /* The topmost chunk */
1433 #define last_remainder(a) (bin_at(a,1)) /* remainder from last split */
1436 Because top initially points to its own bin with initial
1437 zero size, thus forcing extension on the first malloc request,
1438 we avoid having any special code in malloc to check whether
1439 it even exists yet. But we still need to in malloc_extend_top.
1442 #define initial_top(a) ((mchunkptr)bin_at(a, 0))
1446 /* field-extraction macros */
1448 #define first(b) ((b)->fd)
1449 #define last(b) ((b)->bk)
1452 Indexing into bins
1455 #define bin_index(sz) \
1456 (((((unsigned long)(sz)) >> 9) == 0) ? (((unsigned long)(sz)) >> 3):\
1457 ((((unsigned long)(sz)) >> 9) <= 4) ? 56 + (((unsigned long)(sz)) >> 6):\
1458 ((((unsigned long)(sz)) >> 9) <= 20) ? 91 + (((unsigned long)(sz)) >> 9):\
1459 ((((unsigned long)(sz)) >> 9) <= 84) ? 110 + (((unsigned long)(sz)) >> 12):\
1460 ((((unsigned long)(sz)) >> 9) <= 340) ? 119 + (((unsigned long)(sz)) >> 15):\
1461 ((((unsigned long)(sz)) >> 9) <= 1364) ? 124 + (((unsigned long)(sz)) >> 18):\
1462 126)
1464 bins for chunks < 512 are all spaced 8 bytes apart, and hold
1465 identically sized chunks. This is exploited in malloc.
1468 #define MAX_SMALLBIN 63
1469 #define MAX_SMALLBIN_SIZE 512
1470 #define SMALLBIN_WIDTH 8
1472 #define smallbin_index(sz) (((unsigned long)(sz)) >> 3)
1475 Requests are `small' if both the corresponding and the next bin are small
1478 #define is_small_request(nb) ((nb) < MAX_SMALLBIN_SIZE - SMALLBIN_WIDTH)
1483 To help compensate for the large number of bins, a one-level index
1484 structure is used for bin-by-bin searching. `binblocks' is a
1485 one-word bitvector recording whether groups of BINBLOCKWIDTH bins
1486 have any (possibly) non-empty bins, so they can be skipped over
1487 all at once during during traversals. The bits are NOT always
1488 cleared as soon as all bins in a block are empty, but instead only
1489 when all are noticed to be empty during traversal in malloc.
1492 #define BINBLOCKWIDTH 4 /* bins per block */
1494 /* bin<->block macros */
1496 #define idx2binblock(ix) ((unsigned)1 << ((ix) / BINBLOCKWIDTH))
1497 #define mark_binblock(a, ii) (binblocks(a) |= idx2binblock(ii))
1498 #define clear_binblock(a, ii) (binblocks(a) &= ~(idx2binblock(ii)))
1503 /* Static bookkeeping data */
1505 /* Helper macro to initialize bins */
1506 #define IAV(i) _bin_at(&main_arena, i), _bin_at(&main_arena, i)
1508 static arena main_arena = {
1510 0, 0,
1511 IAV(0), IAV(1), IAV(2), IAV(3), IAV(4), IAV(5), IAV(6), IAV(7),
1512 IAV(8), IAV(9), IAV(10), IAV(11), IAV(12), IAV(13), IAV(14), IAV(15),
1513 IAV(16), IAV(17), IAV(18), IAV(19), IAV(20), IAV(21), IAV(22), IAV(23),
1514 IAV(24), IAV(25), IAV(26), IAV(27), IAV(28), IAV(29), IAV(30), IAV(31),
1515 IAV(32), IAV(33), IAV(34), IAV(35), IAV(36), IAV(37), IAV(38), IAV(39),
1516 IAV(40), IAV(41), IAV(42), IAV(43), IAV(44), IAV(45), IAV(46), IAV(47),
1517 IAV(48), IAV(49), IAV(50), IAV(51), IAV(52), IAV(53), IAV(54), IAV(55),
1518 IAV(56), IAV(57), IAV(58), IAV(59), IAV(60), IAV(61), IAV(62), IAV(63),
1519 IAV(64), IAV(65), IAV(66), IAV(67), IAV(68), IAV(69), IAV(70), IAV(71),
1520 IAV(72), IAV(73), IAV(74), IAV(75), IAV(76), IAV(77), IAV(78), IAV(79),
1521 IAV(80), IAV(81), IAV(82), IAV(83), IAV(84), IAV(85), IAV(86), IAV(87),
1522 IAV(88), IAV(89), IAV(90), IAV(91), IAV(92), IAV(93), IAV(94), IAV(95),
1523 IAV(96), IAV(97), IAV(98), IAV(99), IAV(100), IAV(101), IAV(102), IAV(103),
1524 IAV(104), IAV(105), IAV(106), IAV(107), IAV(108), IAV(109), IAV(110), IAV(111),
1525 IAV(112), IAV(113), IAV(114), IAV(115), IAV(116), IAV(117), IAV(118), IAV(119),
1526 IAV(120), IAV(121), IAV(122), IAV(123), IAV(124), IAV(125), IAV(126), IAV(127)
1528 &main_arena, /* next */
1529 0, /* size */
1530 #if THREAD_STATS
1531 0, 0, 0, /* stat_lock_direct, stat_lock_loop, stat_lock_wait */
1532 #endif
1533 MUTEX_INITIALIZER /* mutex */
1536 #undef IAV
1538 /* Thread specific data */
1540 static tsd_key_t arena_key;
1541 static mutex_t list_lock = MUTEX_INITIALIZER;
1543 #if THREAD_STATS
1544 static int stat_n_heaps;
1545 #define THREAD_STAT(x) x
1546 #else
1547 #define THREAD_STAT(x) do ; while(0)
1548 #endif
1550 /* variables holding tunable values */
1552 static unsigned long trim_threshold = DEFAULT_TRIM_THRESHOLD;
1553 static unsigned long top_pad = DEFAULT_TOP_PAD;
1554 static unsigned int n_mmaps_max = DEFAULT_MMAP_MAX;
1555 static unsigned long mmap_threshold = DEFAULT_MMAP_THRESHOLD;
1556 static int check_action = DEFAULT_CHECK_ACTION;
1558 /* The first value returned from sbrk */
1559 static char* sbrk_base = (char*)(-1);
1561 /* The maximum memory obtained from system via sbrk */
1562 static unsigned long max_sbrked_mem;
1564 /* The maximum via either sbrk or mmap (too difficult to track with threads) */
1565 #ifdef NO_THREADS
1566 static unsigned long max_total_mem;
1567 #endif
1569 /* The total memory obtained from system via sbrk */
1570 #define sbrked_mem (main_arena.size)
1572 /* Tracking mmaps */
1574 static unsigned int n_mmaps;
1575 static unsigned int max_n_mmaps;
1576 static unsigned long mmapped_mem;
1577 static unsigned long max_mmapped_mem;
1579 /* Mapped memory in non-main arenas (reliable only for NO_THREADS). */
1580 static unsigned long arena_mem;
1584 #ifndef _LIBC
1585 #define weak_variable
1586 #else
1587 /* In GNU libc we want the hook variables to be weak definitions to
1588 avoid a problem with Emacs. */
1589 #define weak_variable weak_function
1590 #endif
1592 /* Already initialized? */
1593 int __malloc_initialized = -1;
1596 #ifndef NO_THREADS
1598 /* Magic value for the thread-specific arena pointer when
1599 malloc_atfork() is in use. */
1601 #define ATFORK_ARENA_PTR ((Void_t*)-1)
1603 /* The following two functions are registered via thread_atfork() to
1604 make sure that the mutexes remain in a consistent state in the
1605 fork()ed version of a thread. Also adapt the malloc and free hooks
1606 temporarily, because the `atfork' handler mechanism may use
1607 malloc/free internally (e.g. in LinuxThreads). */
1609 #if defined _LIBC || defined MALLOC_HOOKS
1610 static __malloc_ptr_t (*save_malloc_hook) __MALLOC_P ((size_t __size,
1611 const __malloc_ptr_t));
1612 static void (*save_free_hook) __MALLOC_P ((__malloc_ptr_t __ptr,
1613 const __malloc_ptr_t));
1614 static Void_t* save_arena;
1615 #endif
1617 static void
1618 ptmalloc_lock_all __MALLOC_P((void))
1620 arena *ar_ptr;
1622 (void)mutex_lock(&list_lock);
1623 for(ar_ptr = &main_arena;;) {
1624 (void)mutex_lock(&ar_ptr->mutex);
1625 ar_ptr = ar_ptr->next;
1626 if(ar_ptr == &main_arena) break;
1628 #if defined _LIBC || defined MALLOC_HOOKS
1629 save_malloc_hook = __malloc_hook;
1630 save_free_hook = __free_hook;
1631 __malloc_hook = malloc_atfork;
1632 __free_hook = free_atfork;
1633 /* Only the current thread may perform malloc/free calls now. */
1634 tsd_getspecific(arena_key, save_arena);
1635 tsd_setspecific(arena_key, ATFORK_ARENA_PTR);
1636 #endif
1639 static void
1640 ptmalloc_unlock_all __MALLOC_P((void))
1642 arena *ar_ptr;
1644 #if defined _LIBC || defined MALLOC_HOOKS
1645 tsd_setspecific(arena_key, save_arena);
1646 __malloc_hook = save_malloc_hook;
1647 __free_hook = save_free_hook;
1648 #endif
1649 for(ar_ptr = &main_arena;;) {
1650 (void)mutex_unlock(&ar_ptr->mutex);
1651 ar_ptr = ar_ptr->next;
1652 if(ar_ptr == &main_arena) break;
1654 (void)mutex_unlock(&list_lock);
1657 static void
1658 ptmalloc_init_all __MALLOC_P((void))
1660 arena *ar_ptr;
1662 #if defined _LIBC || defined MALLOC_HOOKS
1663 tsd_setspecific(arena_key, save_arena);
1664 __malloc_hook = save_malloc_hook;
1665 __free_hook = save_free_hook;
1666 #endif
1667 for(ar_ptr = &main_arena;;) {
1668 (void)mutex_init(&ar_ptr->mutex);
1669 ar_ptr = ar_ptr->next;
1670 if(ar_ptr == &main_arena) break;
1672 (void)mutex_init(&list_lock);
1675 #endif /* !defined NO_THREADS */
1677 /* Initialization routine. */
1678 #if defined(_LIBC)
1679 #if 0
1680 static void ptmalloc_init __MALLOC_P ((void)) __attribute__ ((constructor));
1681 #endif
1683 #ifdef _LIBC
1684 #include <string.h>
1685 extern char **_environ;
1687 static char *
1688 internal_function
1689 next_env_entry (char ***position)
1691 char **current = *position;
1692 char *result = NULL;
1694 while (*current != NULL)
1696 if (__builtin_expect ((*current)[0] == 'M', 0)
1697 && (*current)[1] == 'A'
1698 && (*current)[2] == 'L'
1699 && (*current)[3] == 'L'
1700 && (*current)[4] == 'O'
1701 && (*current)[5] == 'C'
1702 && (*current)[6] == '_')
1704 result = &(*current)[7];
1706 /* Save current position for next visit. */
1707 *position = ++current;
1709 break;
1712 ++current;
1715 return result;
1717 #endif
1719 static void
1720 ptmalloc_init __MALLOC_P((void))
1721 #else
1722 void
1723 ptmalloc_init __MALLOC_P((void))
1724 #endif
1726 #if defined _LIBC || defined MALLOC_HOOKS
1727 # if __STD_C
1728 const char* s;
1729 # else
1730 char* s;
1731 # endif
1732 #endif
1733 int secure;
1735 if(__malloc_initialized >= 0) return;
1736 __malloc_initialized = 0;
1737 #ifdef _LIBC
1738 __libc_pagesize = __getpagesize();
1739 #endif
1740 #ifndef NO_THREADS
1741 #if defined _LIBC || defined MALLOC_HOOKS
1742 /* With some threads implementations, creating thread-specific data
1743 or initializing a mutex may call malloc() itself. Provide a
1744 simple starter version (realloc() won't work). */
1745 save_malloc_hook = __malloc_hook;
1746 save_free_hook = __free_hook;
1747 __malloc_hook = malloc_starter;
1748 __free_hook = free_starter;
1749 #endif
1750 #ifdef _LIBC
1751 /* Initialize the pthreads interface. */
1752 if (__pthread_initialize != NULL)
1753 __pthread_initialize();
1754 #endif
1755 #endif /* !defined NO_THREADS */
1756 mutex_init(&main_arena.mutex);
1757 mutex_init(&list_lock);
1758 tsd_key_create(&arena_key, NULL);
1759 tsd_setspecific(arena_key, (Void_t *)&main_arena);
1760 thread_atfork(ptmalloc_lock_all, ptmalloc_unlock_all, ptmalloc_init_all);
1761 #if defined _LIBC || defined MALLOC_HOOKS
1762 #ifndef NO_THREADS
1763 __malloc_hook = save_malloc_hook;
1764 __free_hook = save_free_hook;
1765 #endif
1766 secure = __libc_enable_secure;
1767 #ifdef _LIBC
1768 s = NULL;
1769 if (_environ != NULL)
1771 char **runp = _environ;
1772 char *envline;
1774 while (__builtin_expect ((envline = next_env_entry (&runp)) != NULL, 0))
1776 size_t len = strcspn (envline, "=");
1778 if (envline[len] != '=')
1779 /* This is a "MALLOC_" variable at the end of the string
1780 without a '=' character. Ignore it since otherwise we
1781 will access invalid memory below. */
1782 continue;
1784 switch (len)
1786 case 6:
1787 if (memcmp (envline, "CHECK_", 6) == 0)
1788 s = &envline[7];
1789 break;
1790 case 8:
1791 if (! secure && memcmp (envline, "TOP_PAD_", 8) == 0)
1792 mALLOPt(M_TOP_PAD, atoi(&envline[9]));
1793 break;
1794 case 9:
1795 if (! secure && memcmp (envline, "MMAP_MAX_", 9) == 0)
1796 mALLOPt(M_MMAP_MAX, atoi(&envline[10]));
1797 break;
1798 case 15:
1799 if (! secure)
1801 if (memcmp (envline, "TRIM_THRESHOLD_", 15) == 0)
1802 mALLOPt(M_TRIM_THRESHOLD, atoi(&envline[16]));
1803 else if (memcmp (envline, "MMAP_THRESHOLD_", 15) == 0)
1804 mALLOPt(M_MMAP_THRESHOLD, atoi(&envline[16]));
1806 break;
1807 default:
1808 break;
1812 #else
1813 if (! secure)
1815 if((s = getenv("MALLOC_TRIM_THRESHOLD_")))
1816 mALLOPt(M_TRIM_THRESHOLD, atoi(s));
1817 if((s = getenv("MALLOC_TOP_PAD_")))
1818 mALLOPt(M_TOP_PAD, atoi(s));
1819 if((s = getenv("MALLOC_MMAP_THRESHOLD_")))
1820 mALLOPt(M_MMAP_THRESHOLD, atoi(s));
1821 if((s = getenv("MALLOC_MMAP_MAX_")))
1822 mALLOPt(M_MMAP_MAX, atoi(s));
1824 s = getenv("MALLOC_CHECK_");
1825 #endif
1826 if(s) {
1827 if(s[0]) mALLOPt(M_CHECK_ACTION, (int)(s[0] - '0'));
1828 __malloc_check_init();
1830 if(__malloc_initialize_hook != NULL)
1831 (*__malloc_initialize_hook)();
1832 #endif
1833 __malloc_initialized = 1;
1836 /* There are platforms (e.g. Hurd) with a link-time hook mechanism. */
1837 #ifdef thread_atfork_static
1838 thread_atfork_static(ptmalloc_lock_all, ptmalloc_unlock_all, \
1839 ptmalloc_init_all)
1840 #endif
1842 #if defined _LIBC || defined MALLOC_HOOKS
1844 /* Hooks for debugging versions. The initial hooks just call the
1845 initialization routine, then do the normal work. */
1847 static Void_t*
1848 #if __STD_C
1849 malloc_hook_ini(size_t sz, const __malloc_ptr_t caller)
1850 #else
1851 malloc_hook_ini(sz, caller)
1852 size_t sz; const __malloc_ptr_t caller;
1853 #endif
1855 __malloc_hook = NULL;
1856 ptmalloc_init();
1857 return mALLOc(sz);
1860 static Void_t*
1861 #if __STD_C
1862 realloc_hook_ini(Void_t* ptr, size_t sz, const __malloc_ptr_t caller)
1863 #else
1864 realloc_hook_ini(ptr, sz, caller)
1865 Void_t* ptr; size_t sz; const __malloc_ptr_t caller;
1866 #endif
1868 __malloc_hook = NULL;
1869 __realloc_hook = NULL;
1870 ptmalloc_init();
1871 return rEALLOc(ptr, sz);
1874 static Void_t*
1875 #if __STD_C
1876 memalign_hook_ini(size_t alignment, size_t sz, const __malloc_ptr_t caller)
1877 #else
1878 memalign_hook_ini(alignment, sz, caller)
1879 size_t alignment; size_t sz; const __malloc_ptr_t caller;
1880 #endif
1882 __memalign_hook = NULL;
1883 ptmalloc_init();
1884 return mEMALIGn(alignment, sz);
1887 void weak_variable (*__malloc_initialize_hook) __MALLOC_P ((void)) = NULL;
1888 void weak_variable (*__free_hook) __MALLOC_P ((__malloc_ptr_t __ptr,
1889 const __malloc_ptr_t)) = NULL;
1890 __malloc_ptr_t weak_variable (*__malloc_hook)
1891 __MALLOC_P ((size_t __size, const __malloc_ptr_t)) = malloc_hook_ini;
1892 __malloc_ptr_t weak_variable (*__realloc_hook)
1893 __MALLOC_P ((__malloc_ptr_t __ptr, size_t __size, const __malloc_ptr_t))
1894 = realloc_hook_ini;
1895 __malloc_ptr_t weak_variable (*__memalign_hook)
1896 __MALLOC_P ((size_t __alignment, size_t __size, const __malloc_ptr_t))
1897 = memalign_hook_ini;
1898 void weak_variable (*__after_morecore_hook) __MALLOC_P ((void)) = NULL;
1900 /* Whether we are using malloc checking. */
1901 static int using_malloc_checking;
1903 /* A flag that is set by malloc_set_state, to signal that malloc checking
1904 must not be enabled on the request from the user (via the MALLOC_CHECK_
1905 environment variable). It is reset by __malloc_check_init to tell
1906 malloc_set_state that the user has requested malloc checking.
1908 The purpose of this flag is to make sure that malloc checking is not
1909 enabled when the heap to be restored was constructed without malloc
1910 checking, and thus does not contain the required magic bytes.
1911 Otherwise the heap would be corrupted by calls to free and realloc. If
1912 it turns out that the heap was created with malloc checking and the
1913 user has requested it malloc_set_state just calls __malloc_check_init
1914 again to enable it. On the other hand, reusing such a heap without
1915 further malloc checking is safe. */
1916 static int disallow_malloc_check;
1918 /* Activate a standard set of debugging hooks. */
1919 void
1920 __malloc_check_init()
1922 if (disallow_malloc_check) {
1923 disallow_malloc_check = 0;
1924 return;
1926 using_malloc_checking = 1;
1927 __malloc_hook = malloc_check;
1928 __free_hook = free_check;
1929 __realloc_hook = realloc_check;
1930 __memalign_hook = memalign_check;
1931 if(check_action & 1)
1932 fprintf(stderr, "malloc: using debugging hooks\n");
1935 #endif
1941 /* Routines dealing with mmap(). */
1943 #if HAVE_MMAP
1945 #ifndef MAP_ANONYMOUS
1947 static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */
1949 #define MMAP(addr, size, prot, flags) ((dev_zero_fd < 0) ? \
1950 (dev_zero_fd = open("/dev/zero", O_RDWR), \
1951 mmap((addr), (size), (prot), (flags), dev_zero_fd, 0)) : \
1952 mmap((addr), (size), (prot), (flags), dev_zero_fd, 0))
1954 #else
1956 #define MMAP(addr, size, prot, flags) \
1957 (mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS, -1, 0))
1959 #endif
1961 #if defined __GNUC__ && __GNUC__ >= 2
1962 /* This function is only called from one place, inline it. */
1963 __inline__
1964 #endif
1965 static mchunkptr
1966 internal_function
1967 #if __STD_C
1968 mmap_chunk(size_t size)
1969 #else
1970 mmap_chunk(size) size_t size;
1971 #endif
1973 size_t page_mask = malloc_getpagesize - 1;
1974 mchunkptr p;
1976 /* For mmapped chunks, the overhead is one SIZE_SZ unit larger, because
1977 * there is no following chunk whose prev_size field could be used.
1979 size = (size + SIZE_SZ + page_mask) & ~page_mask;
1981 p = (mchunkptr)MMAP(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE);
1982 if(p == (mchunkptr) MAP_FAILED) return 0;
1984 n_mmaps++;
1985 if (n_mmaps > max_n_mmaps) max_n_mmaps = n_mmaps;
1987 /* We demand that eight bytes into a page must be 8-byte aligned. */
1988 assert(aligned_OK(chunk2mem(p)));
1990 /* The offset to the start of the mmapped region is stored
1991 * in the prev_size field of the chunk; normally it is zero,
1992 * but that can be changed in memalign().
1994 p->prev_size = 0;
1995 set_head(p, size|IS_MMAPPED);
1997 mmapped_mem += size;
1998 if ((unsigned long)mmapped_mem > (unsigned long)max_mmapped_mem)
1999 max_mmapped_mem = mmapped_mem;
2000 #ifdef NO_THREADS
2001 if ((unsigned long)(mmapped_mem + arena_mem + sbrked_mem) > max_total_mem)
2002 max_total_mem = mmapped_mem + arena_mem + sbrked_mem;
2003 #endif
2004 return p;
2007 static void
2008 internal_function
2009 #if __STD_C
2010 munmap_chunk(mchunkptr p)
2011 #else
2012 munmap_chunk(p) mchunkptr p;
2013 #endif
2015 INTERNAL_SIZE_T size = chunksize(p);
2016 int ret;
2018 assert (chunk_is_mmapped(p));
2019 assert(! ((char*)p >= sbrk_base && (char*)p < sbrk_base + sbrked_mem));
2020 assert((n_mmaps > 0));
2021 assert(((p->prev_size + size) & (malloc_getpagesize-1)) == 0);
2023 n_mmaps--;
2024 mmapped_mem -= (size + p->prev_size);
2026 ret = munmap((char *)p - p->prev_size, size + p->prev_size);
2028 /* munmap returns non-zero on failure */
2029 assert(ret == 0);
2032 #if HAVE_MREMAP
2034 static mchunkptr
2035 internal_function
2036 #if __STD_C
2037 mremap_chunk(mchunkptr p, size_t new_size)
2038 #else
2039 mremap_chunk(p, new_size) mchunkptr p; size_t new_size;
2040 #endif
2042 size_t page_mask = malloc_getpagesize - 1;
2043 INTERNAL_SIZE_T offset = p->prev_size;
2044 INTERNAL_SIZE_T size = chunksize(p);
2045 char *cp;
2047 assert (chunk_is_mmapped(p));
2048 assert(! ((char*)p >= sbrk_base && (char*)p < sbrk_base + sbrked_mem));
2049 assert((n_mmaps > 0));
2050 assert(((size + offset) & (malloc_getpagesize-1)) == 0);
2052 /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
2053 new_size = (new_size + offset + SIZE_SZ + page_mask) & ~page_mask;
2055 cp = (char *)mremap((char *)p - offset, size + offset, new_size,
2056 MREMAP_MAYMOVE);
2058 if (cp == MAP_FAILED) return 0;
2060 p = (mchunkptr)(cp + offset);
2062 assert(aligned_OK(chunk2mem(p)));
2064 assert((p->prev_size == offset));
2065 set_head(p, (new_size - offset)|IS_MMAPPED);
2067 mmapped_mem -= size + offset;
2068 mmapped_mem += new_size;
2069 if ((unsigned long)mmapped_mem > (unsigned long)max_mmapped_mem)
2070 max_mmapped_mem = mmapped_mem;
2071 #ifdef NO_THREADS
2072 if ((unsigned long)(mmapped_mem + arena_mem + sbrked_mem) > max_total_mem)
2073 max_total_mem = mmapped_mem + arena_mem + sbrked_mem;
2074 #endif
2075 return p;
2078 #endif /* HAVE_MREMAP */
2080 #endif /* HAVE_MMAP */
2084 /* Managing heaps and arenas (for concurrent threads) */
2086 #if USE_ARENAS
2088 /* Create a new heap. size is automatically rounded up to a multiple
2089 of the page size. */
2091 static heap_info *
2092 internal_function
2093 #if __STD_C
2094 new_heap(size_t size)
2095 #else
2096 new_heap(size) size_t size;
2097 #endif
2099 size_t page_mask = malloc_getpagesize - 1;
2100 char *p1, *p2;
2101 unsigned long ul;
2102 heap_info *h;
2104 if(size+top_pad < HEAP_MIN_SIZE)
2105 size = HEAP_MIN_SIZE;
2106 else if(size+top_pad <= HEAP_MAX_SIZE)
2107 size += top_pad;
2108 else if(size > HEAP_MAX_SIZE)
2109 return 0;
2110 else
2111 size = HEAP_MAX_SIZE;
2112 size = (size + page_mask) & ~page_mask;
2114 /* A memory region aligned to a multiple of HEAP_MAX_SIZE is needed.
2115 No swap space needs to be reserved for the following large
2116 mapping (on Linux, this is the case for all non-writable mappings
2117 anyway). */
2118 p1 = (char *)MMAP(0, HEAP_MAX_SIZE<<1, PROT_NONE, MAP_PRIVATE|MAP_NORESERVE);
2119 if(p1 != MAP_FAILED) {
2120 p2 = (char *)(((unsigned long)p1 + (HEAP_MAX_SIZE-1)) & ~(HEAP_MAX_SIZE-1));
2121 ul = p2 - p1;
2122 if (ul)
2123 munmap(p1, ul);
2124 munmap(p2 + HEAP_MAX_SIZE, HEAP_MAX_SIZE - ul);
2125 } else {
2126 /* Try to take the chance that an allocation of only HEAP_MAX_SIZE
2127 is already aligned. */
2128 p2 = (char *)MMAP(0, HEAP_MAX_SIZE, PROT_NONE, MAP_PRIVATE|MAP_NORESERVE);
2129 if(p2 == MAP_FAILED)
2130 return 0;
2131 if((unsigned long)p2 & (HEAP_MAX_SIZE-1)) {
2132 munmap(p2, HEAP_MAX_SIZE);
2133 return 0;
2136 if(MMAP(p2, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED)
2137 == (char *) MAP_FAILED) {
2138 munmap(p2, HEAP_MAX_SIZE);
2139 return 0;
2141 h = (heap_info *)p2;
2142 h->size = size;
2143 THREAD_STAT(stat_n_heaps++);
2144 return h;
2147 /* Grow or shrink a heap. size is automatically rounded up to a
2148 multiple of the page size if it is positive. */
2150 static int
2151 #if __STD_C
2152 grow_heap(heap_info *h, long diff)
2153 #else
2154 grow_heap(h, diff) heap_info *h; long diff;
2155 #endif
2157 size_t page_mask = malloc_getpagesize - 1;
2158 long new_size;
2160 if(diff >= 0) {
2161 diff = (diff + page_mask) & ~page_mask;
2162 new_size = (long)h->size + diff;
2163 if(new_size > HEAP_MAX_SIZE)
2164 return -1;
2165 if(MMAP((char *)h + h->size, diff, PROT_READ|PROT_WRITE,
2166 MAP_PRIVATE|MAP_FIXED) == (char *) MAP_FAILED)
2167 return -2;
2168 } else {
2169 new_size = (long)h->size + diff;
2170 if(new_size < (long)sizeof(*h))
2171 return -1;
2172 /* Try to re-map the extra heap space freshly to save memory, and
2173 make it inaccessible. */
2174 if((char *)MMAP((char *)h + new_size, -diff, PROT_NONE,
2175 MAP_PRIVATE|MAP_FIXED) == (char *) MAP_FAILED)
2176 return -2;
2178 h->size = new_size;
2179 return 0;
2182 /* Delete a heap. */
2184 #define delete_heap(heap) munmap((char*)(heap), HEAP_MAX_SIZE)
2186 /* arena_get() acquires an arena and locks the corresponding mutex.
2187 First, try the one last locked successfully by this thread. (This
2188 is the common case and handled with a macro for speed.) Then, loop
2189 once over the circularly linked list of arenas. If no arena is
2190 readily available, create a new one. In this latter case, `size'
2191 is just a hint as to how much memory will be required immediately
2192 in the new arena. */
2194 #define arena_get(ptr, size) do { \
2195 Void_t *vptr = NULL; \
2196 ptr = (arena *)tsd_getspecific(arena_key, vptr); \
2197 if(ptr && !mutex_trylock(&ptr->mutex)) { \
2198 THREAD_STAT(++(ptr->stat_lock_direct)); \
2199 } else \
2200 ptr = arena_get2(ptr, (size)); \
2201 } while(0)
2203 static arena *
2204 internal_function
2205 #if __STD_C
2206 arena_get2(arena *a_tsd, size_t size)
2207 #else
2208 arena_get2(a_tsd, size) arena *a_tsd; size_t size;
2209 #endif
2211 arena *a;
2212 heap_info *h;
2213 char *ptr;
2214 int i;
2215 unsigned long misalign;
2217 if(!a_tsd)
2218 a = a_tsd = &main_arena;
2219 else {
2220 a = a_tsd->next;
2221 if(!a) {
2222 /* This can only happen while initializing the new arena. */
2223 (void)mutex_lock(&main_arena.mutex);
2224 THREAD_STAT(++(main_arena.stat_lock_wait));
2225 return &main_arena;
2229 /* Check the global, circularly linked list for available arenas. */
2230 repeat:
2231 do {
2232 if(!mutex_trylock(&a->mutex)) {
2233 THREAD_STAT(++(a->stat_lock_loop));
2234 tsd_setspecific(arena_key, (Void_t *)a);
2235 return a;
2237 a = a->next;
2238 } while(a != a_tsd);
2240 /* If not even the list_lock can be obtained, try again. This can
2241 happen during `atfork', or for example on systems where thread
2242 creation makes it temporarily impossible to obtain _any_
2243 locks. */
2244 if(mutex_trylock(&list_lock)) {
2245 a = a_tsd;
2246 goto repeat;
2248 (void)mutex_unlock(&list_lock);
2250 /* Nothing immediately available, so generate a new arena. */
2251 h = new_heap(size + (sizeof(*h) + sizeof(*a) + MALLOC_ALIGNMENT));
2252 if(!h) {
2253 /* Maybe size is too large to fit in a single heap. So, just try
2254 to create a minimally-sized arena and let chunk_alloc() attempt
2255 to deal with the large request via mmap_chunk(). */
2256 h = new_heap(sizeof(*h) + sizeof(*a) + MALLOC_ALIGNMENT);
2257 if(!h)
2258 return 0;
2260 a = h->ar_ptr = (arena *)(h+1);
2261 for(i=0; i<NAV; i++)
2262 init_bin(a, i);
2263 a->next = NULL;
2264 a->size = h->size;
2265 arena_mem += h->size;
2266 #ifdef NO_THREADS
2267 if((unsigned long)(mmapped_mem + arena_mem + sbrked_mem) > max_total_mem)
2268 max_total_mem = mmapped_mem + arena_mem + sbrked_mem;
2269 #endif
2270 tsd_setspecific(arena_key, (Void_t *)a);
2271 mutex_init(&a->mutex);
2272 i = mutex_lock(&a->mutex); /* remember result */
2274 /* Set up the top chunk, with proper alignment. */
2275 ptr = (char *)(a + 1);
2276 misalign = (unsigned long)chunk2mem(ptr) & MALLOC_ALIGN_MASK;
2277 if (misalign > 0)
2278 ptr += MALLOC_ALIGNMENT - misalign;
2279 top(a) = (mchunkptr)ptr;
2280 set_head(top(a), (((char*)h + h->size) - ptr) | PREV_INUSE);
2282 /* Add the new arena to the list. */
2283 (void)mutex_lock(&list_lock);
2284 a->next = main_arena.next;
2285 main_arena.next = a;
2286 (void)mutex_unlock(&list_lock);
2288 if(i) /* locking failed; keep arena for further attempts later */
2289 return 0;
2291 THREAD_STAT(++(a->stat_lock_loop));
2292 return a;
2295 /* find the heap and corresponding arena for a given ptr */
2297 #define heap_for_ptr(ptr) \
2298 ((heap_info *)((unsigned long)(ptr) & ~(HEAP_MAX_SIZE-1)))
2299 #define arena_for_ptr(ptr) \
2300 (((mchunkptr)(ptr) < top(&main_arena) && (char *)(ptr) >= sbrk_base) ? \
2301 &main_arena : heap_for_ptr(ptr)->ar_ptr)
2303 #else /* !USE_ARENAS */
2305 /* There is only one arena, main_arena. */
2307 #define arena_get(ptr, sz) (ptr = &main_arena)
2308 #define arena_for_ptr(ptr) (&main_arena)
2310 #endif /* USE_ARENAS */
2315 Debugging support
2318 #if MALLOC_DEBUG
2322 These routines make a number of assertions about the states
2323 of data structures that should be true at all times. If any
2324 are not true, it's very likely that a user program has somehow
2325 trashed memory. (It's also possible that there is a coding error
2326 in malloc. In which case, please report it!)
2329 #if __STD_C
2330 static void do_check_chunk(arena *ar_ptr, mchunkptr p)
2331 #else
2332 static void do_check_chunk(ar_ptr, p) arena *ar_ptr; mchunkptr p;
2333 #endif
2335 INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
2337 /* No checkable chunk is mmapped */
2338 assert(!chunk_is_mmapped(p));
2340 #if USE_ARENAS
2341 if(ar_ptr != &main_arena) {
2342 heap_info *heap = heap_for_ptr(p);
2343 assert(heap->ar_ptr == ar_ptr);
2344 if(p != top(ar_ptr))
2345 assert((char *)p + sz <= (char *)heap + heap->size);
2346 else
2347 assert((char *)p + sz == (char *)heap + heap->size);
2348 return;
2350 #endif
2352 /* Check for legal address ... */
2353 assert((char*)p >= sbrk_base);
2354 if (p != top(ar_ptr))
2355 assert((char*)p + sz <= (char*)top(ar_ptr));
2356 else
2357 assert((char*)p + sz <= sbrk_base + sbrked_mem);
2362 #if __STD_C
2363 static void do_check_free_chunk(arena *ar_ptr, mchunkptr p)
2364 #else
2365 static void do_check_free_chunk(ar_ptr, p) arena *ar_ptr; mchunkptr p;
2366 #endif
2368 INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
2369 mchunkptr next = chunk_at_offset(p, sz);
2371 do_check_chunk(ar_ptr, p);
2373 /* Check whether it claims to be free ... */
2374 assert(!inuse(p));
2376 /* Must have OK size and fields */
2377 assert((long)sz >= (long)MINSIZE);
2378 assert((sz & MALLOC_ALIGN_MASK) == 0);
2379 assert(aligned_OK(chunk2mem(p)));
2380 /* ... matching footer field */
2381 assert(next->prev_size == sz);
2382 /* ... and is fully consolidated */
2383 assert(prev_inuse(p));
2384 assert (next == top(ar_ptr) || inuse(next));
2386 /* ... and has minimally sane links */
2387 assert(p->fd->bk == p);
2388 assert(p->bk->fd == p);
2391 #if __STD_C
2392 static void do_check_inuse_chunk(arena *ar_ptr, mchunkptr p)
2393 #else
2394 static void do_check_inuse_chunk(ar_ptr, p) arena *ar_ptr; mchunkptr p;
2395 #endif
2397 mchunkptr next = next_chunk(p);
2398 do_check_chunk(ar_ptr, p);
2400 /* Check whether it claims to be in use ... */
2401 assert(inuse(p));
2403 /* ... whether its size is OK (it might be a fencepost) ... */
2404 assert(chunksize(p) >= MINSIZE || next->size == (0|PREV_INUSE));
2406 /* ... and is surrounded by OK chunks.
2407 Since more things can be checked with free chunks than inuse ones,
2408 if an inuse chunk borders them and debug is on, it's worth doing them.
2410 if (!prev_inuse(p))
2412 mchunkptr prv = prev_chunk(p);
2413 assert(next_chunk(prv) == p);
2414 do_check_free_chunk(ar_ptr, prv);
2416 if (next == top(ar_ptr))
2418 assert(prev_inuse(next));
2419 assert(chunksize(next) >= MINSIZE);
2421 else if (!inuse(next))
2422 do_check_free_chunk(ar_ptr, next);
2426 #if __STD_C
2427 static void do_check_malloced_chunk(arena *ar_ptr,
2428 mchunkptr p, INTERNAL_SIZE_T s)
2429 #else
2430 static void do_check_malloced_chunk(ar_ptr, p, s)
2431 arena *ar_ptr; mchunkptr p; INTERNAL_SIZE_T s;
2432 #endif
2434 INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
2435 long room = sz - s;
2437 do_check_inuse_chunk(ar_ptr, p);
2439 /* Legal size ... */
2440 assert((long)sz >= (long)MINSIZE);
2441 assert((sz & MALLOC_ALIGN_MASK) == 0);
2442 assert(room >= 0);
2443 assert(room < (long)MINSIZE);
2445 /* ... and alignment */
2446 assert(aligned_OK(chunk2mem(p)));
2449 /* ... and was allocated at front of an available chunk */
2450 assert(prev_inuse(p));
2455 #define check_free_chunk(A,P) do_check_free_chunk(A,P)
2456 #define check_inuse_chunk(A,P) do_check_inuse_chunk(A,P)
2457 #define check_chunk(A,P) do_check_chunk(A,P)
2458 #define check_malloced_chunk(A,P,N) do_check_malloced_chunk(A,P,N)
2459 #else
2460 #define check_free_chunk(A,P)
2461 #define check_inuse_chunk(A,P)
2462 #define check_chunk(A,P)
2463 #define check_malloced_chunk(A,P,N)
2464 #endif
2469 Macro-based internal utilities
2474 Linking chunks in bin lists.
2475 Call these only with variables, not arbitrary expressions, as arguments.
2479 Place chunk p of size s in its bin, in size order,
2480 putting it ahead of others of same size.
2484 #define frontlink(A, P, S, IDX, BK, FD) \
2486 if (S < MAX_SMALLBIN_SIZE) \
2488 IDX = smallbin_index(S); \
2489 mark_binblock(A, IDX); \
2490 BK = bin_at(A, IDX); \
2491 FD = BK->fd; \
2492 P->bk = BK; \
2493 P->fd = FD; \
2494 FD->bk = BK->fd = P; \
2496 else \
2498 IDX = bin_index(S); \
2499 BK = bin_at(A, IDX); \
2500 FD = BK->fd; \
2501 if (FD == BK) mark_binblock(A, IDX); \
2502 else \
2504 while (FD != BK && S < chunksize(FD)) FD = FD->fd; \
2505 BK = FD->bk; \
2507 P->bk = BK; \
2508 P->fd = FD; \
2509 FD->bk = BK->fd = P; \
2514 /* take a chunk off a list */
2516 #define unlink(P, BK, FD) \
2518 BK = P->bk; \
2519 FD = P->fd; \
2520 FD->bk = BK; \
2521 BK->fd = FD; \
2524 /* Place p as the last remainder */
2526 #define link_last_remainder(A, P) \
2528 last_remainder(A)->fd = last_remainder(A)->bk = P; \
2529 P->fd = P->bk = last_remainder(A); \
2532 /* Clear the last_remainder bin */
2534 #define clear_last_remainder(A) \
2535 (last_remainder(A)->fd = last_remainder(A)->bk = last_remainder(A))
2542 Extend the top-most chunk by obtaining memory from system.
2543 Main interface to sbrk (but see also malloc_trim).
2546 #if defined __GNUC__ && __GNUC__ >= 2
2547 /* This function is called only from one place, inline it. */
2548 __inline__
2549 #endif
2550 static void
2551 internal_function
2552 #if __STD_C
2553 malloc_extend_top(arena *ar_ptr, INTERNAL_SIZE_T nb)
2554 #else
2555 malloc_extend_top(ar_ptr, nb) arena *ar_ptr; INTERNAL_SIZE_T nb;
2556 #endif
2558 unsigned long pagesz = malloc_getpagesize;
2559 mchunkptr old_top = top(ar_ptr); /* Record state of old top */
2560 INTERNAL_SIZE_T old_top_size = chunksize(old_top);
2561 INTERNAL_SIZE_T top_size; /* new size of top chunk */
2563 #if USE_ARENAS
2564 if(ar_ptr == &main_arena) {
2565 #endif
2567 char* brk; /* return value from sbrk */
2568 INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of sbrked space */
2569 INTERNAL_SIZE_T correction; /* bytes for 2nd sbrk call */
2570 char* new_brk; /* return of 2nd sbrk call */
2571 char* old_end = (char*)(chunk_at_offset(old_top, old_top_size));
2573 /* Pad request with top_pad plus minimal overhead */
2574 INTERNAL_SIZE_T sbrk_size = nb + top_pad + MINSIZE;
2576 /* If not the first time through, round to preserve page boundary */
2577 /* Otherwise, we need to correct to a page size below anyway. */
2578 /* (We also correct below if an intervening foreign sbrk call.) */
2580 if (sbrk_base != (char*)(-1))
2581 sbrk_size = (sbrk_size + (pagesz - 1)) & ~(pagesz - 1);
2583 brk = (char*)(MORECORE (sbrk_size));
2585 /* Fail if sbrk failed or if a foreign sbrk call killed our space */
2586 if (brk == (char*)(MORECORE_FAILURE) ||
2587 (brk < old_end && old_top != initial_top(&main_arena)))
2588 return;
2590 #if defined _LIBC || defined MALLOC_HOOKS
2591 /* Call the `morecore' hook if necessary. */
2592 if (__after_morecore_hook)
2593 (*__after_morecore_hook) ();
2594 #endif
2596 sbrked_mem += sbrk_size;
2598 if (brk == old_end) { /* can just add bytes to current top */
2599 top_size = sbrk_size + old_top_size;
2600 set_head(old_top, top_size | PREV_INUSE);
2601 old_top = 0; /* don't free below */
2602 } else {
2603 if (sbrk_base == (char*)(-1)) /* First time through. Record base */
2604 sbrk_base = brk;
2605 else
2606 /* Someone else called sbrk(). Count those bytes as sbrked_mem. */
2607 sbrked_mem += brk - (char*)old_end;
2609 /* Guarantee alignment of first new chunk made from this space */
2610 front_misalign = (unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK;
2611 if (front_misalign > 0) {
2612 correction = (MALLOC_ALIGNMENT) - front_misalign;
2613 brk += correction;
2614 } else
2615 correction = 0;
2617 /* Guarantee the next brk will be at a page boundary */
2618 correction += pagesz - ((unsigned long)(brk + sbrk_size) & (pagesz - 1));
2620 /* Allocate correction */
2621 new_brk = (char*)(MORECORE (correction));
2622 if (new_brk == (char*)(MORECORE_FAILURE)) return;
2624 #if defined _LIBC || defined MALLOC_HOOKS
2625 /* Call the `morecore' hook if necessary. */
2626 if (__after_morecore_hook)
2627 (*__after_morecore_hook) ();
2628 #endif
2630 sbrked_mem += correction;
2632 top(&main_arena) = chunk_at_offset(brk, 0);
2633 top_size = new_brk - brk + correction;
2634 set_head(top(&main_arena), top_size | PREV_INUSE);
2636 if (old_top == initial_top(&main_arena))
2637 old_top = 0; /* don't free below */
2640 if ((unsigned long)sbrked_mem > (unsigned long)max_sbrked_mem)
2641 max_sbrked_mem = sbrked_mem;
2642 #ifdef NO_THREADS
2643 if ((unsigned long)(mmapped_mem + arena_mem + sbrked_mem) > max_total_mem)
2644 max_total_mem = mmapped_mem + arena_mem + sbrked_mem;
2645 #endif
2647 #if USE_ARENAS
2648 } else { /* ar_ptr != &main_arena */
2649 heap_info *old_heap, *heap;
2650 size_t old_heap_size;
2652 if(old_top_size < MINSIZE) /* this should never happen */
2653 return;
2655 /* First try to extend the current heap. */
2656 if(MINSIZE + nb <= old_top_size)
2657 return;
2658 old_heap = heap_for_ptr(old_top);
2659 old_heap_size = old_heap->size;
2660 if(grow_heap(old_heap, MINSIZE + nb - old_top_size) == 0) {
2661 ar_ptr->size += old_heap->size - old_heap_size;
2662 arena_mem += old_heap->size - old_heap_size;
2663 #ifdef NO_THREADS
2664 if(mmapped_mem + arena_mem + sbrked_mem > max_total_mem)
2665 max_total_mem = mmapped_mem + arena_mem + sbrked_mem;
2666 #endif
2667 top_size = ((char *)old_heap + old_heap->size) - (char *)old_top;
2668 set_head(old_top, top_size | PREV_INUSE);
2669 return;
2672 /* A new heap must be created. */
2673 heap = new_heap(nb + (MINSIZE + sizeof(*heap)));
2674 if(!heap)
2675 return;
2676 heap->ar_ptr = ar_ptr;
2677 heap->prev = old_heap;
2678 ar_ptr->size += heap->size;
2679 arena_mem += heap->size;
2680 #ifdef NO_THREADS
2681 if((unsigned long)(mmapped_mem + arena_mem + sbrked_mem) > max_total_mem)
2682 max_total_mem = mmapped_mem + arena_mem + sbrked_mem;
2683 #endif
2685 /* Set up the new top, so we can safely use chunk_free() below. */
2686 top(ar_ptr) = chunk_at_offset(heap, sizeof(*heap));
2687 top_size = heap->size - sizeof(*heap);
2688 set_head(top(ar_ptr), top_size | PREV_INUSE);
2690 #endif /* USE_ARENAS */
2692 /* We always land on a page boundary */
2693 assert(((unsigned long)((char*)top(ar_ptr) + top_size) & (pagesz-1)) == 0);
2695 /* Setup fencepost and free the old top chunk. */
2696 if(old_top) {
2697 /* The fencepost takes at least MINSIZE bytes, because it might
2698 become the top chunk again later. Note that a footer is set
2699 up, too, although the chunk is marked in use. */
2700 old_top_size -= MINSIZE;
2701 set_head(chunk_at_offset(old_top, old_top_size + 2*SIZE_SZ), 0|PREV_INUSE);
2702 if(old_top_size >= MINSIZE) {
2703 set_head(chunk_at_offset(old_top, old_top_size), (2*SIZE_SZ)|PREV_INUSE);
2704 set_foot(chunk_at_offset(old_top, old_top_size), (2*SIZE_SZ));
2705 set_head_size(old_top, old_top_size);
2706 chunk_free(ar_ptr, old_top);
2707 } else {
2708 set_head(old_top, (old_top_size + 2*SIZE_SZ)|PREV_INUSE);
2709 set_foot(old_top, (old_top_size + 2*SIZE_SZ));
2717 /* Main public routines */
2721 Malloc Algorithm:
2723 The requested size is first converted into a usable form, `nb'.
2724 This currently means to add 4 bytes overhead plus possibly more to
2725 obtain 8-byte alignment and/or to obtain a size of at least
2726 MINSIZE (currently 16, 24, or 32 bytes), the smallest allocatable
2727 size. (All fits are considered `exact' if they are within MINSIZE
2728 bytes.)
2730 From there, the first successful of the following steps is taken:
2732 1. The bin corresponding to the request size is scanned, and if
2733 a chunk of exactly the right size is found, it is taken.
2735 2. The most recently remaindered chunk is used if it is big
2736 enough. This is a form of (roving) first fit, used only in
2737 the absence of exact fits. Runs of consecutive requests use
2738 the remainder of the chunk used for the previous such request
2739 whenever possible. This limited use of a first-fit style
2740 allocation strategy tends to give contiguous chunks
2741 coextensive lifetimes, which improves locality and can reduce
2742 fragmentation in the long run.
2744 3. Other bins are scanned in increasing size order, using a
2745 chunk big enough to fulfill the request, and splitting off
2746 any remainder. This search is strictly by best-fit; i.e.,
2747 the smallest (with ties going to approximately the least
2748 recently used) chunk that fits is selected.
2750 4. If large enough, the chunk bordering the end of memory
2751 (`top') is split off. (This use of `top' is in accord with
2752 the best-fit search rule. In effect, `top' is treated as
2753 larger (and thus less well fitting) than any other available
2754 chunk since it can be extended to be as large as necessary
2755 (up to system limitations).
2757 5. If the request size meets the mmap threshold and the
2758 system supports mmap, and there are few enough currently
2759 allocated mmapped regions, and a call to mmap succeeds,
2760 the request is allocated via direct memory mapping.
2762 6. Otherwise, the top of memory is extended by
2763 obtaining more space from the system (normally using sbrk,
2764 but definable to anything else via the MORECORE macro).
2765 Memory is gathered from the system (in system page-sized
2766 units) in a way that allows chunks obtained across different
2767 sbrk calls to be consolidated, but does not require
2768 contiguous memory. Thus, it should be safe to intersperse
2769 mallocs with other sbrk calls.
2772 All allocations are made from the `lowest' part of any found
2773 chunk. (The implementation invariant is that prev_inuse is
2774 always true of any allocated chunk; i.e., that each allocated
2775 chunk borders either a previously allocated and still in-use chunk,
2776 or the base of its memory arena.)
2780 #if __STD_C
2781 Void_t* mALLOc(size_t bytes)
2782 #else
2783 Void_t* mALLOc(bytes) size_t bytes;
2784 #endif
2786 arena *ar_ptr;
2787 INTERNAL_SIZE_T nb; /* padded request size */
2788 mchunkptr victim;
2790 #if defined _LIBC || defined MALLOC_HOOKS
2791 __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, __const __malloc_ptr_t)) =
2792 __malloc_hook;
2793 if (hook != NULL) {
2794 Void_t* result;
2796 #if defined __GNUC__ && __GNUC__ >= 2
2797 result = (*hook)(bytes, RETURN_ADDRESS (0));
2798 #else
2799 result = (*hook)(bytes, NULL);
2800 #endif
2801 return result;
2803 #endif
2805 if(request2size(bytes, nb))
2806 return 0;
2807 arena_get(ar_ptr, nb);
2808 if(!ar_ptr)
2809 return 0;
2810 victim = chunk_alloc(ar_ptr, nb);
2811 if(!victim) {
2812 /* Maybe the failure is due to running out of mmapped areas. */
2813 if(ar_ptr != &main_arena) {
2814 (void)mutex_unlock(&ar_ptr->mutex);
2815 (void)mutex_lock(&main_arena.mutex);
2816 victim = chunk_alloc(&main_arena, nb);
2817 (void)mutex_unlock(&main_arena.mutex);
2818 } else {
2819 #if USE_ARENAS
2820 /* ... or sbrk() has failed and there is still a chance to mmap() */
2821 ar_ptr = arena_get2(ar_ptr->next ? ar_ptr : 0, nb);
2822 (void)mutex_unlock(&main_arena.mutex);
2823 if(ar_ptr) {
2824 victim = chunk_alloc(ar_ptr, nb);
2825 (void)mutex_unlock(&ar_ptr->mutex);
2827 #endif
2829 if(!victim) return 0;
2830 } else
2831 (void)mutex_unlock(&ar_ptr->mutex);
2832 return BOUNDED_N(chunk2mem(victim), bytes);
2835 static mchunkptr
2836 internal_function
2837 #if __STD_C
2838 chunk_alloc(arena *ar_ptr, INTERNAL_SIZE_T nb)
2839 #else
2840 chunk_alloc(ar_ptr, nb) arena *ar_ptr; INTERNAL_SIZE_T nb;
2841 #endif
2843 mchunkptr victim; /* inspected/selected chunk */
2844 INTERNAL_SIZE_T victim_size; /* its size */
2845 int idx; /* index for bin traversal */
2846 mbinptr bin; /* associated bin */
2847 mchunkptr remainder; /* remainder from a split */
2848 long remainder_size; /* its size */
2849 int remainder_index; /* its bin index */
2850 unsigned long block; /* block traverser bit */
2851 int startidx; /* first bin of a traversed block */
2852 mchunkptr fwd; /* misc temp for linking */
2853 mchunkptr bck; /* misc temp for linking */
2854 mbinptr q; /* misc temp */
2857 /* Check for exact match in a bin */
2859 if (is_small_request(nb)) /* Faster version for small requests */
2861 idx = smallbin_index(nb);
2863 /* No traversal or size check necessary for small bins. */
2865 q = _bin_at(ar_ptr, idx);
2866 victim = last(q);
2868 /* Also scan the next one, since it would have a remainder < MINSIZE */
2869 if (victim == q)
2871 q = next_bin(q);
2872 victim = last(q);
2874 if (victim != q)
2876 victim_size = chunksize(victim);
2877 unlink(victim, bck, fwd);
2878 set_inuse_bit_at_offset(victim, victim_size);
2879 check_malloced_chunk(ar_ptr, victim, nb);
2880 return victim;
2883 idx += 2; /* Set for bin scan below. We've already scanned 2 bins. */
2886 else
2888 idx = bin_index(nb);
2889 bin = bin_at(ar_ptr, idx);
2891 for (victim = last(bin); victim != bin; victim = victim->bk)
2893 victim_size = chunksize(victim);
2894 remainder_size = victim_size - nb;
2896 if (remainder_size >= (long)MINSIZE) /* too big */
2898 --idx; /* adjust to rescan below after checking last remainder */
2899 break;
2902 else if (remainder_size >= 0) /* exact fit */
2904 unlink(victim, bck, fwd);
2905 set_inuse_bit_at_offset(victim, victim_size);
2906 check_malloced_chunk(ar_ptr, victim, nb);
2907 return victim;
2911 ++idx;
2915 /* Try to use the last split-off remainder */
2917 if ( (victim = last_remainder(ar_ptr)->fd) != last_remainder(ar_ptr))
2919 victim_size = chunksize(victim);
2920 remainder_size = victim_size - nb;
2922 if (remainder_size >= (long)MINSIZE) /* re-split */
2924 remainder = chunk_at_offset(victim, nb);
2925 set_head(victim, nb | PREV_INUSE);
2926 link_last_remainder(ar_ptr, remainder);
2927 set_head(remainder, remainder_size | PREV_INUSE);
2928 set_foot(remainder, remainder_size);
2929 check_malloced_chunk(ar_ptr, victim, nb);
2930 return victim;
2933 clear_last_remainder(ar_ptr);
2935 if (remainder_size >= 0) /* exhaust */
2937 set_inuse_bit_at_offset(victim, victim_size);
2938 check_malloced_chunk(ar_ptr, victim, nb);
2939 return victim;
2942 /* Else place in bin */
2944 frontlink(ar_ptr, victim, victim_size, remainder_index, bck, fwd);
2948 If there are any possibly nonempty big-enough blocks,
2949 search for best fitting chunk by scanning bins in blockwidth units.
2952 if ( (block = idx2binblock(idx)) <= binblocks(ar_ptr))
2955 /* Get to the first marked block */
2957 if ( (block & binblocks(ar_ptr)) == 0)
2959 /* force to an even block boundary */
2960 idx = (idx & ~(BINBLOCKWIDTH - 1)) + BINBLOCKWIDTH;
2961 block <<= 1;
2962 while ((block & binblocks(ar_ptr)) == 0)
2964 idx += BINBLOCKWIDTH;
2965 block <<= 1;
2969 /* For each possibly nonempty block ... */
2970 for (;;)
2972 startidx = idx; /* (track incomplete blocks) */
2973 q = bin = _bin_at(ar_ptr, idx);
2975 /* For each bin in this block ... */
2978 /* Find and use first big enough chunk ... */
2980 for (victim = last(bin); victim != bin; victim = victim->bk)
2982 victim_size = chunksize(victim);
2983 remainder_size = victim_size - nb;
2985 if (remainder_size >= (long)MINSIZE) /* split */
2987 remainder = chunk_at_offset(victim, nb);
2988 set_head(victim, nb | PREV_INUSE);
2989 unlink(victim, bck, fwd);
2990 link_last_remainder(ar_ptr, remainder);
2991 set_head(remainder, remainder_size | PREV_INUSE);
2992 set_foot(remainder, remainder_size);
2993 check_malloced_chunk(ar_ptr, victim, nb);
2994 return victim;
2997 else if (remainder_size >= 0) /* take */
2999 set_inuse_bit_at_offset(victim, victim_size);
3000 unlink(victim, bck, fwd);
3001 check_malloced_chunk(ar_ptr, victim, nb);
3002 return victim;
3007 bin = next_bin(bin);
3009 } while ((++idx & (BINBLOCKWIDTH - 1)) != 0);
3011 /* Clear out the block bit. */
3013 do /* Possibly backtrack to try to clear a partial block */
3015 if ((startidx & (BINBLOCKWIDTH - 1)) == 0)
3017 binblocks(ar_ptr) &= ~block;
3018 break;
3020 --startidx;
3021 q = prev_bin(q);
3022 } while (first(q) == q);
3024 /* Get to the next possibly nonempty block */
3026 if ( (block <<= 1) <= binblocks(ar_ptr) && (block != 0) )
3028 while ((block & binblocks(ar_ptr)) == 0)
3030 idx += BINBLOCKWIDTH;
3031 block <<= 1;
3034 else
3035 break;
3040 /* Try to use top chunk */
3042 /* Require that there be a remainder, ensuring top always exists */
3043 if ( (remainder_size = chunksize(top(ar_ptr)) - nb) < (long)MINSIZE)
3046 #if HAVE_MMAP
3047 /* If the request is big and there are not yet too many regions,
3048 and we would otherwise need to extend, try to use mmap instead. */
3049 if ((unsigned long)nb >= (unsigned long)mmap_threshold &&
3050 n_mmaps < n_mmaps_max &&
3051 (victim = mmap_chunk(nb)) != 0)
3052 return victim;
3053 #endif
3055 /* Try to extend */
3056 malloc_extend_top(ar_ptr, nb);
3057 if ((remainder_size = chunksize(top(ar_ptr)) - nb) < (long)MINSIZE)
3059 #if HAVE_MMAP
3060 /* A last attempt: when we are out of address space in a
3061 non-main arena, try mmap anyway, as long as it is allowed at
3062 all. */
3063 if (ar_ptr != &main_arena &&
3064 n_mmaps_max > 0 &&
3065 (victim = mmap_chunk(nb)) != 0)
3066 return victim;
3067 #endif
3068 return 0; /* propagate failure */
3072 victim = top(ar_ptr);
3073 set_head(victim, nb | PREV_INUSE);
3074 top(ar_ptr) = chunk_at_offset(victim, nb);
3075 set_head(top(ar_ptr), remainder_size | PREV_INUSE);
3076 check_malloced_chunk(ar_ptr, victim, nb);
3077 return victim;
3086 free() algorithm :
3088 cases:
3090 1. free(0) has no effect.
3092 2. If the chunk was allocated via mmap, it is released via munmap().
3094 3. If a returned chunk borders the current high end of memory,
3095 it is consolidated into the top, and if the total unused
3096 topmost memory exceeds the trim threshold, malloc_trim is
3097 called.
3099 4. Other chunks are consolidated as they arrive, and
3100 placed in corresponding bins. (This includes the case of
3101 consolidating with the current `last_remainder').
3106 #if __STD_C
3107 void fREe(Void_t* mem)
3108 #else
3109 void fREe(mem) Void_t* mem;
3110 #endif
3112 arena *ar_ptr;
3113 mchunkptr p; /* chunk corresponding to mem */
3115 #if defined _LIBC || defined MALLOC_HOOKS
3116 void (*hook) __MALLOC_PMT ((__malloc_ptr_t, __const __malloc_ptr_t)) =
3117 __free_hook;
3119 if (hook != NULL) {
3120 #if defined __GNUC__ && __GNUC__ >= 2
3121 (*hook)(mem, RETURN_ADDRESS (0));
3122 #else
3123 (*hook)(mem, NULL);
3124 #endif
3125 return;
3127 #endif
3129 if (mem == 0) /* free(0) has no effect */
3130 return;
3132 p = mem2chunk(mem);
3134 #if HAVE_MMAP
3135 if (chunk_is_mmapped(p)) /* release mmapped memory. */
3137 munmap_chunk(p);
3138 return;
3140 #endif
3142 ar_ptr = arena_for_ptr(p);
3143 #if THREAD_STATS
3144 if(!mutex_trylock(&ar_ptr->mutex))
3145 ++(ar_ptr->stat_lock_direct);
3146 else {
3147 (void)mutex_lock(&ar_ptr->mutex);
3148 ++(ar_ptr->stat_lock_wait);
3150 #else
3151 (void)mutex_lock(&ar_ptr->mutex);
3152 #endif
3153 chunk_free(ar_ptr, p);
3154 (void)mutex_unlock(&ar_ptr->mutex);
3157 static void
3158 internal_function
3159 #if __STD_C
3160 chunk_free(arena *ar_ptr, mchunkptr p)
3161 #else
3162 chunk_free(ar_ptr, p) arena *ar_ptr; mchunkptr p;
3163 #endif
3165 INTERNAL_SIZE_T hd = p->size; /* its head field */
3166 INTERNAL_SIZE_T sz; /* its size */
3167 int idx; /* its bin index */
3168 mchunkptr next; /* next contiguous chunk */
3169 INTERNAL_SIZE_T nextsz; /* its size */
3170 INTERNAL_SIZE_T prevsz; /* size of previous contiguous chunk */
3171 mchunkptr bck; /* misc temp for linking */
3172 mchunkptr fwd; /* misc temp for linking */
3173 int islr; /* track whether merging with last_remainder */
3175 check_inuse_chunk(ar_ptr, p);
3177 sz = hd & ~PREV_INUSE;
3178 next = chunk_at_offset(p, sz);
3179 nextsz = chunksize(next);
3181 if (next == top(ar_ptr)) /* merge with top */
3183 sz += nextsz;
3185 if (!(hd & PREV_INUSE)) /* consolidate backward */
3187 prevsz = p->prev_size;
3188 p = chunk_at_offset(p, -(long)prevsz);
3189 sz += prevsz;
3190 unlink(p, bck, fwd);
3193 set_head(p, sz | PREV_INUSE);
3194 top(ar_ptr) = p;
3196 #if USE_ARENAS
3197 if(ar_ptr == &main_arena) {
3198 #endif
3199 if ((unsigned long)(sz) >= (unsigned long)trim_threshold)
3200 main_trim(top_pad);
3201 #if USE_ARENAS
3202 } else {
3203 heap_info *heap = heap_for_ptr(p);
3205 assert(heap->ar_ptr == ar_ptr);
3207 /* Try to get rid of completely empty heaps, if possible. */
3208 if((unsigned long)(sz) >= (unsigned long)trim_threshold ||
3209 p == chunk_at_offset(heap, sizeof(*heap)))
3210 heap_trim(heap, top_pad);
3212 #endif
3213 return;
3216 islr = 0;
3218 if (!(hd & PREV_INUSE)) /* consolidate backward */
3220 prevsz = p->prev_size;
3221 p = chunk_at_offset(p, -(long)prevsz);
3222 sz += prevsz;
3224 if (p->fd == last_remainder(ar_ptr)) /* keep as last_remainder */
3225 islr = 1;
3226 else
3227 unlink(p, bck, fwd);
3230 if (!(inuse_bit_at_offset(next, nextsz))) /* consolidate forward */
3232 sz += nextsz;
3234 if (!islr && next->fd == last_remainder(ar_ptr))
3235 /* re-insert last_remainder */
3237 islr = 1;
3238 link_last_remainder(ar_ptr, p);
3240 else
3241 unlink(next, bck, fwd);
3243 next = chunk_at_offset(p, sz);
3245 else
3246 set_head(next, nextsz); /* clear inuse bit */
3248 set_head(p, sz | PREV_INUSE);
3249 next->prev_size = sz;
3250 if (!islr)
3251 frontlink(ar_ptr, p, sz, idx, bck, fwd);
3253 #if USE_ARENAS
3254 /* Check whether the heap containing top can go away now. */
3255 if(next->size < MINSIZE &&
3256 (unsigned long)sz > trim_threshold &&
3257 ar_ptr != &main_arena) { /* fencepost */
3258 heap_info *heap = heap_for_ptr(top(ar_ptr));
3260 if(top(ar_ptr) == chunk_at_offset(heap, sizeof(*heap)) &&
3261 heap->prev == heap_for_ptr(p))
3262 heap_trim(heap, top_pad);
3264 #endif
3273 Realloc algorithm:
3275 Chunks that were obtained via mmap cannot be extended or shrunk
3276 unless HAVE_MREMAP is defined, in which case mremap is used.
3277 Otherwise, if their reallocation is for additional space, they are
3278 copied. If for less, they are just left alone.
3280 Otherwise, if the reallocation is for additional space, and the
3281 chunk can be extended, it is, else a malloc-copy-free sequence is
3282 taken. There are several different ways that a chunk could be
3283 extended. All are tried:
3285 * Extending forward into following adjacent free chunk.
3286 * Shifting backwards, joining preceding adjacent space
3287 * Both shifting backwards and extending forward.
3288 * Extending into newly sbrked space
3290 Unless the #define REALLOC_ZERO_BYTES_FREES is set, realloc with a
3291 size argument of zero (re)allocates a minimum-sized chunk.
3293 If the reallocation is for less space, and the new request is for
3294 a `small' (<512 bytes) size, then the newly unused space is lopped
3295 off and freed.
3297 The old unix realloc convention of allowing the last-free'd chunk
3298 to be used as an argument to realloc is no longer supported.
3299 I don't know of any programs still relying on this feature,
3300 and allowing it would also allow too many other incorrect
3301 usages of realloc to be sensible.
3307 #if __STD_C
3308 Void_t* rEALLOc(Void_t* oldmem, size_t bytes)
3309 #else
3310 Void_t* rEALLOc(oldmem, bytes) Void_t* oldmem; size_t bytes;
3311 #endif
3313 arena *ar_ptr;
3314 INTERNAL_SIZE_T nb; /* padded request size */
3316 mchunkptr oldp; /* chunk corresponding to oldmem */
3317 INTERNAL_SIZE_T oldsize; /* its size */
3319 mchunkptr newp; /* chunk to return */
3321 #if defined _LIBC || defined MALLOC_HOOKS
3322 __malloc_ptr_t (*hook) __MALLOC_PMT ((__malloc_ptr_t, size_t,
3323 __const __malloc_ptr_t)) =
3324 __realloc_hook;
3325 if (hook != NULL) {
3326 Void_t* result;
3328 #if defined __GNUC__ && __GNUC__ >= 2
3329 result = (*hook)(oldmem, bytes, RETURN_ADDRESS (0));
3330 #else
3331 result = (*hook)(oldmem, bytes, NULL);
3332 #endif
3333 return result;
3335 #endif
3337 #ifdef REALLOC_ZERO_BYTES_FREES
3338 if (bytes == 0 && oldmem != NULL) { fREe(oldmem); return 0; }
3339 #endif
3341 /* realloc of null is supposed to be same as malloc */
3342 if (oldmem == 0) return mALLOc(bytes);
3344 oldp = mem2chunk(oldmem);
3345 oldsize = chunksize(oldp);
3347 if(request2size(bytes, nb))
3348 return 0;
3350 #if HAVE_MMAP
3351 if (chunk_is_mmapped(oldp))
3353 Void_t* newmem;
3355 #if HAVE_MREMAP
3356 newp = mremap_chunk(oldp, nb);
3357 if(newp)
3358 return BOUNDED_N(chunk2mem(newp), bytes);
3359 #endif
3360 /* Note the extra SIZE_SZ overhead. */
3361 if(oldsize - SIZE_SZ >= nb) return oldmem; /* do nothing */
3362 /* Must alloc, copy, free. */
3363 newmem = mALLOc(bytes);
3364 if (newmem == 0) return 0; /* propagate failure */
3365 MALLOC_COPY(newmem, oldmem, oldsize - 2*SIZE_SZ, 0);
3366 munmap_chunk(oldp);
3367 return newmem;
3369 #endif
3371 ar_ptr = arena_for_ptr(oldp);
3372 #if THREAD_STATS
3373 if(!mutex_trylock(&ar_ptr->mutex))
3374 ++(ar_ptr->stat_lock_direct);
3375 else {
3376 (void)mutex_lock(&ar_ptr->mutex);
3377 ++(ar_ptr->stat_lock_wait);
3379 #else
3380 (void)mutex_lock(&ar_ptr->mutex);
3381 #endif
3383 #ifndef NO_THREADS
3384 /* As in malloc(), remember this arena for the next allocation. */
3385 tsd_setspecific(arena_key, (Void_t *)ar_ptr);
3386 #endif
3388 newp = chunk_realloc(ar_ptr, oldp, oldsize, nb);
3390 (void)mutex_unlock(&ar_ptr->mutex);
3391 return newp ? BOUNDED_N(chunk2mem(newp), bytes) : NULL;
3394 static mchunkptr
3395 internal_function
3396 #if __STD_C
3397 chunk_realloc(arena* ar_ptr, mchunkptr oldp, INTERNAL_SIZE_T oldsize,
3398 INTERNAL_SIZE_T nb)
3399 #else
3400 chunk_realloc(ar_ptr, oldp, oldsize, nb)
3401 arena* ar_ptr; mchunkptr oldp; INTERNAL_SIZE_T oldsize, nb;
3402 #endif
3404 mchunkptr newp = oldp; /* chunk to return */
3405 INTERNAL_SIZE_T newsize = oldsize; /* its size */
3407 mchunkptr next; /* next contiguous chunk after oldp */
3408 INTERNAL_SIZE_T nextsize; /* its size */
3410 mchunkptr prev; /* previous contiguous chunk before oldp */
3411 INTERNAL_SIZE_T prevsize; /* its size */
3413 mchunkptr remainder; /* holds split off extra space from newp */
3414 INTERNAL_SIZE_T remainder_size; /* its size */
3416 mchunkptr bck; /* misc temp for linking */
3417 mchunkptr fwd; /* misc temp for linking */
3419 check_inuse_chunk(ar_ptr, oldp);
3421 if ((long)(oldsize) < (long)(nb))
3423 Void_t* oldmem = BOUNDED_N(chunk2mem(oldp), oldsize);
3425 /* Try expanding forward */
3427 next = chunk_at_offset(oldp, oldsize);
3428 if (next == top(ar_ptr) || !inuse(next))
3430 nextsize = chunksize(next);
3432 /* Forward into top only if a remainder */
3433 if (next == top(ar_ptr))
3435 if ((long)(nextsize + newsize) >= (long)(nb + MINSIZE))
3437 newsize += nextsize;
3438 top(ar_ptr) = chunk_at_offset(oldp, nb);
3439 set_head(top(ar_ptr), (newsize - nb) | PREV_INUSE);
3440 set_head_size(oldp, nb);
3441 return oldp;
3445 /* Forward into next chunk */
3446 else if (((long)(nextsize + newsize) >= (long)(nb)))
3448 unlink(next, bck, fwd);
3449 newsize += nextsize;
3450 goto split;
3453 else
3455 next = 0;
3456 nextsize = 0;
3459 oldsize -= SIZE_SZ;
3461 /* Try shifting backwards. */
3463 if (!prev_inuse(oldp))
3465 prev = prev_chunk(oldp);
3466 prevsize = chunksize(prev);
3468 /* try forward + backward first to save a later consolidation */
3470 if (next != 0)
3472 /* into top */
3473 if (next == top(ar_ptr))
3475 if ((long)(nextsize + prevsize + newsize) >= (long)(nb + MINSIZE))
3477 unlink(prev, bck, fwd);
3478 newp = prev;
3479 newsize += prevsize + nextsize;
3480 MALLOC_COPY(BOUNDED_N(chunk2mem(newp), oldsize), oldmem, oldsize,
3482 top(ar_ptr) = chunk_at_offset(newp, nb);
3483 set_head(top(ar_ptr), (newsize - nb) | PREV_INUSE);
3484 set_head_size(newp, nb);
3485 return newp;
3489 /* into next chunk */
3490 else if (((long)(nextsize + prevsize + newsize) >= (long)(nb)))
3492 unlink(next, bck, fwd);
3493 unlink(prev, bck, fwd);
3494 newp = prev;
3495 newsize += nextsize + prevsize;
3496 MALLOC_COPY(BOUNDED_N(chunk2mem(newp), oldsize), oldmem, oldsize, 1);
3497 goto split;
3501 /* backward only */
3502 if (prev != 0 && (long)(prevsize + newsize) >= (long)nb)
3504 unlink(prev, bck, fwd);
3505 newp = prev;
3506 newsize += prevsize;
3507 MALLOC_COPY(BOUNDED_N(chunk2mem(newp), oldsize), oldmem, oldsize, 1);
3508 goto split;
3512 /* Must allocate */
3514 newp = chunk_alloc (ar_ptr, nb);
3516 if (newp == 0) {
3517 /* Maybe the failure is due to running out of mmapped areas. */
3518 if (ar_ptr != &main_arena) {
3519 (void)mutex_lock(&main_arena.mutex);
3520 newp = chunk_alloc(&main_arena, nb);
3521 (void)mutex_unlock(&main_arena.mutex);
3522 } else {
3523 #if USE_ARENAS
3524 /* ... or sbrk() has failed and there is still a chance to mmap() */
3525 arena* ar_ptr2 = arena_get2(ar_ptr->next ? ar_ptr : 0, nb);
3526 if(ar_ptr2) {
3527 newp = chunk_alloc(ar_ptr2, nb);
3528 (void)mutex_unlock(&ar_ptr2->mutex);
3530 #endif
3532 if (newp == 0) /* propagate failure */
3533 return 0;
3536 /* Avoid copy if newp is next chunk after oldp. */
3537 /* (This can only happen when new chunk is sbrk'ed.) */
3539 if ( newp == next_chunk(oldp))
3541 newsize += chunksize(newp);
3542 newp = oldp;
3543 goto split;
3546 /* Otherwise copy, free, and exit */
3547 MALLOC_COPY(BOUNDED_N(chunk2mem(newp), oldsize), oldmem, oldsize, 0);
3548 chunk_free(ar_ptr, oldp);
3549 return newp;
3553 split: /* split off extra room in old or expanded chunk */
3555 if (newsize - nb >= MINSIZE) /* split off remainder */
3557 remainder = chunk_at_offset(newp, nb);
3558 remainder_size = newsize - nb;
3559 set_head_size(newp, nb);
3560 set_head(remainder, remainder_size | PREV_INUSE);
3561 set_inuse_bit_at_offset(remainder, remainder_size);
3562 chunk_free(ar_ptr, remainder);
3564 else
3566 set_head_size(newp, newsize);
3567 set_inuse_bit_at_offset(newp, newsize);
3570 check_inuse_chunk(ar_ptr, newp);
3571 return newp;
3579 memalign algorithm:
3581 memalign requests more than enough space from malloc, finds a spot
3582 within that chunk that meets the alignment request, and then
3583 possibly frees the leading and trailing space.
3585 The alignment argument must be a power of two. This property is not
3586 checked by memalign, so misuse may result in random runtime errors.
3588 8-byte alignment is guaranteed by normal malloc calls, so don't
3589 bother calling memalign with an argument of 8 or less.
3591 Overreliance on memalign is a sure way to fragment space.
3596 #if __STD_C
3597 Void_t* mEMALIGn(size_t alignment, size_t bytes)
3598 #else
3599 Void_t* mEMALIGn(alignment, bytes) size_t alignment; size_t bytes;
3600 #endif
3602 arena *ar_ptr;
3603 INTERNAL_SIZE_T nb; /* padded request size */
3604 mchunkptr p;
3606 #if defined _LIBC || defined MALLOC_HOOKS
3607 __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, size_t,
3608 __const __malloc_ptr_t)) =
3609 __memalign_hook;
3610 if (hook != NULL) {
3611 Void_t* result;
3613 #if defined __GNUC__ && __GNUC__ >= 2
3614 result = (*hook)(alignment, bytes, RETURN_ADDRESS (0));
3615 #else
3616 result = (*hook)(alignment, bytes, NULL);
3617 #endif
3618 return result;
3620 #endif
3622 /* If need less alignment than we give anyway, just relay to malloc */
3624 if (alignment <= MALLOC_ALIGNMENT) return mALLOc(bytes);
3626 /* Otherwise, ensure that it is at least a minimum chunk size */
3628 if (alignment < MINSIZE) alignment = MINSIZE;
3630 if(request2size(bytes, nb))
3631 return 0;
3632 arena_get(ar_ptr, nb + alignment + MINSIZE);
3633 if(!ar_ptr)
3634 return 0;
3635 p = chunk_align(ar_ptr, nb, alignment);
3636 (void)mutex_unlock(&ar_ptr->mutex);
3637 if(!p) {
3638 /* Maybe the failure is due to running out of mmapped areas. */
3639 if(ar_ptr != &main_arena) {
3640 (void)mutex_lock(&main_arena.mutex);
3641 p = chunk_align(&main_arena, nb, alignment);
3642 (void)mutex_unlock(&main_arena.mutex);
3643 } else {
3644 #if USE_ARENAS
3645 /* ... or sbrk() has failed and there is still a chance to mmap() */
3646 ar_ptr = arena_get2(ar_ptr->next ? ar_ptr : 0, nb);
3647 if(ar_ptr) {
3648 p = chunk_align(ar_ptr, nb, alignment);
3649 (void)mutex_unlock(&ar_ptr->mutex);
3651 #endif
3653 if(!p) return 0;
3655 return BOUNDED_N(chunk2mem(p), bytes);
3658 static mchunkptr
3659 internal_function
3660 #if __STD_C
3661 chunk_align(arena* ar_ptr, INTERNAL_SIZE_T nb, size_t alignment)
3662 #else
3663 chunk_align(ar_ptr, nb, alignment)
3664 arena* ar_ptr; INTERNAL_SIZE_T nb; size_t alignment;
3665 #endif
3667 unsigned long m; /* memory returned by malloc call */
3668 mchunkptr p; /* corresponding chunk */
3669 char* brk; /* alignment point within p */
3670 mchunkptr newp; /* chunk to return */
3671 INTERNAL_SIZE_T newsize; /* its size */
3672 INTERNAL_SIZE_T leadsize; /* leading space befor alignment point */
3673 mchunkptr remainder; /* spare room at end to split off */
3674 long remainder_size; /* its size */
3676 /* Call chunk_alloc with worst case padding to hit alignment. */
3677 p = chunk_alloc(ar_ptr, nb + alignment + MINSIZE);
3678 if (p == 0)
3679 return 0; /* propagate failure */
3681 m = (unsigned long)chunk2mem(p);
3683 if ((m % alignment) == 0) /* aligned */
3685 #if HAVE_MMAP
3686 if(chunk_is_mmapped(p)) {
3687 return p; /* nothing more to do */
3689 #endif
3691 else /* misaligned */
3694 Find an aligned spot inside chunk.
3695 Since we need to give back leading space in a chunk of at
3696 least MINSIZE, if the first calculation places us at
3697 a spot with less than MINSIZE leader, we can move to the
3698 next aligned spot -- we've allocated enough total room so that
3699 this is always possible.
3702 brk = (char*)mem2chunk(((m + alignment - 1)) & -(long)alignment);
3703 if ((long)(brk - (char*)(p)) < (long)MINSIZE) brk += alignment;
3705 newp = chunk_at_offset(brk, 0);
3706 leadsize = brk - (char*)(p);
3707 newsize = chunksize(p) - leadsize;
3709 #if HAVE_MMAP
3710 if(chunk_is_mmapped(p))
3712 newp->prev_size = p->prev_size + leadsize;
3713 set_head(newp, newsize|IS_MMAPPED);
3714 return newp;
3716 #endif
3718 /* give back leader, use the rest */
3720 set_head(newp, newsize | PREV_INUSE);
3721 set_inuse_bit_at_offset(newp, newsize);
3722 set_head_size(p, leadsize);
3723 chunk_free(ar_ptr, p);
3724 p = newp;
3726 assert (newsize>=nb && (((unsigned long)(chunk2mem(p))) % alignment) == 0);
3729 /* Also give back spare room at the end */
3731 remainder_size = chunksize(p) - nb;
3733 if (remainder_size >= (long)MINSIZE)
3735 remainder = chunk_at_offset(p, nb);
3736 set_head(remainder, remainder_size | PREV_INUSE);
3737 set_head_size(p, nb);
3738 chunk_free(ar_ptr, remainder);
3741 check_inuse_chunk(ar_ptr, p);
3742 return p;
3749 valloc just invokes memalign with alignment argument equal
3750 to the page size of the system (or as near to this as can
3751 be figured out from all the includes/defines above.)
3754 #if __STD_C
3755 Void_t* vALLOc(size_t bytes)
3756 #else
3757 Void_t* vALLOc(bytes) size_t bytes;
3758 #endif
3760 if(__malloc_initialized < 0)
3761 ptmalloc_init ();
3762 return mEMALIGn (malloc_getpagesize, bytes);
3766 pvalloc just invokes valloc for the nearest pagesize
3767 that will accommodate request
3771 #if __STD_C
3772 Void_t* pvALLOc(size_t bytes)
3773 #else
3774 Void_t* pvALLOc(bytes) size_t bytes;
3775 #endif
3777 size_t pagesize;
3778 if(__malloc_initialized < 0)
3779 ptmalloc_init ();
3780 pagesize = malloc_getpagesize;
3781 return mEMALIGn (pagesize, (bytes + pagesize - 1) & ~(pagesize - 1));
3786 calloc calls chunk_alloc, then zeroes out the allocated chunk.
3790 #if __STD_C
3791 Void_t* cALLOc(size_t n, size_t elem_size)
3792 #else
3793 Void_t* cALLOc(n, elem_size) size_t n; size_t elem_size;
3794 #endif
3796 arena *ar_ptr;
3797 mchunkptr p, oldtop;
3798 INTERNAL_SIZE_T sz, csz, oldtopsize;
3799 Void_t* mem;
3801 #if defined _LIBC || defined MALLOC_HOOKS
3802 __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, __const __malloc_ptr_t)) =
3803 __malloc_hook;
3804 if (hook != NULL) {
3805 sz = n * elem_size;
3806 #if defined __GNUC__ && __GNUC__ >= 2
3807 mem = (*hook)(sz, RETURN_ADDRESS (0));
3808 #else
3809 mem = (*hook)(sz, NULL);
3810 #endif
3811 if(mem == 0)
3812 return 0;
3813 #ifdef HAVE_MEMSET
3814 return memset(mem, 0, sz);
3815 #else
3816 while(sz > 0) ((char*)mem)[--sz] = 0; /* rather inefficient */
3817 return mem;
3818 #endif
3820 #endif
3822 if(request2size(n * elem_size, sz))
3823 return 0;
3824 arena_get(ar_ptr, sz);
3825 if(!ar_ptr)
3826 return 0;
3828 /* Check if expand_top called, in which case there may be
3829 no need to clear. */
3830 #if MORECORE_CLEARS
3831 oldtop = top(ar_ptr);
3832 oldtopsize = chunksize(top(ar_ptr));
3833 #if MORECORE_CLEARS < 2
3834 /* Only newly allocated memory is guaranteed to be cleared. */
3835 if (ar_ptr == &main_arena &&
3836 oldtopsize < sbrk_base + max_sbrked_mem - (char *)oldtop)
3837 oldtopsize = (sbrk_base + max_sbrked_mem - (char *)oldtop);
3838 #endif
3839 #endif
3840 p = chunk_alloc (ar_ptr, sz);
3842 /* Only clearing follows, so we can unlock early. */
3843 (void)mutex_unlock(&ar_ptr->mutex);
3845 if (p == 0) {
3846 /* Maybe the failure is due to running out of mmapped areas. */
3847 if(ar_ptr != &main_arena) {
3848 (void)mutex_lock(&main_arena.mutex);
3849 p = chunk_alloc(&main_arena, sz);
3850 (void)mutex_unlock(&main_arena.mutex);
3851 } else {
3852 #if USE_ARENAS
3853 /* ... or sbrk() has failed and there is still a chance to mmap() */
3854 (void)mutex_lock(&main_arena.mutex);
3855 ar_ptr = arena_get2(ar_ptr->next ? ar_ptr : 0, sz);
3856 (void)mutex_unlock(&main_arena.mutex);
3857 if(ar_ptr) {
3858 p = chunk_alloc(ar_ptr, sz);
3859 (void)mutex_unlock(&ar_ptr->mutex);
3861 #endif
3863 if (p == 0) return 0;
3865 mem = BOUNDED_N(chunk2mem(p), n * elem_size);
3867 /* Two optional cases in which clearing not necessary */
3869 #if HAVE_MMAP
3870 if (chunk_is_mmapped(p)) return mem;
3871 #endif
3873 csz = chunksize(p);
3875 #if MORECORE_CLEARS
3876 if (p == oldtop && csz > oldtopsize) {
3877 /* clear only the bytes from non-freshly-sbrked memory */
3878 csz = oldtopsize;
3880 #endif
3882 csz -= SIZE_SZ;
3883 MALLOC_ZERO(BOUNDED_N(chunk2mem(p), csz), csz);
3884 return mem;
3889 cfree just calls free. It is needed/defined on some systems
3890 that pair it with calloc, presumably for odd historical reasons.
3894 #if !defined(_LIBC)
3895 #if __STD_C
3896 void cfree(Void_t *mem)
3897 #else
3898 void cfree(mem) Void_t *mem;
3899 #endif
3901 fREe(mem);
3903 #endif
3909 Malloc_trim gives memory back to the system (via negative
3910 arguments to sbrk) if there is unused memory at the `high' end of
3911 the malloc pool. You can call this after freeing large blocks of
3912 memory to potentially reduce the system-level memory requirements
3913 of a program. However, it cannot guarantee to reduce memory. Under
3914 some allocation patterns, some large free blocks of memory will be
3915 locked between two used chunks, so they cannot be given back to
3916 the system.
3918 The `pad' argument to malloc_trim represents the amount of free
3919 trailing space to leave untrimmed. If this argument is zero,
3920 only the minimum amount of memory to maintain internal data
3921 structures will be left (one page or less). Non-zero arguments
3922 can be supplied to maintain enough trailing space to service
3923 future expected allocations without having to re-obtain memory
3924 from the system.
3926 Malloc_trim returns 1 if it actually released any memory, else 0.
3930 #if __STD_C
3931 int mALLOC_TRIm(size_t pad)
3932 #else
3933 int mALLOC_TRIm(pad) size_t pad;
3934 #endif
3936 int res;
3938 (void)mutex_lock(&main_arena.mutex);
3939 res = main_trim(pad);
3940 (void)mutex_unlock(&main_arena.mutex);
3941 return res;
3944 /* Trim the main arena. */
3946 static int
3947 internal_function
3948 #if __STD_C
3949 main_trim(size_t pad)
3950 #else
3951 main_trim(pad) size_t pad;
3952 #endif
3954 mchunkptr top_chunk; /* The current top chunk */
3955 long top_size; /* Amount of top-most memory */
3956 long extra; /* Amount to release */
3957 char* current_brk; /* address returned by pre-check sbrk call */
3958 char* new_brk; /* address returned by negative sbrk call */
3960 unsigned long pagesz = malloc_getpagesize;
3962 top_chunk = top(&main_arena);
3963 top_size = chunksize(top_chunk);
3964 extra = ((top_size - pad - MINSIZE + (pagesz-1)) / pagesz - 1) * pagesz;
3966 if (extra < (long)pagesz) /* Not enough memory to release */
3967 return 0;
3969 /* Test to make sure no one else called sbrk */
3970 current_brk = (char*)(MORECORE (0));
3971 if (current_brk != (char*)(top_chunk) + top_size)
3972 return 0; /* Apparently we don't own memory; must fail */
3974 new_brk = (char*)(MORECORE (-extra));
3976 #if defined _LIBC || defined MALLOC_HOOKS
3977 /* Call the `morecore' hook if necessary. */
3978 if (__after_morecore_hook)
3979 (*__after_morecore_hook) ();
3980 #endif
3982 if (new_brk == (char*)(MORECORE_FAILURE)) { /* sbrk failed? */
3983 /* Try to figure out what we have */
3984 current_brk = (char*)(MORECORE (0));
3985 top_size = current_brk - (char*)top_chunk;
3986 if (top_size >= (long)MINSIZE) /* if not, we are very very dead! */
3988 sbrked_mem = current_brk - sbrk_base;
3989 set_head(top_chunk, top_size | PREV_INUSE);
3991 check_chunk(&main_arena, top_chunk);
3992 return 0;
3994 sbrked_mem -= extra;
3996 /* Success. Adjust top accordingly. */
3997 set_head(top_chunk, (top_size - extra) | PREV_INUSE);
3998 check_chunk(&main_arena, top_chunk);
3999 return 1;
4002 #if USE_ARENAS
4004 static int
4005 internal_function
4006 #if __STD_C
4007 heap_trim(heap_info *heap, size_t pad)
4008 #else
4009 heap_trim(heap, pad) heap_info *heap; size_t pad;
4010 #endif
4012 unsigned long pagesz = malloc_getpagesize;
4013 arena *ar_ptr = heap->ar_ptr;
4014 mchunkptr top_chunk = top(ar_ptr), p, bck, fwd;
4015 heap_info *prev_heap;
4016 long new_size, top_size, extra;
4018 /* Can this heap go away completely ? */
4019 while(top_chunk == chunk_at_offset(heap, sizeof(*heap))) {
4020 prev_heap = heap->prev;
4021 p = chunk_at_offset(prev_heap, prev_heap->size - (MINSIZE-2*SIZE_SZ));
4022 assert(p->size == (0|PREV_INUSE)); /* must be fencepost */
4023 p = prev_chunk(p);
4024 new_size = chunksize(p) + (MINSIZE-2*SIZE_SZ);
4025 assert(new_size>0 && new_size<(long)(2*MINSIZE));
4026 if(!prev_inuse(p))
4027 new_size += p->prev_size;
4028 assert(new_size>0 && new_size<HEAP_MAX_SIZE);
4029 if(new_size + (HEAP_MAX_SIZE - prev_heap->size) < pad + MINSIZE + pagesz)
4030 break;
4031 ar_ptr->size -= heap->size;
4032 arena_mem -= heap->size;
4033 delete_heap(heap);
4034 heap = prev_heap;
4035 if(!prev_inuse(p)) { /* consolidate backward */
4036 p = prev_chunk(p);
4037 unlink(p, bck, fwd);
4039 assert(((unsigned long)((char*)p + new_size) & (pagesz-1)) == 0);
4040 assert( ((char*)p + new_size) == ((char*)heap + heap->size) );
4041 top(ar_ptr) = top_chunk = p;
4042 set_head(top_chunk, new_size | PREV_INUSE);
4043 check_chunk(ar_ptr, top_chunk);
4045 top_size = chunksize(top_chunk);
4046 extra = ((top_size - pad - MINSIZE + (pagesz-1))/pagesz - 1) * pagesz;
4047 if(extra < (long)pagesz)
4048 return 0;
4049 /* Try to shrink. */
4050 if(grow_heap(heap, -extra) != 0)
4051 return 0;
4052 ar_ptr->size -= extra;
4053 arena_mem -= extra;
4055 /* Success. Adjust top accordingly. */
4056 set_head(top_chunk, (top_size - extra) | PREV_INUSE);
4057 check_chunk(ar_ptr, top_chunk);
4058 return 1;
4061 #endif /* USE_ARENAS */
4066 malloc_usable_size:
4068 This routine tells you how many bytes you can actually use in an
4069 allocated chunk, which may be more than you requested (although
4070 often not). You can use this many bytes without worrying about
4071 overwriting other allocated objects. Not a particularly great
4072 programming practice, but still sometimes useful.
4076 #if __STD_C
4077 size_t mALLOC_USABLE_SIZe(Void_t* mem)
4078 #else
4079 size_t mALLOC_USABLE_SIZe(mem) Void_t* mem;
4080 #endif
4082 mchunkptr p;
4084 if (mem == 0)
4085 return 0;
4086 else
4088 p = mem2chunk(mem);
4089 if(!chunk_is_mmapped(p))
4091 if (!inuse(p)) return 0;
4092 check_inuse_chunk(arena_for_ptr(mem), p);
4093 return chunksize(p) - SIZE_SZ;
4095 return chunksize(p) - 2*SIZE_SZ;
4102 /* Utility to update mallinfo for malloc_stats() and mallinfo() */
4104 static void
4105 #if __STD_C
4106 malloc_update_mallinfo(arena *ar_ptr, struct mallinfo *mi)
4107 #else
4108 malloc_update_mallinfo(ar_ptr, mi) arena *ar_ptr; struct mallinfo *mi;
4109 #endif
4111 int i, navail;
4112 mbinptr b;
4113 mchunkptr p;
4114 #if MALLOC_DEBUG
4115 mchunkptr q;
4116 #endif
4117 INTERNAL_SIZE_T avail;
4119 (void)mutex_lock(&ar_ptr->mutex);
4120 avail = chunksize(top(ar_ptr));
4121 navail = ((long)(avail) >= (long)MINSIZE)? 1 : 0;
4123 for (i = 1; i < NAV; ++i)
4125 b = bin_at(ar_ptr, i);
4126 for (p = last(b); p != b; p = p->bk)
4128 #if MALLOC_DEBUG
4129 check_free_chunk(ar_ptr, p);
4130 for (q = next_chunk(p);
4131 q != top(ar_ptr) && inuse(q) && (long)chunksize(q) > 0;
4132 q = next_chunk(q))
4133 check_inuse_chunk(ar_ptr, q);
4134 #endif
4135 avail += chunksize(p);
4136 navail++;
4140 mi->arena = ar_ptr->size;
4141 mi->ordblks = navail;
4142 mi->smblks = mi->usmblks = mi->fsmblks = 0; /* clear unused fields */
4143 mi->uordblks = ar_ptr->size - avail;
4144 mi->fordblks = avail;
4145 mi->hblks = n_mmaps;
4146 mi->hblkhd = mmapped_mem;
4147 mi->keepcost = chunksize(top(ar_ptr));
4149 (void)mutex_unlock(&ar_ptr->mutex);
4152 #if USE_ARENAS && MALLOC_DEBUG > 1
4154 /* Print the complete contents of a single heap to stderr. */
4156 static void
4157 #if __STD_C
4158 dump_heap(heap_info *heap)
4159 #else
4160 dump_heap(heap) heap_info *heap;
4161 #endif
4163 char *ptr;
4164 mchunkptr p;
4166 fprintf(stderr, "Heap %p, size %10lx:\n", heap, (long)heap->size);
4167 ptr = (heap->ar_ptr != (arena*)(heap+1)) ?
4168 (char*)(heap + 1) : (char*)(heap + 1) + sizeof(arena);
4169 p = (mchunkptr)(((unsigned long)ptr + MALLOC_ALIGN_MASK) &
4170 ~MALLOC_ALIGN_MASK);
4171 for(;;) {
4172 fprintf(stderr, "chunk %p size %10lx", p, (long)p->size);
4173 if(p == top(heap->ar_ptr)) {
4174 fprintf(stderr, " (top)\n");
4175 break;
4176 } else if(p->size == (0|PREV_INUSE)) {
4177 fprintf(stderr, " (fence)\n");
4178 break;
4180 fprintf(stderr, "\n");
4181 p = next_chunk(p);
4185 #endif
4191 malloc_stats:
4193 For all arenas separately and in total, prints on stderr the
4194 amount of space obtained from the system, and the current number
4195 of bytes allocated via malloc (or realloc, etc) but not yet
4196 freed. (Note that this is the number of bytes allocated, not the
4197 number requested. It will be larger than the number requested
4198 because of alignment and bookkeeping overhead.) When not compiled
4199 for multiple threads, the maximum amount of allocated memory
4200 (which may be more than current if malloc_trim and/or munmap got
4201 called) is also reported. When using mmap(), prints the maximum
4202 number of simultaneous mmap regions used, too.
4206 void mALLOC_STATs()
4208 int i;
4209 arena *ar_ptr;
4210 struct mallinfo mi;
4211 unsigned int in_use_b = mmapped_mem, system_b = in_use_b;
4212 #if THREAD_STATS
4213 long stat_lock_direct = 0, stat_lock_loop = 0, stat_lock_wait = 0;
4214 #endif
4216 for(i=0, ar_ptr = &main_arena;; i++) {
4217 malloc_update_mallinfo(ar_ptr, &mi);
4218 fprintf(stderr, "Arena %d:\n", i);
4219 fprintf(stderr, "system bytes = %10u\n", (unsigned int)mi.arena);
4220 fprintf(stderr, "in use bytes = %10u\n", (unsigned int)mi.uordblks);
4221 system_b += mi.arena;
4222 in_use_b += mi.uordblks;
4223 #if THREAD_STATS
4224 stat_lock_direct += ar_ptr->stat_lock_direct;
4225 stat_lock_loop += ar_ptr->stat_lock_loop;
4226 stat_lock_wait += ar_ptr->stat_lock_wait;
4227 #endif
4228 #if USE_ARENAS && MALLOC_DEBUG > 1
4229 if(ar_ptr != &main_arena) {
4230 heap_info *heap;
4231 (void)mutex_lock(&ar_ptr->mutex);
4232 heap = heap_for_ptr(top(ar_ptr));
4233 while(heap) { dump_heap(heap); heap = heap->prev; }
4234 (void)mutex_unlock(&ar_ptr->mutex);
4236 #endif
4237 ar_ptr = ar_ptr->next;
4238 if(ar_ptr == &main_arena) break;
4240 #if HAVE_MMAP
4241 fprintf(stderr, "Total (incl. mmap):\n");
4242 #else
4243 fprintf(stderr, "Total:\n");
4244 #endif
4245 fprintf(stderr, "system bytes = %10u\n", system_b);
4246 fprintf(stderr, "in use bytes = %10u\n", in_use_b);
4247 #ifdef NO_THREADS
4248 fprintf(stderr, "max system bytes = %10u\n", (unsigned int)max_total_mem);
4249 #endif
4250 #if HAVE_MMAP
4251 fprintf(stderr, "max mmap regions = %10u\n", (unsigned int)max_n_mmaps);
4252 fprintf(stderr, "max mmap bytes = %10lu\n", max_mmapped_mem);
4253 #endif
4254 #if THREAD_STATS
4255 fprintf(stderr, "heaps created = %10d\n", stat_n_heaps);
4256 fprintf(stderr, "locked directly = %10ld\n", stat_lock_direct);
4257 fprintf(stderr, "locked in loop = %10ld\n", stat_lock_loop);
4258 fprintf(stderr, "locked waiting = %10ld\n", stat_lock_wait);
4259 fprintf(stderr, "locked total = %10ld\n",
4260 stat_lock_direct + stat_lock_loop + stat_lock_wait);
4261 #endif
4265 mallinfo returns a copy of updated current mallinfo.
4266 The information reported is for the arena last used by the thread.
4269 struct mallinfo mALLINFo()
4271 struct mallinfo mi;
4272 Void_t *vptr = NULL;
4274 #ifndef NO_THREADS
4275 tsd_getspecific(arena_key, vptr);
4276 if(vptr == ATFORK_ARENA_PTR)
4277 vptr = (Void_t*)&main_arena;
4278 #endif
4279 malloc_update_mallinfo((vptr ? (arena*)vptr : &main_arena), &mi);
4280 return mi;
4287 mallopt:
4289 mallopt is the general SVID/XPG interface to tunable parameters.
4290 The format is to provide a (parameter-number, parameter-value) pair.
4291 mallopt then sets the corresponding parameter to the argument
4292 value if it can (i.e., so long as the value is meaningful),
4293 and returns 1 if successful else 0.
4295 See descriptions of tunable parameters above.
4299 #if __STD_C
4300 int mALLOPt(int param_number, int value)
4301 #else
4302 int mALLOPt(param_number, value) int param_number; int value;
4303 #endif
4305 switch(param_number)
4307 case M_TRIM_THRESHOLD:
4308 trim_threshold = value; return 1;
4309 case M_TOP_PAD:
4310 top_pad = value; return 1;
4311 case M_MMAP_THRESHOLD:
4312 #if USE_ARENAS
4313 /* Forbid setting the threshold too high. */
4314 if((unsigned long)value > HEAP_MAX_SIZE/2) return 0;
4315 #endif
4316 mmap_threshold = value; return 1;
4317 case M_MMAP_MAX:
4318 #if HAVE_MMAP
4319 n_mmaps_max = value; return 1;
4320 #else
4321 if (value != 0) return 0; else n_mmaps_max = value; return 1;
4322 #endif
4323 case M_CHECK_ACTION:
4324 check_action = value; return 1;
4326 default:
4327 return 0;
4333 /* Get/set state: malloc_get_state() records the current state of all
4334 malloc variables (_except_ for the actual heap contents and `hook'
4335 function pointers) in a system dependent, opaque data structure.
4336 This data structure is dynamically allocated and can be free()d
4337 after use. malloc_set_state() restores the state of all malloc
4338 variables to the previously obtained state. This is especially
4339 useful when using this malloc as part of a shared library, and when
4340 the heap contents are saved/restored via some other method. The
4341 primary example for this is GNU Emacs with its `dumping' procedure.
4342 `Hook' function pointers are never saved or restored by these
4343 functions, with two exceptions: If malloc checking was in use when
4344 malloc_get_state() was called, then malloc_set_state() calls
4345 __malloc_check_init() if possible; if malloc checking was not in
4346 use in the recorded state but the user requested malloc checking,
4347 then the hooks are reset to 0. */
4349 #define MALLOC_STATE_MAGIC 0x444c4541l
4350 #define MALLOC_STATE_VERSION (0*0x100l + 1l) /* major*0x100 + minor */
4352 struct malloc_state {
4353 long magic;
4354 long version;
4355 mbinptr av[NAV * 2 + 2];
4356 char* sbrk_base;
4357 int sbrked_mem_bytes;
4358 unsigned long trim_threshold;
4359 unsigned long top_pad;
4360 unsigned int n_mmaps_max;
4361 unsigned long mmap_threshold;
4362 int check_action;
4363 unsigned long max_sbrked_mem;
4364 unsigned long max_total_mem;
4365 unsigned int n_mmaps;
4366 unsigned int max_n_mmaps;
4367 unsigned long mmapped_mem;
4368 unsigned long max_mmapped_mem;
4369 int using_malloc_checking;
4372 Void_t*
4373 mALLOC_GET_STATe()
4375 struct malloc_state* ms;
4376 int i;
4377 mbinptr b;
4379 ms = (struct malloc_state*)mALLOc(sizeof(*ms));
4380 if (!ms)
4381 return 0;
4382 (void)mutex_lock(&main_arena.mutex);
4383 ms->magic = MALLOC_STATE_MAGIC;
4384 ms->version = MALLOC_STATE_VERSION;
4385 ms->av[0] = main_arena.av[0];
4386 ms->av[1] = main_arena.av[1];
4387 for(i=0; i<NAV; i++) {
4388 b = bin_at(&main_arena, i);
4389 if(first(b) == b)
4390 ms->av[2*i+2] = ms->av[2*i+3] = 0; /* empty bin (or initial top) */
4391 else {
4392 ms->av[2*i+2] = first(b);
4393 ms->av[2*i+3] = last(b);
4396 ms->sbrk_base = sbrk_base;
4397 ms->sbrked_mem_bytes = sbrked_mem;
4398 ms->trim_threshold = trim_threshold;
4399 ms->top_pad = top_pad;
4400 ms->n_mmaps_max = n_mmaps_max;
4401 ms->mmap_threshold = mmap_threshold;
4402 ms->check_action = check_action;
4403 ms->max_sbrked_mem = max_sbrked_mem;
4404 #ifdef NO_THREADS
4405 ms->max_total_mem = max_total_mem;
4406 #else
4407 ms->max_total_mem = 0;
4408 #endif
4409 ms->n_mmaps = n_mmaps;
4410 ms->max_n_mmaps = max_n_mmaps;
4411 ms->mmapped_mem = mmapped_mem;
4412 ms->max_mmapped_mem = max_mmapped_mem;
4413 #if defined _LIBC || defined MALLOC_HOOKS
4414 ms->using_malloc_checking = using_malloc_checking;
4415 #else
4416 ms->using_malloc_checking = 0;
4417 #endif
4418 (void)mutex_unlock(&main_arena.mutex);
4419 return (Void_t*)ms;
4423 #if __STD_C
4424 mALLOC_SET_STATe(Void_t* msptr)
4425 #else
4426 mALLOC_SET_STATe(msptr) Void_t* msptr;
4427 #endif
4429 struct malloc_state* ms = (struct malloc_state*)msptr;
4430 int i;
4431 mbinptr b;
4433 #if defined _LIBC || defined MALLOC_HOOKS
4434 disallow_malloc_check = 1;
4435 #endif
4436 ptmalloc_init();
4437 if(ms->magic != MALLOC_STATE_MAGIC) return -1;
4438 /* Must fail if the major version is too high. */
4439 if((ms->version & ~0xffl) > (MALLOC_STATE_VERSION & ~0xffl)) return -2;
4440 (void)mutex_lock(&main_arena.mutex);
4441 main_arena.av[0] = ms->av[0];
4442 main_arena.av[1] = ms->av[1];
4443 for(i=0; i<NAV; i++) {
4444 b = bin_at(&main_arena, i);
4445 if(ms->av[2*i+2] == 0)
4446 first(b) = last(b) = b;
4447 else {
4448 first(b) = ms->av[2*i+2];
4449 last(b) = ms->av[2*i+3];
4450 if(i > 0) {
4451 /* Make sure the links to the `av'-bins in the heap are correct. */
4452 first(b)->bk = b;
4453 last(b)->fd = b;
4457 sbrk_base = ms->sbrk_base;
4458 sbrked_mem = ms->sbrked_mem_bytes;
4459 trim_threshold = ms->trim_threshold;
4460 top_pad = ms->top_pad;
4461 n_mmaps_max = ms->n_mmaps_max;
4462 mmap_threshold = ms->mmap_threshold;
4463 check_action = ms->check_action;
4464 max_sbrked_mem = ms->max_sbrked_mem;
4465 #ifdef NO_THREADS
4466 max_total_mem = ms->max_total_mem;
4467 #endif
4468 n_mmaps = ms->n_mmaps;
4469 max_n_mmaps = ms->max_n_mmaps;
4470 mmapped_mem = ms->mmapped_mem;
4471 max_mmapped_mem = ms->max_mmapped_mem;
4472 /* add version-dependent code here */
4473 if (ms->version >= 1) {
4474 #if defined _LIBC || defined MALLOC_HOOKS
4475 /* Check whether it is safe to enable malloc checking, or whether
4476 it is necessary to disable it. */
4477 if (ms->using_malloc_checking && !using_malloc_checking &&
4478 !disallow_malloc_check)
4479 __malloc_check_init ();
4480 else if (!ms->using_malloc_checking && using_malloc_checking) {
4481 __malloc_hook = 0;
4482 __free_hook = 0;
4483 __realloc_hook = 0;
4484 __memalign_hook = 0;
4485 using_malloc_checking = 0;
4487 #endif
4490 (void)mutex_unlock(&main_arena.mutex);
4491 return 0;
4496 #if defined _LIBC || defined MALLOC_HOOKS
4498 /* A simple, standard set of debugging hooks. Overhead is `only' one
4499 byte per chunk; still this will catch most cases of double frees or
4500 overruns. The goal here is to avoid obscure crashes due to invalid
4501 usage, unlike in the MALLOC_DEBUG code. */
4503 #define MAGICBYTE(p) ( ( ((size_t)p >> 3) ^ ((size_t)p >> 11)) & 0xFF )
4505 /* Instrument a chunk with overrun detector byte(s) and convert it
4506 into a user pointer with requested size sz. */
4508 static Void_t*
4509 internal_function
4510 #if __STD_C
4511 chunk2mem_check(mchunkptr p, size_t sz)
4512 #else
4513 chunk2mem_check(p, sz) mchunkptr p; size_t sz;
4514 #endif
4516 unsigned char* m_ptr = (unsigned char*)BOUNDED_N(chunk2mem(p), sz);
4517 size_t i;
4519 for(i = chunksize(p) - (chunk_is_mmapped(p) ? 2*SIZE_SZ+1 : SIZE_SZ+1);
4520 i > sz;
4521 i -= 0xFF) {
4522 if(i-sz < 0x100) {
4523 m_ptr[i] = (unsigned char)(i-sz);
4524 break;
4526 m_ptr[i] = 0xFF;
4528 m_ptr[sz] = MAGICBYTE(p);
4529 return (Void_t*)m_ptr;
4532 /* Convert a pointer to be free()d or realloc()ed to a valid chunk
4533 pointer. If the provided pointer is not valid, return NULL. */
4535 static mchunkptr
4536 internal_function
4537 #if __STD_C
4538 mem2chunk_check(Void_t* mem)
4539 #else
4540 mem2chunk_check(mem) Void_t* mem;
4541 #endif
4543 mchunkptr p;
4544 INTERNAL_SIZE_T sz, c;
4545 unsigned char magic;
4547 p = mem2chunk(mem);
4548 if(!aligned_OK(p)) return NULL;
4549 if( (char*)p>=sbrk_base && (char*)p<(sbrk_base+sbrked_mem) ) {
4550 /* Must be a chunk in conventional heap memory. */
4551 if(chunk_is_mmapped(p) ||
4552 ( (sz = chunksize(p)), ((char*)p + sz)>=(sbrk_base+sbrked_mem) ) ||
4553 sz<MINSIZE || sz&MALLOC_ALIGN_MASK || !inuse(p) ||
4554 ( !prev_inuse(p) && (p->prev_size&MALLOC_ALIGN_MASK ||
4555 (long)prev_chunk(p)<(long)sbrk_base ||
4556 next_chunk(prev_chunk(p))!=p) ))
4557 return NULL;
4558 magic = MAGICBYTE(p);
4559 for(sz += SIZE_SZ-1; (c = ((unsigned char*)p)[sz]) != magic; sz -= c) {
4560 if(c<=0 || sz<(c+2*SIZE_SZ)) return NULL;
4562 ((unsigned char*)p)[sz] ^= 0xFF;
4563 } else {
4564 unsigned long offset, page_mask = malloc_getpagesize-1;
4566 /* mmap()ed chunks have MALLOC_ALIGNMENT or higher power-of-two
4567 alignment relative to the beginning of a page. Check this
4568 first. */
4569 offset = (unsigned long)mem & page_mask;
4570 if((offset!=MALLOC_ALIGNMENT && offset!=0 && offset!=0x10 &&
4571 offset!=0x20 && offset!=0x40 && offset!=0x80 && offset!=0x100 &&
4572 offset!=0x200 && offset!=0x400 && offset!=0x800 && offset!=0x1000 &&
4573 offset<0x2000) ||
4574 !chunk_is_mmapped(p) || (p->size & PREV_INUSE) ||
4575 ( (((unsigned long)p - p->prev_size) & page_mask) != 0 ) ||
4576 ( (sz = chunksize(p)), ((p->prev_size + sz) & page_mask) != 0 ) )
4577 return NULL;
4578 magic = MAGICBYTE(p);
4579 for(sz -= 1; (c = ((unsigned char*)p)[sz]) != magic; sz -= c) {
4580 if(c<=0 || sz<(c+2*SIZE_SZ)) return NULL;
4582 ((unsigned char*)p)[sz] ^= 0xFF;
4584 return p;
4587 /* Check for corruption of the top chunk, and try to recover if
4588 necessary. */
4590 static int
4591 internal_function
4592 #if __STD_C
4593 top_check(void)
4594 #else
4595 top_check()
4596 #endif
4598 mchunkptr t = top(&main_arena);
4599 char* brk, * new_brk;
4600 INTERNAL_SIZE_T front_misalign, sbrk_size;
4601 unsigned long pagesz = malloc_getpagesize;
4603 if((char*)t + chunksize(t) == sbrk_base + sbrked_mem ||
4604 t == initial_top(&main_arena)) return 0;
4606 if(check_action & 1)
4607 fprintf(stderr, "malloc: top chunk is corrupt\n");
4608 if(check_action & 2)
4609 abort();
4611 /* Try to set up a new top chunk. */
4612 brk = MORECORE(0);
4613 front_misalign = (unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK;
4614 if (front_misalign > 0)
4615 front_misalign = MALLOC_ALIGNMENT - front_misalign;
4616 sbrk_size = front_misalign + top_pad + MINSIZE;
4617 sbrk_size += pagesz - ((unsigned long)(brk + sbrk_size) & (pagesz - 1));
4618 new_brk = (char*)(MORECORE (sbrk_size));
4619 if (new_brk == (char*)(MORECORE_FAILURE)) return -1;
4620 sbrked_mem = (new_brk - sbrk_base) + sbrk_size;
4622 top(&main_arena) = (mchunkptr)(brk + front_misalign);
4623 set_head(top(&main_arena), (sbrk_size - front_misalign) | PREV_INUSE);
4625 return 0;
4628 static Void_t*
4629 #if __STD_C
4630 malloc_check(size_t sz, const Void_t *caller)
4631 #else
4632 malloc_check(sz, caller) size_t sz; const Void_t *caller;
4633 #endif
4635 mchunkptr victim;
4636 INTERNAL_SIZE_T nb;
4638 if(request2size(sz+1, nb))
4639 return 0;
4640 (void)mutex_lock(&main_arena.mutex);
4641 victim = (top_check() >= 0) ? chunk_alloc(&main_arena, nb) : NULL;
4642 (void)mutex_unlock(&main_arena.mutex);
4643 if(!victim) return NULL;
4644 return chunk2mem_check(victim, sz);
4647 static void
4648 #if __STD_C
4649 free_check(Void_t* mem, const Void_t *caller)
4650 #else
4651 free_check(mem, caller) Void_t* mem; const Void_t *caller;
4652 #endif
4654 mchunkptr p;
4656 if(!mem) return;
4657 (void)mutex_lock(&main_arena.mutex);
4658 p = mem2chunk_check(mem);
4659 if(!p) {
4660 (void)mutex_unlock(&main_arena.mutex);
4661 if(check_action & 1)
4662 fprintf(stderr, "free(): invalid pointer %p!\n", mem);
4663 if(check_action & 2)
4664 abort();
4665 return;
4667 #if HAVE_MMAP
4668 if (chunk_is_mmapped(p)) {
4669 (void)mutex_unlock(&main_arena.mutex);
4670 munmap_chunk(p);
4671 return;
4673 #endif
4674 #if 0 /* Erase freed memory. */
4675 memset(mem, 0, chunksize(p) - (SIZE_SZ+1));
4676 #endif
4677 chunk_free(&main_arena, p);
4678 (void)mutex_unlock(&main_arena.mutex);
4681 static Void_t*
4682 #if __STD_C
4683 realloc_check(Void_t* oldmem, size_t bytes, const Void_t *caller)
4684 #else
4685 realloc_check(oldmem, bytes, caller)
4686 Void_t* oldmem; size_t bytes; const Void_t *caller;
4687 #endif
4689 mchunkptr oldp, newp;
4690 INTERNAL_SIZE_T nb, oldsize;
4692 if (oldmem == 0) return malloc_check(bytes, NULL);
4693 (void)mutex_lock(&main_arena.mutex);
4694 oldp = mem2chunk_check(oldmem);
4695 if(!oldp) {
4696 (void)mutex_unlock(&main_arena.mutex);
4697 if(check_action & 1)
4698 fprintf(stderr, "realloc(): invalid pointer %p!\n", oldmem);
4699 if(check_action & 2)
4700 abort();
4701 return malloc_check(bytes, NULL);
4703 oldsize = chunksize(oldp);
4705 if(request2size(bytes+1, nb)) {
4706 (void)mutex_unlock(&main_arena.mutex);
4707 return 0;
4710 #if HAVE_MMAP
4711 if (chunk_is_mmapped(oldp)) {
4712 #if HAVE_MREMAP
4713 newp = mremap_chunk(oldp, nb);
4714 if(!newp) {
4715 #endif
4716 /* Note the extra SIZE_SZ overhead. */
4717 if(oldsize - SIZE_SZ >= nb) newp = oldp; /* do nothing */
4718 else {
4719 /* Must alloc, copy, free. */
4720 newp = (top_check() >= 0) ? chunk_alloc(&main_arena, nb) : NULL;
4721 if (newp) {
4722 MALLOC_COPY(BOUNDED_N(chunk2mem(newp), nb),
4723 oldmem, oldsize - 2*SIZE_SZ, 0);
4724 munmap_chunk(oldp);
4727 #if HAVE_MREMAP
4729 #endif
4730 } else {
4731 #endif /* HAVE_MMAP */
4732 newp = (top_check() >= 0) ?
4733 chunk_realloc(&main_arena, oldp, oldsize, nb) : NULL;
4734 #if 0 /* Erase freed memory. */
4735 nb = chunksize(newp);
4736 if(oldp<newp || oldp>=chunk_at_offset(newp, nb)) {
4737 memset((char*)oldmem + 2*sizeof(mbinptr), 0,
4738 oldsize - (2*sizeof(mbinptr)+2*SIZE_SZ+1));
4739 } else if(nb > oldsize+SIZE_SZ) {
4740 memset((char*)BOUNDED_N(chunk2mem(newp), bytes) + oldsize,
4741 0, nb - (oldsize+SIZE_SZ));
4743 #endif
4744 #if HAVE_MMAP
4746 #endif
4747 (void)mutex_unlock(&main_arena.mutex);
4749 if(!newp) return NULL;
4750 return chunk2mem_check(newp, bytes);
4753 static Void_t*
4754 #if __STD_C
4755 memalign_check(size_t alignment, size_t bytes, const Void_t *caller)
4756 #else
4757 memalign_check(alignment, bytes, caller)
4758 size_t alignment; size_t bytes; const Void_t *caller;
4759 #endif
4761 INTERNAL_SIZE_T nb;
4762 mchunkptr p;
4764 if (alignment <= MALLOC_ALIGNMENT) return malloc_check(bytes, NULL);
4765 if (alignment < MINSIZE) alignment = MINSIZE;
4767 if(request2size(bytes+1, nb))
4768 return 0;
4769 (void)mutex_lock(&main_arena.mutex);
4770 p = (top_check() >= 0) ? chunk_align(&main_arena, nb, alignment) : NULL;
4771 (void)mutex_unlock(&main_arena.mutex);
4772 if(!p) return NULL;
4773 return chunk2mem_check(p, bytes);
4776 #ifndef NO_THREADS
4778 /* The following hooks are used when the global initialization in
4779 ptmalloc_init() hasn't completed yet. */
4781 static Void_t*
4782 #if __STD_C
4783 malloc_starter(size_t sz, const Void_t *caller)
4784 #else
4785 malloc_starter(sz, caller) size_t sz; const Void_t *caller;
4786 #endif
4788 INTERNAL_SIZE_T nb;
4789 mchunkptr victim;
4791 if(request2size(sz, nb))
4792 return 0;
4793 victim = chunk_alloc(&main_arena, nb);
4795 return victim ? BOUNDED_N(chunk2mem(victim), sz) : 0;
4798 static void
4799 #if __STD_C
4800 free_starter(Void_t* mem, const Void_t *caller)
4801 #else
4802 free_starter(mem, caller) Void_t* mem; const Void_t *caller;
4803 #endif
4805 mchunkptr p;
4807 if(!mem) return;
4808 p = mem2chunk(mem);
4809 #if HAVE_MMAP
4810 if (chunk_is_mmapped(p)) {
4811 munmap_chunk(p);
4812 return;
4814 #endif
4815 chunk_free(&main_arena, p);
4818 /* The following hooks are used while the `atfork' handling mechanism
4819 is active. */
4821 static Void_t*
4822 #if __STD_C
4823 malloc_atfork (size_t sz, const Void_t *caller)
4824 #else
4825 malloc_atfork(sz, caller) size_t sz; const Void_t *caller;
4826 #endif
4828 Void_t *vptr = NULL;
4829 INTERNAL_SIZE_T nb;
4830 mchunkptr victim;
4832 tsd_getspecific(arena_key, vptr);
4833 if(vptr == ATFORK_ARENA_PTR) {
4834 /* We are the only thread that may allocate at all. */
4835 if(save_malloc_hook != malloc_check) {
4836 if(request2size(sz, nb))
4837 return 0;
4838 victim = chunk_alloc(&main_arena, nb);
4839 return victim ? BOUNDED_N(chunk2mem(victim), sz) : 0;
4840 } else {
4841 if(top_check()<0 || request2size(sz+1, nb))
4842 return 0;
4843 victim = chunk_alloc(&main_arena, nb);
4844 return victim ? chunk2mem_check(victim, sz) : 0;
4846 } else {
4847 /* Suspend the thread until the `atfork' handlers have completed.
4848 By that time, the hooks will have been reset as well, so that
4849 mALLOc() can be used again. */
4850 (void)mutex_lock(&list_lock);
4851 (void)mutex_unlock(&list_lock);
4852 return mALLOc(sz);
4856 static void
4857 #if __STD_C
4858 free_atfork(Void_t* mem, const Void_t *caller)
4859 #else
4860 free_atfork(mem, caller) Void_t* mem; const Void_t *caller;
4861 #endif
4863 Void_t *vptr = NULL;
4864 arena *ar_ptr;
4865 mchunkptr p; /* chunk corresponding to mem */
4867 if (mem == 0) /* free(0) has no effect */
4868 return;
4870 p = mem2chunk(mem); /* do not bother to replicate free_check here */
4872 #if HAVE_MMAP
4873 if (chunk_is_mmapped(p)) /* release mmapped memory. */
4875 munmap_chunk(p);
4876 return;
4878 #endif
4880 ar_ptr = arena_for_ptr(p);
4881 tsd_getspecific(arena_key, vptr);
4882 if(vptr != ATFORK_ARENA_PTR)
4883 (void)mutex_lock(&ar_ptr->mutex);
4884 chunk_free(ar_ptr, p);
4885 if(vptr != ATFORK_ARENA_PTR)
4886 (void)mutex_unlock(&ar_ptr->mutex);
4889 #endif /* !defined NO_THREADS */
4891 #endif /* defined _LIBC || defined MALLOC_HOOKS */
4895 #ifdef _LIBC
4896 /* We need a wrapper function for one of the additions of POSIX. */
4898 __posix_memalign (void **memptr, size_t alignment, size_t size)
4900 void *mem;
4902 /* Test whether the SIZE argument is valid. It must be a power of
4903 two multiple of sizeof (void *). */
4904 if (size % sizeof (void *) != 0 || (size & (size - 1)) != 0)
4905 return EINVAL;
4907 mem = __libc_memalign (alignment, size);
4909 if (mem != NULL)
4911 *memptr = mem;
4912 return 0;
4915 return ENOMEM;
4917 weak_alias (__posix_memalign, posix_memalign)
4919 weak_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)
4920 weak_alias (__libc_free, __cfree) weak_alias (__libc_free, cfree)
4921 weak_alias (__libc_free, __free) weak_alias (__libc_free, free)
4922 weak_alias (__libc_malloc, __malloc) weak_alias (__libc_malloc, malloc)
4923 weak_alias (__libc_memalign, __memalign) weak_alias (__libc_memalign, memalign)
4924 weak_alias (__libc_realloc, __realloc) weak_alias (__libc_realloc, realloc)
4925 weak_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)
4926 weak_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)
4927 weak_alias (__libc_mallinfo, __mallinfo) weak_alias (__libc_mallinfo, mallinfo)
4928 weak_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)
4930 weak_alias (__malloc_stats, malloc_stats)
4931 weak_alias (__malloc_usable_size, malloc_usable_size)
4932 weak_alias (__malloc_trim, malloc_trim)
4933 weak_alias (__malloc_get_state, malloc_get_state)
4934 weak_alias (__malloc_set_state, malloc_set_state)
4935 #endif
4939 History:
4941 V2.6.4-pt3 Thu Feb 20 1997 Wolfram Gloger (wmglo@dent.med.uni-muenchen.de)
4942 * Added malloc_get/set_state() (mainly for use in GNU emacs),
4943 using interface from Marcus Daniels
4944 * All parameters are now adjustable via environment variables
4946 V2.6.4-pt2 Sat Dec 14 1996 Wolfram Gloger (wmglo@dent.med.uni-muenchen.de)
4947 * Added debugging hooks
4948 * Fixed possible deadlock in realloc() when out of memory
4949 * Don't pollute namespace in glibc: use __getpagesize, __mmap, etc.
4951 V2.6.4-pt Wed Dec 4 1996 Wolfram Gloger (wmglo@dent.med.uni-muenchen.de)
4952 * Very minor updates from the released 2.6.4 version.
4953 * Trimmed include file down to exported data structures.
4954 * Changes from H.J. Lu for glibc-2.0.
4956 V2.6.3i-pt Sep 16 1996 Wolfram Gloger (wmglo@dent.med.uni-muenchen.de)
4957 * Many changes for multiple threads
4958 * Introduced arenas and heaps
4960 V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee)
4961 * Added pvalloc, as recommended by H.J. Liu
4962 * Added 64bit pointer support mainly from Wolfram Gloger
4963 * Added anonymously donated WIN32 sbrk emulation
4964 * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
4965 * malloc_extend_top: fix mask error that caused wastage after
4966 foreign sbrks
4967 * Add linux mremap support code from HJ Liu
4969 V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee)
4970 * Integrated most documentation with the code.
4971 * Add support for mmap, with help from
4972 Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
4973 * Use last_remainder in more cases.
4974 * Pack bins using idea from colin@nyx10.cs.du.edu
4975 * Use ordered bins instead of best-fit threshold
4976 * Eliminate block-local decls to simplify tracing and debugging.
4977 * Support another case of realloc via move into top
4978 * Fix error occurring when initial sbrk_base not word-aligned.
4979 * Rely on page size for units instead of SBRK_UNIT to
4980 avoid surprises about sbrk alignment conventions.
4981 * Add mallinfo, mallopt. Thanks to Raymond Nijssen
4982 (raymond@es.ele.tue.nl) for the suggestion.
4983 * Add `pad' argument to malloc_trim and top_pad mallopt parameter.
4984 * More precautions for cases where other routines call sbrk,
4985 courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
4986 * Added macros etc., allowing use in linux libc from
4987 H.J. Lu (hjl@gnu.ai.mit.edu)
4988 * Inverted this history list
4990 V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee)
4991 * Re-tuned and fixed to behave more nicely with V2.6.0 changes.
4992 * Removed all preallocation code since under current scheme
4993 the work required to undo bad preallocations exceeds
4994 the work saved in good cases for most test programs.
4995 * No longer use return list or unconsolidated bins since
4996 no scheme using them consistently outperforms those that don't
4997 given above changes.
4998 * Use best fit for very large chunks to prevent some worst-cases.
4999 * Added some support for debugging
5001 V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee)
5002 * Removed footers when chunks are in use. Thanks to
5003 Paul Wilson (wilson@cs.texas.edu) for the suggestion.
5005 V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee)
5006 * Added malloc_trim, with help from Wolfram Gloger
5007 (wmglo@Dent.MED.Uni-Muenchen.DE).
5009 V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g)
5011 V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g)
5012 * realloc: try to expand in both directions
5013 * malloc: swap order of clean-bin strategy;
5014 * realloc: only conditionally expand backwards
5015 * Try not to scavenge used bins
5016 * Use bin counts as a guide to preallocation
5017 * Occasionally bin return list chunks in first scan
5018 * Add a few optimizations from colin@nyx10.cs.du.edu
5020 V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g)
5021 * faster bin computation & slightly different binning
5022 * merged all consolidations to one part of malloc proper
5023 (eliminating old malloc_find_space & malloc_clean_bin)
5024 * Scan 2 returns chunks (not just 1)
5025 * Propagate failure in realloc if malloc returns 0
5026 * Add stuff to allow compilation on non-ANSI compilers
5027 from kpv@research.att.com
5029 V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu)
5030 * removed potential for odd address access in prev_chunk
5031 * removed dependency on getpagesize.h
5032 * misc cosmetics and a bit more internal documentation
5033 * anticosmetics: mangled names in macros to evade debugger strangeness
5034 * tested on sparc, hp-700, dec-mips, rs6000
5035 with gcc & native cc (hp, dec only) allowing
5036 Detlefs & Zorn comparison study (in SIGPLAN Notices.)
5038 Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu)
5039 * Based loosely on libg++-1.2X malloc. (It retains some of the overall
5040 structure of old version, but most details differ.)