1 /* Malloc implementation for multiple threads without lock contention.
2 Copyright (C) 1996-2009, 2010, 2011, 2012 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Wolfram Gloger <wg@malloc.de>
5 and Doug Lea <dl@cs.oswego.edu>, 2001.
7 The GNU C Library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public License as
9 published by the Free Software Foundation; either version 2.1 of the
10 License, or (at your option) any later version.
12 The GNU C Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public
18 License along with the GNU C Library; see the file COPYING.LIB. If
19 not, see <http://www.gnu.org/licenses/>. */
22 This is a version (aka ptmalloc2) of malloc/free/realloc written by
23 Doug Lea and adapted to multiple threads/arenas by Wolfram Gloger.
25 There have been substantial changesmade after the integration into
26 glibc in all parts of the code. Do not look for much commonality
27 with the ptmalloc2 version.
29 * Version ptmalloc2-20011215
31 VERSION 2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
35 In order to compile this implementation, a Makefile is provided with
36 the ptmalloc2 distribution, which has pre-defined targets for some
37 popular systems (e.g. "make posix" for Posix threads). All that is
38 typically required with regard to compiler flags is the selection of
39 the thread package via defining one out of USE_PTHREADS, USE_THR or
40 USE_SPROC. Check the thread-m.h file for what effects this has.
41 Many/most systems will additionally require USE_TSD_DATA_HACK to be
42 defined, so this is the default for "make posix".
44 * Why use this malloc?
46 This is not the fastest, most space-conserving, most portable, or
47 most tunable malloc ever written. However it is among the fastest
48 while also being among the most space-conserving, portable and tunable.
49 Consistent balance across these factors results in a good general-purpose
50 allocator for malloc-intensive programs.
52 The main properties of the algorithms are:
53 * For large (>= 512 bytes) requests, it is a pure best-fit allocator,
54 with ties normally decided via FIFO (i.e. least recently used).
55 * For small (<= 64 bytes by default) requests, it is a caching
56 allocator, that maintains pools of quickly recycled chunks.
57 * In between, and for combinations of large and small requests, it does
58 the best it can trying to meet both goals at once.
59 * For very large requests (>= 128KB by default), it relies on system
60 memory mapping facilities, if supported.
62 For a longer but slightly out of date high-level description, see
63 http://gee.cs.oswego.edu/dl/html/malloc.html
65 You may already by default be using a C library containing a malloc
66 that is based on some version of this malloc (for example in
67 linux). You might still want to use the one in this file in order to
68 customize settings or to avoid overheads associated with library
71 * Contents, described in more detail in "description of public routines" below.
73 Standard (ANSI/SVID/...) functions:
75 calloc(size_t n_elements, size_t element_size);
77 realloc(void* p, size_t n);
78 memalign(size_t alignment, size_t n);
81 mallopt(int parameter_number, int parameter_value)
84 independent_calloc(size_t n_elements, size_t size, void* chunks[]);
85 independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
88 malloc_trim(size_t pad);
89 malloc_usable_size(void* p);
94 Supported pointer representation: 4 or 8 bytes
95 Supported size_t representation: 4 or 8 bytes
96 Note that size_t is allowed to be 4 bytes even if pointers are 8.
97 You can adjust this by defining INTERNAL_SIZE_T
99 Alignment: 2 * sizeof(size_t) (default)
100 (i.e., 8 byte alignment with 4byte size_t). This suffices for
101 nearly all current machines and C compilers. However, you can
102 define MALLOC_ALIGNMENT to be wider than this if necessary.
104 Minimum overhead per allocated chunk: 4 or 8 bytes
105 Each malloced chunk has a hidden word of overhead holding size
106 and status information.
108 Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead)
109 8-byte ptrs: 24/32 bytes (including, 4/8 overhead)
111 When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte
112 ptrs but 4 byte size) or 24 (for 8/8) additional bytes are
113 needed; 4 (8) for a trailing size field and 8 (16) bytes for
114 free list pointers. Thus, the minimum allocatable size is
117 Even a request for zero bytes (i.e., malloc(0)) returns a
118 pointer to something of the minimum allocatable size.
120 The maximum overhead wastage (i.e., number of extra bytes
121 allocated than were requested in malloc) is less than or equal
122 to the minimum size, except for requests >= mmap_threshold that
123 are serviced via mmap(), where the worst case wastage is 2 *
124 sizeof(size_t) bytes plus the remainder from a system page (the
125 minimal mmap unit); typically 4096 or 8192 bytes.
127 Maximum allocated size: 4-byte size_t: 2^32 minus about two pages
128 8-byte size_t: 2^64 minus about two pages
130 It is assumed that (possibly signed) size_t values suffice to
131 represent chunk sizes. `Possibly signed' is due to the fact
132 that `size_t' may be defined on a system as either a signed or
133 an unsigned type. The ISO C standard says that it must be
134 unsigned, but a few systems are known not to adhere to this.
135 Additionally, even when size_t is unsigned, sbrk (which is by
136 default used to obtain memory from system) accepts signed
137 arguments, and may not be able to handle size_t-wide arguments
138 with negative sign bit. Generally, values that would
139 appear as negative after accounting for overhead and alignment
140 are supported only via mmap(), which does not have this
143 Requests for sizes outside the allowed range will perform an optional
144 failure action and then return null. (Requests may also
145 also fail because a system is out of memory.)
147 Thread-safety: thread-safe
149 Compliance: I believe it is compliant with the 1997 Single Unix Specification
150 Also SVID/XPG, ANSI C, and probably others as well.
152 * Synopsis of compile-time options:
154 People have reported using previous versions of this malloc on all
155 versions of Unix, sometimes by tweaking some of the defines
156 below. It has been tested most extensively on Solaris and Linux.
157 People also report using it in stand-alone embedded systems.
159 The implementation is in straight, hand-tuned ANSI C. It is not
160 at all modular. (Sorry!) It uses a lot of macros. To be at all
161 usable, this code should be compiled using an optimizing compiler
162 (for example gcc -O3) that can simplify expressions and control
163 paths. (FAQ: some macros import variables as arguments rather than
164 declare locals because people reported that some debuggers
165 otherwise get confused.)
169 Compilation Environment options:
171 HAVE_MREMAP 0 unless linux defined
173 Changing default word sizes:
175 INTERNAL_SIZE_T size_t
176 MALLOC_ALIGNMENT MAX (2 * sizeof(INTERNAL_SIZE_T),
177 __alignof__ (long double))
179 Configuration and functionality options:
181 USE_PUBLIC_MALLOC_WRAPPERS NOT defined
182 USE_MALLOC_LOCK NOT defined
183 MALLOC_DEBUG NOT defined
184 REALLOC_ZERO_BYTES_FREES 1
187 Options for customizing MORECORE:
191 MORECORE_CONTIGUOUS 1
192 MORECORE_CANNOT_TRIM NOT defined
194 MMAP_AS_MORECORE_SIZE (1024 * 1024)
196 Tuning options that are also dynamically changeable via mallopt:
198 DEFAULT_MXFAST 64 (for 32bit), 128 (for 64bit)
199 DEFAULT_TRIM_THRESHOLD 128 * 1024
201 DEFAULT_MMAP_THRESHOLD 128 * 1024
202 DEFAULT_MMAP_MAX 65536
204 There are several other #defined constants and macros that you
205 probably don't want to touch unless you are extending or adapting malloc. */
208 void* is the pointer type that malloc should say it returns
215 #include <stddef.h> /* for size_t */
216 #include <stdlib.h> /* for getenv(), abort() */
218 #include <malloc-machine.h>
222 #include <bits/wordsize.h>
223 #include <sys/sysinfo.h>
225 #include <ldsodefs.h>
228 #include <stdio.h> /* needed for malloc_stats */
234 /* For va_arg, va_start, va_end. */
241 Because freed chunks may be overwritten with bookkeeping fields, this
242 malloc will often die when freed memory is overwritten by user
243 programs. This can be very effective (albeit in an annoying way)
244 in helping track down dangling pointers.
246 If you compile with -DMALLOC_DEBUG, a number of assertion checks are
247 enabled that will catch more memory errors. You probably won't be
248 able to make much sense of the actual assertion errors, but they
249 should help you locate incorrectly overwritten memory. The checking
250 is fairly extensive, and will slow down execution
251 noticeably. Calling malloc_stats or mallinfo with MALLOC_DEBUG set
252 will attempt to check every non-mmapped allocated and free chunk in
253 the course of computing the summmaries. (By nature, mmapped regions
254 cannot be checked very much automatically.)
256 Setting MALLOC_DEBUG may also be helpful if you are trying to modify
257 this code. The assertions in the check routines spell out in more
258 detail the assumptions and invariants underlying the algorithms.
260 Setting MALLOC_DEBUG does NOT provide an automated mechanism for
261 checking that all accesses to malloced memory stay within their
262 bounds. However, there are several add-ons and adaptations of this
263 or other mallocs available that do this.
267 # define assert(expr) ((void) 0)
269 # define assert(expr) \
272 : __malloc_assert (__STRING (expr), __FILE__, __LINE__, __func__))
274 extern const char *__progname;
277 __malloc_assert (const char *assertion, const char *file, unsigned int line,
278 const char *function)
280 (void) __fxprintf (NULL, "%s%s%s:%u: %s%sAssertion `%s' failed.\n",
281 __progname, __progname[0] ? ": " : "",
283 function ? function : "", function ? ": " : "",
292 INTERNAL_SIZE_T is the word-size used for internal bookkeeping
295 The default version is the same as size_t.
297 While not strictly necessary, it is best to define this as an
298 unsigned type, even if size_t is a signed type. This may avoid some
299 artificial size limitations on some systems.
301 On a 64-bit machine, you may be able to reduce malloc overhead by
302 defining INTERNAL_SIZE_T to be a 32 bit `unsigned int' at the
303 expense of not being able to handle more than 2^32 of malloced
304 space. If this limitation is acceptable, you are encouraged to set
305 this unless you are on a platform requiring 16byte alignments. In
306 this case the alignment requirements turn out to negate any
307 potential advantages of decreasing size_t word size.
309 Implementors: Beware of the possible combinations of:
310 - INTERNAL_SIZE_T might be signed or unsigned, might be 32 or 64 bits,
311 and might be the same width as int or as long
312 - size_t might have different width and signedness as INTERNAL_SIZE_T
313 - int and long might be 32 or 64 bits, and might be the same width
314 To deal with this, most comparisons and difference computations
315 among INTERNAL_SIZE_Ts should cast them to unsigned long, being
316 aware of the fact that casting an unsigned int to a wider long does
317 not sign-extend. (This also makes checking for negative numbers
318 awkward.) Some of these casts result in harmless compiler warnings
322 #ifndef INTERNAL_SIZE_T
323 #define INTERNAL_SIZE_T size_t
326 /* The corresponding word size */
327 #define SIZE_SZ (sizeof(INTERNAL_SIZE_T))
331 MALLOC_ALIGNMENT is the minimum alignment for malloc'ed chunks.
332 It must be a power of two at least 2 * SIZE_SZ, even on machines
333 for which smaller alignments would suffice. It may be defined as
334 larger than this though. Note however that code and data structures
335 are optimized for the case of 8-byte alignment.
339 #ifndef MALLOC_ALIGNMENT
340 # if !SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_16)
341 /* This is the correct definition when there is no past ABI to constrain it.
343 Among configurations with a past ABI constraint, it differs from
344 2*SIZE_SZ only on powerpc32. For the time being, changing this is
345 causing more compatibility problems due to malloc_get_state and
346 malloc_set_state than will returning blocks not adequately aligned for
347 long double objects under -mlong-double-128. */
349 # define MALLOC_ALIGNMENT (2 * SIZE_SZ < __alignof__ (long double) \
350 ? __alignof__ (long double) : 2 * SIZE_SZ)
352 # define MALLOC_ALIGNMENT (2 * SIZE_SZ)
356 /* The corresponding bit mask value */
357 #define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)
362 REALLOC_ZERO_BYTES_FREES should be set if a call to
363 realloc with zero bytes should be the same as a call to free.
364 This is required by the C standard. Otherwise, since this malloc
365 returns a unique pointer for malloc(0), so does realloc(p, 0).
368 #ifndef REALLOC_ZERO_BYTES_FREES
369 #define REALLOC_ZERO_BYTES_FREES 1
373 TRIM_FASTBINS controls whether free() of a very small chunk can
374 immediately lead to trimming. Setting to true (1) can reduce memory
375 footprint, but will almost always slow down programs that use a lot
378 Define this only if you are willing to give up some speed to more
379 aggressively reduce system-level memory footprint when releasing
380 memory in programs that use many small chunks. You can get
381 essentially the same effect by setting MXFAST to 0, but this can
382 lead to even greater slowdowns in programs using many small chunks.
383 TRIM_FASTBINS is an in-between compile-time option, that disables
384 only those chunks bordering topmost memory from being placed in
388 #ifndef TRIM_FASTBINS
389 #define TRIM_FASTBINS 0
393 /* Definition for getting more memory from the OS. */
394 #define MORECORE (*__morecore)
395 #define MORECORE_FAILURE 0
396 void * __default_morecore (ptrdiff_t);
397 void *(*__morecore)(ptrdiff_t) = __default_morecore;
403 /* Force a value to be in a register and stop the compiler referring
404 to the source (mostly memory location) again. */
405 #define force_reg(val) \
406 ({ __typeof (val) _v; asm ("" : "=r" (_v) : "0" (val)); _v; })
410 MORECORE-related declarations. By default, rely on sbrk
415 MORECORE is the name of the routine to call to obtain more memory
416 from the system. See below for general guidance on writing
417 alternative MORECORE functions, as well as a version for WIN32 and a
418 sample version for pre-OSX macos.
422 #define MORECORE sbrk
426 MORECORE_FAILURE is the value returned upon failure of MORECORE
427 as well as mmap. Since it cannot be an otherwise valid memory address,
428 and must reflect values of standard sys calls, you probably ought not
432 #ifndef MORECORE_FAILURE
433 #define MORECORE_FAILURE (-1)
437 If MORECORE_CONTIGUOUS is true, take advantage of fact that
438 consecutive calls to MORECORE with positive arguments always return
439 contiguous increasing addresses. This is true of unix sbrk. Even
440 if not defined, when regions happen to be contiguous, malloc will
441 permit allocations spanning regions obtained from different
442 calls. But defining this when applicable enables some stronger
443 consistency checks and space efficiencies.
446 #ifndef MORECORE_CONTIGUOUS
447 #define MORECORE_CONTIGUOUS 1
451 Define MORECORE_CANNOT_TRIM if your version of MORECORE
452 cannot release space back to the system when given negative
453 arguments. This is generally necessary only if you are using
454 a hand-crafted MORECORE function that cannot handle negative arguments.
457 /* #define MORECORE_CANNOT_TRIM */
459 /* MORECORE_CLEARS (default 1)
460 The degree to which the routine mapped to MORECORE zeroes out
461 memory: never (0), only for newly allocated space (1) or always
462 (2). The distinction between (1) and (2) is necessary because on
463 some systems, if the application first decrements and then
464 increments the break value, the contents of the reallocated space
468 #ifndef MORECORE_CLEARS
469 #define MORECORE_CLEARS 1
474 MMAP_AS_MORECORE_SIZE is the minimum mmap size argument to use if
475 sbrk fails, and mmap is used as a backup. The value must be a
476 multiple of page size. This backup strategy generally applies only
477 when systems have "holes" in address space, so sbrk cannot perform
478 contiguous expansion, but there is still space available on system.
479 On systems for which this is known to be useful (i.e. most linux
480 kernels), this occurs only when programs allocate huge amounts of
481 memory. Between this, and the fact that mmap regions tend to be
482 limited, the size should be large, to avoid too many mmap calls and
483 thus avoid running out of kernel resources. */
485 #ifndef MMAP_AS_MORECORE_SIZE
486 #define MMAP_AS_MORECORE_SIZE (1024 * 1024)
490 Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
491 large blocks. This is currently only possible on Linux with
492 kernel versions newer than 1.3.77.
497 #define HAVE_MREMAP 1
499 #define HAVE_MREMAP 0
502 #endif /* HAVE_MREMAP */
506 This version of malloc supports the standard SVID/XPG mallinfo
507 routine that returns a struct containing usage properties and
508 statistics. It should work on any SVID/XPG compliant system that has
509 a /usr/include/malloc.h defining struct mallinfo. (If you'd like to
510 install such a thing yourself, cut out the preliminary declarations
511 as described above and below and save them in a malloc.h file. But
512 there's no compelling reason to bother to do this.)
514 The main declaration needed is the mallinfo struct that is returned
515 (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
516 bunch of fields that are not even meaningful in this version of
517 malloc. These fields are are instead filled by mallinfo() with
518 other numbers that might be of interest.
522 /* ---------- description of public routines ------------ */
526 Returns a pointer to a newly allocated chunk of at least n bytes, or null
527 if no space is available. Additionally, on failure, errno is
528 set to ENOMEM on ANSI C systems.
530 If n is zero, malloc returns a minumum-sized chunk. (The minimum
531 size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit
532 systems.) On most systems, size_t is an unsigned type, so calls
533 with negative arguments are interpreted as requests for huge amounts
534 of space, which will often fail. The maximum supported value of n
535 differs across systems, but is in all cases less than the maximum
536 representable value of a size_t.
538 void* __libc_malloc(size_t);
539 libc_hidden_proto (__libc_malloc)
543 Releases the chunk of memory pointed to by p, that had been previously
544 allocated using malloc or a related routine such as realloc.
545 It has no effect if p is null. It can have arbitrary (i.e., bad!)
546 effects if p has already been freed.
548 Unless disabled (using mallopt), freeing very large spaces will
549 when possible, automatically trigger operations that give
550 back unused memory to the system, thus reducing program footprint.
552 void __libc_free(void*);
553 libc_hidden_proto (__libc_free)
556 calloc(size_t n_elements, size_t element_size);
557 Returns a pointer to n_elements * element_size bytes, with all locations
560 void* __libc_calloc(size_t, size_t);
563 realloc(void* p, size_t n)
564 Returns a pointer to a chunk of size n that contains the same data
565 as does chunk p up to the minimum of (n, p's size) bytes, or null
566 if no space is available.
568 The returned pointer may or may not be the same as p. The algorithm
569 prefers extending p when possible, otherwise it employs the
570 equivalent of a malloc-copy-free sequence.
572 If p is null, realloc is equivalent to malloc.
574 If space is not available, realloc returns null, errno is set (if on
575 ANSI) and p is NOT freed.
577 if n is for fewer bytes than already held by p, the newly unused
578 space is lopped off and freed if possible. Unless the #define
579 REALLOC_ZERO_BYTES_FREES is set, realloc with a size argument of
580 zero (re)allocates a minimum-sized chunk.
582 Large chunks that were internally obtained via mmap will always
583 be reallocated using malloc-copy-free sequences unless
584 the system supports MREMAP (currently only linux).
586 The old unix realloc convention of allowing the last-free'd chunk
587 to be used as an argument to realloc is not supported.
589 void* __libc_realloc(void*, size_t);
590 libc_hidden_proto (__libc_realloc)
593 memalign(size_t alignment, size_t n);
594 Returns a pointer to a newly allocated chunk of n bytes, aligned
595 in accord with the alignment argument.
597 The alignment argument should be a power of two. If the argument is
598 not a power of two, the nearest greater power is used.
599 8-byte alignment is guaranteed by normal malloc calls, so don't
600 bother calling memalign with an argument of 8 or less.
602 Overreliance on memalign is a sure way to fragment space.
604 void* __libc_memalign(size_t, size_t);
605 libc_hidden_proto (__libc_memalign)
609 Equivalent to memalign(pagesize, n), where pagesize is the page
610 size of the system. If the pagesize is unknown, 4096 is used.
612 void* __libc_valloc(size_t);
617 mallopt(int parameter_number, int parameter_value)
618 Sets tunable parameters The format is to provide a
619 (parameter-number, parameter-value) pair. mallopt then sets the
620 corresponding parameter to the argument value if it can (i.e., so
621 long as the value is meaningful), and returns 1 if successful else
622 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
623 normally defined in malloc.h. Only one of these (M_MXFAST) is used
624 in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,
625 so setting them has no effect. But this malloc also supports four
626 other options in mallopt. See below for details. Briefly, supported
627 parameters are as follows (listed defaults are for "typical"
630 Symbol param # default allowed param values
631 M_MXFAST 1 64 0-80 (0 disables fastbins)
632 M_TRIM_THRESHOLD -1 128*1024 any (-1U disables trimming)
634 M_MMAP_THRESHOLD -3 128*1024 any (or 0 if no MMAP support)
635 M_MMAP_MAX -4 65536 any (0 disables use of mmap)
637 int __libc_mallopt(int, int);
638 libc_hidden_proto (__libc_mallopt)
643 Returns (by copy) a struct containing various summary statistics:
645 arena: current total non-mmapped bytes allocated from system
646 ordblks: the number of free chunks
647 smblks: the number of fastbin blocks (i.e., small chunks that
648 have been freed but not use resused or consolidated)
649 hblks: current number of mmapped regions
650 hblkhd: total bytes held in mmapped regions
651 usmblks: the maximum total allocated space. This will be greater
652 than current total if trimming has occurred.
653 fsmblks: total bytes held in fastbin blocks
654 uordblks: current total allocated space (normal or mmapped)
655 fordblks: total free space
656 keepcost: the maximum number of bytes that could ideally be released
657 back to system via malloc_trim. ("ideally" means that
658 it ignores page restrictions etc.)
660 Because these fields are ints, but internal bookkeeping may
661 be kept as longs, the reported values may wrap around zero and
664 struct mallinfo __libc_mallinfo(void);
669 Equivalent to valloc(minimum-page-that-holds(n)), that is,
670 round up n to nearest pagesize.
672 void* __libc_pvalloc(size_t);
675 malloc_trim(size_t pad);
677 If possible, gives memory back to the system (via negative
678 arguments to sbrk) if there is unused memory at the `high' end of
679 the malloc pool. You can call this after freeing large blocks of
680 memory to potentially reduce the system-level memory requirements
681 of a program. However, it cannot guarantee to reduce memory. Under
682 some allocation patterns, some large free blocks of memory will be
683 locked between two used chunks, so they cannot be given back to
686 The `pad' argument to malloc_trim represents the amount of free
687 trailing space to leave untrimmed. If this argument is zero,
688 only the minimum amount of memory to maintain internal data
689 structures will be left (one page or less). Non-zero arguments
690 can be supplied to maintain enough trailing space to service
691 future expected allocations without having to re-obtain memory
694 Malloc_trim returns 1 if it actually released any memory, else 0.
695 On systems that do not support "negative sbrks", it will always
698 int __malloc_trim(size_t);
701 malloc_usable_size(void* p);
703 Returns the number of bytes you can actually use in
704 an allocated chunk, which may be more than you requested (although
705 often not) due to alignment and minimum size constraints.
706 You can use this many bytes without worrying about
707 overwriting other allocated objects. This is not a particularly great
708 programming practice. malloc_usable_size can be more useful in
709 debugging and assertions, for example:
712 assert(malloc_usable_size(p) >= 256);
715 size_t __malloc_usable_size(void*);
719 Prints on stderr the amount of space obtained from the system (both
720 via sbrk and mmap), the maximum amount (which may be more than
721 current if malloc_trim and/or munmap got called), and the current
722 number of bytes allocated via malloc (or realloc, etc) but not yet
723 freed. Note that this is the number of bytes allocated, not the
724 number requested. It will be larger than the number requested
725 because of alignment and bookkeeping overhead. Because it includes
726 alignment wastage as being in use, this figure may be greater than
727 zero even when no user-level chunks are allocated.
729 The reported current and maximum system memory can be inaccurate if
730 a program makes other calls to system memory allocation functions
731 (normally sbrk) outside of malloc.
733 malloc_stats prints only the most commonly interesting statistics.
734 More information can be obtained by calling mallinfo.
737 void __malloc_stats(void);
740 malloc_get_state(void);
742 Returns the state of all malloc variables in an opaque data
745 void* __malloc_get_state(void);
748 malloc_set_state(void* state);
750 Restore the state of all malloc variables from data obtained with
753 int __malloc_set_state(void*);
756 posix_memalign(void **memptr, size_t alignment, size_t size);
758 POSIX wrapper like memalign(), checking for validity of size.
760 int __posix_memalign(void **, size_t, size_t);
762 /* mallopt tuning options */
765 M_MXFAST is the maximum request size used for "fastbins", special bins
766 that hold returned chunks without consolidating their spaces. This
767 enables future requests for chunks of the same size to be handled
768 very quickly, but can increase fragmentation, and thus increase the
769 overall memory footprint of a program.
771 This malloc manages fastbins very conservatively yet still
772 efficiently, so fragmentation is rarely a problem for values less
773 than or equal to the default. The maximum supported value of MXFAST
774 is 80. You wouldn't want it any higher than this anyway. Fastbins
775 are designed especially for use with many small structs, objects or
776 strings -- the default handles structs/objects/arrays with sizes up
777 to 8 4byte fields, or small strings representing words, tokens,
778 etc. Using fastbins for larger objects normally worsens
779 fragmentation without improving speed.
781 M_MXFAST is set in REQUEST size units. It is internally used in
782 chunksize units, which adds padding and alignment. You can reduce
783 M_MXFAST to 0 to disable all use of fastbins. This causes the malloc
784 algorithm to be a closer approximation of fifo-best-fit in all cases,
785 not just for larger requests, but will generally cause it to be
790 /* M_MXFAST is a standard SVID/XPG tuning option, usually listed in malloc.h */
795 #ifndef DEFAULT_MXFAST
796 #define DEFAULT_MXFAST (64 * SIZE_SZ / 4)
801 M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
802 to keep before releasing via malloc_trim in free().
804 Automatic trimming is mainly useful in long-lived programs.
805 Because trimming via sbrk can be slow on some systems, and can
806 sometimes be wasteful (in cases where programs immediately
807 afterward allocate more large chunks) the value should be high
808 enough so that your overall system performance would improve by
809 releasing this much memory.
811 The trim threshold and the mmap control parameters (see below)
812 can be traded off with one another. Trimming and mmapping are
813 two different ways of releasing unused memory back to the
814 system. Between these two, it is often possible to keep
815 system-level demands of a long-lived program down to a bare
816 minimum. For example, in one test suite of sessions measuring
817 the XF86 X server on Linux, using a trim threshold of 128K and a
818 mmap threshold of 192K led to near-minimal long term resource
821 If you are using this malloc in a long-lived program, it should
822 pay to experiment with these values. As a rough guide, you
823 might set to a value close to the average size of a process
824 (program) running on your system. Releasing this much memory
825 would allow such a process to run in memory. Generally, it's
826 worth it to tune for trimming rather tham memory mapping when a
827 program undergoes phases where several large chunks are
828 allocated and released in ways that can reuse each other's
829 storage, perhaps mixed with phases where there are no such
830 chunks at all. And in well-behaved long-lived programs,
831 controlling release of large blocks via trimming versus mapping
834 However, in most programs, these parameters serve mainly as
835 protection against the system-level effects of carrying around
836 massive amounts of unneeded memory. Since frequent calls to
837 sbrk, mmap, and munmap otherwise degrade performance, the default
838 parameters are set to relatively high values that serve only as
841 The trim value It must be greater than page size to have any useful
842 effect. To disable trimming completely, you can set to
845 Trim settings interact with fastbin (MXFAST) settings: Unless
846 TRIM_FASTBINS is defined, automatic trimming never takes place upon
847 freeing a chunk with size less than or equal to MXFAST. Trimming is
848 instead delayed until subsequent freeing of larger chunks. However,
849 you can still force an attempted trim by calling malloc_trim.
851 Also, trimming is not generally possible in cases where
852 the main arena is obtained via mmap.
854 Note that the trick some people use of mallocing a huge space and
855 then freeing it at program startup, in an attempt to reserve system
856 memory, doesn't have the intended effect under automatic trimming,
857 since that memory will immediately be returned to the system.
860 #define M_TRIM_THRESHOLD -1
862 #ifndef DEFAULT_TRIM_THRESHOLD
863 #define DEFAULT_TRIM_THRESHOLD (128 * 1024)
867 M_TOP_PAD is the amount of extra `padding' space to allocate or
868 retain whenever sbrk is called. It is used in two ways internally:
870 * When sbrk is called to extend the top of the arena to satisfy
871 a new malloc request, this much padding is added to the sbrk
874 * When malloc_trim is called automatically from free(),
875 it is used as the `pad' argument.
877 In both cases, the actual amount of padding is rounded
878 so that the end of the arena is always a system page boundary.
880 The main reason for using padding is to avoid calling sbrk so
881 often. Having even a small pad greatly reduces the likelihood
882 that nearly every malloc request during program start-up (or
883 after trimming) will invoke sbrk, which needlessly wastes
886 Automatic rounding-up to page-size units is normally sufficient
887 to avoid measurable overhead, so the default is 0. However, in
888 systems where sbrk is relatively slow, it can pay to increase
889 this value, at the expense of carrying around more memory than
895 #ifndef DEFAULT_TOP_PAD
896 #define DEFAULT_TOP_PAD (0)
900 MMAP_THRESHOLD_MAX and _MIN are the bounds on the dynamically
901 adjusted MMAP_THRESHOLD.
904 #ifndef DEFAULT_MMAP_THRESHOLD_MIN
905 #define DEFAULT_MMAP_THRESHOLD_MIN (128 * 1024)
908 #ifndef DEFAULT_MMAP_THRESHOLD_MAX
909 /* For 32-bit platforms we cannot increase the maximum mmap
910 threshold much because it is also the minimum value for the
911 maximum heap size and its alignment. Going above 512k (i.e., 1M
912 for new heaps) wastes too much address space. */
913 # if __WORDSIZE == 32
914 # define DEFAULT_MMAP_THRESHOLD_MAX (512 * 1024)
916 # define DEFAULT_MMAP_THRESHOLD_MAX (4 * 1024 * 1024 * sizeof(long))
921 M_MMAP_THRESHOLD is the request size threshold for using mmap()
922 to service a request. Requests of at least this size that cannot
923 be allocated using already-existing space will be serviced via mmap.
924 (If enough normal freed space already exists it is used instead.)
926 Using mmap segregates relatively large chunks of memory so that
927 they can be individually obtained and released from the host
928 system. A request serviced through mmap is never reused by any
929 other request (at least not directly; the system may just so
930 happen to remap successive requests to the same locations).
932 Segregating space in this way has the benefits that:
934 1. Mmapped space can ALWAYS be individually released back
935 to the system, which helps keep the system level memory
936 demands of a long-lived program low.
937 2. Mapped memory can never become `locked' between
938 other chunks, as can happen with normally allocated chunks, which
939 means that even trimming via malloc_trim would not release them.
940 3. On some systems with "holes" in address spaces, mmap can obtain
941 memory that sbrk cannot.
943 However, it has the disadvantages that:
945 1. The space cannot be reclaimed, consolidated, and then
946 used to service later requests, as happens with normal chunks.
947 2. It can lead to more wastage because of mmap page alignment
949 3. It causes malloc performance to be more dependent on host
950 system memory management support routines which may vary in
951 implementation quality and may impose arbitrary
952 limitations. Generally, servicing a request via normal
953 malloc steps is faster than going through a system's mmap.
955 The advantages of mmap nearly always outweigh disadvantages for
956 "large" chunks, but the value of "large" varies across systems. The
957 default is an empirically derived value that works well in most
962 The above was written in 2001. Since then the world has changed a lot.
963 Memory got bigger. Applications got bigger. The virtual address space
964 layout in 32 bit linux changed.
966 In the new situation, brk() and mmap space is shared and there are no
967 artificial limits on brk size imposed by the kernel. What is more,
968 applications have started using transient allocations larger than the
969 128Kb as was imagined in 2001.
971 The price for mmap is also high now; each time glibc mmaps from the
972 kernel, the kernel is forced to zero out the memory it gives to the
973 application. Zeroing memory is expensive and eats a lot of cache and
974 memory bandwidth. This has nothing to do with the efficiency of the
975 virtual memory system, by doing mmap the kernel just has no choice but
978 In 2001, the kernel had a maximum size for brk() which was about 800
979 megabytes on 32 bit x86, at that point brk() would hit the first
980 mmaped shared libaries and couldn't expand anymore. With current 2.6
981 kernels, the VA space layout is different and brk() and mmap
982 both can span the entire heap at will.
984 Rather than using a static threshold for the brk/mmap tradeoff,
985 we are now using a simple dynamic one. The goal is still to avoid
986 fragmentation. The old goals we kept are
987 1) try to get the long lived large allocations to use mmap()
988 2) really large allocations should always use mmap()
989 and we're adding now:
990 3) transient allocations should use brk() to avoid forcing the kernel
991 having to zero memory over and over again
993 The implementation works with a sliding threshold, which is by default
994 limited to go between 128Kb and 32Mb (64Mb for 64 bitmachines) and starts
995 out at 128Kb as per the 2001 default.
997 This allows us to satisfy requirement 1) under the assumption that long
998 lived allocations are made early in the process' lifespan, before it has
999 started doing dynamic allocations of the same size (which will
1000 increase the threshold).
1002 The upperbound on the threshold satisfies requirement 2)
1004 The threshold goes up in value when the application frees memory that was
1005 allocated with the mmap allocator. The idea is that once the application
1006 starts freeing memory of a certain size, it's highly probable that this is
1007 a size the application uses for transient allocations. This estimator
1008 is there to satisfy the new third requirement.
1012 #define M_MMAP_THRESHOLD -3
1014 #ifndef DEFAULT_MMAP_THRESHOLD
1015 #define DEFAULT_MMAP_THRESHOLD DEFAULT_MMAP_THRESHOLD_MIN
1019 M_MMAP_MAX is the maximum number of requests to simultaneously
1020 service using mmap. This parameter exists because
1021 some systems have a limited number of internal tables for
1022 use by mmap, and using more than a few of them may degrade
1025 The default is set to a value that serves only as a safeguard.
1026 Setting to 0 disables use of mmap for servicing large requests.
1029 #define M_MMAP_MAX -4
1031 #ifndef DEFAULT_MMAP_MAX
1032 #define DEFAULT_MMAP_MAX (65536)
1037 #ifndef RETURN_ADDRESS
1038 #define RETURN_ADDRESS(X_) (NULL)
1041 /* On some platforms we can compile internal, not exported functions better.
1042 Let the environment provide a macro and define it to be empty if it
1043 is not available. */
1044 #ifndef internal_function
1045 # define internal_function
1048 /* Forward declarations. */
1049 struct malloc_chunk;
1050 typedef struct malloc_chunk* mchunkptr;
1052 /* Internal routines. */
1054 static void* _int_malloc(mstate, size_t);
1055 static void _int_free(mstate, mchunkptr, int);
1056 static void* _int_realloc(mstate, mchunkptr, INTERNAL_SIZE_T,
1058 static void* _int_memalign(mstate, size_t, size_t);
1059 static void* _int_valloc(mstate, size_t);
1060 static void* _int_pvalloc(mstate, size_t);
1061 static void malloc_printerr(int action, const char *str, void *ptr);
1063 static void* internal_function mem2mem_check(void *p, size_t sz);
1064 static int internal_function top_check(void);
1065 static void internal_function munmap_chunk(mchunkptr p);
1067 static mchunkptr internal_function mremap_chunk(mchunkptr p, size_t new_size);
1070 static void* malloc_check(size_t sz, const void *caller);
1071 static void free_check(void* mem, const void *caller);
1072 static void* realloc_check(void* oldmem, size_t bytes,
1073 const void *caller);
1074 static void* memalign_check(size_t alignment, size_t bytes,
1075 const void *caller);
1076 /* These routines are never needed in this configuration. */
1077 static void* malloc_atfork(size_t sz, const void *caller);
1078 static void free_atfork(void* mem, const void *caller);
1081 /* ------------- Optional versions of memcopy ---------------- */
1085 Note: memcpy is ONLY invoked with non-overlapping regions,
1086 so the (usually slower) memmove is not needed.
1089 #define MALLOC_COPY(dest, src, nbytes) memcpy(dest, src, nbytes)
1090 #define MALLOC_ZERO(dest, nbytes) memset(dest, 0, nbytes)
1093 /* ------------------ MMAP support ------------------ */
1097 #include <sys/mman.h>
1099 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
1100 # define MAP_ANONYMOUS MAP_ANON
1103 #ifndef MAP_NORESERVE
1104 # define MAP_NORESERVE 0
1107 #define MMAP(addr, size, prot, flags) \
1108 __mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS|MAP_PRIVATE, -1, 0)
1112 ----------------------- Chunk representations -----------------------
1117 This struct declaration is misleading (but accurate and necessary).
1118 It declares a "view" into memory allowing access to necessary
1119 fields at known offsets from a given base. See explanation below.
1122 struct malloc_chunk {
1124 INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
1125 INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */
1127 struct malloc_chunk* fd; /* double links -- used only if free. */
1128 struct malloc_chunk* bk;
1130 /* Only used for large blocks: pointer to next larger size. */
1131 struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */
1132 struct malloc_chunk* bk_nextsize;
1137 malloc_chunk details:
1139 (The following includes lightly edited explanations by Colin Plumb.)
1141 Chunks of memory are maintained using a `boundary tag' method as
1142 described in e.g., Knuth or Standish. (See the paper by Paul
1143 Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
1144 survey of such techniques.) Sizes of free chunks are stored both
1145 in the front of each chunk and at the end. This makes
1146 consolidating fragmented chunks into bigger chunks very fast. The
1147 size fields also hold bits representing whether chunks are free or
1150 An allocated chunk looks like this:
1153 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1154 | Size of previous chunk, if allocated | |
1155 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1156 | Size of chunk, in bytes |M|P|
1157 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1158 | User data starts here... .
1160 . (malloc_usable_size() bytes) .
1162 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1164 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1167 Where "chunk" is the front of the chunk for the purpose of most of
1168 the malloc code, but "mem" is the pointer that is returned to the
1169 user. "Nextchunk" is the beginning of the next contiguous chunk.
1171 Chunks always begin on even word boundries, so the mem portion
1172 (which is returned to the user) is also on an even word boundary, and
1173 thus at least double-word aligned.
1175 Free chunks are stored in circular doubly-linked lists, and look like this:
1177 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1178 | Size of previous chunk |
1179 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1180 `head:' | Size of chunk, in bytes |P|
1181 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1182 | Forward pointer to next chunk in list |
1183 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1184 | Back pointer to previous chunk in list |
1185 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1186 | Unused space (may be 0 bytes long) .
1189 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1190 `foot:' | Size of chunk, in bytes |
1191 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1193 The P (PREV_INUSE) bit, stored in the unused low-order bit of the
1194 chunk size (which is always a multiple of two words), is an in-use
1195 bit for the *previous* chunk. If that bit is *clear*, then the
1196 word before the current chunk size contains the previous chunk
1197 size, and can be used to find the front of the previous chunk.
1198 The very first chunk allocated always has this bit set,
1199 preventing access to non-existent (or non-owned) memory. If
1200 prev_inuse is set for any given chunk, then you CANNOT determine
1201 the size of the previous chunk, and might even get a memory
1202 addressing fault when trying to do so.
1204 Note that the `foot' of the current chunk is actually represented
1205 as the prev_size of the NEXT chunk. This makes it easier to
1206 deal with alignments etc but can be very confusing when trying
1207 to extend or adapt this code.
1209 The two exceptions to all this are
1211 1. The special chunk `top' doesn't bother using the
1212 trailing size field since there is no next contiguous chunk
1213 that would have to index off it. After initialization, `top'
1214 is forced to always exist. If it would become less than
1215 MINSIZE bytes long, it is replenished.
1217 2. Chunks allocated via mmap, which have the second-lowest-order
1218 bit M (IS_MMAPPED) set in their size fields. Because they are
1219 allocated one-by-one, each must contain its own trailing size field.
1224 ---------- Size and alignment checks and conversions ----------
1227 /* conversion from malloc headers to user pointers, and back */
1229 #define chunk2mem(p) ((void*)((char*)(p) + 2*SIZE_SZ))
1230 #define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
1232 /* The smallest possible chunk */
1233 #define MIN_CHUNK_SIZE (offsetof(struct malloc_chunk, fd_nextsize))
1235 /* The smallest size we can malloc is an aligned minimal chunk */
1238 (unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))
1240 /* Check if m has acceptable alignment */
1242 #define aligned_OK(m) (((unsigned long)(m) & MALLOC_ALIGN_MASK) == 0)
1244 #define misaligned_chunk(p) \
1245 ((uintptr_t)(MALLOC_ALIGNMENT == 2 * SIZE_SZ ? (p) : chunk2mem (p)) \
1246 & MALLOC_ALIGN_MASK)
1250 Check if a request is so large that it would wrap around zero when
1251 padded and aligned. To simplify some other code, the bound is made
1252 low enough so that adding MINSIZE will also not wrap around zero.
1255 #define REQUEST_OUT_OF_RANGE(req) \
1256 ((unsigned long)(req) >= \
1257 (unsigned long)(INTERNAL_SIZE_T)(-2 * MINSIZE))
1259 /* pad request bytes into a usable size -- internal version */
1261 #define request2size(req) \
1262 (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \
1264 ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
1266 /* Same, except also perform argument check */
1268 #define checked_request2size(req, sz) \
1269 if (REQUEST_OUT_OF_RANGE(req)) { \
1270 __set_errno (ENOMEM); \
1273 (sz) = request2size(req);
1276 --------------- Physical chunk operations ---------------
1280 /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
1281 #define PREV_INUSE 0x1
1283 /* extract inuse bit of previous chunk */
1284 #define prev_inuse(p) ((p)->size & PREV_INUSE)
1287 /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
1288 #define IS_MMAPPED 0x2
1290 /* check for mmap()'ed chunk */
1291 #define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
1294 /* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained
1295 from a non-main arena. This is only set immediately before handing
1296 the chunk to the user, if necessary. */
1297 #define NON_MAIN_ARENA 0x4
1299 /* check for chunk from non-main arena */
1300 #define chunk_non_main_arena(p) ((p)->size & NON_MAIN_ARENA)
1304 Bits to mask off when extracting size
1306 Note: IS_MMAPPED is intentionally not masked off from size field in
1307 macros for which mmapped chunks should never be seen. This should
1308 cause helpful core dumps to occur if it is tried by accident by
1309 people extending or adapting this malloc.
1311 #define SIZE_BITS (PREV_INUSE|IS_MMAPPED|NON_MAIN_ARENA)
1313 /* Get size, ignoring use bits */
1314 #define chunksize(p) ((p)->size & ~(SIZE_BITS))
1317 /* Ptr to next physical malloc_chunk. */
1318 #define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->size & ~SIZE_BITS) ))
1320 /* Ptr to previous physical malloc_chunk */
1321 #define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_size) ))
1323 /* Treat space at ptr + offset as a chunk */
1324 #define chunk_at_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
1326 /* extract p's inuse bit */
1328 ((((mchunkptr)(((char*)(p))+((p)->size & ~SIZE_BITS)))->size) & PREV_INUSE)
1330 /* set/clear chunk as being inuse without otherwise disturbing */
1331 #define set_inuse(p)\
1332 ((mchunkptr)(((char*)(p)) + ((p)->size & ~SIZE_BITS)))->size |= PREV_INUSE
1334 #define clear_inuse(p)\
1335 ((mchunkptr)(((char*)(p)) + ((p)->size & ~SIZE_BITS)))->size &= ~(PREV_INUSE)
1338 /* check/set/clear inuse bits in known places */
1339 #define inuse_bit_at_offset(p, s)\
1340 (((mchunkptr)(((char*)(p)) + (s)))->size & PREV_INUSE)
1342 #define set_inuse_bit_at_offset(p, s)\
1343 (((mchunkptr)(((char*)(p)) + (s)))->size |= PREV_INUSE)
1345 #define clear_inuse_bit_at_offset(p, s)\
1346 (((mchunkptr)(((char*)(p)) + (s)))->size &= ~(PREV_INUSE))
1349 /* Set size at head, without disturbing its use bit */
1350 #define set_head_size(p, s) ((p)->size = (((p)->size & SIZE_BITS) | (s)))
1352 /* Set size/use field */
1353 #define set_head(p, s) ((p)->size = (s))
1355 /* Set size at footer (only when chunk is not in use) */
1356 #define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_size = (s))
1360 -------------------- Internal data structures --------------------
1362 All internal state is held in an instance of malloc_state defined
1363 below. There are no other static variables, except in two optional
1365 * If USE_MALLOC_LOCK is defined, the mALLOC_MUTEx declared above.
1366 * If mmap doesn't support MAP_ANONYMOUS, a dummy file descriptor
1369 Beware of lots of tricks that minimize the total bookkeeping space
1370 requirements. The result is a little over 1K bytes (for 4byte
1371 pointers and size_t.)
1377 An array of bin headers for free chunks. Each bin is doubly
1378 linked. The bins are approximately proportionally (log) spaced.
1379 There are a lot of these bins (128). This may look excessive, but
1380 works very well in practice. Most bins hold sizes that are
1381 unusual as malloc request sizes, but are more usual for fragments
1382 and consolidated sets of chunks, which is what these bins hold, so
1383 they can be found quickly. All procedures maintain the invariant
1384 that no consolidated chunk physically borders another one, so each
1385 chunk in a list is known to be preceeded and followed by either
1386 inuse chunks or the ends of memory.
1388 Chunks in bins are kept in size order, with ties going to the
1389 approximately least recently used chunk. Ordering isn't needed
1390 for the small bins, which all contain the same-sized chunks, but
1391 facilitates best-fit allocation for larger chunks. These lists
1392 are just sequential. Keeping them in order almost never requires
1393 enough traversal to warrant using fancier ordered data
1396 Chunks of the same size are linked with the most
1397 recently freed at the front, and allocations are taken from the
1398 back. This results in LRU (FIFO) allocation order, which tends
1399 to give each chunk an equal opportunity to be consolidated with
1400 adjacent freed chunks, resulting in larger free chunks and less
1403 To simplify use in double-linked lists, each bin header acts
1404 as a malloc_chunk. This avoids special-casing for headers.
1405 But to conserve space and improve locality, we allocate
1406 only the fd/bk pointers of bins, and then use repositioning tricks
1407 to treat these as the fields of a malloc_chunk*.
1410 typedef struct malloc_chunk* mbinptr;
1412 /* addressing -- note that bin_at(0) does not exist */
1413 #define bin_at(m, i) \
1414 (mbinptr) (((char *) &((m)->bins[((i) - 1) * 2])) \
1415 - offsetof (struct malloc_chunk, fd))
1417 /* analog of ++bin */
1418 #define next_bin(b) ((mbinptr)((char*)(b) + (sizeof(mchunkptr)<<1)))
1420 /* Reminders about list directionality within bins */
1421 #define first(b) ((b)->fd)
1422 #define last(b) ((b)->bk)
1424 /* Take a chunk off a bin list */
1425 #define unlink(P, BK, FD) { \
1428 if (__builtin_expect (FD->bk != P || BK->fd != P, 0)) \
1429 malloc_printerr (check_action, "corrupted double-linked list", P); \
1433 if (!in_smallbin_range (P->size) \
1434 && __builtin_expect (P->fd_nextsize != NULL, 0)) { \
1435 assert (P->fd_nextsize->bk_nextsize == P); \
1436 assert (P->bk_nextsize->fd_nextsize == P); \
1437 if (FD->fd_nextsize == NULL) { \
1438 if (P->fd_nextsize == P) \
1439 FD->fd_nextsize = FD->bk_nextsize = FD; \
1441 FD->fd_nextsize = P->fd_nextsize; \
1442 FD->bk_nextsize = P->bk_nextsize; \
1443 P->fd_nextsize->bk_nextsize = FD; \
1444 P->bk_nextsize->fd_nextsize = FD; \
1447 P->fd_nextsize->bk_nextsize = P->bk_nextsize; \
1448 P->bk_nextsize->fd_nextsize = P->fd_nextsize; \
1457 Bins for sizes < 512 bytes contain chunks of all the same size, spaced
1458 8 bytes apart. Larger bins are approximately logarithmically spaced:
1464 4 bins of size 32768
1465 2 bins of size 262144
1466 1 bin of size what's left
1468 There is actually a little bit of slop in the numbers in bin_index
1469 for the sake of speed. This makes no difference elsewhere.
1471 The bins top out around 1MB because we expect to service large
1476 #define NSMALLBINS 64
1477 #define SMALLBIN_WIDTH MALLOC_ALIGNMENT
1478 #define MIN_LARGE_SIZE (NSMALLBINS * SMALLBIN_WIDTH)
1480 #define in_smallbin_range(sz) \
1481 ((unsigned long)(sz) < (unsigned long)MIN_LARGE_SIZE)
1483 #define smallbin_index(sz) \
1484 (SMALLBIN_WIDTH == 16 ? (((unsigned)(sz)) >> 4) : (((unsigned)(sz)) >> 3))
1486 #define largebin_index_32(sz) \
1487 (((((unsigned long)(sz)) >> 6) <= 38)? 56 + (((unsigned long)(sz)) >> 6): \
1488 ((((unsigned long)(sz)) >> 9) <= 20)? 91 + (((unsigned long)(sz)) >> 9): \
1489 ((((unsigned long)(sz)) >> 12) <= 10)? 110 + (((unsigned long)(sz)) >> 12): \
1490 ((((unsigned long)(sz)) >> 15) <= 4)? 119 + (((unsigned long)(sz)) >> 15): \
1491 ((((unsigned long)(sz)) >> 18) <= 2)? 124 + (((unsigned long)(sz)) >> 18): \
1494 // XXX It remains to be seen whether it is good to keep the widths of
1495 // XXX the buckets the same or whether it should be scaled by a factor
1496 // XXX of two as well.
1497 #define largebin_index_64(sz) \
1498 (((((unsigned long)(sz)) >> 6) <= 48)? 48 + (((unsigned long)(sz)) >> 6): \
1499 ((((unsigned long)(sz)) >> 9) <= 20)? 91 + (((unsigned long)(sz)) >> 9): \
1500 ((((unsigned long)(sz)) >> 12) <= 10)? 110 + (((unsigned long)(sz)) >> 12): \
1501 ((((unsigned long)(sz)) >> 15) <= 4)? 119 + (((unsigned long)(sz)) >> 15): \
1502 ((((unsigned long)(sz)) >> 18) <= 2)? 124 + (((unsigned long)(sz)) >> 18): \
1505 #define largebin_index(sz) \
1506 (SIZE_SZ == 8 ? largebin_index_64 (sz) : largebin_index_32 (sz))
1508 #define bin_index(sz) \
1509 ((in_smallbin_range(sz)) ? smallbin_index(sz) : largebin_index(sz))
1515 All remainders from chunk splits, as well as all returned chunks,
1516 are first placed in the "unsorted" bin. They are then placed
1517 in regular bins after malloc gives them ONE chance to be used before
1518 binning. So, basically, the unsorted_chunks list acts as a queue,
1519 with chunks being placed on it in free (and malloc_consolidate),
1520 and taken off (to be either used or placed in bins) in malloc.
1522 The NON_MAIN_ARENA flag is never set for unsorted chunks, so it
1523 does not have to be taken into account in size comparisons.
1526 /* The otherwise unindexable 1-bin is used to hold unsorted chunks. */
1527 #define unsorted_chunks(M) (bin_at(M, 1))
1532 The top-most available chunk (i.e., the one bordering the end of
1533 available memory) is treated specially. It is never included in
1534 any bin, is used only if no other chunk is available, and is
1535 released back to the system if it is very large (see
1536 M_TRIM_THRESHOLD). Because top initially
1537 points to its own bin with initial zero size, thus forcing
1538 extension on the first malloc request, we avoid having any special
1539 code in malloc to check whether it even exists yet. But we still
1540 need to do so when getting memory from system, so we make
1541 initial_top treat the bin as a legal but unusable chunk during the
1542 interval between initialization and the first call to
1543 sysmalloc. (This is somewhat delicate, since it relies on
1544 the 2 preceding words to be zero during this interval as well.)
1547 /* Conveniently, the unsorted bin can be used as dummy top on first call */
1548 #define initial_top(M) (unsorted_chunks(M))
1553 To help compensate for the large number of bins, a one-level index
1554 structure is used for bin-by-bin searching. `binmap' is a
1555 bitvector recording whether bins are definitely empty so they can
1556 be skipped over during during traversals. The bits are NOT always
1557 cleared as soon as bins are empty, but instead only
1558 when they are noticed to be empty during traversal in malloc.
1561 /* Conservatively use 32 bits per map word, even if on 64bit system */
1562 #define BINMAPSHIFT 5
1563 #define BITSPERMAP (1U << BINMAPSHIFT)
1564 #define BINMAPSIZE (NBINS / BITSPERMAP)
1566 #define idx2block(i) ((i) >> BINMAPSHIFT)
1567 #define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT)-1))))
1569 #define mark_bin(m,i) ((m)->binmap[idx2block(i)] |= idx2bit(i))
1570 #define unmark_bin(m,i) ((m)->binmap[idx2block(i)] &= ~(idx2bit(i)))
1571 #define get_binmap(m,i) ((m)->binmap[idx2block(i)] & idx2bit(i))
1576 An array of lists holding recently freed small chunks. Fastbins
1577 are not doubly linked. It is faster to single-link them, and
1578 since chunks are never removed from the middles of these lists,
1579 double linking is not necessary. Also, unlike regular bins, they
1580 are not even processed in FIFO order (they use faster LIFO) since
1581 ordering doesn't much matter in the transient contexts in which
1582 fastbins are normally used.
1584 Chunks in fastbins keep their inuse bit set, so they cannot
1585 be consolidated with other free chunks. malloc_consolidate
1586 releases all chunks in fastbins and consolidates them with
1590 typedef struct malloc_chunk* mfastbinptr;
1591 #define fastbin(ar_ptr, idx) ((ar_ptr)->fastbinsY[idx])
1593 /* offset 2 to use otherwise unindexable first 2 bins */
1594 #define fastbin_index(sz) \
1595 ((((unsigned int)(sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2)
1598 /* The maximum fastbin request size we support */
1599 #define MAX_FAST_SIZE (80 * SIZE_SZ / 4)
1601 #define NFASTBINS (fastbin_index(request2size(MAX_FAST_SIZE))+1)
1604 FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free()
1605 that triggers automatic consolidation of possibly-surrounding
1606 fastbin chunks. This is a heuristic, so the exact value should not
1607 matter too much. It is defined at half the default trim threshold as a
1608 compromise heuristic to only attempt consolidation if it is likely
1609 to lead to trimming. However, it is not dynamically tunable, since
1610 consolidation reduces fragmentation surrounding large chunks even
1611 if trimming is not used.
1614 #define FASTBIN_CONSOLIDATION_THRESHOLD (65536UL)
1617 Since the lowest 2 bits in max_fast don't matter in size comparisons,
1618 they are used as flags.
1622 FASTCHUNKS_BIT held in max_fast indicates that there are probably
1623 some fastbin chunks. It is set true on entering a chunk into any
1624 fastbin, and cleared only in malloc_consolidate.
1626 The truth value is inverted so that have_fastchunks will be true
1627 upon startup (since statics are zero-filled), simplifying
1628 initialization checks.
1631 #define FASTCHUNKS_BIT (1U)
1633 #define have_fastchunks(M) (((M)->flags & FASTCHUNKS_BIT) == 0)
1634 #define clear_fastchunks(M) catomic_or (&(M)->flags, FASTCHUNKS_BIT)
1635 #define set_fastchunks(M) catomic_and (&(M)->flags, ~FASTCHUNKS_BIT)
1638 NONCONTIGUOUS_BIT indicates that MORECORE does not return contiguous
1639 regions. Otherwise, contiguity is exploited in merging together,
1640 when possible, results from consecutive MORECORE calls.
1642 The initial value comes from MORECORE_CONTIGUOUS, but is
1643 changed dynamically if mmap is ever used as an sbrk substitute.
1646 #define NONCONTIGUOUS_BIT (2U)
1648 #define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0)
1649 #define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0)
1650 #define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT)
1651 #define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT)
1654 Set value of max_fast.
1655 Use impossibly small value if 0.
1656 Precondition: there are no existing fastbin chunks.
1657 Setting the value clears fastchunk bit but preserves noncontiguous bit.
1660 #define set_max_fast(s) \
1661 global_max_fast = (((s) == 0) \
1662 ? SMALLBIN_WIDTH: ((s + SIZE_SZ) & ~MALLOC_ALIGN_MASK))
1663 #define get_max_fast() global_max_fast
1667 ----------- Internal state representation and initialization -----------
1670 struct malloc_state {
1671 /* Serialize access. */
1674 /* Flags (formerly in max_fast). */
1678 /* Statistics for locking. Only used if THREAD_STATS is defined. */
1679 long stat_lock_direct, stat_lock_loop, stat_lock_wait;
1683 mfastbinptr fastbinsY[NFASTBINS];
1685 /* Base of the topmost chunk -- not otherwise kept in a bin */
1688 /* The remainder from the most recent split of a small request */
1689 mchunkptr last_remainder;
1691 /* Normal bins packed as described above */
1692 mchunkptr bins[NBINS * 2 - 2];
1694 /* Bitmap of bins */
1695 unsigned int binmap[BINMAPSIZE];
1698 struct malloc_state *next;
1701 /* Linked list for free arenas. */
1702 struct malloc_state *next_free;
1705 /* Memory allocated from the system in this arena. */
1706 INTERNAL_SIZE_T system_mem;
1707 INTERNAL_SIZE_T max_system_mem;
1711 /* Tunable parameters */
1712 unsigned long trim_threshold;
1713 INTERNAL_SIZE_T top_pad;
1714 INTERNAL_SIZE_T mmap_threshold;
1716 INTERNAL_SIZE_T arena_test;
1717 INTERNAL_SIZE_T arena_max;
1720 /* Memory map support */
1724 /* the mmap_threshold is dynamic, until the user sets
1725 it manually, at which point we need to disable any
1726 dynamic behavior. */
1727 int no_dyn_threshold;
1730 INTERNAL_SIZE_T mmapped_mem;
1731 /*INTERNAL_SIZE_T sbrked_mem;*/
1732 /*INTERNAL_SIZE_T max_sbrked_mem;*/
1733 INTERNAL_SIZE_T max_mmapped_mem;
1734 INTERNAL_SIZE_T max_total_mem; /* only kept for NO_THREADS */
1736 /* First address handed out by MORECORE/sbrk. */
1740 /* There are several instances of this struct ("arenas") in this
1741 malloc. If you are adapting this malloc in a way that does NOT use
1742 a static or mmapped malloc_state, you MUST explicitly zero-fill it
1743 before using. This malloc relies on the property that malloc_state
1744 is initialized to all zeroes (as is true of C statics). */
1746 static struct malloc_state main_arena =
1748 .mutex = MUTEX_INITIALIZER,
1752 /* There is only one instance of the malloc parameters. */
1754 static struct malloc_par mp_ =
1756 .top_pad = DEFAULT_TOP_PAD,
1757 .n_mmaps_max = DEFAULT_MMAP_MAX,
1758 .mmap_threshold = DEFAULT_MMAP_THRESHOLD,
1759 .trim_threshold = DEFAULT_TRIM_THRESHOLD,
1761 # define NARENAS_FROM_NCORES(n) ((n) * (sizeof(long) == 4 ? 2 : 8))
1762 .arena_test = NARENAS_FROM_NCORES (1)
1768 /* Non public mallopt parameters. */
1769 #define M_ARENA_TEST -7
1770 #define M_ARENA_MAX -8
1774 /* Maximum size of memory handled in fastbins. */
1775 static INTERNAL_SIZE_T global_max_fast;
1778 Initialize a malloc_state struct.
1780 This is called only from within malloc_consolidate, which needs
1781 be called in the same contexts anyway. It is never called directly
1782 outside of malloc_consolidate because some optimizing compilers try
1783 to inline it at all call points, which turns out not to be an
1784 optimization at all. (Inlining it in malloc_consolidate is fine though.)
1787 static void malloc_init_state(mstate av)
1792 /* Establish circular links for normal bins */
1793 for (i = 1; i < NBINS; ++i) {
1795 bin->fd = bin->bk = bin;
1798 #if MORECORE_CONTIGUOUS
1799 if (av != &main_arena)
1801 set_noncontiguous(av);
1802 if (av == &main_arena)
1803 set_max_fast(DEFAULT_MXFAST);
1804 av->flags |= FASTCHUNKS_BIT;
1806 av->top = initial_top(av);
1810 Other internal utilities operating on mstates
1813 static void* sysmalloc(INTERNAL_SIZE_T, mstate);
1814 static int systrim(size_t, mstate);
1815 static void malloc_consolidate(mstate);
1818 /* -------------- Early definitions for debugging hooks ---------------- */
1820 /* Define and initialize the hook variables. These weak definitions must
1821 appear before any use of the variables in a function (arena.c uses one). */
1822 #ifndef weak_variable
1823 /* In GNU libc we want the hook variables to be weak definitions to
1824 avoid a problem with Emacs. */
1825 # define weak_variable weak_function
1828 /* Forward declarations. */
1829 static void* malloc_hook_ini __MALLOC_P ((size_t sz,
1830 const __malloc_ptr_t caller));
1831 static void* realloc_hook_ini __MALLOC_P ((void* ptr, size_t sz,
1832 const __malloc_ptr_t caller));
1833 static void* memalign_hook_ini __MALLOC_P ((size_t alignment, size_t sz,
1834 const __malloc_ptr_t caller));
1836 void weak_variable (*__malloc_initialize_hook) (void) = NULL;
1837 void weak_variable (*__free_hook) (__malloc_ptr_t __ptr,
1838 const __malloc_ptr_t) = NULL;
1839 __malloc_ptr_t weak_variable (*__malloc_hook)
1840 (size_t __size, const __malloc_ptr_t) = malloc_hook_ini;
1841 __malloc_ptr_t weak_variable (*__realloc_hook)
1842 (__malloc_ptr_t __ptr, size_t __size, const __malloc_ptr_t)
1844 __malloc_ptr_t weak_variable (*__memalign_hook)
1845 (size_t __alignment, size_t __size, const __malloc_ptr_t)
1846 = memalign_hook_ini;
1847 void weak_variable (*__after_morecore_hook) (void) = NULL;
1850 /* ---------------- Error behavior ------------------------------------ */
1852 #ifndef DEFAULT_CHECK_ACTION
1853 #define DEFAULT_CHECK_ACTION 3
1856 static int check_action = DEFAULT_CHECK_ACTION;
1859 /* ------------------ Testing support ----------------------------------*/
1861 static int perturb_byte;
1863 #define alloc_perturb(p, n) memset (p, (perturb_byte ^ 0xff) & 0xff, n)
1864 #define free_perturb(p, n) memset (p, perturb_byte & 0xff, n)
1867 /* ------------------- Support for multiple arenas -------------------- */
1873 These routines make a number of assertions about the states
1874 of data structures that should be true at all times. If any
1875 are not true, it's very likely that a user program has somehow
1876 trashed memory. (It's also possible that there is a coding error
1877 in malloc. In which case, please report it!)
1882 #define check_chunk(A,P)
1883 #define check_free_chunk(A,P)
1884 #define check_inuse_chunk(A,P)
1885 #define check_remalloced_chunk(A,P,N)
1886 #define check_malloced_chunk(A,P,N)
1887 #define check_malloc_state(A)
1891 #define check_chunk(A,P) do_check_chunk(A,P)
1892 #define check_free_chunk(A,P) do_check_free_chunk(A,P)
1893 #define check_inuse_chunk(A,P) do_check_inuse_chunk(A,P)
1894 #define check_remalloced_chunk(A,P,N) do_check_remalloced_chunk(A,P,N)
1895 #define check_malloced_chunk(A,P,N) do_check_malloced_chunk(A,P,N)
1896 #define check_malloc_state(A) do_check_malloc_state(A)
1899 Properties of all chunks
1902 static void do_check_chunk(mstate av, mchunkptr p)
1904 unsigned long sz = chunksize(p);
1905 /* min and max possible addresses assuming contiguous allocation */
1906 char* max_address = (char*)(av->top) + chunksize(av->top);
1907 char* min_address = max_address - av->system_mem;
1909 if (!chunk_is_mmapped(p)) {
1911 /* Has legal address ... */
1913 if (contiguous(av)) {
1914 assert(((char*)p) >= min_address);
1915 assert(((char*)p + sz) <= ((char*)(av->top)));
1919 /* top size is always at least MINSIZE */
1920 assert((unsigned long)(sz) >= MINSIZE);
1921 /* top predecessor always marked inuse */
1922 assert(prev_inuse(p));
1927 /* address is outside main heap */
1928 if (contiguous(av) && av->top != initial_top(av)) {
1929 assert(((char*)p) < min_address || ((char*)p) >= max_address);
1931 /* chunk is page-aligned */
1932 assert(((p->prev_size + sz) & (GLRO(dl_pagesize)-1)) == 0);
1933 /* mem is aligned */
1934 assert(aligned_OK(chunk2mem(p)));
1939 Properties of free chunks
1942 static void do_check_free_chunk(mstate av, mchunkptr p)
1944 INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE|NON_MAIN_ARENA);
1945 mchunkptr next = chunk_at_offset(p, sz);
1947 do_check_chunk(av, p);
1949 /* Chunk must claim to be free ... */
1951 assert (!chunk_is_mmapped(p));
1953 /* Unless a special marker, must have OK fields */
1954 if ((unsigned long)(sz) >= MINSIZE)
1956 assert((sz & MALLOC_ALIGN_MASK) == 0);
1957 assert(aligned_OK(chunk2mem(p)));
1958 /* ... matching footer field */
1959 assert(next->prev_size == sz);
1960 /* ... and is fully consolidated */
1961 assert(prev_inuse(p));
1962 assert (next == av->top || inuse(next));
1964 /* ... and has minimally sane links */
1965 assert(p->fd->bk == p);
1966 assert(p->bk->fd == p);
1968 else /* markers are always of size SIZE_SZ */
1969 assert(sz == SIZE_SZ);
1973 Properties of inuse chunks
1976 static void do_check_inuse_chunk(mstate av, mchunkptr p)
1980 do_check_chunk(av, p);
1982 if (chunk_is_mmapped(p))
1983 return; /* mmapped chunks have no next/prev */
1985 /* Check whether it claims to be in use ... */
1988 next = next_chunk(p);
1990 /* ... and is surrounded by OK chunks.
1991 Since more things can be checked with free chunks than inuse ones,
1992 if an inuse chunk borders them and debug is on, it's worth doing them.
1994 if (!prev_inuse(p)) {
1995 /* Note that we cannot even look at prev unless it is not inuse */
1996 mchunkptr prv = prev_chunk(p);
1997 assert(next_chunk(prv) == p);
1998 do_check_free_chunk(av, prv);
2001 if (next == av->top) {
2002 assert(prev_inuse(next));
2003 assert(chunksize(next) >= MINSIZE);
2005 else if (!inuse(next))
2006 do_check_free_chunk(av, next);
2010 Properties of chunks recycled from fastbins
2013 static void do_check_remalloced_chunk(mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2015 INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE|NON_MAIN_ARENA);
2017 if (!chunk_is_mmapped(p)) {
2018 assert(av == arena_for_chunk(p));
2019 if (chunk_non_main_arena(p))
2020 assert(av != &main_arena);
2022 assert(av == &main_arena);
2025 do_check_inuse_chunk(av, p);
2027 /* Legal size ... */
2028 assert((sz & MALLOC_ALIGN_MASK) == 0);
2029 assert((unsigned long)(sz) >= MINSIZE);
2030 /* ... and alignment */
2031 assert(aligned_OK(chunk2mem(p)));
2032 /* chunk is less than MINSIZE more than request */
2033 assert((long)(sz) - (long)(s) >= 0);
2034 assert((long)(sz) - (long)(s + MINSIZE) < 0);
2038 Properties of nonrecycled chunks at the point they are malloced
2041 static void do_check_malloced_chunk(mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2043 /* same as recycled case ... */
2044 do_check_remalloced_chunk(av, p, s);
2047 ... plus, must obey implementation invariant that prev_inuse is
2048 always true of any allocated chunk; i.e., that each allocated
2049 chunk borders either a previously allocated and still in-use
2050 chunk, or the base of its memory arena. This is ensured
2051 by making all allocations from the `lowest' part of any found
2052 chunk. This does not necessarily hold however for chunks
2053 recycled via fastbins.
2056 assert(prev_inuse(p));
2061 Properties of malloc_state.
2063 This may be useful for debugging malloc, as well as detecting user
2064 programmer errors that somehow write into malloc_state.
2066 If you are extending or experimenting with this malloc, you can
2067 probably figure out how to hack this routine to print out or
2068 display chunk addresses, sizes, bins, and other instrumentation.
2071 static void do_check_malloc_state(mstate av)
2078 INTERNAL_SIZE_T size;
2079 unsigned long total = 0;
2082 /* internal size_t must be no wider than pointer type */
2083 assert(sizeof(INTERNAL_SIZE_T) <= sizeof(char*));
2085 /* alignment is a power of 2 */
2086 assert((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-1)) == 0);
2088 /* cannot run remaining checks until fully initialized */
2089 if (av->top == 0 || av->top == initial_top(av))
2092 /* pagesize is a power of 2 */
2093 assert((GLRO(dl_pagesize) & (GLRO(dl_pagesize)-1)) == 0);
2095 /* A contiguous main_arena is consistent with sbrk_base. */
2096 if (av == &main_arena && contiguous(av))
2097 assert((char*)mp_.sbrk_base + av->system_mem ==
2098 (char*)av->top + chunksize(av->top));
2100 /* properties of fastbins */
2102 /* max_fast is in allowed range */
2103 assert((get_max_fast () & ~1) <= request2size(MAX_FAST_SIZE));
2105 max_fast_bin = fastbin_index(get_max_fast ());
2107 for (i = 0; i < NFASTBINS; ++i) {
2108 p = fastbin (av, i);
2110 /* The following test can only be performed for the main arena.
2111 While mallopt calls malloc_consolidate to get rid of all fast
2112 bins (especially those larger than the new maximum) this does
2113 only happen for the main arena. Trying to do this for any
2114 other arena would mean those arenas have to be locked and
2115 malloc_consolidate be called for them. This is excessive. And
2116 even if this is acceptable to somebody it still cannot solve
2117 the problem completely since if the arena is locked a
2118 concurrent malloc call might create a new arena which then
2119 could use the newly invalid fast bins. */
2121 /* all bins past max_fast are empty */
2122 if (av == &main_arena && i > max_fast_bin)
2126 /* each chunk claims to be inuse */
2127 do_check_inuse_chunk(av, p);
2128 total += chunksize(p);
2129 /* chunk belongs in this bin */
2130 assert(fastbin_index(chunksize(p)) == i);
2136 assert(have_fastchunks(av));
2137 else if (!have_fastchunks(av))
2140 /* check normal bins */
2141 for (i = 1; i < NBINS; ++i) {
2144 /* binmap is accurate (except for bin 1 == unsorted_chunks) */
2146 unsigned int binbit = get_binmap(av,i);
2147 int empty = last(b) == b;
2154 for (p = last(b); p != b; p = p->bk) {
2155 /* each chunk claims to be free */
2156 do_check_free_chunk(av, p);
2157 size = chunksize(p);
2160 /* chunk belongs in bin */
2161 idx = bin_index(size);
2163 /* lists are sorted */
2164 assert(p->bk == b ||
2165 (unsigned long)chunksize(p->bk) >= (unsigned long)chunksize(p));
2167 if (!in_smallbin_range(size))
2169 if (p->fd_nextsize != NULL)
2171 if (p->fd_nextsize == p)
2172 assert (p->bk_nextsize == p);
2175 if (p->fd_nextsize == first (b))
2176 assert (chunksize (p) < chunksize (p->fd_nextsize));
2178 assert (chunksize (p) > chunksize (p->fd_nextsize));
2181 assert (chunksize (p) > chunksize (p->bk_nextsize));
2183 assert (chunksize (p) < chunksize (p->bk_nextsize));
2187 assert (p->bk_nextsize == NULL);
2189 } else if (!in_smallbin_range(size))
2190 assert (p->fd_nextsize == NULL && p->bk_nextsize == NULL);
2191 /* chunk is followed by a legal chain of inuse chunks */
2192 for (q = next_chunk(p);
2193 (q != av->top && inuse(q) &&
2194 (unsigned long)(chunksize(q)) >= MINSIZE);
2196 do_check_inuse_chunk(av, q);
2200 /* top chunk is OK */
2201 check_chunk(av, av->top);
2203 /* sanity checks for statistics */
2205 assert(mp_.n_mmaps <= mp_.max_n_mmaps);
2207 assert((unsigned long)(av->system_mem) <=
2208 (unsigned long)(av->max_system_mem));
2210 assert((unsigned long)(mp_.mmapped_mem) <=
2211 (unsigned long)(mp_.max_mmapped_mem));
2216 /* ----------------- Support for debugging hooks -------------------- */
2220 /* ----------- Routines dealing with system allocation -------------- */
2223 sysmalloc handles malloc cases requiring more memory from the system.
2224 On entry, it is assumed that av->top does not have enough
2225 space to service request for nb bytes, thus requiring that av->top
2226 be extended or replaced.
2229 static void* sysmalloc(INTERNAL_SIZE_T nb, mstate av)
2231 mchunkptr old_top; /* incoming value of av->top */
2232 INTERNAL_SIZE_T old_size; /* its size */
2233 char* old_end; /* its end address */
2235 long size; /* arg to first MORECORE or mmap call */
2236 char* brk; /* return value from MORECORE */
2238 long correction; /* arg to 2nd MORECORE call */
2239 char* snd_brk; /* 2nd return val */
2241 INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */
2242 INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */
2243 char* aligned_brk; /* aligned offset into brk */
2245 mchunkptr p; /* the allocated/returned chunk */
2246 mchunkptr remainder; /* remainder from allocation */
2247 unsigned long remainder_size; /* its size */
2249 unsigned long sum; /* for updating stats */
2251 size_t pagemask = GLRO(dl_pagesize) - 1;
2252 bool tried_mmap = false;
2256 If have mmap, and the request size meets the mmap threshold, and
2257 the system supports mmap, and there are few enough currently
2258 allocated mmapped regions, try to directly map this request
2259 rather than expanding top.
2262 if ((unsigned long)(nb) >= (unsigned long)(mp_.mmap_threshold) &&
2263 (mp_.n_mmaps < mp_.n_mmaps_max)) {
2265 char* mm; /* return value from mmap call*/
2269 Round up size to nearest page. For mmapped chunks, the overhead
2270 is one SIZE_SZ unit larger than for normal chunks, because there
2271 is no following chunk whose prev_size field could be used.
2273 See the front_misalign handling below, for glibc there is no
2274 need for further alignments. */
2275 size = (nb + SIZE_SZ + pagemask) & ~pagemask;
2278 /* Don't try if size wraps around 0 */
2279 if ((unsigned long)(size) > (unsigned long)(nb)) {
2281 mm = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE, 0));
2283 if (mm != MAP_FAILED) {
2286 The offset to the start of the mmapped region is stored
2287 in the prev_size field of the chunk. This allows us to adjust
2288 returned start address to meet alignment requirements here
2289 and in memalign(), and still be able to compute proper
2290 address argument for later munmap in free() and realloc().
2292 For glibc, chunk2mem increases the address by 2*SIZE_SZ and
2293 MALLOC_ALIGN_MASK is 2*SIZE_SZ-1. Each mmap'ed area is page
2294 aligned and therefore definitely MALLOC_ALIGN_MASK-aligned. */
2295 assert (((INTERNAL_SIZE_T)chunk2mem(mm) & MALLOC_ALIGN_MASK) == 0);
2298 set_head(p, size|IS_MMAPPED);
2300 /* update statistics */
2302 if (++mp_.n_mmaps > mp_.max_n_mmaps)
2303 mp_.max_n_mmaps = mp_.n_mmaps;
2305 sum = mp_.mmapped_mem += size;
2306 if (sum > (unsigned long)(mp_.max_mmapped_mem))
2307 mp_.max_mmapped_mem = sum;
2311 return chunk2mem(p);
2316 /* Record incoming configuration of top */
2319 old_size = chunksize(old_top);
2320 old_end = (char*)(chunk_at_offset(old_top, old_size));
2322 brk = snd_brk = (char*)(MORECORE_FAILURE);
2325 If not the first time through, we require old_size to be
2326 at least MINSIZE and to have prev_inuse set.
2329 assert((old_top == initial_top(av) && old_size == 0) ||
2330 ((unsigned long) (old_size) >= MINSIZE &&
2331 prev_inuse(old_top) &&
2332 ((unsigned long)old_end & pagemask) == 0));
2334 /* Precondition: not enough current space to satisfy nb request */
2335 assert((unsigned long)(old_size) < (unsigned long)(nb + MINSIZE));
2338 if (av != &main_arena) {
2340 heap_info *old_heap, *heap;
2341 size_t old_heap_size;
2343 /* First try to extend the current heap. */
2344 old_heap = heap_for_ptr(old_top);
2345 old_heap_size = old_heap->size;
2346 if ((long) (MINSIZE + nb - old_size) > 0
2347 && grow_heap(old_heap, MINSIZE + nb - old_size) == 0) {
2348 av->system_mem += old_heap->size - old_heap_size;
2349 arena_mem += old_heap->size - old_heap_size;
2350 set_head(old_top, (((char *)old_heap + old_heap->size) - (char *)old_top)
2353 else if ((heap = new_heap(nb + (MINSIZE + sizeof(*heap)), mp_.top_pad))) {
2354 /* Use a newly allocated heap. */
2356 heap->prev = old_heap;
2357 av->system_mem += heap->size;
2358 arena_mem += heap->size;
2359 /* Set up the new top. */
2360 top(av) = chunk_at_offset(heap, sizeof(*heap));
2361 set_head(top(av), (heap->size - sizeof(*heap)) | PREV_INUSE);
2363 /* Setup fencepost and free the old top chunk. */
2364 /* The fencepost takes at least MINSIZE bytes, because it might
2365 become the top chunk again later. Note that a footer is set
2366 up, too, although the chunk is marked in use. */
2367 old_size -= MINSIZE;
2368 set_head(chunk_at_offset(old_top, old_size + 2*SIZE_SZ), 0|PREV_INUSE);
2369 if (old_size >= MINSIZE) {
2370 set_head(chunk_at_offset(old_top, old_size), (2*SIZE_SZ)|PREV_INUSE);
2371 set_foot(chunk_at_offset(old_top, old_size), (2*SIZE_SZ));
2372 set_head(old_top, old_size|PREV_INUSE|NON_MAIN_ARENA);
2373 _int_free(av, old_top, 1);
2375 set_head(old_top, (old_size + 2*SIZE_SZ)|PREV_INUSE);
2376 set_foot(old_top, (old_size + 2*SIZE_SZ));
2379 else if (!tried_mmap)
2380 /* We can at least try to use to mmap memory. */
2383 } else { /* av == main_arena */
2386 /* Request enough space for nb + pad + overhead */
2388 size = nb + mp_.top_pad + MINSIZE;
2391 If contiguous, we can subtract out existing space that we hope to
2392 combine with new space. We add it back later only if
2393 we don't actually get contiguous space.
2400 Round to a multiple of page size.
2401 If MORECORE is not contiguous, this ensures that we only call it
2402 with whole-page arguments. And if MORECORE is contiguous and
2403 this is not first time through, this preserves page-alignment of
2404 previous calls. Otherwise, we correct to page-align below.
2407 size = (size + pagemask) & ~pagemask;
2410 Don't try to call MORECORE if argument is so big as to appear
2411 negative. Note that since mmap takes size_t arg, it may succeed
2412 below even if we cannot call MORECORE.
2416 brk = (char*)(MORECORE(size));
2418 if (brk != (char*)(MORECORE_FAILURE)) {
2419 /* Call the `morecore' hook if necessary. */
2420 void (*hook) (void) = force_reg (__after_morecore_hook);
2421 if (__builtin_expect (hook != NULL, 0))
2425 If have mmap, try using it as a backup when MORECORE fails or
2426 cannot be used. This is worth doing on systems that have "holes" in
2427 address space, so sbrk cannot extend to give contiguous space, but
2428 space is available elsewhere. Note that we ignore mmap max count
2429 and threshold limits, since the space will not be used as a
2430 segregated mmap region.
2433 /* Cannot merge with old top, so add its size back in */
2435 size = (size + old_size + pagemask) & ~pagemask;
2437 /* If we are relying on mmap as backup, then use larger units */
2438 if ((unsigned long)(size) < (unsigned long)(MMAP_AS_MORECORE_SIZE))
2439 size = MMAP_AS_MORECORE_SIZE;
2441 /* Don't try if size wraps around 0 */
2442 if ((unsigned long)(size) > (unsigned long)(nb)) {
2444 char *mbrk = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE, 0));
2446 if (mbrk != MAP_FAILED) {
2448 /* We do not need, and cannot use, another sbrk call to find end */
2450 snd_brk = brk + size;
2453 Record that we no longer have a contiguous sbrk region.
2454 After the first time mmap is used as backup, we do not
2455 ever rely on contiguous space since this could incorrectly
2458 set_noncontiguous(av);
2463 if (brk != (char*)(MORECORE_FAILURE)) {
2464 if (mp_.sbrk_base == 0)
2465 mp_.sbrk_base = brk;
2466 av->system_mem += size;
2469 If MORECORE extends previous space, we can likewise extend top size.
2472 if (brk == old_end && snd_brk == (char*)(MORECORE_FAILURE))
2473 set_head(old_top, (size + old_size) | PREV_INUSE);
2475 else if (contiguous(av) && old_size && brk < old_end) {
2476 /* Oops! Someone else killed our space.. Can't touch anything. */
2477 malloc_printerr (3, "break adjusted to free malloc space", brk);
2481 Otherwise, make adjustments:
2483 * If the first time through or noncontiguous, we need to call sbrk
2484 just to find out where the end of memory lies.
2486 * We need to ensure that all returned chunks from malloc will meet
2489 * If there was an intervening foreign sbrk, we need to adjust sbrk
2490 request size to account for fact that we will not be able to
2491 combine new space with existing space in old_top.
2493 * Almost all systems internally allocate whole pages at a time, in
2494 which case we might as well use the whole last page of request.
2495 So we allocate enough more memory to hit a page boundary now,
2496 which in turn causes future contiguous calls to page-align.
2505 /* handle contiguous cases */
2506 if (contiguous(av)) {
2508 /* Count foreign sbrk as system_mem. */
2510 av->system_mem += brk - old_end;
2512 /* Guarantee alignment of first new chunk made from this space */
2514 front_misalign = (INTERNAL_SIZE_T)chunk2mem(brk) & MALLOC_ALIGN_MASK;
2515 if (front_misalign > 0) {
2518 Skip over some bytes to arrive at an aligned position.
2519 We don't need to specially mark these wasted front bytes.
2520 They will never be accessed anyway because
2521 prev_inuse of av->top (and any chunk created from its start)
2522 is always true after initialization.
2525 correction = MALLOC_ALIGNMENT - front_misalign;
2526 aligned_brk += correction;
2530 If this isn't adjacent to existing space, then we will not
2531 be able to merge with old_top space, so must add to 2nd request.
2534 correction += old_size;
2536 /* Extend the end address to hit a page boundary */
2537 end_misalign = (INTERNAL_SIZE_T)(brk + size + correction);
2538 correction += ((end_misalign + pagemask) & ~pagemask) - end_misalign;
2540 assert(correction >= 0);
2541 snd_brk = (char*)(MORECORE(correction));
2544 If can't allocate correction, try to at least find out current
2545 brk. It might be enough to proceed without failing.
2547 Note that if second sbrk did NOT fail, we assume that space
2548 is contiguous with first sbrk. This is a safe assumption unless
2549 program is multithreaded but doesn't use locks and a foreign sbrk
2550 occurred between our first and second calls.
2553 if (snd_brk == (char*)(MORECORE_FAILURE)) {
2555 snd_brk = (char*)(MORECORE(0));
2557 /* Call the `morecore' hook if necessary. */
2558 void (*hook) (void) = force_reg (__after_morecore_hook);
2559 if (__builtin_expect (hook != NULL, 0))
2564 /* handle non-contiguous cases */
2566 /* MORECORE/mmap must correctly align */
2567 assert(((unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK) == 0);
2569 /* Find out current end of memory */
2570 if (snd_brk == (char*)(MORECORE_FAILURE)) {
2571 snd_brk = (char*)(MORECORE(0));
2575 /* Adjust top based on results of second sbrk */
2576 if (snd_brk != (char*)(MORECORE_FAILURE)) {
2577 av->top = (mchunkptr)aligned_brk;
2578 set_head(av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);
2579 av->system_mem += correction;
2582 If not the first time through, we either have a
2583 gap due to foreign sbrk or a non-contiguous region. Insert a
2584 double fencepost at old_top to prevent consolidation with space
2585 we don't own. These fenceposts are artificial chunks that are
2586 marked as inuse and are in any case too small to use. We need
2587 two to make sizes and alignments work out.
2590 if (old_size != 0) {
2592 Shrink old_top to insert fenceposts, keeping size a
2593 multiple of MALLOC_ALIGNMENT. We know there is at least
2594 enough space in old_top to do this.
2596 old_size = (old_size - 4*SIZE_SZ) & ~MALLOC_ALIGN_MASK;
2597 set_head(old_top, old_size | PREV_INUSE);
2600 Note that the following assignments completely overwrite
2601 old_top when old_size was previously MINSIZE. This is
2602 intentional. We need the fencepost, even if old_top otherwise gets
2605 chunk_at_offset(old_top, old_size )->size =
2606 (2*SIZE_SZ)|PREV_INUSE;
2608 chunk_at_offset(old_top, old_size + 2*SIZE_SZ)->size =
2609 (2*SIZE_SZ)|PREV_INUSE;
2611 /* If possible, release the rest. */
2612 if (old_size >= MINSIZE) {
2613 _int_free(av, old_top, 1);
2621 } /* if (av != &main_arena) */
2623 if ((unsigned long)av->system_mem > (unsigned long)(av->max_system_mem))
2624 av->max_system_mem = av->system_mem;
2625 check_malloc_state(av);
2627 /* finally, do the allocation */
2629 size = chunksize(p);
2631 /* check that one of the above allocation paths succeeded */
2632 if ((unsigned long)(size) >= (unsigned long)(nb + MINSIZE)) {
2633 remainder_size = size - nb;
2634 remainder = chunk_at_offset(p, nb);
2635 av->top = remainder;
2636 set_head(p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0));
2637 set_head(remainder, remainder_size | PREV_INUSE);
2638 check_malloced_chunk(av, p, nb);
2639 return chunk2mem(p);
2642 /* catch all failure paths */
2643 __set_errno (ENOMEM);
2649 systrim is an inverse of sorts to sysmalloc. It gives memory back
2650 to the system (via negative arguments to sbrk) if there is unused
2651 memory at the `high' end of the malloc pool. It is called
2652 automatically by free() when top space exceeds the trim
2653 threshold. It is also called by the public malloc_trim routine. It
2654 returns 1 if it actually released any memory, else 0.
2657 static int systrim(size_t pad, mstate av)
2659 long top_size; /* Amount of top-most memory */
2660 long extra; /* Amount to release */
2661 long released; /* Amount actually released */
2662 char* current_brk; /* address returned by pre-check sbrk call */
2663 char* new_brk; /* address returned by post-check sbrk call */
2666 pagesz = GLRO(dl_pagesize);
2667 top_size = chunksize(av->top);
2669 /* Release in pagesize units, keeping at least one page */
2670 extra = (top_size - pad - MINSIZE - 1) & ~(pagesz - 1);
2675 Only proceed if end of memory is where we last set it.
2676 This avoids problems if there were foreign sbrk calls.
2678 current_brk = (char*)(MORECORE(0));
2679 if (current_brk == (char*)(av->top) + top_size) {
2682 Attempt to release memory. We ignore MORECORE return value,
2683 and instead call again to find out where new end of memory is.
2684 This avoids problems if first call releases less than we asked,
2685 of if failure somehow altered brk value. (We could still
2686 encounter problems if it altered brk in some very bad way,
2687 but the only thing we can do is adjust anyway, which will cause
2688 some downstream failure.)
2692 /* Call the `morecore' hook if necessary. */
2693 void (*hook) (void) = force_reg (__after_morecore_hook);
2694 if (__builtin_expect (hook != NULL, 0))
2696 new_brk = (char*)(MORECORE(0));
2698 if (new_brk != (char*)MORECORE_FAILURE) {
2699 released = (long)(current_brk - new_brk);
2701 if (released != 0) {
2702 /* Success. Adjust top. */
2703 av->system_mem -= released;
2704 set_head(av->top, (top_size - released) | PREV_INUSE);
2705 check_malloc_state(av);
2716 munmap_chunk(mchunkptr p)
2718 INTERNAL_SIZE_T size = chunksize(p);
2720 assert (chunk_is_mmapped(p));
2722 uintptr_t block = (uintptr_t) p - p->prev_size;
2723 size_t total_size = p->prev_size + size;
2724 /* Unfortunately we have to do the compilers job by hand here. Normally
2725 we would test BLOCK and TOTAL-SIZE separately for compliance with the
2726 page size. But gcc does not recognize the optimization possibility
2727 (in the moment at least) so we combine the two values into one before
2729 if (__builtin_expect (((block | total_size) & (GLRO(dl_pagesize) - 1)) != 0, 0))
2731 malloc_printerr (check_action, "munmap_chunk(): invalid pointer",
2737 mp_.mmapped_mem -= total_size;
2739 /* If munmap failed the process virtual memory address space is in a
2740 bad shape. Just leave the block hanging around, the process will
2741 terminate shortly anyway since not much can be done. */
2742 __munmap((char *)block, total_size);
2749 mremap_chunk(mchunkptr p, size_t new_size)
2751 size_t page_mask = GLRO(dl_pagesize) - 1;
2752 INTERNAL_SIZE_T offset = p->prev_size;
2753 INTERNAL_SIZE_T size = chunksize(p);
2756 assert (chunk_is_mmapped(p));
2757 assert(((size + offset) & (GLRO(dl_pagesize)-1)) == 0);
2759 /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
2760 new_size = (new_size + offset + SIZE_SZ + page_mask) & ~page_mask;
2762 /* No need to remap if the number of pages does not change. */
2763 if (size + offset == new_size)
2766 cp = (char *)__mremap((char *)p - offset, size + offset, new_size,
2769 if (cp == MAP_FAILED) return 0;
2771 p = (mchunkptr)(cp + offset);
2773 assert(aligned_OK(chunk2mem(p)));
2775 assert((p->prev_size == offset));
2776 set_head(p, (new_size - offset)|IS_MMAPPED);
2778 mp_.mmapped_mem -= size + offset;
2779 mp_.mmapped_mem += new_size;
2780 if ((unsigned long)mp_.mmapped_mem > (unsigned long)mp_.max_mmapped_mem)
2781 mp_.max_mmapped_mem = mp_.mmapped_mem;
2785 #endif /* HAVE_MREMAP */
2787 /*------------------------ Public wrappers. --------------------------------*/
2790 __libc_malloc(size_t bytes)
2795 __malloc_ptr_t (*hook) (size_t, const __malloc_ptr_t)
2796 = force_reg (__malloc_hook);
2797 if (__builtin_expect (hook != NULL, 0))
2798 return (*hook)(bytes, RETURN_ADDRESS (0));
2800 arena_lookup(ar_ptr);
2802 arena_lock(ar_ptr, bytes);
2805 victim = _int_malloc(ar_ptr, bytes);
2807 /* Maybe the failure is due to running out of mmapped areas. */
2808 if(ar_ptr != &main_arena) {
2809 (void)mutex_unlock(&ar_ptr->mutex);
2810 ar_ptr = &main_arena;
2811 (void)mutex_lock(&ar_ptr->mutex);
2812 victim = _int_malloc(ar_ptr, bytes);
2813 (void)mutex_unlock(&ar_ptr->mutex);
2815 /* ... or sbrk() has failed and there is still a chance to mmap() */
2816 ar_ptr = arena_get2(ar_ptr->next ? ar_ptr : 0, bytes);
2817 (void)mutex_unlock(&main_arena.mutex);
2819 victim = _int_malloc(ar_ptr, bytes);
2820 (void)mutex_unlock(&ar_ptr->mutex);
2824 (void)mutex_unlock(&ar_ptr->mutex);
2825 assert(!victim || chunk_is_mmapped(mem2chunk(victim)) ||
2826 ar_ptr == arena_for_chunk(mem2chunk(victim)));
2829 libc_hidden_def(__libc_malloc)
2832 __libc_free(void* mem)
2835 mchunkptr p; /* chunk corresponding to mem */
2837 void (*hook) (__malloc_ptr_t, const __malloc_ptr_t)
2838 = force_reg (__free_hook);
2839 if (__builtin_expect (hook != NULL, 0)) {
2840 (*hook)(mem, RETURN_ADDRESS (0));
2844 if (mem == 0) /* free(0) has no effect */
2849 if (chunk_is_mmapped(p)) /* release mmapped memory. */
2851 /* see if the dynamic brk/mmap threshold needs adjusting */
2852 if (!mp_.no_dyn_threshold
2853 && p->size > mp_.mmap_threshold
2854 && p->size <= DEFAULT_MMAP_THRESHOLD_MAX)
2856 mp_.mmap_threshold = chunksize (p);
2857 mp_.trim_threshold = 2 * mp_.mmap_threshold;
2863 ar_ptr = arena_for_chunk(p);
2864 _int_free(ar_ptr, p, 0);
2866 libc_hidden_def (__libc_free)
2869 __libc_realloc(void* oldmem, size_t bytes)
2872 INTERNAL_SIZE_T nb; /* padded request size */
2874 void* newp; /* chunk to return */
2876 __malloc_ptr_t (*hook) (__malloc_ptr_t, size_t, const __malloc_ptr_t) =
2877 force_reg (__realloc_hook);
2878 if (__builtin_expect (hook != NULL, 0))
2879 return (*hook)(oldmem, bytes, RETURN_ADDRESS (0));
2881 #if REALLOC_ZERO_BYTES_FREES
2882 if (bytes == 0 && oldmem != NULL) { __libc_free(oldmem); return 0; }
2885 /* realloc of null is supposed to be same as malloc */
2886 if (oldmem == 0) return __libc_malloc(bytes);
2888 /* chunk corresponding to oldmem */
2889 const mchunkptr oldp = mem2chunk(oldmem);
2891 const INTERNAL_SIZE_T oldsize = chunksize(oldp);
2893 /* Little security check which won't hurt performance: the
2894 allocator never wrapps around at the end of the address space.
2895 Therefore we can exclude some size values which might appear
2896 here by accident or by "design" from some intruder. */
2897 if (__builtin_expect ((uintptr_t) oldp > (uintptr_t) -oldsize, 0)
2898 || __builtin_expect (misaligned_chunk (oldp), 0))
2900 malloc_printerr (check_action, "realloc(): invalid pointer", oldmem);
2904 checked_request2size(bytes, nb);
2906 if (chunk_is_mmapped(oldp))
2911 newp = mremap_chunk(oldp, nb);
2912 if(newp) return chunk2mem(newp);
2914 /* Note the extra SIZE_SZ overhead. */
2915 if(oldsize - SIZE_SZ >= nb) return oldmem; /* do nothing */
2916 /* Must alloc, copy, free. */
2917 newmem = __libc_malloc(bytes);
2918 if (newmem == 0) return 0; /* propagate failure */
2919 MALLOC_COPY(newmem, oldmem, oldsize - 2*SIZE_SZ);
2924 ar_ptr = arena_for_chunk(oldp);
2926 if(!mutex_trylock(&ar_ptr->mutex))
2927 ++(ar_ptr->stat_lock_direct);
2929 (void)mutex_lock(&ar_ptr->mutex);
2930 ++(ar_ptr->stat_lock_wait);
2933 (void)mutex_lock(&ar_ptr->mutex);
2936 #if !defined PER_THREAD
2937 /* As in malloc(), remember this arena for the next allocation. */
2938 tsd_setspecific(arena_key, (void *)ar_ptr);
2941 newp = _int_realloc(ar_ptr, oldp, oldsize, nb);
2943 (void)mutex_unlock(&ar_ptr->mutex);
2944 assert(!newp || chunk_is_mmapped(mem2chunk(newp)) ||
2945 ar_ptr == arena_for_chunk(mem2chunk(newp)));
2949 /* Try harder to allocate memory in other arenas. */
2950 newp = __libc_malloc(bytes);
2953 MALLOC_COPY (newp, oldmem, oldsize - SIZE_SZ);
2954 _int_free(ar_ptr, oldp, 0);
2960 libc_hidden_def (__libc_realloc)
2963 __libc_memalign(size_t alignment, size_t bytes)
2968 __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, size_t,
2969 const __malloc_ptr_t)) =
2970 force_reg (__memalign_hook);
2971 if (__builtin_expect (hook != NULL, 0))
2972 return (*hook)(alignment, bytes, RETURN_ADDRESS (0));
2974 /* If need less alignment than we give anyway, just relay to malloc */
2975 if (alignment <= MALLOC_ALIGNMENT) return __libc_malloc(bytes);
2977 /* Otherwise, ensure that it is at least a minimum chunk size */
2978 if (alignment < MINSIZE) alignment = MINSIZE;
2980 arena_get(ar_ptr, bytes + alignment + MINSIZE);
2983 p = _int_memalign(ar_ptr, alignment, bytes);
2985 /* Maybe the failure is due to running out of mmapped areas. */
2986 if(ar_ptr != &main_arena) {
2987 (void)mutex_unlock(&ar_ptr->mutex);
2988 ar_ptr = &main_arena;
2989 (void)mutex_lock(&ar_ptr->mutex);
2990 p = _int_memalign(ar_ptr, alignment, bytes);
2991 (void)mutex_unlock(&ar_ptr->mutex);
2993 /* ... or sbrk() has failed and there is still a chance to mmap() */
2994 mstate prev = ar_ptr->next ? ar_ptr : 0;
2995 (void)mutex_unlock(&ar_ptr->mutex);
2996 ar_ptr = arena_get2(prev, bytes);
2998 p = _int_memalign(ar_ptr, alignment, bytes);
2999 (void)mutex_unlock(&ar_ptr->mutex);
3003 (void)mutex_unlock(&ar_ptr->mutex);
3004 assert(!p || chunk_is_mmapped(mem2chunk(p)) ||
3005 ar_ptr == arena_for_chunk(mem2chunk(p)));
3009 weak_alias (__libc_memalign, aligned_alloc)
3010 libc_hidden_def (__libc_memalign)
3013 __libc_valloc(size_t bytes)
3018 if(__malloc_initialized < 0)
3021 size_t pagesz = GLRO(dl_pagesize);
3023 __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, size_t,
3024 const __malloc_ptr_t)) =
3025 force_reg (__memalign_hook);
3026 if (__builtin_expect (hook != NULL, 0))
3027 return (*hook)(pagesz, bytes, RETURN_ADDRESS (0));
3029 arena_get(ar_ptr, bytes + pagesz + MINSIZE);
3032 p = _int_valloc(ar_ptr, bytes);
3033 (void)mutex_unlock(&ar_ptr->mutex);
3035 /* Maybe the failure is due to running out of mmapped areas. */
3036 if(ar_ptr != &main_arena) {
3037 ar_ptr = &main_arena;
3038 (void)mutex_lock(&ar_ptr->mutex);
3039 p = _int_memalign(ar_ptr, pagesz, bytes);
3040 (void)mutex_unlock(&ar_ptr->mutex);
3042 /* ... or sbrk() has failed and there is still a chance to mmap() */
3043 ar_ptr = arena_get2(ar_ptr->next ? ar_ptr : 0, bytes);
3045 p = _int_memalign(ar_ptr, pagesz, bytes);
3046 (void)mutex_unlock(&ar_ptr->mutex);
3050 assert(!p || chunk_is_mmapped(mem2chunk(p)) ||
3051 ar_ptr == arena_for_chunk(mem2chunk(p)));
3057 __libc_pvalloc(size_t bytes)
3062 if(__malloc_initialized < 0)
3065 size_t pagesz = GLRO(dl_pagesize);
3066 size_t page_mask = GLRO(dl_pagesize) - 1;
3067 size_t rounded_bytes = (bytes + page_mask) & ~(page_mask);
3069 __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, size_t,
3070 const __malloc_ptr_t)) =
3071 force_reg (__memalign_hook);
3072 if (__builtin_expect (hook != NULL, 0))
3073 return (*hook)(pagesz, rounded_bytes, RETURN_ADDRESS (0));
3075 arena_get(ar_ptr, bytes + 2*pagesz + MINSIZE);
3076 p = _int_pvalloc(ar_ptr, bytes);
3077 (void)mutex_unlock(&ar_ptr->mutex);
3079 /* Maybe the failure is due to running out of mmapped areas. */
3080 if(ar_ptr != &main_arena) {
3081 ar_ptr = &main_arena;
3082 (void)mutex_lock(&ar_ptr->mutex);
3083 p = _int_memalign(ar_ptr, pagesz, rounded_bytes);
3084 (void)mutex_unlock(&ar_ptr->mutex);
3086 /* ... or sbrk() has failed and there is still a chance to mmap() */
3087 ar_ptr = arena_get2(ar_ptr->next ? ar_ptr : 0,
3088 bytes + 2*pagesz + MINSIZE);
3090 p = _int_memalign(ar_ptr, pagesz, rounded_bytes);
3091 (void)mutex_unlock(&ar_ptr->mutex);
3095 assert(!p || chunk_is_mmapped(mem2chunk(p)) ||
3096 ar_ptr == arena_for_chunk(mem2chunk(p)));
3102 __libc_calloc(size_t n, size_t elem_size)
3105 mchunkptr oldtop, p;
3106 INTERNAL_SIZE_T bytes, sz, csz, oldtopsize;
3108 unsigned long clearsize;
3109 unsigned long nclears;
3112 /* size_t is unsigned so the behavior on overflow is defined. */
3113 bytes = n * elem_size;
3114 #define HALF_INTERNAL_SIZE_T \
3115 (((INTERNAL_SIZE_T) 1) << (8 * sizeof (INTERNAL_SIZE_T) / 2))
3116 if (__builtin_expect ((n | elem_size) >= HALF_INTERNAL_SIZE_T, 0)) {
3117 if (elem_size != 0 && bytes / elem_size != n) {
3118 __set_errno (ENOMEM);
3123 __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, const __malloc_ptr_t)) =
3124 force_reg (__malloc_hook);
3125 if (__builtin_expect (hook != NULL, 0)) {
3127 mem = (*hook)(sz, RETURN_ADDRESS (0));
3130 return memset(mem, 0, sz);
3139 /* Check if we hand out the top chunk, in which case there may be no
3143 oldtopsize = chunksize(top(av));
3144 #if MORECORE_CLEARS < 2
3145 /* Only newly allocated memory is guaranteed to be cleared. */
3146 if (av == &main_arena &&
3147 oldtopsize < mp_.sbrk_base + av->max_system_mem - (char *)oldtop)
3148 oldtopsize = (mp_.sbrk_base + av->max_system_mem - (char *)oldtop);
3150 if (av != &main_arena)
3152 heap_info *heap = heap_for_ptr (oldtop);
3153 if (oldtopsize < (char *) heap + heap->mprotect_size - (char *) oldtop)
3154 oldtopsize = (char *) heap + heap->mprotect_size - (char *) oldtop;
3157 mem = _int_malloc(av, sz);
3159 /* Only clearing follows, so we can unlock early. */
3160 (void)mutex_unlock(&av->mutex);
3162 assert(!mem || chunk_is_mmapped(mem2chunk(mem)) ||
3163 av == arena_for_chunk(mem2chunk(mem)));
3166 /* Maybe the failure is due to running out of mmapped areas. */
3167 if(av != &main_arena) {
3168 (void)mutex_lock(&main_arena.mutex);
3169 mem = _int_malloc(&main_arena, sz);
3170 (void)mutex_unlock(&main_arena.mutex);
3172 /* ... or sbrk() has failed and there is still a chance to mmap() */
3173 (void)mutex_lock(&main_arena.mutex);
3174 av = arena_get2(av->next ? av : 0, sz);
3175 (void)mutex_unlock(&main_arena.mutex);
3177 mem = _int_malloc(av, sz);
3178 (void)mutex_unlock(&av->mutex);
3181 if (mem == 0) return 0;
3185 /* Two optional cases in which clearing not necessary */
3186 if (chunk_is_mmapped (p))
3188 if (__builtin_expect (perturb_byte, 0))
3189 MALLOC_ZERO (mem, sz);
3196 if (perturb_byte == 0 && (p == oldtop && csz > oldtopsize)) {
3197 /* clear only the bytes from non-freshly-sbrked memory */
3202 /* Unroll clear of <= 36 bytes (72 if 8byte sizes). We know that
3203 contents have an odd number of INTERNAL_SIZE_T-sized words;
3205 d = (INTERNAL_SIZE_T*)mem;
3206 clearsize = csz - SIZE_SZ;
3207 nclears = clearsize / sizeof(INTERNAL_SIZE_T);
3208 assert(nclears >= 3);
3211 MALLOC_ZERO(d, clearsize);
3235 ------------------------------ malloc ------------------------------
3239 _int_malloc(mstate av, size_t bytes)
3241 INTERNAL_SIZE_T nb; /* normalized request size */
3242 unsigned int idx; /* associated bin index */
3243 mbinptr bin; /* associated bin */
3245 mchunkptr victim; /* inspected/selected chunk */
3246 INTERNAL_SIZE_T size; /* its size */
3247 int victim_index; /* its bin index */
3249 mchunkptr remainder; /* remainder from a split */
3250 unsigned long remainder_size; /* its size */
3252 unsigned int block; /* bit map traverser */
3253 unsigned int bit; /* bit map traverser */
3254 unsigned int map; /* current word of binmap */
3256 mchunkptr fwd; /* misc temp for linking */
3257 mchunkptr bck; /* misc temp for linking */
3259 const char *errstr = NULL;
3262 Convert request size to internal form by adding SIZE_SZ bytes
3263 overhead plus possibly more to obtain necessary alignment and/or
3264 to obtain a size of at least MINSIZE, the smallest allocatable
3265 size. Also, checked_request2size traps (returning 0) request sizes
3266 that are so large that they wrap around zero when padded and
3270 checked_request2size(bytes, nb);
3273 If the size qualifies as a fastbin, first check corresponding bin.
3274 This code is safe to execute even if av is not yet initialized, so we
3275 can try it without checking, which saves some time on this fast path.
3278 if ((unsigned long)(nb) <= (unsigned long)(get_max_fast ())) {
3279 idx = fastbin_index(nb);
3280 mfastbinptr* fb = &fastbin (av, idx);
3288 while ((pp = catomic_compare_and_exchange_val_acq (fb, victim->fd, victim))
3291 if (__builtin_expect (fastbin_index (chunksize (victim)) != idx, 0))
3293 errstr = "malloc(): memory corruption (fast)";
3295 malloc_printerr (check_action, errstr, chunk2mem (victim));
3298 check_remalloced_chunk(av, victim, nb);
3299 void *p = chunk2mem(victim);
3300 if (__builtin_expect (perturb_byte, 0))
3301 alloc_perturb (p, bytes);
3307 If a small request, check regular bin. Since these "smallbins"
3308 hold one size each, no searching within bins is necessary.
3309 (For a large request, we need to wait until unsorted chunks are
3310 processed to find best fit. But for small ones, fits are exact
3311 anyway, so we can check now, which is faster.)
3314 if (in_smallbin_range(nb)) {
3315 idx = smallbin_index(nb);
3316 bin = bin_at(av,idx);
3318 if ( (victim = last(bin)) != bin) {
3319 if (victim == 0) /* initialization check */
3320 malloc_consolidate(av);
3323 if (__builtin_expect (bck->fd != victim, 0))
3325 errstr = "malloc(): smallbin double linked list corrupted";
3328 set_inuse_bit_at_offset(victim, nb);
3332 if (av != &main_arena)
3333 victim->size |= NON_MAIN_ARENA;
3334 check_malloced_chunk(av, victim, nb);
3335 void *p = chunk2mem(victim);
3336 if (__builtin_expect (perturb_byte, 0))
3337 alloc_perturb (p, bytes);
3344 If this is a large request, consolidate fastbins before continuing.
3345 While it might look excessive to kill all fastbins before
3346 even seeing if there is space available, this avoids
3347 fragmentation problems normally associated with fastbins.
3348 Also, in practice, programs tend to have runs of either small or
3349 large requests, but less often mixtures, so consolidation is not
3350 invoked all that often in most programs. And the programs that
3351 it is called frequently in otherwise tend to fragment.
3355 idx = largebin_index(nb);
3356 if (have_fastchunks(av))
3357 malloc_consolidate(av);
3361 Process recently freed or remaindered chunks, taking one only if
3362 it is exact fit, or, if this a small request, the chunk is remainder from
3363 the most recent non-exact fit. Place other traversed chunks in
3364 bins. Note that this step is the only place in any routine where
3365 chunks are placed in bins.
3367 The outer loop here is needed because we might not realize until
3368 near the end of malloc that we should have consolidated, so must
3369 do so and retry. This happens at most once, and only when we would
3370 otherwise need to expand memory to service a "small" request.
3376 while ( (victim = unsorted_chunks(av)->bk) != unsorted_chunks(av)) {
3378 if (__builtin_expect (victim->size <= 2 * SIZE_SZ, 0)
3379 || __builtin_expect (victim->size > av->system_mem, 0))
3380 malloc_printerr (check_action, "malloc(): memory corruption",
3381 chunk2mem (victim));
3382 size = chunksize(victim);
3385 If a small request, try to use last remainder if it is the
3386 only chunk in unsorted bin. This helps promote locality for
3387 runs of consecutive small requests. This is the only
3388 exception to best-fit, and applies only when there is
3389 no exact fit for a small chunk.
3392 if (in_smallbin_range(nb) &&
3393 bck == unsorted_chunks(av) &&
3394 victim == av->last_remainder &&
3395 (unsigned long)(size) > (unsigned long)(nb + MINSIZE)) {
3397 /* split and reattach remainder */
3398 remainder_size = size - nb;
3399 remainder = chunk_at_offset(victim, nb);
3400 unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;
3401 av->last_remainder = remainder;
3402 remainder->bk = remainder->fd = unsorted_chunks(av);
3403 if (!in_smallbin_range(remainder_size))
3405 remainder->fd_nextsize = NULL;
3406 remainder->bk_nextsize = NULL;
3409 set_head(victim, nb | PREV_INUSE |
3410 (av != &main_arena ? NON_MAIN_ARENA : 0));
3411 set_head(remainder, remainder_size | PREV_INUSE);
3412 set_foot(remainder, remainder_size);
3414 check_malloced_chunk(av, victim, nb);
3415 void *p = chunk2mem(victim);
3416 if (__builtin_expect (perturb_byte, 0))
3417 alloc_perturb (p, bytes);
3421 /* remove from unsorted list */
3422 unsorted_chunks(av)->bk = bck;
3423 bck->fd = unsorted_chunks(av);
3425 /* Take now instead of binning if exact fit */
3428 set_inuse_bit_at_offset(victim, size);
3429 if (av != &main_arena)
3430 victim->size |= NON_MAIN_ARENA;
3431 check_malloced_chunk(av, victim, nb);
3432 void *p = chunk2mem(victim);
3433 if (__builtin_expect (perturb_byte, 0))
3434 alloc_perturb (p, bytes);
3438 /* place chunk in bin */
3440 if (in_smallbin_range(size)) {
3441 victim_index = smallbin_index(size);
3442 bck = bin_at(av, victim_index);
3446 victim_index = largebin_index(size);
3447 bck = bin_at(av, victim_index);
3450 /* maintain large bins in sorted order */
3452 /* Or with inuse bit to speed comparisons */
3454 /* if smaller than smallest, bypass loop below */
3455 assert((bck->bk->size & NON_MAIN_ARENA) == 0);
3456 if ((unsigned long)(size) < (unsigned long)(bck->bk->size)) {
3460 victim->fd_nextsize = fwd->fd;
3461 victim->bk_nextsize = fwd->fd->bk_nextsize;
3462 fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim;
3465 assert((fwd->size & NON_MAIN_ARENA) == 0);
3466 while ((unsigned long) size < fwd->size)
3468 fwd = fwd->fd_nextsize;
3469 assert((fwd->size & NON_MAIN_ARENA) == 0);
3472 if ((unsigned long) size == (unsigned long) fwd->size)
3473 /* Always insert in the second position. */
3477 victim->fd_nextsize = fwd;
3478 victim->bk_nextsize = fwd->bk_nextsize;
3479 fwd->bk_nextsize = victim;
3480 victim->bk_nextsize->fd_nextsize = victim;
3485 victim->fd_nextsize = victim->bk_nextsize = victim;
3488 mark_bin(av, victim_index);
3494 #define MAX_ITERS 10000
3495 if (++iters >= MAX_ITERS)
3500 If a large request, scan through the chunks of current bin in
3501 sorted order to find smallest that fits. Use the skip list for this.
3504 if (!in_smallbin_range(nb)) {
3505 bin = bin_at(av, idx);
3507 /* skip scan if empty or largest chunk is too small */
3508 if ((victim = first(bin)) != bin &&
3509 (unsigned long)(victim->size) >= (unsigned long)(nb)) {
3511 victim = victim->bk_nextsize;
3512 while (((unsigned long)(size = chunksize(victim)) <
3513 (unsigned long)(nb)))
3514 victim = victim->bk_nextsize;
3516 /* Avoid removing the first entry for a size so that the skip
3517 list does not have to be rerouted. */
3518 if (victim != last(bin) && victim->size == victim->fd->size)
3519 victim = victim->fd;
3521 remainder_size = size - nb;
3522 unlink(victim, bck, fwd);
3525 if (remainder_size < MINSIZE) {
3526 set_inuse_bit_at_offset(victim, size);
3527 if (av != &main_arena)
3528 victim->size |= NON_MAIN_ARENA;
3532 remainder = chunk_at_offset(victim, nb);
3533 /* We cannot assume the unsorted list is empty and therefore
3534 have to perform a complete insert here. */
3535 bck = unsorted_chunks(av);
3537 if (__builtin_expect (fwd->bk != bck, 0))
3539 errstr = "malloc(): corrupted unsorted chunks";
3542 remainder->bk = bck;
3543 remainder->fd = fwd;
3544 bck->fd = remainder;
3545 fwd->bk = remainder;
3546 if (!in_smallbin_range(remainder_size))
3548 remainder->fd_nextsize = NULL;
3549 remainder->bk_nextsize = NULL;
3551 set_head(victim, nb | PREV_INUSE |
3552 (av != &main_arena ? NON_MAIN_ARENA : 0));
3553 set_head(remainder, remainder_size | PREV_INUSE);
3554 set_foot(remainder, remainder_size);
3556 check_malloced_chunk(av, victim, nb);
3557 void *p = chunk2mem(victim);
3558 if (__builtin_expect (perturb_byte, 0))
3559 alloc_perturb (p, bytes);
3565 Search for a chunk by scanning bins, starting with next largest
3566 bin. This search is strictly by best-fit; i.e., the smallest
3567 (with ties going to approximately the least recently used) chunk
3568 that fits is selected.
3570 The bitmap avoids needing to check that most blocks are nonempty.
3571 The particular case of skipping all bins during warm-up phases
3572 when no chunks have been returned yet is faster than it might look.
3576 bin = bin_at(av,idx);
3577 block = idx2block(idx);
3578 map = av->binmap[block];
3583 /* Skip rest of block if there are no more set bits in this block. */
3584 if (bit > map || bit == 0) {
3586 if (++block >= BINMAPSIZE) /* out of bins */
3588 } while ( (map = av->binmap[block]) == 0);
3590 bin = bin_at(av, (block << BINMAPSHIFT));
3594 /* Advance to bin with set bit. There must be one. */
3595 while ((bit & map) == 0) {
3596 bin = next_bin(bin);
3601 /* Inspect the bin. It is likely to be non-empty */
3604 /* If a false alarm (empty bin), clear the bit. */
3605 if (victim == bin) {
3606 av->binmap[block] = map &= ~bit; /* Write through */
3607 bin = next_bin(bin);
3612 size = chunksize(victim);
3614 /* We know the first chunk in this bin is big enough to use. */
3615 assert((unsigned long)(size) >= (unsigned long)(nb));
3617 remainder_size = size - nb;
3620 unlink(victim, bck, fwd);
3623 if (remainder_size < MINSIZE) {
3624 set_inuse_bit_at_offset(victim, size);
3625 if (av != &main_arena)
3626 victim->size |= NON_MAIN_ARENA;
3631 remainder = chunk_at_offset(victim, nb);
3633 /* We cannot assume the unsorted list is empty and therefore
3634 have to perform a complete insert here. */
3635 bck = unsorted_chunks(av);
3637 if (__builtin_expect (fwd->bk != bck, 0))
3639 errstr = "malloc(): corrupted unsorted chunks 2";
3642 remainder->bk = bck;
3643 remainder->fd = fwd;
3644 bck->fd = remainder;
3645 fwd->bk = remainder;
3647 /* advertise as last remainder */
3648 if (in_smallbin_range(nb))
3649 av->last_remainder = remainder;
3650 if (!in_smallbin_range(remainder_size))
3652 remainder->fd_nextsize = NULL;
3653 remainder->bk_nextsize = NULL;
3655 set_head(victim, nb | PREV_INUSE |
3656 (av != &main_arena ? NON_MAIN_ARENA : 0));
3657 set_head(remainder, remainder_size | PREV_INUSE);
3658 set_foot(remainder, remainder_size);
3660 check_malloced_chunk(av, victim, nb);
3661 void *p = chunk2mem(victim);
3662 if (__builtin_expect (perturb_byte, 0))
3663 alloc_perturb (p, bytes);
3670 If large enough, split off the chunk bordering the end of memory
3671 (held in av->top). Note that this is in accord with the best-fit
3672 search rule. In effect, av->top is treated as larger (and thus
3673 less well fitting) than any other available chunk since it can
3674 be extended to be as large as necessary (up to system
3677 We require that av->top always exists (i.e., has size >=
3678 MINSIZE) after initialization, so if it would otherwise be
3679 exhausted by current request, it is replenished. (The main
3680 reason for ensuring it exists is that we may need MINSIZE space
3681 to put in fenceposts in sysmalloc.)
3685 size = chunksize(victim);
3687 if ((unsigned long)(size) >= (unsigned long)(nb + MINSIZE)) {
3688 remainder_size = size - nb;
3689 remainder = chunk_at_offset(victim, nb);
3690 av->top = remainder;
3691 set_head(victim, nb | PREV_INUSE |
3692 (av != &main_arena ? NON_MAIN_ARENA : 0));
3693 set_head(remainder, remainder_size | PREV_INUSE);
3695 check_malloced_chunk(av, victim, nb);
3696 void *p = chunk2mem(victim);
3697 if (__builtin_expect (perturb_byte, 0))
3698 alloc_perturb (p, bytes);
3702 /* When we are using atomic ops to free fast chunks we can get
3703 here for all block sizes. */
3704 else if (have_fastchunks(av)) {
3705 malloc_consolidate(av);
3706 /* restore original bin index */
3707 if (in_smallbin_range(nb))
3708 idx = smallbin_index(nb);
3710 idx = largebin_index(nb);
3714 Otherwise, relay to handle system-dependent cases
3717 void *p = sysmalloc(nb, av);
3718 if (p != NULL && __builtin_expect (perturb_byte, 0))
3719 alloc_perturb (p, bytes);
3726 ------------------------------ free ------------------------------
3730 _int_free(mstate av, mchunkptr p, int have_lock)
3732 INTERNAL_SIZE_T size; /* its size */
3733 mfastbinptr* fb; /* associated fastbin */
3734 mchunkptr nextchunk; /* next contiguous chunk */
3735 INTERNAL_SIZE_T nextsize; /* its size */
3736 int nextinuse; /* true if nextchunk is used */
3737 INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */
3738 mchunkptr bck; /* misc temp for linking */
3739 mchunkptr fwd; /* misc temp for linking */
3741 const char *errstr = NULL;
3744 size = chunksize(p);
3746 /* Little security check which won't hurt performance: the
3747 allocator never wrapps around at the end of the address space.
3748 Therefore we can exclude some size values which might appear
3749 here by accident or by "design" from some intruder. */
3750 if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0)
3751 || __builtin_expect (misaligned_chunk (p), 0))
3753 errstr = "free(): invalid pointer";
3755 if (! have_lock && locked)
3756 (void)mutex_unlock(&av->mutex);
3757 malloc_printerr (check_action, errstr, chunk2mem(p));
3760 /* We know that each chunk is at least MINSIZE bytes in size. */
3761 if (__builtin_expect (size < MINSIZE, 0))
3763 errstr = "free(): invalid size";
3767 check_inuse_chunk(av, p);
3770 If eligible, place chunk on a fastbin so it can be found
3771 and used quickly in malloc.
3774 if ((unsigned long)(size) <= (unsigned long)(get_max_fast ())
3778 If TRIM_FASTBINS set, don't place chunks
3779 bordering top into fastbins
3781 && (chunk_at_offset(p, size) != av->top)
3785 if (__builtin_expect (chunk_at_offset (p, size)->size <= 2 * SIZE_SZ, 0)
3786 || __builtin_expect (chunksize (chunk_at_offset (p, size))
3787 >= av->system_mem, 0))
3789 /* We might not have a lock at this point and concurrent modifications
3790 of system_mem might have let to a false positive. Redo the test
3791 after getting the lock. */
3793 || ({ assert (locked == 0);
3794 mutex_lock(&av->mutex);
3796 chunk_at_offset (p, size)->size <= 2 * SIZE_SZ
3797 || chunksize (chunk_at_offset (p, size)) >= av->system_mem;
3800 errstr = "free(): invalid next size (fast)";
3805 (void)mutex_unlock(&av->mutex);
3810 if (__builtin_expect (perturb_byte, 0))
3811 free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);
3814 unsigned int idx = fastbin_index(size);
3815 fb = &fastbin (av, idx);
3818 mchunkptr old = *fb;
3819 unsigned int old_idx = ~0u;
3822 /* Another simple check: make sure the top of the bin is not the
3823 record we are going to add (i.e., double free). */
3824 if (__builtin_expect (old == p, 0))
3826 errstr = "double free or corruption (fasttop)";
3830 old_idx = fastbin_index(chunksize(old));
3833 while ((old = catomic_compare_and_exchange_val_rel (fb, p, fd)) != fd);
3835 if (fd != NULL && __builtin_expect (old_idx != idx, 0))
3837 errstr = "invalid fastbin entry (free)";
3843 Consolidate other non-mmapped chunks as they arrive.
3846 else if (!chunk_is_mmapped(p)) {
3849 if(!mutex_trylock(&av->mutex))
3850 ++(av->stat_lock_direct);
3852 (void)mutex_lock(&av->mutex);
3853 ++(av->stat_lock_wait);
3856 (void)mutex_lock(&av->mutex);
3861 nextchunk = chunk_at_offset(p, size);
3863 /* Lightweight tests: check whether the block is already the
3865 if (__builtin_expect (p == av->top, 0))
3867 errstr = "double free or corruption (top)";
3870 /* Or whether the next chunk is beyond the boundaries of the arena. */
3871 if (__builtin_expect (contiguous (av)
3872 && (char *) nextchunk
3873 >= ((char *) av->top + chunksize(av->top)), 0))
3875 errstr = "double free or corruption (out)";
3878 /* Or whether the block is actually not marked used. */
3879 if (__builtin_expect (!prev_inuse(nextchunk), 0))
3881 errstr = "double free or corruption (!prev)";
3885 nextsize = chunksize(nextchunk);
3886 if (__builtin_expect (nextchunk->size <= 2 * SIZE_SZ, 0)
3887 || __builtin_expect (nextsize >= av->system_mem, 0))
3889 errstr = "free(): invalid next size (normal)";
3893 if (__builtin_expect (perturb_byte, 0))
3894 free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);
3896 /* consolidate backward */
3897 if (!prev_inuse(p)) {
3898 prevsize = p->prev_size;
3900 p = chunk_at_offset(p, -((long) prevsize));
3901 unlink(p, bck, fwd);
3904 if (nextchunk != av->top) {
3905 /* get and clear inuse bit */
3906 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
3908 /* consolidate forward */
3910 unlink(nextchunk, bck, fwd);
3913 clear_inuse_bit_at_offset(nextchunk, 0);
3916 Place the chunk in unsorted chunk list. Chunks are
3917 not placed into regular bins until after they have
3918 been given one chance to be used in malloc.
3921 bck = unsorted_chunks(av);
3923 if (__builtin_expect (fwd->bk != bck, 0))
3925 errstr = "free(): corrupted unsorted chunks";
3930 if (!in_smallbin_range(size))
3932 p->fd_nextsize = NULL;
3933 p->bk_nextsize = NULL;
3938 set_head(p, size | PREV_INUSE);
3941 check_free_chunk(av, p);
3945 If the chunk borders the current high end of memory,
3946 consolidate into top
3951 set_head(p, size | PREV_INUSE);
3957 If freeing a large space, consolidate possibly-surrounding
3958 chunks. Then, if the total unused topmost memory exceeds trim
3959 threshold, ask malloc_trim to reduce top.
3961 Unless max_fast is 0, we don't know if there are fastbins
3962 bordering top, so we cannot tell for sure whether threshold
3963 has been reached unless fastbins are consolidated. But we
3964 don't want to consolidate on each free. As a compromise,
3965 consolidation is performed if FASTBIN_CONSOLIDATION_THRESHOLD
3969 if ((unsigned long)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) {
3970 if (have_fastchunks(av))
3971 malloc_consolidate(av);
3973 if (av == &main_arena) {
3974 #ifndef MORECORE_CANNOT_TRIM
3975 if ((unsigned long)(chunksize(av->top)) >=
3976 (unsigned long)(mp_.trim_threshold))
3977 systrim(mp_.top_pad, av);
3980 /* Always try heap_trim(), even if the top chunk is not
3981 large, because the corresponding heap might go away. */
3982 heap_info *heap = heap_for_ptr(top(av));
3984 assert(heap->ar_ptr == av);
3985 heap_trim(heap, mp_.top_pad);
3991 (void)mutex_unlock(&av->mutex);
3995 If the chunk was allocated via mmap, release via munmap().
4004 ------------------------- malloc_consolidate -------------------------
4006 malloc_consolidate is a specialized version of free() that tears
4007 down chunks held in fastbins. Free itself cannot be used for this
4008 purpose since, among other things, it might place chunks back onto
4009 fastbins. So, instead, we need to use a minor variant of the same
4012 Also, because this routine needs to be called the first time through
4013 malloc anyway, it turns out to be the perfect place to trigger
4014 initialization code.
4017 static void malloc_consolidate(mstate av)
4019 mfastbinptr* fb; /* current fastbin being consolidated */
4020 mfastbinptr* maxfb; /* last fastbin (for loop control) */
4021 mchunkptr p; /* current chunk being consolidated */
4022 mchunkptr nextp; /* next chunk to consolidate */
4023 mchunkptr unsorted_bin; /* bin header */
4024 mchunkptr first_unsorted; /* chunk to link to */
4026 /* These have same use as in free() */
4027 mchunkptr nextchunk;
4028 INTERNAL_SIZE_T size;
4029 INTERNAL_SIZE_T nextsize;
4030 INTERNAL_SIZE_T prevsize;
4036 If max_fast is 0, we know that av hasn't
4037 yet been initialized, in which case do so below
4040 if (get_max_fast () != 0) {
4041 clear_fastchunks(av);
4043 unsorted_bin = unsorted_chunks(av);
4046 Remove each chunk from fast bin and consolidate it, placing it
4047 then in unsorted bin. Among other reasons for doing this,
4048 placing in unsorted bin avoids needing to calculate actual bins
4049 until malloc is sure that chunks aren't immediately going to be
4053 maxfb = &fastbin (av, NFASTBINS - 1);
4054 fb = &fastbin (av, 0);
4056 p = atomic_exchange_acq (fb, 0);
4059 check_inuse_chunk(av, p);
4062 /* Slightly streamlined version of consolidation code in free() */
4063 size = p->size & ~(PREV_INUSE|NON_MAIN_ARENA);
4064 nextchunk = chunk_at_offset(p, size);
4065 nextsize = chunksize(nextchunk);
4067 if (!prev_inuse(p)) {
4068 prevsize = p->prev_size;
4070 p = chunk_at_offset(p, -((long) prevsize));
4071 unlink(p, bck, fwd);
4074 if (nextchunk != av->top) {
4075 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4079 unlink(nextchunk, bck, fwd);
4081 clear_inuse_bit_at_offset(nextchunk, 0);
4083 first_unsorted = unsorted_bin->fd;
4084 unsorted_bin->fd = p;
4085 first_unsorted->bk = p;
4087 if (!in_smallbin_range (size)) {
4088 p->fd_nextsize = NULL;
4089 p->bk_nextsize = NULL;
4092 set_head(p, size | PREV_INUSE);
4093 p->bk = unsorted_bin;
4094 p->fd = first_unsorted;
4100 set_head(p, size | PREV_INUSE);
4104 } while ( (p = nextp) != 0);
4107 } while (fb++ != maxfb);
4110 malloc_init_state(av);
4111 check_malloc_state(av);
4116 ------------------------------ realloc ------------------------------
4120 _int_realloc(mstate av, mchunkptr oldp, INTERNAL_SIZE_T oldsize,
4123 mchunkptr newp; /* chunk to return */
4124 INTERNAL_SIZE_T newsize; /* its size */
4125 void* newmem; /* corresponding user mem */
4127 mchunkptr next; /* next contiguous chunk after oldp */
4129 mchunkptr remainder; /* extra space at end of newp */
4130 unsigned long remainder_size; /* its size */
4132 mchunkptr bck; /* misc temp for linking */
4133 mchunkptr fwd; /* misc temp for linking */
4135 unsigned long copysize; /* bytes to copy */
4136 unsigned int ncopies; /* INTERNAL_SIZE_T words to copy */
4137 INTERNAL_SIZE_T* s; /* copy source */
4138 INTERNAL_SIZE_T* d; /* copy destination */
4140 const char *errstr = NULL;
4143 if (__builtin_expect (oldp->size <= 2 * SIZE_SZ, 0)
4144 || __builtin_expect (oldsize >= av->system_mem, 0))
4146 errstr = "realloc(): invalid old size";
4148 malloc_printerr (check_action, errstr, chunk2mem(oldp));
4152 check_inuse_chunk(av, oldp);
4154 /* All callers already filter out mmap'ed chunks. */
4155 assert (!chunk_is_mmapped(oldp));
4157 next = chunk_at_offset(oldp, oldsize);
4158 INTERNAL_SIZE_T nextsize = chunksize(next);
4159 if (__builtin_expect (next->size <= 2 * SIZE_SZ, 0)
4160 || __builtin_expect (nextsize >= av->system_mem, 0))
4162 errstr = "realloc(): invalid next size";
4166 if ((unsigned long)(oldsize) >= (unsigned long)(nb)) {
4167 /* already big enough; split below */
4173 /* Try to expand forward into top */
4174 if (next == av->top &&
4175 (unsigned long)(newsize = oldsize + nextsize) >=
4176 (unsigned long)(nb + MINSIZE)) {
4177 set_head_size(oldp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4178 av->top = chunk_at_offset(oldp, nb);
4179 set_head(av->top, (newsize - nb) | PREV_INUSE);
4180 check_inuse_chunk(av, oldp);
4181 return chunk2mem(oldp);
4184 /* Try to expand forward into next chunk; split off remainder below */
4185 else if (next != av->top &&
4187 (unsigned long)(newsize = oldsize + nextsize) >=
4188 (unsigned long)(nb)) {
4190 unlink(next, bck, fwd);
4193 /* allocate, copy, free */
4195 newmem = _int_malloc(av, nb - MALLOC_ALIGN_MASK);
4197 return 0; /* propagate failure */
4199 newp = mem2chunk(newmem);
4200 newsize = chunksize(newp);
4203 Avoid copy if newp is next chunk after oldp.
4211 Unroll copy of <= 36 bytes (72 if 8byte sizes)
4212 We know that contents have an odd number of
4213 INTERNAL_SIZE_T-sized words; minimally 3.
4216 copysize = oldsize - SIZE_SZ;
4217 s = (INTERNAL_SIZE_T*)(chunk2mem(oldp));
4218 d = (INTERNAL_SIZE_T*)(newmem);
4219 ncopies = copysize / sizeof(INTERNAL_SIZE_T);
4220 assert(ncopies >= 3);
4223 MALLOC_COPY(d, s, copysize);
4243 _int_free(av, oldp, 1);
4244 check_inuse_chunk(av, newp);
4245 return chunk2mem(newp);
4250 /* If possible, free extra space in old or extended chunk */
4252 assert((unsigned long)(newsize) >= (unsigned long)(nb));
4254 remainder_size = newsize - nb;
4256 if (remainder_size < MINSIZE) { /* not enough extra to split off */
4257 set_head_size(newp, newsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4258 set_inuse_bit_at_offset(newp, newsize);
4260 else { /* split remainder */
4261 remainder = chunk_at_offset(newp, nb);
4262 set_head_size(newp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4263 set_head(remainder, remainder_size | PREV_INUSE |
4264 (av != &main_arena ? NON_MAIN_ARENA : 0));
4265 /* Mark remainder as inuse so free() won't complain */
4266 set_inuse_bit_at_offset(remainder, remainder_size);
4267 _int_free(av, remainder, 1);
4270 check_inuse_chunk(av, newp);
4271 return chunk2mem(newp);
4275 ------------------------------ memalign ------------------------------
4279 _int_memalign(mstate av, size_t alignment, size_t bytes)
4281 INTERNAL_SIZE_T nb; /* padded request size */
4282 char* m; /* memory returned by malloc call */
4283 mchunkptr p; /* corresponding chunk */
4284 char* brk; /* alignment point within p */
4285 mchunkptr newp; /* chunk to return */
4286 INTERNAL_SIZE_T newsize; /* its size */
4287 INTERNAL_SIZE_T leadsize; /* leading space before alignment point */
4288 mchunkptr remainder; /* spare room at end to split off */
4289 unsigned long remainder_size; /* its size */
4290 INTERNAL_SIZE_T size;
4292 /* If need less alignment than we give anyway, just relay to malloc */
4294 if (alignment <= MALLOC_ALIGNMENT) return _int_malloc(av, bytes);
4296 /* Otherwise, ensure that it is at least a minimum chunk size */
4298 if (alignment < MINSIZE) alignment = MINSIZE;
4300 /* Make sure alignment is power of 2 (in case MINSIZE is not). */
4301 if ((alignment & (alignment - 1)) != 0) {
4302 size_t a = MALLOC_ALIGNMENT * 2;
4303 while ((unsigned long)a < (unsigned long)alignment) a <<= 1;
4307 checked_request2size(bytes, nb);
4310 Strategy: find a spot within that chunk that meets the alignment
4311 request, and then possibly free the leading and trailing space.
4315 /* Call malloc with worst case padding to hit alignment. */
4317 m = (char*)(_int_malloc(av, nb + alignment + MINSIZE));
4319 if (m == 0) return 0; /* propagate failure */
4323 if ((((unsigned long)(m)) % alignment) != 0) { /* misaligned */
4326 Find an aligned spot inside chunk. Since we need to give back
4327 leading space in a chunk of at least MINSIZE, if the first
4328 calculation places us at a spot with less than MINSIZE leader,
4329 we can move to the next aligned spot -- we've allocated enough
4330 total room so that this is always possible.
4333 brk = (char*)mem2chunk(((unsigned long)(m + alignment - 1)) &
4334 -((signed long) alignment));
4335 if ((unsigned long)(brk - (char*)(p)) < MINSIZE)
4338 newp = (mchunkptr)brk;
4339 leadsize = brk - (char*)(p);
4340 newsize = chunksize(p) - leadsize;
4342 /* For mmapped chunks, just adjust offset */
4343 if (chunk_is_mmapped(p)) {
4344 newp->prev_size = p->prev_size + leadsize;
4345 set_head(newp, newsize|IS_MMAPPED);
4346 return chunk2mem(newp);
4349 /* Otherwise, give back leader, use the rest */
4350 set_head(newp, newsize | PREV_INUSE |
4351 (av != &main_arena ? NON_MAIN_ARENA : 0));
4352 set_inuse_bit_at_offset(newp, newsize);
4353 set_head_size(p, leadsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4354 _int_free(av, p, 1);
4357 assert (newsize >= nb &&
4358 (((unsigned long)(chunk2mem(p))) % alignment) == 0);
4361 /* Also give back spare room at the end */
4362 if (!chunk_is_mmapped(p)) {
4363 size = chunksize(p);
4364 if ((unsigned long)(size) > (unsigned long)(nb + MINSIZE)) {
4365 remainder_size = size - nb;
4366 remainder = chunk_at_offset(p, nb);
4367 set_head(remainder, remainder_size | PREV_INUSE |
4368 (av != &main_arena ? NON_MAIN_ARENA : 0));
4369 set_head_size(p, nb);
4370 _int_free(av, remainder, 1);
4374 check_inuse_chunk(av, p);
4375 return chunk2mem(p);
4380 ------------------------------ valloc ------------------------------
4384 _int_valloc(mstate av, size_t bytes)
4386 /* Ensure initialization/consolidation */
4387 if (have_fastchunks(av)) malloc_consolidate(av);
4388 return _int_memalign(av, GLRO(dl_pagesize), bytes);
4392 ------------------------------ pvalloc ------------------------------
4397 _int_pvalloc(mstate av, size_t bytes)
4401 /* Ensure initialization/consolidation */
4402 if (have_fastchunks(av)) malloc_consolidate(av);
4403 pagesz = GLRO(dl_pagesize);
4404 return _int_memalign(av, pagesz, (bytes + pagesz - 1) & ~(pagesz - 1));
4409 ------------------------------ malloc_trim ------------------------------
4412 static int mtrim(mstate av, size_t pad)
4414 /* Ensure initialization/consolidation */
4415 malloc_consolidate (av);
4417 const size_t ps = GLRO(dl_pagesize);
4418 int psindex = bin_index (ps);
4419 const size_t psm1 = ps - 1;
4422 for (int i = 1; i < NBINS; ++i)
4423 if (i == 1 || i >= psindex)
4425 mbinptr bin = bin_at (av, i);
4427 for (mchunkptr p = last (bin); p != bin; p = p->bk)
4429 INTERNAL_SIZE_T size = chunksize (p);
4431 if (size > psm1 + sizeof (struct malloc_chunk))
4433 /* See whether the chunk contains at least one unused page. */
4434 char *paligned_mem = (char *) (((uintptr_t) p
4435 + sizeof (struct malloc_chunk)
4438 assert ((char *) chunk2mem (p) + 4 * SIZE_SZ <= paligned_mem);
4439 assert ((char *) p + size > paligned_mem);
4441 /* This is the size we could potentially free. */
4442 size -= paligned_mem - (char *) p;
4447 /* When debugging we simulate destroying the memory
4449 memset (paligned_mem, 0x89, size & ~psm1);
4451 madvise (paligned_mem, size & ~psm1, MADV_DONTNEED);
4459 #ifndef MORECORE_CANNOT_TRIM
4460 return result | (av == &main_arena ? systrim (pad, av) : 0);
4468 __malloc_trim(size_t s)
4472 if(__malloc_initialized < 0)
4475 mstate ar_ptr = &main_arena;
4478 (void) mutex_lock (&ar_ptr->mutex);
4479 result |= mtrim (ar_ptr, s);
4480 (void) mutex_unlock (&ar_ptr->mutex);
4482 ar_ptr = ar_ptr->next;
4484 while (ar_ptr != &main_arena);
4491 ------------------------- malloc_usable_size -------------------------
4500 if (chunk_is_mmapped(p))
4501 return chunksize(p) - 2*SIZE_SZ;
4503 return chunksize(p) - SIZE_SZ;
4510 __malloc_usable_size(void* m)
4514 result = musable(m);
4519 ------------------------------ mallinfo ------------------------------
4520 Accumulate malloc statistics for arena AV into M.
4524 int_mallinfo(mstate av, struct mallinfo *m)
4529 INTERNAL_SIZE_T avail;
4530 INTERNAL_SIZE_T fastavail;
4534 /* Ensure initialization */
4535 if (av->top == 0) malloc_consolidate(av);
4537 check_malloc_state(av);
4539 /* Account for top */
4540 avail = chunksize(av->top);
4541 nblocks = 1; /* top always exists */
4543 /* traverse fastbins */
4547 for (i = 0; i < NFASTBINS; ++i) {
4548 for (p = fastbin (av, i); p != 0; p = p->fd) {
4550 fastavail += chunksize(p);
4556 /* traverse regular bins */
4557 for (i = 1; i < NBINS; ++i) {
4559 for (p = last(b); p != b; p = p->bk) {
4561 avail += chunksize(p);
4565 m->smblks += nfastblocks;
4566 m->ordblks += nblocks;
4567 m->fordblks += avail;
4568 m->uordblks += av->system_mem - avail;
4569 m->arena += av->system_mem;
4570 m->fsmblks += fastavail;
4571 if (av == &main_arena)
4573 m->hblks = mp_.n_mmaps;
4574 m->hblkhd = mp_.mmapped_mem;
4575 m->usmblks = mp_.max_total_mem;
4576 m->keepcost = chunksize(av->top);
4581 struct mallinfo __libc_mallinfo()
4586 if(__malloc_initialized < 0)
4589 memset(&m, 0, sizeof (m));
4590 ar_ptr = &main_arena;
4592 (void)mutex_lock(&ar_ptr->mutex);
4593 int_mallinfo(ar_ptr, &m);
4594 (void)mutex_unlock(&ar_ptr->mutex);
4596 ar_ptr = ar_ptr->next;
4597 } while (ar_ptr != &main_arena);
4603 ------------------------------ malloc_stats ------------------------------
4611 unsigned int in_use_b = mp_.mmapped_mem, system_b = in_use_b;
4613 long stat_lock_direct = 0, stat_lock_loop = 0, stat_lock_wait = 0;
4616 if(__malloc_initialized < 0)
4618 _IO_flockfile (stderr);
4619 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
4620 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
4621 for (i=0, ar_ptr = &main_arena;; i++) {
4624 memset(&mi, 0, sizeof(mi));
4625 (void)mutex_lock(&ar_ptr->mutex);
4626 int_mallinfo(ar_ptr, &mi);
4627 fprintf(stderr, "Arena %d:\n", i);
4628 fprintf(stderr, "system bytes = %10u\n", (unsigned int)mi.arena);
4629 fprintf(stderr, "in use bytes = %10u\n", (unsigned int)mi.uordblks);
4630 #if MALLOC_DEBUG > 1
4632 dump_heap(heap_for_ptr(top(ar_ptr)));
4634 system_b += mi.arena;
4635 in_use_b += mi.uordblks;
4637 stat_lock_direct += ar_ptr->stat_lock_direct;
4638 stat_lock_loop += ar_ptr->stat_lock_loop;
4639 stat_lock_wait += ar_ptr->stat_lock_wait;
4641 (void)mutex_unlock(&ar_ptr->mutex);
4642 ar_ptr = ar_ptr->next;
4643 if(ar_ptr == &main_arena) break;
4645 fprintf(stderr, "Total (incl. mmap):\n");
4646 fprintf(stderr, "system bytes = %10u\n", system_b);
4647 fprintf(stderr, "in use bytes = %10u\n", in_use_b);
4648 fprintf(stderr, "max mmap regions = %10u\n", (unsigned int)mp_.max_n_mmaps);
4649 fprintf(stderr, "max mmap bytes = %10lu\n",
4650 (unsigned long)mp_.max_mmapped_mem);
4652 fprintf(stderr, "heaps created = %10d\n", stat_n_heaps);
4653 fprintf(stderr, "locked directly = %10ld\n", stat_lock_direct);
4654 fprintf(stderr, "locked in loop = %10ld\n", stat_lock_loop);
4655 fprintf(stderr, "locked waiting = %10ld\n", stat_lock_wait);
4656 fprintf(stderr, "locked total = %10ld\n",
4657 stat_lock_direct + stat_lock_loop + stat_lock_wait);
4659 ((_IO_FILE *) stderr)->_flags2 |= old_flags2;
4660 _IO_funlockfile (stderr);
4665 ------------------------------ mallopt ------------------------------
4668 int __libc_mallopt(int param_number, int value)
4670 mstate av = &main_arena;
4673 if(__malloc_initialized < 0)
4675 (void)mutex_lock(&av->mutex);
4676 /* Ensure initialization/consolidation */
4677 malloc_consolidate(av);
4679 switch(param_number) {
4681 if (value >= 0 && value <= MAX_FAST_SIZE) {
4682 set_max_fast(value);
4688 case M_TRIM_THRESHOLD:
4689 mp_.trim_threshold = value;
4690 mp_.no_dyn_threshold = 1;
4694 mp_.top_pad = value;
4695 mp_.no_dyn_threshold = 1;
4698 case M_MMAP_THRESHOLD:
4699 /* Forbid setting the threshold too high. */
4700 if((unsigned long)value > HEAP_MAX_SIZE/2)
4703 mp_.mmap_threshold = value;
4704 mp_.no_dyn_threshold = 1;
4708 mp_.n_mmaps_max = value;
4709 mp_.no_dyn_threshold = 1;
4712 case M_CHECK_ACTION:
4713 check_action = value;
4717 perturb_byte = value;
4723 mp_.arena_test = value;
4728 mp_.arena_max = value;
4732 (void)mutex_unlock(&av->mutex);
4735 libc_hidden_def (__libc_mallopt)
4739 -------------------- Alternative MORECORE functions --------------------
4744 General Requirements for MORECORE.
4746 The MORECORE function must have the following properties:
4748 If MORECORE_CONTIGUOUS is false:
4750 * MORECORE must allocate in multiples of pagesize. It will
4751 only be called with arguments that are multiples of pagesize.
4753 * MORECORE(0) must return an address that is at least
4754 MALLOC_ALIGNMENT aligned. (Page-aligning always suffices.)
4756 else (i.e. If MORECORE_CONTIGUOUS is true):
4758 * Consecutive calls to MORECORE with positive arguments
4759 return increasing addresses, indicating that space has been
4760 contiguously extended.
4762 * MORECORE need not allocate in multiples of pagesize.
4763 Calls to MORECORE need not have args of multiples of pagesize.
4765 * MORECORE need not page-align.
4769 * MORECORE may allocate more memory than requested. (Or even less,
4770 but this will generally result in a malloc failure.)
4772 * MORECORE must not allocate memory when given argument zero, but
4773 instead return one past the end address of memory from previous
4774 nonzero call. This malloc does NOT call MORECORE(0)
4775 until at least one call with positive arguments is made, so
4776 the initial value returned is not important.
4778 * Even though consecutive calls to MORECORE need not return contiguous
4779 addresses, it must be OK for malloc'ed chunks to span multiple
4780 regions in those cases where they do happen to be contiguous.
4782 * MORECORE need not handle negative arguments -- it may instead
4783 just return MORECORE_FAILURE when given negative arguments.
4784 Negative arguments are always multiples of pagesize. MORECORE
4785 must not misinterpret negative args as large positive unsigned
4786 args. You can suppress all such calls from even occurring by defining
4787 MORECORE_CANNOT_TRIM,
4789 There is some variation across systems about the type of the
4790 argument to sbrk/MORECORE. If size_t is unsigned, then it cannot
4791 actually be size_t, because sbrk supports negative args, so it is
4792 normally the signed type of the same width as size_t (sometimes
4793 declared as "intptr_t", and sometimes "ptrdiff_t"). It doesn't much
4794 matter though. Internally, we use "long" as arguments, which should
4795 work across all reasonable possibilities.
4797 Additionally, if MORECORE ever returns failure for a positive
4798 request, then mmap is used as a noncontiguous system allocator. This
4799 is a useful backup strategy for systems with holes in address spaces
4800 -- in this case sbrk cannot contiguously expand the heap, but mmap
4801 may be able to map noncontiguous space.
4803 If you'd like mmap to ALWAYS be used, you can define MORECORE to be
4804 a function that always returns MORECORE_FAILURE.
4806 If you are using this malloc with something other than sbrk (or its
4807 emulation) to supply memory regions, you probably want to set
4808 MORECORE_CONTIGUOUS as false. As an example, here is a custom
4809 allocator kindly contributed for pre-OSX macOS. It uses virtually
4810 but not necessarily physically contiguous non-paged memory (locked
4811 in, present and won't get swapped out). You can use it by
4812 uncommenting this section, adding some #includes, and setting up the
4813 appropriate defines above:
4815 #define MORECORE osMoreCore
4816 #define MORECORE_CONTIGUOUS 0
4818 There is also a shutdown routine that should somehow be called for
4819 cleanup upon program exit.
4821 #define MAX_POOL_ENTRIES 100
4822 #define MINIMUM_MORECORE_SIZE (64 * 1024)
4823 static int next_os_pool;
4824 void *our_os_pools[MAX_POOL_ENTRIES];
4826 void *osMoreCore(int size)
4829 static void *sbrk_top = 0;
4833 if (size < MINIMUM_MORECORE_SIZE)
4834 size = MINIMUM_MORECORE_SIZE;
4835 if (CurrentExecutionLevel() == kTaskLevel)
4836 ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
4839 return (void *) MORECORE_FAILURE;
4841 // save ptrs so they can be freed during cleanup
4842 our_os_pools[next_os_pool] = ptr;
4844 ptr = (void *) ((((unsigned long) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
4845 sbrk_top = (char *) ptr + size;
4850 // we don't currently support shrink behavior
4851 return (void *) MORECORE_FAILURE;
4859 // cleanup any allocated memory pools
4860 // called as last thing before shutting down driver
4862 void osCleanupMem(void)
4866 for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
4869 PoolDeallocate(*ptr);
4879 extern char **__libc_argv attribute_hidden;
4882 malloc_printerr(int action, const char *str, void *ptr)
4884 if ((action & 5) == 5)
4885 __libc_message (action & 2, "%s\n", str);
4886 else if (action & 1)
4888 char buf[2 * sizeof (uintptr_t) + 1];
4890 buf[sizeof (buf) - 1] = '\0';
4891 char *cp = _itoa_word ((uintptr_t) ptr, &buf[sizeof (buf) - 1], 16, 0);
4895 __libc_message (action & 2,
4896 "*** glibc detected *** %s: %s: 0x%s ***\n",
4897 __libc_argv[0] ?: "<unknown>", str, cp);
4899 else if (action & 2)
4903 #include <sys/param.h>
4905 /* We need a wrapper function for one of the additions of POSIX. */
4907 __posix_memalign (void **memptr, size_t alignment, size_t size)
4911 /* Test whether the SIZE argument is valid. It must be a power of
4912 two multiple of sizeof (void *). */
4913 if (alignment % sizeof (void *) != 0
4914 || !powerof2 (alignment / sizeof (void *)) != 0
4918 /* Call the hook here, so that caller is posix_memalign's caller
4919 and not posix_memalign itself. */
4920 __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, size_t,
4921 const __malloc_ptr_t)) =
4922 force_reg (__memalign_hook);
4923 if (__builtin_expect (hook != NULL, 0))
4924 mem = (*hook)(alignment, size, RETURN_ADDRESS (0));
4926 mem = __libc_memalign (alignment, size);
4935 weak_alias (__posix_memalign, posix_memalign)
4939 malloc_info (int options, FILE *fp)
4941 /* For now, at least. */
4946 size_t total_nblocks = 0;
4947 size_t total_nfastblocks = 0;
4948 size_t total_avail = 0;
4949 size_t total_fastavail = 0;
4950 size_t total_system = 0;
4951 size_t total_max_system = 0;
4952 size_t total_aspace = 0;
4953 size_t total_aspace_mprotect = 0;
4955 void mi_arena (mstate ar_ptr)
4957 fprintf (fp, "<heap nr=\"%d\">\n<sizes>\n", n++);
4960 size_t nfastblocks = 0;
4962 size_t fastavail = 0;
4969 } sizes[NFASTBINS + NBINS - 1];
4970 #define nsizes (sizeof (sizes) / sizeof (sizes[0]))
4972 mutex_lock (&ar_ptr->mutex);
4974 for (size_t i = 0; i < NFASTBINS; ++i)
4976 mchunkptr p = fastbin (ar_ptr, i);
4979 size_t nthissize = 0;
4980 size_t thissize = chunksize (p);
4988 fastavail += nthissize * thissize;
4989 nfastblocks += nthissize;
4990 sizes[i].from = thissize - (MALLOC_ALIGNMENT - 1);
4991 sizes[i].to = thissize;
4992 sizes[i].count = nthissize;
4995 sizes[i].from = sizes[i].to = sizes[i].count = 0;
4997 sizes[i].total = sizes[i].count * sizes[i].to;
5000 mbinptr bin = bin_at (ar_ptr, 1);
5001 struct malloc_chunk *r = bin->fd;
5006 ++sizes[NFASTBINS].count;
5007 sizes[NFASTBINS].total += r->size;
5008 sizes[NFASTBINS].from = MIN (sizes[NFASTBINS].from, r->size);
5009 sizes[NFASTBINS].to = MAX (sizes[NFASTBINS].to, r->size);
5012 nblocks += sizes[NFASTBINS].count;
5013 avail += sizes[NFASTBINS].total;
5016 for (size_t i = 2; i < NBINS; ++i)
5018 bin = bin_at (ar_ptr, i);
5020 sizes[NFASTBINS - 1 + i].from = ~((size_t) 0);
5021 sizes[NFASTBINS - 1 + i].to = sizes[NFASTBINS - 1 + i].total
5022 = sizes[NFASTBINS - 1 + i].count = 0;
5027 ++sizes[NFASTBINS - 1 + i].count;
5028 sizes[NFASTBINS - 1 + i].total += r->size;
5029 sizes[NFASTBINS - 1 + i].from
5030 = MIN (sizes[NFASTBINS - 1 + i].from, r->size);
5031 sizes[NFASTBINS - 1 + i].to = MAX (sizes[NFASTBINS - 1 + i].to,
5037 if (sizes[NFASTBINS - 1 + i].count == 0)
5038 sizes[NFASTBINS - 1 + i].from = 0;
5039 nblocks += sizes[NFASTBINS - 1 + i].count;
5040 avail += sizes[NFASTBINS - 1 + i].total;
5043 mutex_unlock (&ar_ptr->mutex);
5045 total_nfastblocks += nfastblocks;
5046 total_fastavail += fastavail;
5048 total_nblocks += nblocks;
5049 total_avail += avail;
5051 for (size_t i = 0; i < nsizes; ++i)
5052 if (sizes[i].count != 0 && i != NFASTBINS)
5054 <size from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
5055 sizes[i].from, sizes[i].to, sizes[i].total, sizes[i].count);
5057 if (sizes[NFASTBINS].count != 0)
5059 <unsorted from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
5060 sizes[NFASTBINS].from, sizes[NFASTBINS].to,
5061 sizes[NFASTBINS].total, sizes[NFASTBINS].count);
5063 total_system += ar_ptr->system_mem;
5064 total_max_system += ar_ptr->max_system_mem;
5067 "</sizes>\n<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
5068 "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
5069 "<system type=\"current\" size=\"%zu\"/>\n"
5070 "<system type=\"max\" size=\"%zu\"/>\n",
5071 nfastblocks, fastavail, nblocks, avail,
5072 ar_ptr->system_mem, ar_ptr->max_system_mem);
5074 if (ar_ptr != &main_arena)
5076 heap_info *heap = heap_for_ptr(top(ar_ptr));
5078 "<aspace type=\"total\" size=\"%zu\"/>\n"
5079 "<aspace type=\"mprotect\" size=\"%zu\"/>\n",
5080 heap->size, heap->mprotect_size);
5081 total_aspace += heap->size;
5082 total_aspace_mprotect += heap->mprotect_size;
5087 "<aspace type=\"total\" size=\"%zu\"/>\n"
5088 "<aspace type=\"mprotect\" size=\"%zu\"/>\n",
5089 ar_ptr->system_mem, ar_ptr->system_mem);
5090 total_aspace += ar_ptr->system_mem;
5091 total_aspace_mprotect += ar_ptr->system_mem;
5094 fputs ("</heap>\n", fp);
5097 if(__malloc_initialized < 0)
5100 fputs ("<malloc version=\"1\">\n", fp);
5102 /* Iterate over all arenas currently in use. */
5103 mstate ar_ptr = &main_arena;
5107 ar_ptr = ar_ptr->next;
5109 while (ar_ptr != &main_arena);
5112 "<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
5113 "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
5114 "<system type=\"current\" size=\"%zu\"/>\n"
5115 "<system type=\"max\" size=\"%zu\"/>\n"
5116 "<aspace type=\"total\" size=\"%zu\"/>\n"
5117 "<aspace type=\"mprotect\" size=\"%zu\"/>\n"
5119 total_nfastblocks, total_fastavail, total_nblocks, total_avail,
5120 total_system, total_max_system,
5121 total_aspace, total_aspace_mprotect);
5127 strong_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)
5128 strong_alias (__libc_free, __cfree) weak_alias (__libc_free, cfree)
5129 strong_alias (__libc_free, __free) strong_alias (__libc_free, free)
5130 strong_alias (__libc_malloc, __malloc) strong_alias (__libc_malloc, malloc)
5131 strong_alias (__libc_memalign, __memalign)
5132 weak_alias (__libc_memalign, memalign)
5133 strong_alias (__libc_realloc, __realloc) strong_alias (__libc_realloc, realloc)
5134 strong_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)
5135 strong_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)
5136 strong_alias (__libc_mallinfo, __mallinfo)
5137 weak_alias (__libc_mallinfo, mallinfo)
5138 strong_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)
5140 weak_alias (__malloc_stats, malloc_stats)
5141 weak_alias (__malloc_usable_size, malloc_usable_size)
5142 weak_alias (__malloc_trim, malloc_trim)
5143 weak_alias (__malloc_get_state, malloc_get_state)
5144 weak_alias (__malloc_set_state, malloc_set_state)
5147 /* ------------------------------------------------------------
5150 [see ftp://g.oswego.edu/pub/misc/malloc.c for the history of dlmalloc]